: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(experiments): stop the exposure filter aggregating every distinct id (#83421)
Marcel Poelkera0b97b7b9ceb
diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_experiment_exposure.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_experiment_exposure.pyindex 62db55a69e11..9458a3fd95ec 100644--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_experiment_exposure.py+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_experiment_exposure.py@@ -28,7 +28,7 @@ from posthog.session_recordings.queries.test.listing_recordings.test_utils imporfrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom posthog.session_recordings.session_recording_api import list_recordings_from_queryfrom posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL-from posthog.test.persons import create_person+from posthog.test.persons import add_distinct_id, create_personfrom products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResultfrom products.experiments.backend.hogql_queries.experiment_exposure_query_builder import ExposureQueryBuilder@@ -197,6 +197,32 @@ class TestSessionRecordingsListByExperimentExposure(ClickhouseTestMixin, APIBase["session-on-browser"],)+ def test_distinct_id_reassigned_away_from_an_exposed_person_stays_excluded(self) -> None:+ # The linkage narrows its distinct-id scan to ids that ever mapped to an exposed person,+ # then resolves each id's latest mapping over all its version rows. Resolving from only+ # the exposed person's rows instead would resurrect the stale mapping here and leak the+ # reassigned id's sessions into the exposed list.+ experiment = self._create_experiment()+ exposed = create_person(team=self.team, distinct_ids=["exposed-id", "reassigned-id"])+ unexposed = create_person(team=self.team, distinct_ids=["unexposed-id"])+ add_distinct_id(person=unexposed, distinct_id="reassigned-id", version=1)+ exposure_time = BASE_TIME + timedelta(hours=2)+ self._create_exposure_event("exposed-id", exposure_time, "test", person_uuid=str(exposed.uuid))+ flush_persons_and_events()++ session_start = exposure_time + timedelta(hours=1)+ self._produce_recording(+ "exposed-id", "session-of-exposed", session_start, session_start + timedelta(minutes=10)+ )+ self._produce_recording(+ "reassigned-id", "session-of-reassigned", session_start, session_start + timedelta(minutes=10)+ )++ self._assert_query_matches_session_ids(+ {"experiment_exposure": {"experiment_id": experiment.id}},+ ["session-of-exposed"],+ )+def test_excludes_persons_exposed_to_multiple_variants(self) -> None:# Default multiple-variant handling is "exclude": the analysis counts these persons in# no variant, so their sessions must not appear as exposed either.diff --git a/products/experiments/backend/replay_linkage.py b/products/experiments/backend/replay_linkage.pyindex 3585813390ce..e00dce1a9353 100644--- a/products/experiments/backend/replay_linkage.py+++ b/products/experiments/backend/replay_linkage.py@@ -271,6 +271,17 @@ def exposed_distinct_ids_select(linkage: ExperimentExposureLinkage) -> ast.Selecpreaggregation_job_ids=linkage.preaggregation_job_ids,).select_query()+ # The distinct-id expansion must not aggregate the team's whole mapping table: its memory+ # scales with the team's total distinct ids rather than with the exposed population, which+ # OOMs the recordings request on the largest teams. So a prefilter first nominates the+ # distinct ids that ever mapped to an exposed person (a row-level scan, no aggregation+ # state), and argMax then resolves the latest mapping over every version row of those+ # candidates only. Filtering rows by person_id directly instead would resurrect stale+ # mappings: a distinct id reassigned away from an exposed person keeps its old rows, and+ # argMax over just those would report the old person as current. The prefilter is a+ # superset (it ignores variant and reassignment), and the join keeps only candidates whose+ # latest person really is exposed.+ ## The WHERE on variant also drops entities attributed MULTIPLE_VARIANT_KEY under "exclude"# handling, matching who the analysis counts. Both join sides are pre-grouped, so each# distinct id carries exactly one exposure row and min() merely satisfies the GROUP BY.@@ -286,18 +297,29 @@ def exposed_distinct_ids_select(linkage: ExperimentExposureLinkage) -> ast.SelecargMax(is_deleted, version) AS is_deletedFROM raw_person_distinct_idsWHERE team_id = {team_id}+ AND distinct_id IN (+ SELECT distinct_id+ FROM raw_person_distinct_ids+ WHERE team_id = {prefilter_team_id}+ AND person_id IN (SELECT entity_id FROM exposures)+ )GROUP BY distinct_idHAVING is_deleted = 0) AS pdi- INNER JOIN ({exposure_select}) AS exposures ON exposures.entity_id = pdi.person_id+ INNER JOIN exposures ON exposures.entity_id = pdi.person_idWHERE exposures.variant IN {requested_variants}GROUP BY pdi.distinct_id""",placeholders={"team_id": ast.Constant(value=linkage.context.team.pk),- "exposure_select": exposure_select,+ "prefilter_team_id": ast.Constant(value=linkage.context.team.pk),"requested_variants": ast.Constant(value=linkage.requested_variants),},)assert isinstance(query, ast.SelectQuery)+ # Both the prefilter and the join read the exposed population, and ClickHouse substitutes a+ # plain CTE at each reference rather than computing it once, so a bare `WITH` would scan the+ # exposure source twice. MATERIALIZED computes it once and reuses the result, which keeps the+ # live path to a single events scan and holds only the exposed rows in memory.+ query.ctes = {"exposures": ast.CTE(name="exposures", expr=exposure_select, cte_type="subquery", materialized=True)}return query