:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(customer-analytics): clear synced account properties on null (#99229)
danazou33a69a2f4b86
diff --git a/docs/internal/customer-analytics-account-sidebar.md b/docs/internal/customer-analytics-account-sidebar.mdindex 477f27a3d2d6..1a86545408a2 100644--- a/docs/internal/customer-analytics-account-sidebar.md+++ b/docs/internal/customer-analytics-account-sidebar.md@@ -36,6 +36,11 @@ Clearing a custom value requires confirmation and posts a null value toThe endpoint returns 204, soft-deletes the current value, and preserves its history.Warehouse-backed and canonical values reject both manual sets and clears.+A warehouse sync clears a saved custom property when the source row contains an explicit+null for that property. The sidebar then displays "Not set". The clear preserves history+and emits a property-change event. Repeated nulls do not emit another change event.+Missing source rows or columns leave saved values unchanged.+Relationship editors support single and multiple holders. Removing a holder ends theassignment without deleting its history. Multi-holder changes retain unchanged holders.Relationship saves apply the edits relative to the assignments shown when editing began.diff --git a/products/customer_analytics/backend/logic/account_property_sync.py b/products/customer_analytics/backend/logic/account_property_sync.pyindex 0c95024a01df..2083600da5e5 100644--- a/products/customer_analytics/backend/logic/account_property_sync.py+++ b/products/customer_analytics/backend/logic/account_property_sync.py@@ -125,6 +125,14 @@ def _value_hash(value: Any) -> str:return hashlib.sha256(json.dumps(_json_safe(value), sort_keys=True).encode("utf-8")).hexdigest()+def _source_values(rows: list[dict[str, Any]], key_column: str, source_column: str) -> dict[str, Any]:+ return {+ str(row[key_column]): _json_safe(row[source_column])+ for row in rows+ if row.get(key_column) is not None and source_column in row+ }++def _decode_parquet_rows(data: bytes) -> list[dict[str, Any]]:return pq.read_table(io.BytesIO(data)).to_pylist()@@ -387,12 +395,7 @@ async def run_account_property_segment_sync(continuephase_started_at = asyncio.get_running_loop().time()- values_by_external_id: dict[str, Any] = {}- for row in rows:- external_id = row.get(source.key_column)- value = row.get(source_column)- if external_id is not None and value is not None:- values_by_external_id[str(external_id)] = _json_safe(value)+ values_by_external_id = _source_values(rows, source.key_column, source_column)changed = {external_id: valuefor external_id, value in values_by_external_id.items()diff --git a/products/customer_analytics/backend/logic/account_property_sync_test.py b/products/customer_analytics/backend/logic/account_property_sync_test.pyindex 7c51b26e1b07..51cf2f8f0c63 100644--- a/products/customer_analytics/backend/logic/account_property_sync_test.py+++ b/products/customer_analytics/backend/logic/account_property_sync_test.py@@ -22,6 +22,7 @@ from products.customer_analytics.backend.logic.account_property_sync import (_iter_parquet_row_batches,_mark_completed_and_maybe_cleanup,_matching_account_ids,+ _source_values,_value_hash,run_account_property_segment_sync,)@@ -218,6 +219,27 @@ class _S3ClientContext:return False+ "rows, expected",+ [+ ([{"external_id": "org-1", "plan": None}], {"org-1": None}),+ ([{"external_id": "org-1", "plan": 0}], {"org-1": 0}),+ ([{"external_id": "org-1", "plan": False}], {"org-1": False}),+ ([{"external_id": "org-1", "plan": ""}], {"org-1": ""}),+ ([{"external_id": "org-1"}], {}),+ ([{"plan": None}], {}),+ ([{"external_id": None, "plan": None}], {}),+ ([], {}),+ (+ [{"external_id": "org-1", "plan": "silver"}, {"external_id": "org-1", "plan": None}],+ {"org-1": None},+ ),+ ],+)+def test_source_values_preserve_explicit_nulls_but_skip_missing_columns(rows, expected) -> None:+ assert _source_values(rows, "external_id", "plan") == expected++@pytest.mark.asyncioasync def test_each_staged_batch_is_shared_across_sources() -> None:binding = saved_query_binding("019f0000-0000-7000-8000-000000000001")diff --git a/products/customer_analytics/backend/logic/custom_property_sync.py b/products/customer_analytics/backend/logic/custom_property_sync.pyindex 73fac1029eaf..647c49838a2d 100644--- a/products/customer_analytics/backend/logic/custom_property_sync.py+++ b/products/customer_analytics/backend/logic/custom_property_sync.py@@ -23,6 +23,7 @@ from products.customer_analytics.backend.logic.custom_property_values import (CustomPropertyValueConflict,InvalidCustomPropertyValue,set_custom_property_value,+ set_synced_custom_property_value,)from products.customer_analytics.backend.models import Account, CustomPropertySource@@ -100,8 +101,6 @@ def sync_custom_property_values(if account_id is None:unmatched.add(key)continue- if row[value_index] is None:- continueif _write(team_id=team_id, account_id=account_id, source=source, value=row[value_index], result=result):result.written += 1result.unmatched_keys = len(unmatched)@@ -121,6 +120,10 @@ def _write(*, team_id: int, account_id: Any, source: CustomPropertySource, valuelast_conflict: CustomPropertyValueConflict | None = Nonefor _ in range(_WRITE_CONFLICT_RETRIES):try:+ if value is None:+ return set_synced_custom_property_value(+ team_id=team_id, account_id=account_id, definition=source.definition, value=None+ )set_custom_property_value(team_id=team_id, account_id=account_id, definition_id=source.definition_id, value=value)diff --git a/products/customer_analytics/backend/logic/custom_property_sync_test.py b/products/customer_analytics/backend/logic/custom_property_sync_test.pyindex ddf42cc90d78..b406d8e928ff 100644--- a/products/customer_analytics/backend/logic/custom_property_sync_test.py+++ b/products/customer_analytics/backend/logic/custom_property_sync_test.py@@ -3,6 +3,8 @@ from unittest.mock import Mock, patchfrom django.apps import apps+from parameterized import parameterized+from products.customer_analytics.backend.logic.custom_property_sync import (_read_view,sync_custom_properties_for_account,@@ -79,10 +81,14 @@ class CustomPropertySyncTest(TeamScopedTestMixin, BaseTest):def test_missing_column_marks_source_error_and_skips(self):source = self._source(self.mrr_def, "does_not_exist")+ current = CustomPropertyValue.objects.create(+ team=self.team, account=self.acme, definition=self.mrr_def, value_num=100.0+ )result = self._sync([(100.0, "acme")])assert result.written == 0assert str(source.id) in result.source_errors+ assert self._active(self.acme, self.mrr_def).id == current.iddef test_deleted_view_returns_not_found(self):self._source(self.mrr_def, "mrr")@@ -94,13 +100,26 @@ class CustomPropertySyncTest(TeamScopedTestMixin, BaseTest):assert result.view_found is Falseassert result.written == 0- def test_skips_null_values(self):+ @parameterized.expand([("unset", None), ("zero", 0.0), ("positive", 100.0)])+ def test_null_clears_only_the_matched_value_and_preserves_history(self, _name, initial_value):self._source(self.mrr_def, "mrr")- # selected columns are sorted: mrr, org_id+ initial_rows = [(200.0, "globex")]+ if initial_value is not None:+ initial_rows.append((initial_value, "acme"))+ self._sync(initial_rows)+result = self._sync([(None, "acme")])- assert result.written == 0- assert not CustomPropertyValue.objects.filter(definition=self.mrr_def, account=self.acme).exists()+ assert result.written == int(initial_value is not None)+ assert result.source_errors == {}+ history = CustomPropertyValue.objects.filter(definition=self.mrr_def, account=self.acme)+ assert not history.filter(is_deleted=False).exists()+ assert history.filter(is_deleted=True).count() == int(initial_value is not None)+ assert self._active(self.globex, self.mrr_def).value_num == 200.0++ assert self._sync([(None, "acme")]).written == 0+ assert self._sync([(0.0, "acme")]).written == 1+ assert self._active(self.acme, self.mrr_def).value_num == 0.0def test_skips_null_keys(self):self._source(self.mrr_def, "mrr")diff --git a/products/customer_analytics/backend/logic/custom_property_values.py b/products/customer_analytics/backend/logic/custom_property_values.pyindex d835e2a3474e..e787a8f2c721 100644--- a/products/customer_analytics/backend/logic/custom_property_values.py+++ b/products/customer_analytics/backend/logic/custom_property_values.py@@ -199,7 +199,9 @@ def record_last_slack_message_at(*, team_id: int, account_id: str | UUID, timestdef set_synced_custom_property_value(*, team_id: int, account_id: str | UUID, definition: CustomPropertyDefinition, value: Any) -> bool:- """Set a staged warehouse value for an account already resolved inside this team."""+ """Set or clear a warehouse value for an account already resolved inside this team."""+ if value is None:+ return _clear_value(team_id=team_id, account_id=account_id, definition=definition)_, coerced = _coerce_to_column(definition, value)current = (CustomPropertyValue.objects.for_team(team_id)@@ -272,14 +274,14 @@ def _clear_value(definition: CustomPropertyDefinition,actor: User | None = None,workflow_id: str | None = None,-) -> None:+) -> bool:with transaction.atomic():active_rows = CustomPropertyValue.objects.for_team(team_id).filter(account_id=account_id, definition_id=definition.id, is_deleted=False)previous_row = active_rows.first()if previous_row is None:- return+ return Falsecleared_rows = active_rows.filter(id=previous_row.id).update(is_deleted=True)if cleared_rows == 0:raise CustomPropertyValueConflict(@@ -294,6 +296,7 @@ def _clear_value(actor=actor,workflow_id=workflow_id,)+ return Truedef _schedule_value_changed_event(diff --git a/products/customer_analytics/backend/test/test_events.py b/products/customer_analytics/backend/test/test_events.pyindex 5bbfbb9f5f27..0bc6abd0114e 100644--- a/products/customer_analytics/backend/test/test_events.py+++ b/products/customer_analytics/backend/test/test_events.py@@ -13,6 +13,7 @@ from products.customer_analytics.backend.facade import (api as facade,contracts,)+from products.customer_analytics.backend.logic.custom_property_values import set_synced_custom_property_valuefrom products.customer_analytics.backend.models import AccountRelationshipDefinitionfrom products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition@@ -310,34 +311,53 @@ class TestAccountCustomPropertyChangedEvent(BaseTest):assert event["properties"]["actor_type"] == "workflow"assert event["properties"]["workflow_id"] == WORKFLOW_ID- def test_workflow_clear_emits_null_current_value(self, mock_capture):+ @parameterized.expand([("workflow",), ("system",)])+ def test_clear_emits_null_current_value(self, mock_capture, actor_type):definition = create_custom_property_definition(team_id=self.team.id, name="Plan")self._set_value(definition, "silver")mock_capture.reset_mock()with self.captureOnCommitCallbacks(execute=True):- result = facade.set_external_account_custom_properties(- self.team.id, "acme-1", properties={str(definition.id): None}, workflow_id=WORKFLOW_ID- )+ if actor_type == "workflow":+ result = facade.set_external_account_custom_properties(+ self.team.id, "acme-1", properties={str(definition.id): None}, workflow_id=WORKFLOW_ID+ )+ assert result.error is None+ assert result.values == []+ else:+ assert set_synced_custom_property_value(+ team_id=self.team.id, account_id=self.account.id, definition=definition, value=None+ )- assert result.error is None- assert result.values == []mock_capture.assert_called_once()(event,) = mock_capture.call_args.kwargs["events"]assert event["properties"]["previous_value"] == "silver"assert event["properties"]["current_value"] is None- assert event["properties"]["actor_type"] == "workflow"+ assert event["properties"]["actor_type"] == actor_type++ mock_capture.reset_mock()+ with self.captureOnCommitCallbacks(execute=True):+ assert not set_synced_custom_property_value(+ team_id=self.team.id, account_id=self.account.id, definition=definition, value=None+ )+ mock_capture.assert_not_called()- def test_clearing_an_unset_value_emits_nothing(self, mock_capture):+ @parameterized.expand([("workflow",), ("system",)])+ def test_clearing_an_unset_value_emits_nothing(self, mock_capture, actor_type):definition = create_custom_property_definition(team_id=self.team.id, name="Plan")with self.captureOnCommitCallbacks(execute=True):- result = facade.set_external_account_custom_properties(- self.team.id, "acme-1", properties={str(definition.id): None}, workflow_id=WORKFLOW_ID- )+ if actor_type == "workflow":+ result = facade.set_external_account_custom_properties(+ self.team.id, "acme-1", properties={str(definition.id): None}, workflow_id=WORKFLOW_ID+ )+ assert result.error is None+ assert result.values == []+ else:+ assert not set_synced_custom_property_value(+ team_id=self.team.id, account_id=self.account.id, definition=definition, value=None+ )- assert result.error is None- assert result.values == []mock_capture.assert_not_called()def test_user_actor_populates_actor_fields(self, mock_capture):