: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): cheaper exposure linkage for pinned and empty lists (#98902)
Marcel Poelker3867ab1127d2
diff --git a/posthog/session_recordings/queries/session_recording_list_from_query.py b/posthog/session_recordings/queries/session_recording_list_from_query.pyindex 5925704bdef2..cf0cdefda751 100644--- a/posthog/session_recordings/queries/session_recording_list_from_query.py+++ b/posthog/session_recordings/queries/session_recording_list_from_query.py@@ -236,6 +236,16 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):@tracer.start_as_current_span("SessionRecordingListFromQuery.run")def run(self) -> SessionRecordingQueryResult:+ # An explicitly empty id set matches nothing, but ClickHouse only finds that out after it+ # has built every subquery and GLOBAL JOIN side the filters ask for, and on precomputing+ # teams the exposure resolution below would first run its synchronous inserts. Neither can+ # change an empty result, so answer here and run nothing. The access check still runs: a+ # viewer the experiment denies gets the same refusal whatever the id set, so the empty+ # answer never tells them the filter was accepted.+ if isinstance(self._query.session_ids, list) and not self._query.session_ids:+ self._check_experiment_exposure_access()+ return SessionRecordingQueryResult(results=[], has_more_recording=False)+# Resolved before query construction: the resolution validates the experiment and can# run preaggregation-job bookkeeping and synchronous ClickHouse inserts, which is run# work, not AST building.@@ -342,21 +352,15 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):]return parsed_query- def _resolve_experiment_exposure(self) -> None:- """Resolve the experiment-exposure linkage once per query instance.-- run() resolves eagerly, but composition callers (to_query(), the replay-vision- candidate query) consume get_query() without run(), so get_query() resolves too;- the cached linkage keeps the resolution from running twice.- """- if self._query.experiment_exposure is None or self._experiment_exposure_linkage is not None:+ def _check_experiment_exposure_access(self) -> None:+ """Refuse the experiment-exposure filter for viewers the experiment denies, and for+ userless callers. Reached by the run() short-circuit too, which answers without ever+ resolving the linkage."""+ if self._query.experiment_exposure is None:return# Deferred: the experiments facade package imports posthog.api on init, which# circles back into this module through the replay-deletion temporal activities.- from products.experiments.backend.facade.replay import ( # noqa: PLC0415- resolve_exposure_linkage,- validate_experiment_exposure_access,- )+ from products.experiments.backend.facade.replay import validate_experiment_exposure_access # noqa: PLC0415try:validate_experiment_exposure_access(self._team, self._user, self._query.experiment_exposure.experiment_id)@@ -364,6 +368,20 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):# Only the /query pipeline renders UserAccessControlError; on the recordings API# it would surface as a 500, so translate to what DRF renders as a 403.raise PermissionDenied(str(error))++ def _resolve_experiment_exposure(self) -> None:+ """Resolve the experiment-exposure linkage once per query instance.++ run() resolves eagerly, but composition callers (to_query(), the replay-vision+ candidate query) consume get_query() without run(), so get_query() resolves too;+ the cached linkage keeps the resolution from running twice.+ """+ if self._query.experiment_exposure is None or self._experiment_exposure_linkage is not None:+ return+ self._check_experiment_exposure_access()+ # Deferred, for the same reason as in _check_experiment_exposure_access.+ from products.experiments.backend.facade.replay import resolve_exposure_linkage # noqa: PLC0415+self._experiment_exposure_linkage = resolve_exposure_linkage(self._team,experiment_id=self._query.experiment_exposure.experiment_id,@@ -398,6 +416,24 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):self._resolve_experiment_exposure()assert self._experiment_exposure_linkage is not None++ # The linkage's default candidate prefilter reads the team's whole distinct-id mapping to+ # find the ids of exposed persons, and on large teams that read is most of the listing's+ # cost. A pinned list can only ever join the distinct ids of the pinned sessions' rows,+ # so those rows nominate the candidates instead. The candidate select reuses the+ # listing's own session-scope predicates, so it always covers every row the join can+ # see, and the linkage still resolves each candidate's latest person over all of its+ # mapping rows. Unpinned lists keep the default: their sessions' distinct ids can cover+ # most of the mapping, and the replay scan then costs more than the mapping read it+ # replaces.+ candidate_distinct_ids: ast.SelectQuery | None = None+ if self._query.session_ids:+ candidate_distinct_ids = ast.SelectQuery(+ select=[ast.Field(chain=["s", "distinct_id"])],+ select_from=ast.JoinExpr(table=ast.Field(chain=["raw_session_replay_events"]), alias="s"),+ where=ast.And(exprs=self._session_scope_predicates()),+ )+join = parsed_query.select_fromassert join is not Nonewhile join.next_join is not None:@@ -406,7 +442,9 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):# GLOBAL: the subquery scans events over the whole experiment window; without it,# every shard of the sharded replay table re-evaluates that scan independently.join_type="GLOBAL INNER JOIN",- table=exposed_distinct_ids_select(self._experiment_exposure_linkage),+ table=exposed_distinct_ids_select(+ self._experiment_exposure_linkage, candidate_distinct_ids=candidate_distinct_ids+ ),alias="exposure",constraint=ast.JoinConstraint(expr=ast.CompareOperation(@@ -484,15 +522,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):elif len(person_subexprs) > 1:exprs.append(ast.Or(exprs=person_subexprs))- # we check for session_ids type not for truthiness since we want to allow empty lists- if isinstance(self._query.session_ids, list):- exprs.append(- ast.CompareOperation(- op=ast.CompareOperationOp.In,- left=ast.Field(chain=["session_id"]),- right=ast.Constant(value=self._query.session_ids),- )- )+ exprs.extend(self._session_scope_predicates())# Exclude already-viewed recordings (the "hide viewed recordings" filter). Unlike session_ids,# an empty list means "exclude nothing", so we only add the predicate when there's something to exclude.@@ -505,45 +535,6 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):))- # the replay-page list opts in so explicitly selected sessions are not hidden by the- # default date range. comment-derived session_ids (see session_recording_api) stay windowed,- # and event/person subqueries still scan within the date range either way.- bypass_date_window = (- self._bypass_date_window_for_session_ids- and isinstance(self._query.session_ids, list)- and len(self._query.session_ids) > 0- and not self._query.comment_text- )- if bypass_date_window:- # bound at the longest retention period (5y) to keep partition pruning- exprs.append(- ast.CompareOperation(- op=ast.CompareOperationOp.GtEq,- left=ast.Field(chain=["s", "min_first_timestamp"]),- right=ast.Constant(value=datetime.now(UTC) - relativedelta(years=5)),- )- )- else:- query_date_from = self.query_date_range.date_from()- if query_date_from:- exprs.append(- ast.CompareOperation(- op=ast.CompareOperationOp.GtEq,- left=ast.Field(chain=["s", "min_first_timestamp"]),- right=ast.Constant(value=query_date_from),- )- )-- query_date_to = self.query_date_range.date_to()- if query_date_to:- exprs.append(- ast.CompareOperation(- op=ast.CompareOperationOp.LtEq,- left=ast.Field(chain=["s", "min_first_timestamp"]),- right=ast.Constant(value=query_date_to),- )- )-optional_exprs: list[ast.Expr] = []# if in PoE mode then we should be pushing person property queries into here@@ -739,9 +730,9 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):# Evidence lives inside the sessions being listed, so scanning outside the query's own# range (with the ±1 day session buffer the console-logs subquery also uses) could only# nominate sessions the date predicates already exclude. Skipped when pinned session_ids- # bypass the date window above: the listing then admits sessions from outside the range,+ # bypass the date window: the listing then admits sessions from outside the range,# so their evidence must stay in scope too.- clamp = not bypass_date_window+ clamp = not self._bypass_date_window()exprs.append(ast.CompareOperation(op=ast.CompareOperationOp.GlobalIn,@@ -764,6 +755,67 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):return ast.And(exprs=exprs)+ def _bypass_date_window(self) -> bool:+ # the replay-page list opts in so explicitly selected sessions are not hidden by the+ # default date range. comment-derived session_ids (see session_recording_api) stay windowed,+ # and event/person subqueries still scan within the date range either way.+ return (+ self._bypass_date_window_for_session_ids+ and isinstance(self._query.session_ids, list)+ and len(self._query.session_ids) > 0+ and not self._query.comment_text+ )++ def _session_scope_predicates(self) -> list[ast.Expr]:+ """The predicates that pick which replay rows are in scope: the pinned session ids and the date bound.++ Shared by the listing's WHERE and the experiment exposure join's candidate select, so the+ candidates can never cover fewer rows than the join sees.+ """+ exprs: list[ast.Expr] = []++ # we check for session_ids type not for truthiness since we want to allow empty lists+ if isinstance(self._query.session_ids, list):+ exprs.append(+ ast.CompareOperation(+ op=ast.CompareOperationOp.In,+ left=ast.Field(chain=["session_id"]),+ right=ast.Constant(value=self._query.session_ids),+ )+ )++ if self._bypass_date_window():+ # bound at the longest retention period (5y) to keep partition pruning+ exprs.append(+ ast.CompareOperation(+ op=ast.CompareOperationOp.GtEq,+ left=ast.Field(chain=["s", "min_first_timestamp"]),+ right=ast.Constant(value=datetime.now(UTC) - relativedelta(years=5)),+ )+ )+ else:+ query_date_from = self.query_date_range.date_from()+ if query_date_from:+ exprs.append(+ ast.CompareOperation(+ op=ast.CompareOperationOp.GtEq,+ left=ast.Field(chain=["s", "min_first_timestamp"]),+ right=ast.Constant(value=query_date_from),+ )+ )++ query_date_to = self.query_date_range.date_to()+ if query_date_to:+ exprs.append(+ ast.CompareOperation(+ op=ast.CompareOperationOp.LtEq,+ left=ast.Field(chain=["s", "min_first_timestamp"]),+ right=ast.Constant(value=query_date_to),+ )+ )++ return exprs+@tracer.start_as_current_span("SessionRecordingListFromQuery._having_predicates")def _having_predicates(self) -> ast.Expr | None:exprs: list[ast.Expr] = [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 91d3d7bda551..180681deb83f 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@@ -247,10 +247,18 @@ class TestSessionRecordingsListByExperimentExposure(ClickhouseTestMixin, APIBaseexpected_sessions,)- def test_links_server_side_exposures_through_the_person(self) -> None:+ @parameterized.expand(+ [+ ("unpinned", None),+ ("pinned", ["session-on-browser"]),+ ]+ )+ def test_links_server_side_exposures_through_the_person(self, _name: str, session_ids: list[str] | None) -> None:# The case the person-scoped linkage exists for: the exposure event is captured# server-side under a backend distinct id and without a usable $session_id, while the- # recording belongs to the same person's browser distinct id.+ # recording belongs to the same person's browser distinct id. A pinned list nominates its+ # candidate distinct ids from the pinned sessions' rows, and must still expand them+ # through the person to the server-side id the exposure was captured under.experiment = self._create_experiment()person = create_person(team=self.team, distinct_ids=["server-side-id", "browser-id"])exposure_time = BASE_TIME + timedelta(hours=2)@@ -263,15 +271,24 @@ class TestSessionRecordingsListByExperimentExposure(ClickhouseTestMixin, APIBase)self._assert_query_matches_session_ids(- {"experiment_exposure": {"experiment_id": experiment.id}},+ {"session_ids": session_ids, "experiment_exposure": {"experiment_id": experiment.id}},["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.+ @parameterized.expand(+ [+ ("unpinned", None),+ ("pinned", ["session-of-exposed", "session-of-reassigned"]),+ ]+ )+ def test_distinct_id_reassigned_away_from_an_exposed_person_stays_excluded(+ self, _name: str, session_ids: list[str] | None+ ) -> None:+ # The linkage narrows its distinct-id scan to candidate ids (the ids that ever mapped to+ # an exposed person, or the pinned sessions' ids), 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"])@@ -289,7 +306,7 @@ class TestSessionRecordingsListByExperimentExposure(ClickhouseTestMixin, APIBase)self._assert_query_matches_session_ids(- {"experiment_exposure": {"experiment_id": experiment.id}},+ {"session_ids": session_ids, "experiment_exposure": {"experiment_id": experiment.id}},["session-of-exposed"],)@@ -792,6 +809,32 @@ class TestSessionRecordingsListByExperimentExposure(ClickhouseTestMixin, APIBaseassert [recording.session_id for recording in result.recordings] == ["session-of-exposed"]+ def test_an_empty_pinned_set_answers_without_reaching_clickhouse(self) -> None:+ # The recordings tab pins an empty id set for an empty metric bucket. The list can only+ # be empty, but ClickHouse would still build the exposure join's GLOBAL side before it+ # finds that out, and a precomputing team would first run the linkage's synchronous+ # precompute inserts.+ self._enable_precomputation()+ experiment = self._create_experiment()++ with (+ patch("products.experiments.backend.replay_linkage.ensure_precomputed") as ensure_mock,+ patch.object(+ HogQLCursorPaginator,+ "execute_hogql_query",+ side_effect=AssertionError("an empty session set reached ClickHouse"),+ ),+ ):+ result = filter_recordings_by(+ team=self.team,+ recordings_filter={"session_ids": [], "experiment_exposure": {"experiment_id": experiment.id}},+ user=self.user,+ )++ assert result.results == []+ assert result.has_more_recording is False+ ensure_mock.assert_not_called()+def test_precomputing_teams_read_exposures_from_the_preaggregated_table(self) -> None:# The default start_date is 34 hours before the frozen now, past the minimum# precompute runtime, so the preaggregated read is the required path here.@@ -982,11 +1025,20 @@ class TestSessionRecordingsListByExperimentExposure(ClickhouseTestMixin, APIBase)return experiment, self._create_user("[email protected]")- def test_denies_viewers_the_experiment_denies(self) -> None:+ @parameterized.expand(+ [+ ("unpinned", None),+ ("empty_pinned_set", []),+ ]+ )+ def test_denies_viewers_the_experiment_denies(self, _name: str, session_ids: list[str] | None) -> None:# The filter reveals which recordings belong to an experiment's exposed persons, so a- # viewer barred from the experiment must not be able to list them.+ # viewer barred from the experiment must not be able to list them. An empty pinned set+ # answers before the linkage resolves, and must refuse the same viewer on that path too.experiment, denied_viewer = self._create_denied_experiment_and_viewer()- query = RecordingsQuery.model_validate({"experiment_exposure": {"experiment_id": experiment.id}})+ query = RecordingsQuery.model_validate(+ {"session_ids": session_ids, "experiment_exposure": {"experiment_id": experiment.id}}+ )with self.assertRaises(PermissionDenied):SessionRecordingListFromQuery(@@ -999,12 +1051,21 @@ class TestSessionRecordingsListByExperimentExposure(ClickhouseTestMixin, APIBase).run()assert result.results == []- def test_refuses_userless_callers(self) -> None:+ @parameterized.expand(+ [+ ("unpinned", None),+ ("empty_pinned_set", []),+ ]+ )+ def test_refuses_userless_callers(self, _name: str, session_ids: list[str] | None) -> None:# Userless background jobs (the playlist counting task, scanner sweeps) cache or surface# their output to viewers this check never evaluated, so the filter fails closed without- # a viewer, regardless of the experiment's access controls.+ # a viewer, regardless of the experiment's access controls, and on the empty-set+ # short-circuit as much as on a full run.experiment = self._create_experiment()- query = RecordingsQuery.model_validate({"experiment_exposure": {"experiment_id": experiment.id}})+ query = RecordingsQuery.model_validate(+ {"session_ids": session_ids, "experiment_exposure": {"experiment_id": experiment.id}}+ )with self.assertRaises(PermissionDenied):SessionRecordingListFromQuery(team=self.team, query=query, hogql_query_modifiers=None, user=None).run()diff --git a/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr b/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambrindex 668511abe097..6cb375c0eef6 100644--- a/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr+++ b/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr@@ -1969,21 +1969,6 @@AND "posthog_exportedasset"."export_context" IS NOT NULL))) subquery'''# ----# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.49- '''- SELECT COUNT(*)- FROM- (SELECT DISTINCT ("posthog_exportedasset"."export_context" -> 'session_recording_id') AS "export_context__session_recording_id"- FROM "posthog_exportedasset"- WHERE (("posthog_exportedasset"."expires_after" >= '2025-01-01 12:00:00+00:00'::timestamptz- OR "posthog_exportedasset"."expires_after" IS NULL)- AND "posthog_exportedasset"."team_id" = 99999- AND "posthog_exportedasset"."export_context" ? 'session_recording_id'- AND NOT (("posthog_exportedasset"."export_context" -> 'session_recording_id') IS NULL)- AND NOT (("posthog_exportedasset"."export_context" -> 'session_recording_id') = '""'::jsonb- AND "posthog_exportedasset"."export_context" IS NOT NULL))) subquery- '''-# ---# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.5'''SELECT "posthog_team"."id",diff --git a/posthog/session_recordings/test/__snapshots__/test_session_recordings.ambr b/posthog/session_recordings/test/__snapshots__/test_session_recordings.ambrindex efee639cea94..703e813f8070 100644--- a/posthog/session_recordings/test/__snapshots__/test_session_recordings.ambr+++ b/posthog/session_recordings/test/__snapshots__/test_session_recordings.ambr@@ -226,19 +226,6 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_get_session_recordings_returns_newest_first.16- '''- SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id",- "posthog_user"."email" AS "user__email"- FROM "posthog_sessionrecordingviewed"- INNER JOIN "posthog_user" ON ("posthog_sessionrecordingviewed"."user_id" = "posthog_user"."id")- WHERE ("posthog_sessionrecordingviewed"."session_id" IN ('new_session',- 'middle_session',- 'old_session')- AND "posthog_sessionrecordingviewed"."team_id" = 99999- AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))- '''-# ---# name: TestSessionRecordings.test_get_session_recordings_returns_newest_first.2'''SELECT "posthog_team"."id",@@ -897,18 +884,6 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_get_session_recordings_scenarios_0_basic_listing.16- '''- SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id",- "posthog_user"."email" AS "user__email"- FROM "posthog_sessionrecordingviewed"- INNER JOIN "posthog_user" ON ("posthog_sessionrecordingviewed"."user_id" = "posthog_user"."id")- WHERE ("posthog_sessionrecordingviewed"."session_id" IN ('session2',- 'session1')- AND "posthog_sessionrecordingviewed"."team_id" = 99999- AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))- '''-# ---# name: TestSessionRecordings.test_get_session_recordings_scenarios_0_basic_listing.2'''SELECT "posthog_team"."id",@@ -1564,17 +1539,6 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_get_session_recordings_scenarios_1_multiple_snapshots.16- '''- SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id",- "posthog_user"."email" AS "user__email"- FROM "posthog_sessionrecordingviewed"- INNER JOIN "posthog_user" ON ("posthog_sessionrecordingviewed"."user_id" = "posthog_user"."id")- WHERE ("posthog_sessionrecordingviewed"."session_id" IN ('session_with_duration')- AND "posthog_sessionrecordingviewed"."team_id" = 99999- AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))- '''-# ---# name: TestSessionRecordings.test_get_session_recordings_scenarios_1_multiple_snapshots.2'''SELECT "posthog_team"."id",@@ -2230,17 +2194,6 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_get_session_recordings_scenarios_2_many_distinct_ids.16- '''- SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id",- "posthog_user"."email" AS "user__email"- FROM "posthog_sessionrecordingviewed"- INNER JOIN "posthog_user" ON ("posthog_sessionrecordingviewed"."user_id" = "posthog_user"."id")- WHERE ("posthog_sessionrecordingviewed"."session_id" IN ('session_many_ids')- AND "posthog_sessionrecordingviewed"."team_id" = 99999- AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))- '''-# ---# name: TestSessionRecordings.test_get_session_recordings_scenarios_2_many_distinct_ids.2'''SELECT "posthog_team"."id",@@ -2899,18 +2852,6 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_get_session_recordings_sorted_0_descending_original_.16- '''- SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id",- "posthog_user"."email" AS "user__email"- FROM "posthog_sessionrecordingviewed"- INNER JOIN "posthog_user" ON ("posthog_sessionrecordingviewed"."user_id" = "posthog_user"."id")- WHERE ("posthog_sessionrecordingviewed"."session_id" IN ('at_base_time_plus_20',- 'at_base_time')- AND "posthog_sessionrecordingviewed"."team_id" = 99999- AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))- '''-# ---# name: TestSessionRecordings.test_get_session_recordings_sorted_0_descending_original_.2'''SELECT "posthog_team"."id",@@ -3569,18 +3510,6 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_get_session_recordings_sorted_1_descending.16- '''- SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id",- "posthog_user"."email" AS "user__email"- FROM "posthog_sessionrecordingviewed"- INNER JOIN "posthog_user" ON ("posthog_sessionrecordingviewed"."user_id" = "posthog_user"."id")- WHERE ("posthog_sessionrecordingviewed"."session_id" IN ('at_base_time_plus_20',- 'at_base_time')- AND "posthog_sessionrecordingviewed"."team_id" = 99999- AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))- '''-# ---# name: TestSessionRecordings.test_get_session_recordings_sorted_1_descending.2'''SELECT "posthog_team"."id",@@ -4239,18 +4168,6 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_get_session_recordings_sorted_2_ascending.16- '''- SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id",- "posthog_user"."email" AS "user__email"- FROM "posthog_sessionrecordingviewed"- INNER JOIN "posthog_user" ON ("posthog_sessionrecordingviewed"."user_id" = "posthog_user"."id")- WHERE ("posthog_sessionrecordingviewed"."session_id" IN ('at_base_time',- 'at_base_time_plus_20')- AND "posthog_sessionrecordingviewed"."team_id" = 99999- AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))- '''-# ---# name: TestSessionRecordings.test_get_session_recordings_sorted_2_ascending.2'''SELECT "posthog_team"."id",@@ -7824,7 +7741,7 @@AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.162+# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.17'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -7877,542 +7794,6 @@WHERE "posthog_organizationmembership"."user_id" = 99999'''# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.163- '''- SELECT "posthog_organizationmembership"."id",- "posthog_organizationmembership"."organization_id",- "posthog_organizationmembership"."user_id",- "posthog_organizationmembership"."level",- "posthog_organizationmembership"."joined_at",- "posthog_organizationmembership"."updated_at",- "posthog_organizationmembership"."invited_by_id",- "posthog_organization"."id",- "posthog_organization"."name",- "posthog_organization"."slug",- "posthog_organization"."logo_media_id",- "posthog_organization"."created_at",- "posthog_organization"."updated_at",- "posthog_organization"."is_active",- "posthog_organization"."is_not_active_reason",- "posthog_organization"."session_cookie_age",- "posthog_organization"."is_member_join_email_enabled",- "posthog_organization"."is_ai_data_processing_approved",- "posthog_organization"."is_ai_training_opted_in",- "posthog_organization"."is_ai_training_locked",- "posthog_organization"."is_ai_training_cta_shown",- "posthog_organization"."enforce_2fa",- "posthog_organization"."enforce_verified_domains",- "posthog_organization"."members_can_invite",- "posthog_organization"."members_can_create_projects",- "posthog_organization"."members_can_use_personal_api_keys",- "posthog_organization"."members_can_see_org_members",- "posthog_organization"."uses_most_specific_access_resolution",- "posthog_organization"."allow_publicly_shared_resources",- "posthog_organization"."read_only_mcp_access",- "posthog_organization"."default_role_id",- "posthog_organization"."plugins_access_level",- "posthog_organization"."for_internal_metrics",- "posthog_organization"."default_experiment_stats_method",- "posthog_organization"."default_anonymize_ips",- "posthog_organization"."is_pending_deletion",- "posthog_organization"."customer_id",- "posthog_organization"."available_product_features",- "posthog_organization"."usage",- "posthog_organization"."never_drop_data",- "posthog_organization"."customer_trust_scores",- "posthog_organization"."has_active_subscription",- "posthog_organization"."setup_section_2_completed",- "posthog_organization"."personalization",- "posthog_organization"."domain_whitelist",- "posthog_organization"."is_platform"- FROM "posthog_organizationmembership"- INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")- WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid- AND "posthog_organizationmembership"."user_id" = 99999)- LIMIT 21- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.164- '''- SELECT "posthog_datawarehousesavedquery"."created_by_id",- "posthog_datawarehousesavedquery"."created_at",- "posthog_datawarehousesavedquery"."updated_at",- "posthog_datawarehousesavedquery"."deleted",- "posthog_datawarehousesavedquery"."deleted_at",- "posthog_datawarehousesavedquery"."id",- "posthog_datawarehousesavedquery"."name",- "posthog_datawarehousesavedquery"."team_id",- "posthog_datawarehousesavedquery"."latest_error",- "posthog_datawarehousesavedquery"."columns",- "posthog_datawarehousesavedquery"."column_order",- "posthog_datawarehousesavedquery"."external_tables",- "posthog_datawarehousesavedquery"."query",- "posthog_datawarehousesavedquery"."status",- "posthog_datawarehousesavedquery"."last_run_at",- "posthog_datawarehousesavedquery"."sync_frequency_interval",- "posthog_datawarehousesavedquery"."table_id",- "posthog_datawarehousesavedquery"."is_materialized",- "posthog_datawarehousesavedquery"."deleted_name",- "posthog_datawarehousesavedquery"."managed_viewset_id",- "posthog_datawarehousesavedquery"."folder_id",- "posthog_datawarehousesavedquery"."origin",- "posthog_datawarehousesavedquery"."is_test",- "posthog_datawarehousesavedquery"."expires_at",- "posthog_datawarehousesavedquery"."semantic_enrichment_hash",- "posthog_datawarehousesavedquery"."incremental_config",- "posthog_datawarehousesavedquery"."incremental_state",- "posthog_user"."id",- "posthog_user"."password",- "posthog_user"."last_login",- "posthog_user"."first_name",- "posthog_user"."last_name",- "posthog_user"."is_staff",- "posthog_user"."date_joined",- "posthog_user"."uuid",- "posthog_user"."current_organization_id",- "posthog_user"."current_team_id",- "posthog_user"."email",- "posthog_user"."pending_email",- "posthog_user"."distinct_id",- "posthog_user"."is_email_verified",- "posthog_user"."credentials_reviewed_at",- "posthog_user"."requested_password_reset_at",- "posthog_user"."requested_2fa_reset_at",- "posthog_user"."has_seen_product_intro_for",- "posthog_user"."strapi_id",- "posthog_user"."is_active",- "posthog_user"."role_at_organization",- "posthog_user"."theme_mode",- "posthog_user"."partial_notification_settings",- "posthog_user"."anonymize_data",- "posthog_user"."allow_impersonation",- "posthog_user"."toolbar_mode",- "posthog_user"."hedgehog_config",- "posthog_user"."allow_sidebar_suggestions",- "posthog_user"."shortcut_position",- "posthog_user"."passkeys_enabled_for_2fa",- "posthog_user"."hide_mcp_hints",- "posthog_user"."ui_configuration",- "posthog_user"."onboarding_skipped_at",- "posthog_user"."onboarding_skipped_reason",- "posthog_user"."onboarding_skipped_organization_id",- "posthog_user"."onboarding_delegated_to_invite_id",- "posthog_user"."onboarding_delegated_to_organization_id",- "posthog_user"."onboarding_delegation_accepted_at",- "posthog_user"."events_column_config",- "posthog_user"."email_opt_in",- "posthog_datawarehousetable"."created_by_id",- "posthog_datawarehousetable"."created_at",- "posthog_datawarehousetable"."updated_at",- "posthog_datawarehousetable"."deleted",- "posthog_datawarehousetable"."deleted_at",- "posthog_datawarehousetable"."id",- "posthog_datawarehousetable"."name",- "posthog_datawarehousetable"."format",- "posthog_datawarehousetable"."team_id",- "posthog_datawarehousetable"."url_pattern",- "posthog_datawarehousetable"."queryable_folder",- "posthog_datawarehousetable"."credential_id",- "posthog_datawarehousetable"."external_data_source_id",- "posthog_datawarehousetable"."created_via",- "posthog_datawarehousetable"."columns",- "posthog_datawarehousetable"."column_order",- "posthog_datawarehousetable"."options",- "posthog_datawarehousetable"."row_count",- "posthog_datawarehousetable"."size_in_s3_mib",- "posthog_datawarehousemanagedviewset"."created_by_id",- "posthog_datawarehousemanagedviewset"."created_at",- "posthog_datawarehousemanagedviewset"."updated_at",- "posthog_datawarehousemanagedviewset"."id",- "posthog_datawarehousemanagedviewset"."team_id",- "posthog_datawarehousemanagedviewset"."kind"- FROM "posthog_datawarehousesavedquery"- LEFT OUTER JOIN "posthog_user" ON ("posthog_datawarehousesavedquery"."created_by_id" = "posthog_user"."id")- LEFT OUTER JOIN "posthog_datawarehousetable" ON ("posthog_datawarehousesavedquery"."table_id" = "posthog_datawarehousetable"."id")- LEFT OUTER JOIN "posthog_datawarehousemanagedviewset" ON ("posthog_datawarehousesavedquery"."managed_viewset_id" = "posthog_datawarehousemanagedviewset"."id")- WHERE ("posthog_datawarehousesavedquery"."team_id" = 99999- AND NOT ("posthog_datawarehousesavedquery"."deleted"- AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL))- ORDER BY "posthog_datawarehousesavedquery"."name" ASC- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.165- '''- SELECT "posthog_datawarehousesavedquery"."created_by_id",- "posthog_datawarehousesavedquery"."created_at",- "posthog_datawarehousesavedquery"."updated_at",- "posthog_datawarehousesavedquery"."deleted",- "posthog_datawarehousesavedquery"."deleted_at",- "posthog_datawarehousesavedquery"."id",- "posthog_datawarehousesavedquery"."name",- "posthog_datawarehousesavedquery"."team_id",- "posthog_datawarehousesavedquery"."latest_error",- "posthog_datawarehousesavedquery"."columns",- "posthog_datawarehousesavedquery"."column_order",- "posthog_datawarehousesavedquery"."external_tables",- "posthog_datawarehousesavedquery"."query",- "posthog_datawarehousesavedquery"."status",- "posthog_datawarehousesavedquery"."last_run_at",- "posthog_datawarehousesavedquery"."sync_frequency_interval",- "posthog_datawarehousesavedquery"."table_id",- "posthog_datawarehousesavedquery"."is_materialized",- "posthog_datawarehousesavedquery"."deleted_name",- "posthog_datawarehousesavedquery"."managed_viewset_id",- "posthog_datawarehousesavedquery"."folder_id",- "posthog_datawarehousesavedquery"."origin",- "posthog_datawarehousesavedquery"."is_test",- "posthog_datawarehousesavedquery"."expires_at",- "posthog_datawarehousesavedquery"."semantic_enrichment_hash",- "posthog_datawarehousesavedquery"."incremental_config",- "posthog_datawarehousesavedquery"."incremental_state",- "posthog_user"."id",- "posthog_user"."password",- "posthog_user"."last_login",- "posthog_user"."first_name",- "posthog_user"."last_name",- "posthog_user"."is_staff",- "posthog_user"."date_joined",- "posthog_user"."uuid",- "posthog_user"."current_organization_id",- "posthog_user"."current_team_id",- "posthog_user"."email",- "posthog_user"."pending_email",- "posthog_user"."distinct_id",- "posthog_user"."is_email_verified",- "posthog_user"."credentials_reviewed_at",- "posthog_user"."requested_password_reset_at",- "posthog_user"."requested_2fa_reset_at",- "posthog_user"."has_seen_product_intro_for",- "posthog_user"."strapi_id",- "posthog_user"."is_active",- "posthog_user"."role_at_organization",- "posthog_user"."theme_mode",- "posthog_user"."partial_notification_settings",- "posthog_user"."anonymize_data",- "posthog_user"."allow_impersonation",- "posthog_user"."toolbar_mode",- "posthog_user"."hedgehog_config",- "posthog_user"."allow_sidebar_suggestions",- "posthog_user"."shortcut_position",- "posthog_user"."passkeys_enabled_for_2fa",- "posthog_user"."hide_mcp_hints",- "posthog_user"."ui_configuration",- "posthog_user"."onboarding_skipped_at",- "posthog_user"."onboarding_skipped_reason",- "posthog_user"."onboarding_skipped_organization_id",- "posthog_user"."onboarding_delegated_to_invite_id",- "posthog_user"."onboarding_delegated_to_organization_id",- "posthog_user"."onboarding_delegation_accepted_at",- "posthog_user"."events_column_config",- "posthog_user"."email_opt_in",- "posthog_datawarehousetable"."created_by_id",- "posthog_datawarehousetable"."created_at",- "posthog_datawarehousetable"."updated_at",- "posthog_datawarehousetable"."deleted",- "posthog_datawarehousetable"."deleted_at",- "posthog_datawarehousetable"."id",- "posthog_datawarehousetable"."name",- "posthog_datawarehousetable"."format",- "posthog_datawarehousetable"."team_id",- "posthog_datawarehousetable"."url_pattern",- "posthog_datawarehousetable"."queryable_folder",- "posthog_datawarehousetable"."credential_id",- "posthog_datawarehousetable"."external_data_source_id",- "posthog_datawarehousetable"."created_via",- "posthog_datawarehousetable"."columns",- "posthog_datawarehousetable"."column_order",- "posthog_datawarehousetable"."options",- "posthog_datawarehousetable"."row_count",- "posthog_datawarehousetable"."size_in_s3_mib"- FROM "posthog_datawarehousesavedquery"- LEFT OUTER JOIN "posthog_user" ON ("posthog_datawarehousesavedquery"."created_by_id" = "posthog_user"."id")- LEFT OUTER JOIN "posthog_datawarehousetable" ON ("posthog_datawarehousesavedquery"."table_id" = "posthog_datawarehousetable"."id")- WHERE ("posthog_datawarehousesavedquery"."team_id" = 99999- AND "posthog_datawarehousesavedquery"."origin" = 'endpoint'- AND NOT ("posthog_datawarehousesavedquery"."deleted"- AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL))- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.166- '''- SELECT "posthog_externaldatasource"."created_by_id",- "posthog_externaldatasource"."created_at",- "posthog_externaldatasource"."updated_at",- "posthog_externaldatasource"."deleted",- "posthog_externaldatasource"."deleted_at",- "posthog_externaldatasource"."id",- "posthog_externaldatasource"."source_id",- "posthog_externaldatasource"."connection_id",- "posthog_externaldatasource"."destination_id",- "posthog_externaldatasource"."team_id",- "posthog_externaldatasource"."sync_frequency",- "posthog_externaldatasource"."status",- "posthog_externaldatasource"."source_type",- "posthog_externaldatasource"."api_version",- "posthog_externaldatasource"."job_inputs",- "posthog_externaldatasource"."connection_metadata",- "posthog_externaldatasource"."are_tables_created",- "posthog_externaldatasource"."prefix",- "posthog_externaldatasource"."description",- "posthog_externaldatasource"."created_via",- "posthog_externaldatasource"."access_method",- "posthog_externaldatasource"."direct_query_enabled",- "posthog_externaldatasource"."auto_sync_new_schemas",- "posthog_externaldatasource"."auto_sync_schema_patterns",- "posthog_externaldatasource"."revenue_analytics_enabled",- "posthog_externaldatasourcerevenueanalyticsconfig"."external_data_source_id",- "posthog_externaldatasourcerevenueanalyticsconfig"."enabled",- "posthog_externaldatasourcerevenueanalyticsconfig"."include_invoiceless_charges"- FROM "posthog_externaldatasource"- LEFT OUTER JOIN "posthog_externaldatasourcerevenueanalyticsconfig" ON ("posthog_externaldatasource"."id" = "posthog_externaldatasourcerevenueanalyticsconfig"."external_data_source_id")- WHERE ("posthog_externaldatasource"."team_id" = 99999- AND NOT ("posthog_externaldatasource"."deleted"- AND "posthog_externaldatasource"."deleted" IS NOT NULL)- AND "posthog_externaldatasource"."source_type" IN ('Stripe'))- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.167- '''- SELECT "posthog_datawarehousetable"."created_by_id",- "posthog_datawarehousetable"."created_at",- "posthog_datawarehousetable"."updated_at",- "posthog_datawarehousetable"."deleted",- "posthog_datawarehousetable"."deleted_at",- "posthog_datawarehousetable"."id",- "posthog_datawarehousetable"."name",- "posthog_datawarehousetable"."format",- "posthog_datawarehousetable"."team_id",- "posthog_datawarehousetable"."url_pattern",- "posthog_datawarehousetable"."queryable_folder",- "posthog_datawarehousetable"."credential_id",- "posthog_datawarehousetable"."external_data_source_id",- "posthog_datawarehousetable"."created_via",- "posthog_datawarehousetable"."columns",- "posthog_datawarehousetable"."column_order",- "posthog_datawarehousetable"."options",- "posthog_datawarehousetable"."row_count",- "posthog_datawarehousetable"."size_in_s3_mib",- "posthog_user"."id",- "posthog_user"."password",- "posthog_user"."last_login",- "posthog_user"."first_name",- "posthog_user"."last_name",- "posthog_user"."is_staff",- "posthog_user"."date_joined",- "posthog_user"."uuid",- "posthog_user"."current_organization_id",- "posthog_user"."current_team_id",- "posthog_user"."email",- "posthog_user"."pending_email",- "posthog_user"."distinct_id",- "posthog_user"."is_email_verified",- "posthog_user"."credentials_reviewed_at",- "posthog_user"."requested_password_reset_at",- "posthog_user"."requested_2fa_reset_at",- "posthog_user"."has_seen_product_intro_for",- "posthog_user"."strapi_id",- "posthog_user"."is_active",- "posthog_user"."role_at_organization",- "posthog_user"."theme_mode",- "posthog_user"."partial_notification_settings",- "posthog_user"."anonymize_data",- "posthog_user"."allow_impersonation",- "posthog_user"."toolbar_mode",- "posthog_user"."hedgehog_config",- "posthog_user"."allow_sidebar_suggestions",- "posthog_user"."shortcut_position",- "posthog_user"."passkeys_enabled_for_2fa",- "posthog_user"."hide_mcp_hints",- "posthog_user"."ui_configuration",- "posthog_user"."onboarding_skipped_at",- "posthog_user"."onboarding_skipped_reason",- "posthog_user"."onboarding_skipped_organization_id",- "posthog_user"."onboarding_delegated_to_invite_id",- "posthog_user"."onboarding_delegated_to_organization_id",- "posthog_user"."onboarding_delegation_accepted_at",- "posthog_user"."events_column_config",- "posthog_user"."email_opt_in"- FROM "posthog_datawarehousetable"- LEFT OUTER JOIN "posthog_externaldatasource" ON ("posthog_datawarehousetable"."external_data_source_id" = "posthog_externaldatasource"."id")- LEFT OUTER JOIN "posthog_user" ON ("posthog_datawarehousetable"."created_by_id" = "posthog_user"."id")- WHERE ("posthog_datawarehousetable"."team_id" = 99999- AND NOT ("posthog_datawarehousetable"."deleted"- AND "posthog_datawarehousetable"."deleted" IS NOT NULL)- AND NOT ("posthog_externaldatasource"."deleted"- AND "posthog_externaldatasource"."deleted" IS NOT NULL)- AND NOT ("posthog_externaldatasource"."access_method" = 'direct'- AND "posthog_externaldatasource"."access_method" IS NOT NULL))- ORDER BY "posthog_datawarehousetable"."created_at" DESC- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.168- '''- SELECT "posthog_datawarehousejoin"."created_by_id",- "posthog_datawarehousejoin"."created_at",- "posthog_datawarehousejoin"."deleted",- "posthog_datawarehousejoin"."deleted_at",- "posthog_datawarehousejoin"."id",- "posthog_datawarehousejoin"."team_id",- "posthog_datawarehousejoin"."source_table_name",- "posthog_datawarehousejoin"."source_table_key",- "posthog_datawarehousejoin"."joining_table_name",- "posthog_datawarehousejoin"."joining_table_key",- "posthog_datawarehousejoin"."field_name",- "posthog_datawarehousejoin"."configuration"- FROM "posthog_datawarehousejoin"- WHERE ("posthog_datawarehousejoin"."team_id" = 99999- AND NOT ("posthog_datawarehousejoin"."deleted"- AND "posthog_datawarehousejoin"."deleted" IS NOT NULL))- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.169- '''- SELECT "data_tools_datawarehouseexpression"."deleted",- "data_tools_datawarehouseexpression"."deleted_at",- "data_tools_datawarehouseexpression"."id",- "data_tools_datawarehouseexpression"."team_id",- "data_tools_datawarehouseexpression"."created_at",- "data_tools_datawarehouseexpression"."created_by_id",- "data_tools_datawarehouseexpression"."table_name",- "data_tools_datawarehouseexpression"."field_name",- "data_tools_datawarehouseexpression"."expression",- "data_tools_datawarehouseexpression"."connection_id"- FROM "data_tools_datawarehouseexpression"- WHERE ("data_tools_datawarehouseexpression"."team_id" = 99999- AND NOT ("data_tools_datawarehouseexpression"."deleted"- AND "data_tools_datawarehouseexpression"."deleted" IS NOT NULL)- AND "data_tools_datawarehouseexpression"."connection_id" IS NULL)- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.17- '''- SELECT "posthog_organizationmembership"."id",- "posthog_organizationmembership"."organization_id",- "posthog_organizationmembership"."user_id",- "posthog_organizationmembership"."level",- "posthog_organizationmembership"."joined_at",- "posthog_organizationmembership"."updated_at",- "posthog_organizationmembership"."invited_by_id",- "posthog_organization"."id",- "posthog_organization"."name",- "posthog_organization"."slug",- "posthog_organization"."logo_media_id",- "posthog_organization"."created_at",- "posthog_organization"."updated_at",- "posthog_organization"."is_active",- "posthog_organization"."is_not_active_reason",- "posthog_organization"."session_cookie_age",- "posthog_organization"."is_member_join_email_enabled",- "posthog_organization"."is_ai_data_processing_approved",- "posthog_organization"."is_ai_training_opted_in",- "posthog_organization"."is_ai_training_locked",- "posthog_organization"."is_ai_training_cta_shown",- "posthog_organization"."enforce_2fa",- "posthog_organization"."enforce_verified_domains",- "posthog_organization"."members_can_invite",- "posthog_organization"."members_can_create_projects",- "posthog_organization"."members_can_use_personal_api_keys",- "posthog_organization"."members_can_see_org_members",- "posthog_organization"."uses_most_specific_access_resolution",- "posthog_organization"."allow_publicly_shared_resources",- "posthog_organization"."read_only_mcp_access",- "posthog_organization"."default_role_id",- "posthog_organization"."plugins_access_level",- "posthog_organization"."for_internal_metrics",- "posthog_organization"."default_experiment_stats_method",- "posthog_organization"."default_anonymize_ips",- "posthog_organization"."is_pending_deletion",- "posthog_organization"."customer_id",- "posthog_organization"."available_product_features",- "posthog_organization"."usage",- "posthog_organization"."never_drop_data",- "posthog_organization"."customer_trust_scores",- "posthog_organization"."has_active_subscription",- "posthog_organization"."setup_section_2_completed",- "posthog_organization"."personalization",- "posthog_organization"."domain_whitelist",- "posthog_organization"."is_platform"- FROM "posthog_organizationmembership"- INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")- WHERE "posthog_organizationmembership"."user_id" = 99999- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.170- '''- SELECT "posthog_sessionrecording"."id",- "posthog_sessionrecording"."session_id",- "posthog_sessionrecording"."team_id",- "posthog_sessionrecording"."created_at",- "posthog_sessionrecording"."deleted",- "posthog_sessionrecording"."object_storage_path",- "posthog_sessionrecording"."full_recording_v2_path",- "posthog_sessionrecording"."distinct_id",- "posthog_sessionrecording"."duration",- "posthog_sessionrecording"."active_seconds",- "posthog_sessionrecording"."inactive_seconds",- "posthog_sessionrecording"."start_time",- "posthog_sessionrecording"."end_time",- "posthog_sessionrecording"."click_count",- "posthog_sessionrecording"."keypress_count",- "posthog_sessionrecording"."mouse_activity_count",- "posthog_sessionrecording"."console_log_count",- "posthog_sessionrecording"."console_warn_count",- "posthog_sessionrecording"."console_error_count",- "posthog_sessionrecording"."start_url",- "posthog_sessionrecording"."storage_version",- "posthog_sessionrecording"."retention_period_days"- FROM "posthog_sessionrecording"- WHERE ("posthog_sessionrecording"."session_id" IN ('1',- '10',- '2',- '3',- '4',- '5',- '6',- '7',- '8',- '9')- AND "posthog_sessionrecording"."team_id" = 99999)- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.171- '''- SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"- FROM "posthog_sessionrecordingviewed"- WHERE ("posthog_sessionrecordingviewed"."team_id" = 99999- AND "posthog_sessionrecordingviewed"."user_id" = 99999- AND "posthog_sessionrecordingviewed"."session_id" IN ('9',- '8',- '7',- '6',- '5',- '4',- '3',- '2',- '10',- '1'))- '''-# ----# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.172- '''- SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id",- "posthog_user"."email" AS "user__email"- FROM "posthog_sessionrecordingviewed"- INNER JOIN "posthog_user" ON ("posthog_sessionrecordingviewed"."user_id" = "posthog_user"."id")- WHERE ("posthog_sessionrecordingviewed"."session_id" IN ('9',- '8',- '7',- '6',- '5',- '4',- '3',- '2',- '10',- '1')- AND "posthog_sessionrecordingviewed"."team_id" = 99999- AND NOT ("posthog_sessionrecordingviewed"."user_id" = 99999))- '''-# ---# name: TestSessionRecordings.test_listing_recordings_is_not_nplus1_for_persons.18'''SELECT "posthog_organizationmembership"."id",diff --git a/products/experiments/backend/replay_linkage.py b/products/experiments/backend/replay_linkage.pyindex 51dc1804d449..f6a9f2ba609a 100644--- a/products/experiments/backend/replay_linkage.py+++ b/products/experiments/backend/replay_linkage.py@@ -485,13 +485,27 @@ def _resolve_exposure_read(team: Team, experiment: Experiment, context: Experime)-def exposed_distinct_ids_select(linkage: ExperimentExposureLinkage) -> ast.SelectQuery:+def exposed_distinct_ids_select(+ linkage: ExperimentExposureLinkage, *, candidate_distinct_ids: ast.SelectQuery | None = None+) -> ast.SelectQuery:"""One row per exposed distinct id: (distinct_id, first_exposure_time).Pure AST construction; :func:`resolve_exposure_linkage` carries the validation and theprecompute decision, so callers can build query ASTs without side effects.++ ``candidate_distinct_ids`` narrows the mapping read to the distinct ids the caller can join+ on. The select must return one ``distinct_id`` column, and it must return a superset of the+ distinct ids the caller joins on: a distinct id it omits is never resolved, so an exposed+ person's session under that id would silently drop out of the result. By default the+ candidates come from the mapping table itself, which is exact for any caller but reads the+ team's whole mapping on every query."""- return _exposed_population_select(linkage, project_attribution=False, variants=list(linkage.requested_variants))+ return _exposed_population_select(+ linkage,+ project_attribution=False,+ variants=list(linkage.requested_variants),+ candidate_distinct_ids=candidate_distinct_ids,+ )def exposed_persons_select(linkage: ExperimentExposureLinkage, *, include_multiple_variant: bool) -> ast.SelectQuery:@@ -512,8 +526,30 @@ def exposed_persons_select(linkage: ExperimentExposureLinkage, *, include_multipreturn _exposed_population_select(linkage, project_attribution=True, variants=variants)+def _distinct_ids_mapped_to_exposed_persons_select(linkage: ExperimentExposureLinkage) -> ast.SelectQuery:+ """The default candidate prefilter: every distinct id that ever mapped to an exposed person.++ Reads the ``exposures`` CTE of the enclosing population select, so it only resolves inside it.+ """+ query = parse_select(+ """+ SELECT distinct_id+ FROM raw_person_distinct_ids+ WHERE team_id = {team_id}+ AND person_id IN (SELECT entity_id FROM exposures)+ """,+ placeholders={"team_id": ast.Constant(value=linkage.context.team.pk)},+ )+ assert isinstance(query, ast.SelectQuery)+ return query++def _exposed_population_select(- linkage: ExperimentExposureLinkage, *, project_attribution: bool, variants: list[str]+ linkage: ExperimentExposureLinkage,+ *,+ project_attribution: bool,+ variants: list[str],+ candidate_distinct_ids: ast.SelectQuery | None = None,) -> ast.SelectQuery:exposure_select = ExposureQueryBuilder(context=linkage.context,@@ -522,15 +558,21 @@ def _exposed_population_select(# 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.+ # OOMs the recordings request on the largest teams. So a prefilter first nominates candidate+ # distinct ids (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.#+ # By default the candidates are the distinct ids that ever mapped to an exposed person. The+ # mapping table is sorted by distinct id, not person id, so that prefilter reads the team's+ # whole mapping on every query. A caller that already knows which distinct ids it joins on+ # passes them as `candidate_distinct_ids`, and the mapping is then read for those ids only.+ if candidate_distinct_ids is None:+ candidate_distinct_ids = _distinct_ids_mapped_to_exposed_persons_select(linkage)+# The WHERE on variant drops entities attributed MULTIPLE_VARIANT_KEY under "exclude"# handling, matching who the analysis counts, unless the caller passed the key back in via# `variants`. Both join sides are pre-grouped, so each distinct id carries exactly one@@ -547,12 +589,7 @@ def _exposed_population_select(argMax(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)- )+ AND distinct_id IN {candidate_distinct_ids}GROUP BY distinct_idHAVING is_deleted = 0) AS pdi@@ -562,7 +599,7 @@ def _exposed_population_select(""",placeholders={"team_id": ast.Constant(value=linkage.context.team.pk),- "prefilter_team_id": ast.Constant(value=linkage.context.team.pk),+ "candidate_distinct_ids": candidate_distinct_ids,"requested_variants": ast.Constant(value=variants),},)@@ -574,10 +611,12 @@ def _exposed_population_select(ast.Alias(alias="person_id", expr=ast.Call(name="any", args=[ast.Field(chain=["pdi", "person_id"])])),ast.Alias(alias="variant", expr=ast.Call(name="any", args=[ast.Field(chain=["exposures", "variant"])])),]- # 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.+ # Both the default 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. With caller-supplied candidates only the join reads it, and the single computation+ # costs the same either way.query.ctes = {"exposures": ast.CTE(name="exposures", expr=exposure_select, cte_type="subquery", materialized=True)}return query