: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(warehouse): reconcile property definition provenance (#88928)
Andrew Ghostuhin4c5b51864c38
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync.pyindex ce466abbdfd8..a07f674a2392 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync.py@@ -31,6 +31,7 @@ from decimal import Decimalfrom typing import Anyfrom django.conf import settings+from django.db.models import Qimport structlogimport pyarrow.parquet as pq@@ -68,6 +69,10 @@ EVENT_SOURCE = "customer_analytics_person_property_sync"# customer_analytics config models, matching the isolation the hooks already preserve)._GROUP_TARGET = "group"+# Keep this in lockstep with property-defs-rs: it admits property names up to half Django's+# CharField limit, measured as UTF-8 bytes, and sanitizes NULs immediately before persistence.+_MAX_PROPERTY_NAME_BYTES = 200+def _log_fields(binding: WarehouseBinding) -> dict[str, str]:"""Structlog fields naming the warehouse object a run read from."""@@ -404,12 +409,13 @@ def _produce_intents(return produced-def _stamp_provenance(- team_id: int, binding: WarehouseBinding, source: PersonPropertySyncSource, property_names: list[str]+def _reconcile_property_definitions(+ team_id: int,+ project_id: int,+ binding: WarehouseBinding,+ source: PersonPropertySyncSource,+ property_names: list[str],) -> None:- # UPDATE-only on purpose: definitions are created by ingestion's propdef upsert when the $set /- # $groupidentify lands, so a brand-new property may not have a row yet on the first sync — the next- # sync's stamp catches it. Never inserting means this can't race that upsert.origin: dict[str, str] = {"source_id": str(source.definition_id),"custom_property_source_id": str(source.source_id),@@ -420,22 +426,72 @@ def _stamp_provenance(# it would leave two stamps of the same schema describing it differently.if not binding.is_saved_query:origin["schema_id"] = binding.id- query = PropertyDefinition.objects.filter(team_id=team_id)++ descriptions = source.property_descriptions or {}+ canonical_descriptions: dict[str, str] = {}+ for name in property_names:+ if len(name.encode()) > _MAX_PROPERTY_NAME_BYTES:+ continue+ canonical_name = name.replace("\x00", "\ufffd")+ canonical_descriptions.setdefault(canonical_name, descriptions.get(name, ""))++ if not canonical_descriptions:+ return++ property_names = list(canonical_descriptions)+ definition_type = PropertyDefinition.Type.PERSON+ group_type_index = None+ if source.target == _GROUP_TARGET:+ if source.group_type_index is None:+ return+ definition_type = PropertyDefinition.Type.GROUP+ group_type_index = source.group_type_index++ # Property definitions are unique and read by effective project. Include legacy rows whose+ # project_id is null so the conflict-safe insert and the final stamp address the same identity.+ query = PropertyDefinition.objects.filter(Q(project_id=project_id) | Q(project_id__isnull=True, team_id=project_id))if source.target == _GROUP_TARGET:# Group propdefs are keyed per group type, so the index predicate is mandatory.query = query.filter(type=PropertyDefinition.Type.GROUP, group_type_index=source.group_type_index)else:query = query.filter(type=PropertyDefinition.Type.PERSON)- # Properties given a description carry it inside their provenance, so stamp those one at a time;- # the rest share the base origin and go in a single bulk update.- descriptions = source.property_descriptions or {}- described = [name for name in property_names if descriptions.get(name)]- plain = [name for name in property_names if not descriptions.get(name)]+ current_origins = dict(query.filter(name__in=property_names).values_list("name", "warehouse_origin"))+ missing = [name for name in property_names if name not in current_origins]+ if missing:+ # Ingestion may create the same effective-project identity after the read above. Ignore that+ # conflict, then read back the winner before deciding which origins still need a write.+ PropertyDefinition.objects.bulk_create(+ [+ PropertyDefinition(+ team_id=team_id,+ project_id=project_id,+ name=name,+ type=definition_type,+ group_type_index=group_type_index,+ warehouse_origin={+ **origin,+ **({"description": canonical_descriptions[name]} if canonical_descriptions[name] else {}),+ },+ )+ for name in missing+ ],+ ignore_conflicts=True,+ )+ current_origins.update(query.filter(name__in=missing).values_list("name", "warehouse_origin"))++ plain = [+ name for name in property_names if not canonical_descriptions[name] and current_origins.get(name) != origin+ ]if plain:query.filter(name__in=plain).update(warehouse_origin=origin)- for name in described:- query.filter(name=name).update(warehouse_origin={**origin, "description": descriptions[name]})+ for name in property_names:+ description = canonical_descriptions[name]+ if not description:+ continue+ described_origin = {**origin, "description": description}+ if current_origins.get(name) != described_origin:+ query.filter(name=name).update(warehouse_origin=described_origin)# --- orchestration -----------------------------------------------------------------------@@ -459,6 +515,9 @@ async def _process_source_bundles((staged rows vs a full Delta read)."""ps = PerSourceResult(source_id=str(source.source_id), rows_read=rows_read)prior = await _read_snapshot_hashes(team_id, binding, str(source.source_id))+ await database_sync_to_async(_reconcile_property_definitions, thread_sensitive=False)(+ team_id, project_id, binding, source, list((source.column_property_map or {}).values())+ )changed, new_hashes = select_changed(bundles, prior)ps.changed = len(changed)if not changed:@@ -502,13 +561,6 @@ async def _process_source_bundles()ps.produced = produced- # Stamp provenance before advancing the snapshot: the snapshot is the checkpoint that makes- # these rows look unchanged on the next run, so anything that must accompany a produce has to- # happen first. Stamping is an idempotent update, safe to repeat if a retry re-produces.- await database_sync_to_async(_stamp_provenance, thread_sensitive=False)(- team_id, binding, source, list((source.column_property_map or {}).values())- )-# Record only the distinct_ids we actually produced, as this run's snapshot file.sent_ids = {distinct_id for distinct_id, _ in to_send}produced_hashes = {d: h for d, h in new_hashes.items() if d in sent_ids}diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync_test.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync_test.pyindex a78e1c206bd7..aaa831c0dcc6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync_test.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync_test.py@@ -1,10 +1,16 @@import json+import threadingfrom datetime import date, datetimefrom decimal import Decimalimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch+from django.db import close_old_connections, connection+from django.db.models import Q+from django.test import TransactionTestCase+from django.test.utils import CaptureQueriesContext+from parameterized import parameterizedfrom posthog.models import Organization, PropertyDefinition, Team@@ -112,20 +118,32 @@ class TestRunOrchestration:@pytest.mark.asyncioasync def test_produces_only_changed_and_existing_persons_and_advances_snapshot(self):team = MagicMock(api_token="tok", project_id=7)+ order: list[str] = []rows = [{"distinct_id": "a", "plan": "pro"},{"distinct_id": "b", "plan": "free"},{"distinct_id": "ghost", "plan": "x"},]++ def _record_produce(*_args: object, **_kwargs: object) -> int:+ order.append("produce")+ return 2+with (patch(f"{_MODULE}.person_property_sync_sources_for", return_value=[self._source()]),patch(f"{_MODULE}.Team") as team_cls,patch(f"{_MODULE}._read_staged_rows", new=AsyncMock(return_value=rows)),patch(f"{_MODULE}._read_snapshot_hashes", new=AsyncMock(return_value={})),patch(f"{_MODULE}._filter_existing_ids", return_value={"a", "b"}) as existing,- patch(f"{_MODULE}._produce_intents", return_value=2) as produce,- patch(f"{_MODULE}._write_snapshot_hashes", new=AsyncMock()) as write_snapshot,- patch(f"{_MODULE}._stamp_provenance") as stamp,+ patch(f"{_MODULE}._produce_intents", side_effect=_record_produce) as produce,+ patch(+ f"{_MODULE}._write_snapshot_hashes",+ new=AsyncMock(side_effect=lambda *_args, **_kwargs: order.append("snapshot")),+ ) as write_snapshot,+ patch(+ f"{_MODULE}._reconcile_property_definitions",+ side_effect=lambda *_args, **_kwargs: order.append("reconcile"),+ ) as reconcile,patch(f"{_MODULE}._clear_staged", new=AsyncMock()) as clear,):team_cls.objects.get.return_value = team@@ -148,8 +166,9 @@ class TestRunOrchestration:assert set(written) == {"a", "b"}existing.assert_called_once()- stamp.assert_called_once()+ reconcile.assert_called_once()clear.assert_awaited_once()+ assert order == ["reconcile", "produce", "snapshot"]@pytest.mark.asyncioasync def test_no_sources_is_a_noop(self):@@ -164,6 +183,33 @@ class TestRunOrchestration:read.assert_not_awaited()clear.assert_not_awaited()+ @pytest.mark.asyncio+ async def test_reconciles_provenance_before_unchanged_return(self):+ source = self._source()+ with (+ patch(f"{_MODULE}._read_snapshot_hashes", new=AsyncMock(return_value={"a": "prior"})),+ patch(f"{_MODULE}.select_changed", return_value=([], {})),+ patch(f"{_MODULE}._reconcile_property_definitions") as reconcile,+ patch(f"{_MODULE}._filter_existing_ids") as existing,+ patch(f"{_MODULE}._produce_intents") as produce,+ ):+ result = await pps._process_source_bundles(+ team_id=1,+ project_id=7,+ binding=_SCHEMA,+ team_api_token="tok",+ team_uuid="team-uuid",+ source=source,+ bundles=[("a", {"plan_tier": "pro"})],+ rows_read=1,+ run_token="job-1",+ )++ reconcile.assert_called_once_with(1, 7, _SCHEMA, source, ["plan_tier"])+ existing.assert_not_called()+ produce.assert_not_called()+ assert result.changed == 0 and result.produced == 0+class TestReadDeltaBundles:"""The backfill's Delta reader accumulates last-write-wins per source, scoped to each source's map."""@@ -211,7 +257,7 @@ class TestBackfillOrchestration:@pytest.mark.asyncioasync def test_reads_once_and_produces_per_source(self):- team = MagicMock(api_token="tok")+ team = MagicMock(api_token="tok", project_id=7)schema = MagicMock()schema.folder_path.return_value = "team_1_stripe_schema-1"# The backfill resolves the Delta folder from the loader's actual folder name, not normalized_name.@@ -232,7 +278,7 @@ class TestBackfillOrchestration:patch(f"{_MODULE}._filter_existing_ids", return_value={"a"}),patch(f"{_MODULE}._produce_intents", return_value=1) as produce,patch(f"{_MODULE}._write_snapshot_hashes", new=AsyncMock()) as write_snapshot,- patch(f"{_MODULE}._stamp_provenance"),+ patch(f"{_MODULE}._reconcile_property_definitions"),):team_cls.objects.get.return_value = teamresult = await pps.run_person_property_backfill(team_id=1, binding=_SCHEMA, trigger="manual")@@ -277,6 +323,8 @@ class TestBackfillOrchestration:return_value="s3://bucket/team_1_model_abc/modeling/enriched_users",) as model_uri,patch(f"{_MODULE}._read_delta_bundles", return_value=({"s1": {}}, 0)) as read_delta,+ patch(f"{_MODULE}._read_snapshot_hashes", new=AsyncMock(return_value={})),+ patch(f"{_MODULE}._reconcile_property_definitions"),):team_cls.objects.get.return_value = teamawait pps.run_person_property_backfill(team_id=1, binding=_VIEW, trigger="manual")@@ -418,14 +466,14 @@ class TestGroupTarget:patch(f"{_MODULE}._group_type_name", return_value=None),patch(f"{_MODULE}._produce_intents", return_value=1) as produce,patch(f"{_MODULE}._write_snapshot_hashes", new=AsyncMock()) as write_snapshot,- patch(f"{_MODULE}._stamp_provenance") as stamp,+ patch(f"{_MODULE}._reconcile_property_definitions") as reconcile,patch(f"{_MODULE}._clear_staged", new=AsyncMock()),):team_cls.objects.get.return_value = teamresult = await pps.run_person_property_sync(team_id=1, binding=_SCHEMA, job_id="job-1")produce.assert_not_called()- stamp.assert_not_called()+ reconcile.assert_called_once()write_snapshot.assert_not_awaited()assert result.produced == 0@@ -449,7 +497,7 @@ class TestGroupTarget:) as lookup,patch(f"{_MODULE}._produce_intents", return_value=1) as produce,patch(f"{_MODULE}._write_snapshot_hashes", new=AsyncMock()),- patch(f"{_MODULE}._stamp_provenance"),+ patch(f"{_MODULE}._reconcile_property_definitions"),patch(f"{_MODULE}._clear_staged", new=AsyncMock()),):team_cls.objects.get.return_value = team@@ -508,9 +556,8 @@ class TestExistenceLookupChunking:@pytest.mark.django_db-class TestStampProvenance:- """`_stamp_provenance` updates existing property definitions with warehouse provenance, folding a- per-property description into the origin when the source carries one."""+class TestReconcilePropertyDefinitions:+ """Source configuration creates and repairs project-scoped warehouse provenance."""def _team(self):org = Organization.objects.create(name="o")@@ -518,8 +565,6 @@ class TestStampProvenance:def test_folds_descriptions_into_provenance_only_where_present(self):team = self._team()- PropertyDefinition.objects.create(team=team, name="plan_tier", type=PropertyDefinition.Type.PERSON)- PropertyDefinition.objects.create(team=team, name="seat_count", type=PropertyDefinition.Type.PERSON)source = PersonPropertySyncSource("s1","d1",@@ -528,10 +573,12 @@ class TestStampProvenance:property_descriptions={"plan_tier": "The plan tier"},)- pps._stamp_provenance(team.id, _SCHEMA, source, ["plan_tier", "seat_count"])+ pps._reconcile_property_definitions(+ team.id, team.project_id, _SCHEMA, source, ["plan_tier", "seat_count", "plan_tier"]+ )- described = PropertyDefinition.objects.get(team=team, name="plan_tier")- plain = PropertyDefinition.objects.get(team=team, name="seat_count")+ described = PropertyDefinition.objects.get(project_id=team.project_id, name="plan_tier")+ plain = PropertyDefinition.objects.get(project_id=team.project_id, name="seat_count")assert described.warehouse_origin is not Noneassert plain.warehouse_origin is not Noneassert described.warehouse_origin["custom_property_source_id"] == "s1"@@ -545,12 +592,11 @@ class TestStampProvenance:# `schema_id` is what rows stamped before views existed carry, so a schema binding must keep# writing it; a view has no schema and must not claim one.team = self._team()- PropertyDefinition.objects.create(team=team, name="plan_tier", type=PropertyDefinition.Type.PERSON)source = PersonPropertySyncSource("s1", "d1", "distinct_id", {"plan": "plan_tier"})- pps._stamp_provenance(team.id, binding, source, ["plan_tier"])+ pps._reconcile_property_definitions(team.id, team.project_id, binding, source, ["plan_tier"])- origin = PropertyDefinition.objects.get(team=team, name="plan_tier").warehouse_origin+ origin = PropertyDefinition.objects.get(project_id=team.project_id, name="plan_tier").warehouse_originassert origin is not Noneassert (origin["binding_kind"], origin["binding_id"]) == (binding.kind, binding.id)assert origin.get("schema_id") == expected_schema_id@@ -565,9 +611,206 @@ class TestStampProvenance:)source = PersonPropertySyncSource("s1", "d1", "group_key", {"plan": "tier"}, target="group", group_type_index=0)- pps._stamp_provenance(team.id, _SCHEMA, source, ["tier"])+ pps._reconcile_property_definitions(team.id, team.project_id, _SCHEMA, source, ["tier"])assert PropertyDefinition.objects.get(id=other.id).warehouse_origin is Nonestamped = PropertyDefinition.objects.get(team=team, name="tier", group_type_index=0)assert stamped.warehouse_origin is not Noneassert stamped.warehouse_origin["custom_property_source_id"] == "s1"++ def test_idempotently_repairs_historical_null_without_replacing_other_fields(self):+ team = self._team()+ historical = PropertyDefinition.objects.create(+ team=team,+ project_id=team.project_id,+ name="plan_tier",+ type=PropertyDefinition.Type.PERSON,+ property_type="Numeric",+ )+ source = PersonPropertySyncSource("s1", "d1", "distinct_id", {"plan": "plan_tier"})++ pps._reconcile_property_definitions(team.id, team.project_id, _SCHEMA, source, ["plan_tier"])+ pps._reconcile_property_definitions(team.id, team.project_id, _SCHEMA, source, ["plan_tier"])++ historical.refresh_from_db()+ assert PropertyDefinition.objects.filter(project_id=team.project_id, name="plan_tier").count() == 1+ assert historical.property_type == "Numeric"+ assert historical.warehouse_origin is not None+ assert historical.warehouse_origin["custom_property_source_id"] == "s1"++ def test_second_reconciliation_is_sql_write_free(self):+ team = self._team()+ source = PersonPropertySyncSource(+ "s1",+ "d1",+ "distinct_id",+ {"plan": "plan_tier", "seats": "seat_count"},+ property_descriptions={"plan_tier": "The plan tier"},+ )+ names = ["plan_tier", "seat_count"]+ pps._reconcile_property_definitions(team.id, team.project_id, _SCHEMA, source, names)++ with CaptureQueriesContext(connection) as queries:+ pps._reconcile_property_definitions(team.id, team.project_id, _SCHEMA, source, names)++ statements = [query["sql"].lstrip().upper() for query in queries.captured_queries]+ assert not any(statement.startswith(("INSERT", "UPDATE")) for statement in statements)++ def test_matches_ingestion_property_name_admission_and_sanitization(self):+ team = self._team()+ accepted_multibyte = "é" * 100+ oversized_multibyte = "é" * 101+ raw_nul_name = "plan\x00tier"+ source = PersonPropertySyncSource(+ "s1",+ "d1",+ "distinct_id",+ {"accepted": accepted_multibyte, "oversized": oversized_multibyte, "nul": raw_nul_name},+ property_descriptions={raw_nul_name: "The plan tier"},+ )++ pps._reconcile_property_definitions(+ team.id,+ team.project_id,+ _SCHEMA,+ source,+ [accepted_multibyte, oversized_multibyte, raw_nul_name],+ )++ names = set(PropertyDefinition.objects.filter(project_id=team.project_id).values_list("name", flat=True))+ assert names == {accepted_multibyte, "plan�tier"}+ sanitized = PropertyDefinition.objects.get(project_id=team.project_id, name="plan�tier")+ assert sanitized.warehouse_origin is not None+ assert sanitized.warehouse_origin["description"] == "The plan tier"++ @parameterized.expand(+ [("person", PropertyDefinition.Type.PERSON, None), ("group", PropertyDefinition.Type.GROUP, 0)]+ )+ def test_reconciles_legacy_effective_project_definition(self, target, definition_type, group_index):+ team = self._team()+ assert team.id == team.project_id+ existing = PropertyDefinition.objects.create(+ team=team,+ project_id=None,+ name="tier",+ type=definition_type,+ group_type_index=group_index,+ )+ source = PersonPropertySyncSource(+ "s1",+ "d1",+ "key",+ {"plan": "tier"},+ target=target,+ group_type_index=group_index,+ )++ pps._reconcile_property_definitions(team.id, team.project_id, _SCHEMA, source, ["tier"])++ existing.refresh_from_db()+ assert existing.warehouse_origin is not None+ assert existing.warehouse_origin["custom_property_source_id"] == "s1"+ assert (+ PropertyDefinition.objects.filter(+ Q(project_id=team.project_id) | Q(project_id__isnull=True, team_id=team.project_id),+ name="tier",+ type=definition_type,+ group_type_index=group_index,+ ).count()+ == 1+ )++ @parameterized.expand(+ [("person", PropertyDefinition.Type.PERSON, None), ("group", PropertyDefinition.Type.GROUP, 0)]+ )+ def test_reconciles_same_project_definition_created_by_another_team(self, target, definition_type, group_index):+ team = self._team()+ other_team = Team.objects.create(organization=team.organization, name="other", project_id=team.project_id)+ existing = PropertyDefinition.objects.create(+ team=other_team,+ project_id=team.project_id,+ name="tier",+ type=definition_type,+ group_type_index=group_index,+ )+ source = PersonPropertySyncSource(+ "s1",+ "d1",+ "key",+ {"plan": "tier"},+ target=target,+ group_type_index=group_index,+ )++ pps._reconcile_property_definitions(team.id, team.project_id, _SCHEMA, source, ["tier"])++ existing.refresh_from_db()+ assert PropertyDefinition.objects.filter(project_id=team.project_id, name="tier").count() == 1+ assert existing.warehouse_origin is not None+ assert existing.warehouse_origin["custom_property_source_id"] == "s1"+++class TestReconcilePropertyDefinitionsConcurrency(TransactionTestCase):+ @parameterized.expand(+ [("person", PropertyDefinition.Type.PERSON, None), ("group", PropertyDefinition.Type.GROUP, 0)]+ )+ def test_ingestion_insert_winning_the_race_is_stamped_once(self, target, definition_type, group_index):+ organization = Organization.objects.create(name="o")+ team = Team.objects.create(organization=organization, name="t")+ other_team = Team.objects.create(organization=organization, name="other", project_id=team.project_id)+ source = PersonPropertySyncSource(+ "s1",+ "d1",+ "key",+ {"plan": "tier"},+ target=target,+ group_type_index=group_index,+ )+ bulk_create_reached = threading.Event()+ ingestion_committed = threading.Event()+ errors: list[BaseException] = []+ original_bulk_create = PropertyDefinition.objects.bulk_create++ def pause_before_conflict_insert(*args, **kwargs):+ bulk_create_reached.set()+ if not ingestion_committed.wait(timeout=5):+ raise TimeoutError("ingestion insert did not commit")+ return original_bulk_create(*args, **kwargs)++ def reconcile() -> None:+ close_old_connections()+ try:+ pps._reconcile_property_definitions(team.id, team.project_id, _SCHEMA, source, ["tier"])+ except BaseException as error:+ errors.append(error)+ finally:+ close_old_connections()++ with patch.object(PropertyDefinition.objects, "bulk_create", side_effect=pause_before_conflict_insert):+ thread = threading.Thread(target=reconcile)+ thread.start()+ assert bulk_create_reached.wait(timeout=5)+ PropertyDefinition.objects.create(+ team=other_team,+ project_id=team.project_id,+ name="tier",+ type=definition_type,+ group_type_index=group_index,+ property_type="Numeric",+ )+ ingestion_committed.set()+ thread.join(timeout=5)++ assert not thread.is_alive()+ assert errors == []+ definitions = PropertyDefinition.objects.filter(+ project_id=team.project_id,+ name="tier",+ type=definition_type,+ group_type_index=group_index,+ )+ assert definitions.count() == 1+ definition = definitions.get()+ assert definition.property_type == "Numeric"+ assert definition.warehouse_origin is not None+ assert definition.warehouse_origin["custom_property_source_id"] == "s1"