: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
perf(cohorts): optimize realtime cohort membership diff query (#64696)
Gustavo H. Strassburger20e37b2ff635
diff --git a/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py b/posthog/temporal/messaging/realtime_cohort_calculation_workflow.pyindex b9dee9834294..f0b736c0231c 100644--- a/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py+++ b/posthog/temporal/messaging/realtime_cohort_calculation_workflow.py@@ -273,6 +273,40 @@ def _batch_update_cohort_metrics(cohort_durations: dict[int, int]) -> int:return duration_updates_count+def build_final_query(current_members_sql: str) -> str:+ """Build the membership diff query that compares current cohort matches against stored membership.++ Uses a FULL OUTER JOIN between the current-match subquery and the latest cohort_membership+ state. Only rows where exactly one side is NULL (i.e. the person entered or left) pass+ the WHERE filter; unchanged members are excluded without materialising the 'unchanged' string.++ The returned SQL references the %(team_id)s and %(cohort_id)s bind params; the caller must+ pass both in query_parameters when executing the query.+ """+ return f"""+ SELECT+ COALESCE(current_matches.id, previous_members.person_id) as person_id,+ if(previous_members.person_id IS NULL, 'entered', 'left') as status+ FROM+ (+ {current_members_sql}+ ) AS current_matches+ FULL OUTER JOIN+ (+ SELECT person_id, argMax(status, last_updated) as status+ FROM cohort_membership+ WHERE+ team_id = %(team_id)s+ AND cohort_id = %(cohort_id)s+ GROUP BY person_id+ HAVING status = 'entered'+ ) previous_members ON current_matches.id = previous_members.person_id+ WHERE (previous_members.person_id IS NULL) OR (current_matches.id IS NULL)+ SETTINGS join_use_nulls = 1+ FORMAT JSONEachRow+ """++@temporalio.activity.defnasync def process_realtime_cohort_calculation_activity(inputs: RealtimeCohortCalculationWorkflowInputs) -> None:"""Process a batch of realtime cohorts using HogQLRealtimeCohortQuery."""@@ -361,32 +395,7 @@ async def process_realtime_cohort_calculation_activity(inputs: RealtimeCohortCal"cohort_id": cohort.pk,}- final_query = f"""- SELECT- COALESCE(current_matches.id, previous_members.person_id) as person_id,- CASE- WHEN previous_members.person_id IS NULL THEN 'entered'- WHEN current_matches.id IS NULL THEN 'left'- ELSE 'unchanged'- END as status- FROM- (- {current_members_sql}- ) AS current_matches- FULL OUTER JOIN- (- SELECT team_id, person_id, argMax(status, last_updated) as status- FROM cohort_membership- WHERE- team_id = %(team_id)s- AND cohort_id = %(cohort_id)s- GROUP BY team_id, person_id- HAVING status = 'entered'- ) previous_members ON current_matches.id = previous_members.person_id- WHERE status IN ('entered', 'left')- SETTINGS join_use_nulls = 1- FORMAT JSONEachRow- """+ final_query = build_final_query(current_members_sql)heartbeater.details = (f"Executing query for cohort {idx}/{len(cohorts)} (cohort_id={cohort.pk})",)diff --git a/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py b/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.pyindex ad843bd35823..2feba623bb00 100644--- a/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py+++ b/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py@@ -5,6 +5,7 @@ from unittest.mock import Mock, patchfrom posthog.temporal.messaging.realtime_cohort_calculation_workflow import (_batch_update_cohort_metrics,+ build_final_query,flush_kafka_batch,)from posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator import (@@ -1633,3 +1634,108 @@ class TestBatchUpdateCohortMetrics:# Assert correct countassert duration_updates_count == 1+++class TestFinalQueryMembershipStatuses:+ """Tests for the final_query membership diff logic.++ The query determines 'entered'/'left' via a FULL OUTER JOIN between+ current cohort matches and the previous cohort_membership state.+ These tests verify that status assignment and filtering are correct+ for each membership scenario without requiring a live ClickHouse.+ """++ @pytest.mark.parametrize(+ "rows,expected_statuses",+ [+ # New members only → all 'entered'+ (+ [{"person_id": "aaa", "status": "entered"}, {"person_id": "bbb", "status": "entered"}],+ {"aaa": "entered", "bbb": "entered"},+ ),+ # Departing members only → all 'left'+ (+ [{"person_id": "ccc", "status": "left"}, {"person_id": "ddd", "status": "left"}],+ {"ccc": "left", "ddd": "left"},+ ),+ # Mixed+ (+ [{"person_id": "eee", "status": "entered"}, {"person_id": "fff", "status": "left"}],+ {"eee": "entered", "fff": "left"},+ ),+ # No changes → empty (WHERE clause filters out unchanged rows)+ ([], {}),+ ],+ )+ def test_only_entered_and_left_statuses_are_emitted(self, rows, expected_statuses):+ """The WHERE clause must exclude 'unchanged' rows; only 'entered'/'left' reach the activity loop.++ Note: this test operates on hand-built row dicts, not on query output. An execution-level+ test seeding cohort_membership with entered/left/unchanged persons and asserting the+ unchanged one is dropped would give stronger coverage but requires a ClickHouse harness+ that this suite (which mocks Kafka) does not have. Track separately if desired.+ """+ observed: dict[str, str] = {}++ for row in rows:+ status = row["status"]+ assert status in ("entered", "left"), (+ f"Query should only emit 'entered' or 'left'; got {status!r}. "+ "'unchanged' rows must be filtered out by the WHERE clause."+ )+ observed[row["person_id"]] = status++ assert observed == expected_statuses++ def test_build_final_query_contains_expected_predicates(self):+ """build_final_query must contain the key SQL predicates from the optimized query.++ Asserts that regressions (e.g. reverting to CASE/ELSE or GROUP BY team_id) are caught+ by directly inspecting the produced SQL.+ """+ sql = build_final_query("SELECT id FROM nowhere")++ # Status is computed with if(), not CASE ... ELSE 'unchanged'+ assert "if(previous_members.person_id IS NULL, 'entered', 'left')" in sql+ assert "CASE" not in sql+ assert "'unchanged'" not in sql++ # Unchanged rows are filtered by NULL checks, not a string IN list+ assert "(previous_members.person_id IS NULL) OR (current_matches.id IS NULL)" in sql+ assert "status IN" not in sql++ # cohort_membership subquery groups only by person_id, not team_id+ assert "GROUP BY person_id" in sql+ assert "GROUP BY team_id" not in sql++ # The inner subquery is embedded correctly+ assert "SELECT id FROM nowhere" in sql++ def test_if_expression_matches_full_outer_join_semantics(self):+ """The if() expression and WHERE clause encode the FULL OUTER JOIN membership diff contract.++ - NULL previous_person_id → person is new → 'entered'+ - NULL current_id → person departed → 'left'+ - Both non-NULL → unchanged → excluded by WHERE+ """++ def compute_status(previous_person_id, current_id):+ """Mirrors: if(previous_members.person_id IS NULL, 'entered', 'left')"""+ return "entered" if previous_person_id is None else "left"++ def passes_where(previous_person_id, current_id):+ """Mirrors: WHERE (previous_members.person_id IS NULL) OR (current_matches.id IS NULL)"""+ return (previous_person_id is None) or (current_id is None)++ pid = "person-abc"++ # New member: present in current, absent from previous → WHERE passes, status 'entered'+ assert passes_where(None, pid) is True+ assert compute_status(None, pid) == "entered"++ # Departing member: present in previous, absent from current → WHERE passes, status 'left'+ assert passes_where(pid, None) is True+ assert compute_status(pid, None) == "left"++ # Unchanged member: present in both → WHERE filters it out entirely+ assert passes_where(pid, pid) is Falsediff --git a/products/batch_exports/backend/tests/temporal/backfills/conftest.py b/products/batch_exports/backend/tests/temporal/backfills/conftest.pyindex 64b52c16cffd..765502ff25a2 100644--- a/products/batch_exports/backend/tests/temporal/backfills/conftest.py+++ b/products/batch_exports/backend/tests/temporal/backfills/conftest.py@@ -25,7 +25,7 @@ async def wait_for_workflows(if elapsed > timeout:raise TimeoutError(f"Timed-out waiting for workflows for schedule {schedule_id} to be query-able. "- f"Found {len(workflows)} workflows, expected {expected_count}"+ f"Found {len(workflows)} workflows, expected at least {expected_count}")await asyncio.sleep(delay)@@ -33,7 +33,6 @@ async def wait_for_workflows(delay = min(delay * 2, 5)workflows = [workflow async for workflow in temporal_client.list_workflows(query=query)]- assert len(workflows) == expected_countreturn workflowsdiff --git a/products/batch_exports/backend/tests/temporal/backfills/test_backfill_workflow.py b/products/batch_exports/backend/tests/temporal/backfills/test_backfill_workflow.pyindex 05da387aebc3..aaf099c6c780 100644--- a/products/batch_exports/backend/tests/temporal/backfills/test_backfill_workflow.py+++ b/products/batch_exports/backend/tests/temporal/backfills/test_backfill_workflow.py@@ -300,6 +300,7 @@ async def test_backfill_batch_export_workflow(raise AssertionError("Backfill completed early with no records")workflows = await wait_for_workflows(temporal_client, batch_export.id, expected_num_workflows, timeout=50)+ assert len(workflows) == expected_num_workflows# Check that the individual workflow IDs and TemporalScheduledStartTime search attributes are set correctly.for index, workflow in enumerate(workflows, start=1):@@ -352,6 +353,7 @@ async def test_backfill_batch_export_workflow_no_end_at()workflows = await wait_for_workflows(temporal_client, desc.id, expected_count=2)+ assert len(workflows) == 2event_backfill_ids = await assert_backfill_details_in_workflow_events(temporal_client,