: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(data-warehouse): chunk entity lookups in warehouse property sync (#81266)
Tom Owers07f2ddc8d79b
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 790c6e68903b..f09e2d8239cc 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@@ -56,6 +56,13 @@ EVENT_SOURCE = "customer_analytics_person_property_sync"# customer_analytics config models, matching the isolation the hooks already preserve)._GROUP_TARGET = "group"+# Identifiers per existence-lookup call. Both personhog helpers return whole Person/Group models,+# properties included, and accumulate every model before returning. This activity only needs the+# identifier back, so chunking here caps peak memory at one chunk's models instead of the entire+# changed set — an organization group carries tens of KB of properties, so a six-figure changed set+# would otherwise materialize gigabytes and get the worker OOM-killed.+_EXISTENCE_LOOKUP_CHUNK_SIZE = 1_000+@dataclasses.dataclassclass PerSourceResult:@@ -286,14 +293,26 @@ def _get_schema(team_id: int, schema_id: str) -> ExternalDataSchema | None:def _filter_existing_ids(team_id: int, source: PersonPropertySyncSource, ids: list[str]) -> set[str]:"""The subset of ``ids`` that resolve to an existing person (or group, for group targets). We only- enrich entities that already exist — the same rule for both, just a different lookup."""+ enrich entities that already exist — the same rule for both, just a different lookup.++ Chunked so only one chunk's models are alive at a time (see ``_EXISTENCE_LOOKUP_CHUNK_SIZE``);+ each chunk's identifiers are kept and its models dropped before the next call."""if not ids:return set()- if source.target == _GROUP_TARGET:- if source.group_type_index is None:- return set()- return {group.group_key for group in get_groups_by_identifiers(team_id, source.group_type_index, ids)}- return set(get_persons_mapped_by_distinct_id(team_id, ids).keys())+ # Stays None for person targets, so the loop below picks its lookup off this alone.+ is_group = source.target == _GROUP_TARGET+ group_type_index = source.group_type_index if is_group else None+ if is_group and group_type_index is None:+ return set()++ existing: set[str] = set()+ for start in range(0, len(ids), _EXISTENCE_LOOKUP_CHUNK_SIZE):+ chunk = ids[start : start + _EXISTENCE_LOOKUP_CHUNK_SIZE]+ if group_type_index is not None:+ existing.update(group.group_key for group in get_groups_by_identifiers(team_id, group_type_index, chunk))+ else:+ existing.update(get_persons_mapped_by_distinct_id(team_id, chunk).keys())+ return existingdef _group_type_name(team_id: int, group_type_index: int) -> str | None: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 51b97c2691c9..aaf0905729e1 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@@ -379,6 +379,53 @@ class TestGroupTarget:assert result.produced == 0+class TestExistenceLookupChunking:+ """Both personhog helpers return whole models (properties included) and hold every one before+ returning, so `_filter_existing_ids` must ask in chunks — an unchunked call over a large changed+ set materializes the lot at once and OOM-kills the worker."""++ @parameterized.expand(+ [+ (+ "group",+ PersonPropertySyncSource("s1", "d1", "group_key", {"plan": "tier"}, target="group", group_type_index=0),+ "get_groups_by_identifiers",+ lambda _team_id, _index, chunk: [MagicMock(group_key=key) for key in chunk if key != "ghost"],+ ),+ (+ "person",+ PersonPropertySyncSource("s1", "d1", "distinct_id", {"plan": "tier"}),+ "get_persons_mapped_by_distinct_id",+ lambda _team_id, chunk: {key: MagicMock() for key in chunk if key != "ghost"},+ ),+ ]+ )+ def test_lookup_is_chunked_and_results_are_unioned(self, _name, source, helper, fake):+ ids = [f"e{n}" for n in range(2_500)] + ["ghost"]+ with patch(f"{_MODULE}.{helper}", side_effect=fake) as lookup:+ result = pps._filter_existing_ids(9, source, ids)++ chunks = [call.args[-1] for call in lookup.call_args_list]+ assert [len(chunk) for chunk in chunks] == [1000, 1000, 501]+ assert result == set(ids) - {"ghost"}++ def test_single_call_below_the_chunk_size(self):+ source = PersonPropertySyncSource("s1", "d1", "distinct_id", {"plan": "tier"})+ with patch(f"{_MODULE}.get_persons_mapped_by_distinct_id", return_value={"a": MagicMock()}) as lookup:+ assert pps._filter_existing_ids(9, source, ["a"]) == {"a"}+ lookup.assert_called_once_with(9, ["a"])++ def test_group_source_without_a_type_index_never_looks_up(self):+ source = PersonPropertySyncSource("s1", "d1", "group_key", {"plan": "tier"}, target="group")+ with (+ patch(f"{_MODULE}.get_groups_by_identifiers") as groups,+ patch(f"{_MODULE}.get_persons_mapped_by_distinct_id") as persons,+ ):+ assert pps._filter_existing_ids(9, source, ["acme"]) == set()+ groups.assert_not_called()+ persons.assert_not_called() # must not silently fall through to the person lookup++@pytest.mark.django_dbclass TestStampProvenance:"""`_stamp_provenance` updates existing property definitions with warehouse provenance, folding a