: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
feat(data-warehouse): derive stable event id per row per job in cdp producer (#62419)
Tom Owersa5266858d507
diff --git a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.test.tsindex 9605b33dedcb..39f5045b7247 100644--- a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.test.ts@@ -24,6 +24,7 @@ describe('CdpDatawarehouseEventsConsumer', () => {const createDataWarehouseEvent = (teamId: number, properties: Record<string, any> = {}): CdpDataWarehouseEvent => {return {team_id: teamId,+ event_id: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',properties: {column1: 'value1',column2: 123,@@ -103,8 +104,8 @@ describe('CdpDatawarehouseEventsConsumer', () => {column2: 123,test_prop: 'test_value',})- expect(invocations[0].event.uuid).toBe('data-warehouse-table-uuid-do-not-use')- expect(invocations[0].event.event).toBe('data-warehouse-table-event-do-not-use')+ expect(invocations[0].event.uuid).toBe('aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee')+ expect(invocations[0].event.event).toBe('$warehouse_source_row')})it('should not parse events for teams without hog functions or flows', async () => {diff --git a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.tsindex eda20cedb8c7..82ff80987367 100644--- a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts@@ -150,8 +150,8 @@ function convertDataWarehouseEventToHogFunctionInvocationGlobals(url: projectUrl,},event: {- uuid: 'data-warehouse-table-uuid-do-not-use',- event: 'data-warehouse-table-event-do-not-use',+ uuid: event.event_id,+ event: '$warehouse_source_row',elements_chain: '', // Not applicable but left here for compatibilitydistinct_id: 'data-warehouse-table-distinct-id-do-not-use',properties: data,diff --git a/nodejs/src/cdp/schema.ts b/nodejs/src/cdp/schema.tsindex 961f330b93da..3f15237a7b77 100644--- a/nodejs/src/cdp/schema.ts+++ b/nodejs/src/cdp/schema.ts@@ -28,6 +28,8 @@ export type CdpInternalEvent = z.infer<typeof CdpInternalEventSchema>export const CdpDataWarehouseEventSchema = z.object({team_id: z.number(),+ // Deterministic id, unique per row per external data job run (see CDPProducer._build_event_id)+ event_id: z.string(),properties: z.record(z.string(), z.any()),})diff --git a/posthog/temporal/data_imports/pipelines/pipeline/cdp_producer.py b/posthog/temporal/data_imports/pipelines/pipeline/cdp_producer.pyindex d8581013c157..74409ff533ed 100644--- a/posthog/temporal/data_imports/pipelines/pipeline/cdp_producer.py+++ b/posthog/temporal/data_imports/pipelines/pipeline/cdp_producer.py@@ -1,5 +1,7 @@import json+import uuidimport asyncio+import hashlibfrom django.conf import settings@@ -67,19 +69,29 @@ class CDPProducer:except FileNotFoundError:return []- def _serialize_json(self, record: object) -> bytes:+ def _serialize_json(self, record: object, *, sort_keys: bool = False) -> bytes:try:- return orjson.dumps(record)+ return orjson.dumps(record, option=orjson.OPT_SORT_KEYS if sort_keys else None)except TypeError:try:- return json.dumps(record).encode("utf-8")+ return json.dumps(record, sort_keys=sort_keys).encode("utf-8")except Exception as e:if isinstance(record, dict):record = {str(k): str(v) for k, v in record.items()}- return json.dumps(record).encode("utf-8")+ return json.dumps(record, sort_keys=sort_keys).encode("utf-8")raise ValueError("Could not serialize record to JSON") from e+ def _build_event_id(self, row: object) -> str:+ """Build a deterministic event id that is unique per row per job.++ The row is hashed (sorted keys so re-runs of the same job produce the same hash)+ and combined with the job id, so the id is stable for the same row + job but+ changes whenever the row's data changes.+ """+ row_hash = hashlib.sha256(self._serialize_json(row, sort_keys=True)).hexdigest()+ return str(uuid.uuid5(uuid.NAMESPACE_OID, f"{self.job_id}:{row_hash}"))+async def should_produce_table(self) -> bool:if self._should_produce_cache is not None:return self._should_produce_cache@@ -152,7 +164,11 @@ class CDPProducer:for batch in pf.iter_batches(batch_size=10_000):for row in batch.to_pylist():- row_as_props = {"team_id": self.team_id, "properties": row}+ row_as_props = {+ "team_id": self.team_id,+ "event_id": self._build_event_id(row),+ "properties": row,+ }await kafka_producer.produce(topic=KAFKA_DWH_CDP_RAW_TABLE,data=row_as_props,diff --git a/posthog/temporal/data_imports/pipelines/pipeline/test/test_cdp_producer.py b/posthog/temporal/data_imports/pipelines/pipeline/test/test_cdp_producer.pyindex 9b87cdb38250..7e27e9ab537f 100644--- a/posthog/temporal/data_imports/pipelines/pipeline/test/test_cdp_producer.py+++ b/posthog/temporal/data_imports/pipelines/pipeline/test/test_cdp_producer.py@@ -1,4 +1,5 @@import json+import uuidfrom contextlib import asynccontextmanagerfrom io import BytesIO@@ -244,6 +245,13 @@ async def test_produce_to_kafka_from_s3_success(mock_get_s3_client, team):assert "properties" in first_call_kwargs["data"]assert "id" in first_call_kwargs["data"]["properties"]+ # Each row carries a deterministic event id (valid UUID, stable per distinct row).+ # Both chunks contain the same 3 rows, so we expect 3 unique ids repeated across the 6 messages.+ event_ids = [call[1]["data"]["event_id"] for call in mock_kafka_producer.produce.call_args_list]+ assert all(uuid.UUID(event_id) for event_id in event_ids)+ assert len(set(event_ids)) == 3+ assert event_ids[:3] == event_ids[3:]+@pytest.mark.django_db(transaction=True)@pytest.mark.asyncio@@ -671,3 +679,42 @@ async def test_serialize_json_raises_on_non_dict_unsupported(team):mock_orjson.side_effect = TypeError("Cannot serialize")with pytest.raises(ValueError, match="Could not serialize record to JSON"):producer._serialize_json(record)+++def _make_producer(job_id: str) -> CDPProducer:+ return CDPProducer(team_id=1, schema_id="schema_1", job_id=job_id, logger=mock.AsyncMock())+++def test_build_event_id_is_a_valid_uuid():+ event_id = _make_producer("job_1")._build_event_id({"id": 1, "name": "Alice"})+ assert str(uuid.UUID(event_id)) == event_id+++def test_build_event_id_is_stable_for_same_row_and_job():+ producer = _make_producer("job_1")+ row = {"id": 1, "name": "Alice"}+ assert producer._build_event_id(row) == producer._build_event_id(dict(row))+++def test_build_event_id_is_independent_of_key_order():+ producer = _make_producer("job_1")+ assert producer._build_event_id({"id": 1, "name": "Alice"}) == producer._build_event_id({"name": "Alice", "id": 1})+++ "row_a,row_b",+ [+ ({"id": 1, "name": "Alice"}, {"id": 1, "name": "Bob"}),+ ({"id": 1, "name": "Alice"}, {"id": 2, "name": "Alice"}),+ ({"id": 1}, {"id": 1, "name": "Alice"}),+ ({"value": 1}, {"value": "1"}),+ ],+)+def test_build_event_id_changes_when_row_data_changes(row_a, row_b):+ producer = _make_producer("job_1")+ assert producer._build_event_id(row_a) != producer._build_event_id(row_b)+++def test_build_event_id_changes_with_job_id():+ row = {"id": 1, "name": "Alice"}+ assert _make_producer("job_1")._build_event_id(row) != _make_producer("job_2")._build_event_id(row)diff --git a/posthog/temporal/tests/data_imports/test_end_to_end.py b/posthog/temporal/tests/data_imports/test_end_to_end.pyindex 5fe85de88006..d54dc79939cc 100644--- a/posthog/temporal/tests/data_imports/test_end_to_end.py+++ b/posthog/temporal/tests/data_imports/test_end_to_end.py@@ -3536,7 +3536,11 @@ async def test_cdp_producer_push_to_kafka(team, stripe_customer, mock_stripe_cliif pipeline_mode == "non_dlt":expected_properties["_ph_partition_key"] = "2023-w14"- assert call_kwargs["data"] == {+ # The producer derives a deterministic event id per row per job. Its value depends on the+ # dynamic job id, so assert it is a valid UUID and compare the rest of the payload.+ data = call_kwargs["data"]+ assert str(uuid.UUID(data["event_id"])) == data["event_id"]+ assert {key: value for key, value in data.items() if key != "event_id"} == {"team_id": team.id,"properties": expected_properties,}