: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(replay): fix persons page replay filtering (#58372)
Kim Svatos Dugane60da883c1a8
diff --git a/posthog/session_recordings/queries/session_recording_list_from_query.py b/posthog/session_recordings/queries/session_recording_list_from_query.pyindex 8faa3dcd7334..f2c9e64fd2a3 100644--- a/posthog/session_recordings/queries/session_recording_list_from_query.py+++ b/posthog/session_recordings/queries/session_recording_list_from_query.py@@ -263,18 +263,31 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):def _where_predicates(self) -> Union[ast.And, ast.Or]:exprs: list[ast.Expr] = []+ # When both distinct_ids and person_uuid are provided (e.g. person profile+ # replay tab), OR them together so we find:+ # - sessions recorded under the known distinct_ids (covers replay-only+ # sessions with no product analytics events), AND+ # - sessions linked via person_id on the events table through POE (covers+ # anonymous distinct IDs that aren't in person.distinct_ids yet)+ person_subexprs: list[ast.Expr] = []+if self._query.distinct_ids:- exprs.append(+ person_subexprs.append(ast.CompareOperation(op=ast.CompareOperationOp.In,left=ast.Field(chain=["distinct_id"]),right=ast.Constant(value=self._query.distinct_ids),))- else:- person_id_compare_operation = PersonsIdCompareOperation(self._team, self._query).get_operation()- if person_id_compare_operation:- exprs.append(person_id_compare_operation)++ person_id_compare_operation = PersonsIdCompareOperation(self._team, self._query).get_operation()+ if person_id_compare_operation:+ person_subexprs.append(person_id_compare_operation)++ if len(person_subexprs) == 1:+ exprs.append(person_subexprs[0])+ 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 listsif isinstance(self._query.session_ids, list):diff --git a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambrindex c370dd0e4e7b..ecc480b7e3cc 100644--- a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr+++ b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr@@ -8020,6 +8020,55 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordingsListFromQuery_0.test_person_profile_finds_anonymous_distinct_id_sessions+ '''+ SELECT s.session_id AS session_id,+ any(s.team_id) AS `any(s.team_id)`,+ any(s.distinct_id) AS `any(s.distinct_id)`,+ min(toTimeZone(s.min_first_timestamp, 'UTC')) AS start_time,+ max(toTimeZone(s.max_last_timestamp, 'UTC')) AS end_time,+ dateDiff('SECOND', start_time, end_time) AS duration,+ argMinMerge(s.first_url) AS first_url,+ sum(s.click_count) AS click_count,+ sum(s.keypress_count) AS keypress_count,+ sum(s.mouse_activity_count) AS mouse_activity_count,+ divide(sum(s.active_milliseconds), 1000) AS active_seconds,+ minus(duration, active_seconds) AS inactive_seconds,+ sum(s.console_log_count) AS console_log_count,+ sum(s.console_warn_count) AS console_warn_count,+ sum(s.console_error_count) AS console_error_count,+ max(s.retention_period_days) AS retention_period_days,+ plus(dateTrunc('DAY', start_time), toIntervalDay(coalesce(retention_period_days, 30))) AS expiry_time,+ dateDiff('DAY', toDateTime64('today', 6, 'UTC'), expiry_time) AS recording_ttl,+ greaterOrEquals(max(toTimeZone(s._timestamp, 'UTC')), toDateTime64('today', 6, 'UTC')) AS ongoing,+ round(multiply(divide(plus(plus(plus(divide(sum(s.active_milliseconds), 1000), sum(s.click_count)), sum(s.keypress_count)), sum(s.console_error_count)), plus(plus(plus(plus(sum(s.mouse_activity_count), dateDiff('SECOND', start_time, end_time)), sum(s.console_error_count)), sum(s.console_log_count)), sum(s.console_warn_count))), 100), 2) AS activity_score+ FROM session_replay_events AS s+ WHERE and(equals(s.team_id, 99999), or(in(s.distinct_id, ['identified-user']), globalIn(s.session_id,+ (SELECT DISTINCT events.`$session_id` AS `$session_id`+ FROM events+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 99999), ifNull(equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), '00000000-0000-0000-0000-000000000000'), 0), lessOrEquals(events.timestamp, toDateTime64(toDateTime64('today', 6, 'UTC'), 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), notEmpty(events.`$session_id`))))), greaterOrEquals(s.min_first_timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')))+ GROUP BY s.session_id+ HAVING and(ifNull(greaterOrEquals(expiry_time, toDateTime64('today', 6, 'UTC')), 0), ifNull(equals(max(s.is_deleted), 0), 0))+ ORDER BY start_time DESC,+ s.session_id DESC+ LIMIT 51 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordingsListFromQuery_0.test_recording_property_in_properties_is_routed_to_having_predicates'''SELECT s.session_id AS session_id,@@ -15437,6 +15486,55 @@use_hive_partitioning=0'''# ---+# name: TestSessionRecordingsListFromQuery_1.test_person_profile_finds_anonymous_distinct_id_sessions+ '''+ SELECT s.session_id AS session_id,+ any(s.team_id) AS `any(s.team_id)`,+ any(s.distinct_id) AS `any(s.distinct_id)`,+ min(toTimeZone(s.min_first_timestamp, 'UTC')) AS start_time,+ max(toTimeZone(s.max_last_timestamp, 'UTC')) AS end_time,+ dateDiff('SECOND', start_time, end_time) AS duration,+ argMinMerge(s.first_url) AS first_url,+ sum(s.click_count) AS click_count,+ sum(s.keypress_count) AS keypress_count,+ sum(s.mouse_activity_count) AS mouse_activity_count,+ divide(sum(s.active_milliseconds), 1000) AS active_seconds,+ minus(duration, active_seconds) AS inactive_seconds,+ sum(s.console_log_count) AS console_log_count,+ sum(s.console_warn_count) AS console_warn_count,+ sum(s.console_error_count) AS console_error_count,+ max(s.retention_period_days) AS retention_period_days,+ plus(dateTrunc('DAY', start_time), toIntervalDay(coalesce(retention_period_days, 30))) AS expiry_time,+ dateDiff('DAY', toDateTime64('today', 6, 'UTC'), expiry_time) AS recording_ttl,+ greaterOrEquals(max(toTimeZone(s._timestamp, 'UTC')), toDateTime64('today', 6, 'UTC')) AS ongoing,+ round(multiply(divide(plus(plus(plus(divide(sum(s.active_milliseconds), 1000), sum(s.click_count)), sum(s.keypress_count)), sum(s.console_error_count)), plus(plus(plus(plus(sum(s.mouse_activity_count), dateDiff('SECOND', start_time, end_time)), sum(s.console_error_count)), sum(s.console_log_count)), sum(s.console_warn_count))), 100), 2) AS activity_score+ FROM session_replay_events AS s+ WHERE and(equals(s.team_id, 99999), or(in(s.distinct_id, ['identified-user']), globalIn(s.session_id,+ (SELECT DISTINCT events.`$session_id` AS `$session_id`+ FROM events+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ WHERE and(equals(events.team_id, 99999), ifNull(equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), '00000000-0000-0000-0000-000000000000'), 0), lessOrEquals(events.timestamp, toDateTime64(toDateTime64('today', 6, 'UTC'), 6, 'UTC')), greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(events.timestamp, toDateTime64('today', 6, 'UTC')), notEmpty(events.`$session_id`))))), greaterOrEquals(s.min_first_timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')))+ GROUP BY s.session_id+ HAVING and(ifNull(greaterOrEquals(expiry_time, toDateTime64('today', 6, 'UTC')), 0), ifNull(equals(max(s.is_deleted), 0), 0))+ ORDER BY start_time DESC,+ s.session_id DESC+ LIMIT 51 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---# name: TestSessionRecordingsListFromQuery_1.test_recording_property_in_properties_is_routed_to_having_predicates'''SELECT s.session_id AS session_id,diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.pyindex 15096b855b32..b5bd9933b9f6 100644--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py@@ -4120,6 +4120,59 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):# Test filteringself._assert_query_matches_session_ids(query={"distinct_ids": distinct_ids}, expected=expected)+ @snapshot_clickhouse_queries+ def test_person_profile_finds_anonymous_distinct_id_sessions(self):+ """+ Regression test: the person profile replay tab sends both distinct_ids+ (from person.distinct_ids) and person_uuid. Before the fix, distinct_ids+ took priority and sessions recorded under an anonymous distinct_id that+ wasn't in person.distinct_ids were missed. With the OR fix, both paths+ are used so the anonymous session is found via the POE person_id lookup.+ """+ identified_id = "identified-user"+ anonymous_id = "anon-uuid-123"++ person = Person.objects.create(team=self.team, distinct_ids=[identified_id, anonymous_id])++ identified_session = f"identified-session-{uuid4()}"+ anonymous_session = f"anonymous-session-{uuid4()}"++ # session recorded under the identified distinct_id+ produce_replay_summary(+ distinct_id=identified_id,+ session_id=identified_session,+ first_timestamp=self.an_hour_ago,+ team_id=self.team.pk,+ )++ # session recorded under the anonymous distinct_id+ produce_replay_summary(+ distinct_id=anonymous_id,+ session_id=anonymous_session,+ first_timestamp=self.an_hour_ago,+ team_id=self.team.pk,+ )++ # an event linking the anonymous distinct_id to the person (for POE)+ create_event(+ distinct_id=anonymous_id,+ timestamp=self.an_hour_ago,+ team=self.team,+ event_name="$pageview",+ properties={"$session_id": anonymous_session, "$window_id": "1"},+ )++ # simulate the person profile replay tab: sends only the identified+ # distinct_id (as if the anonymous one isn't in person.distinct_ids)+ # plus the person_uuid+ self._assert_query_matches_session_ids(+ query={+ "distinct_ids": [identified_id],+ "person_uuid": str(person.uuid),+ },+ expected=[identified_session, anonymous_session],+ )+@also_test_with_materialized_columns(person_properties=["email"], verify_no_jsonextract=False)@freeze_time("2021-01-21T20:00:00.000Z")@snapshot_clickhouse_queries