: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(replay): explain why a non-matching recording stays in the list (#76890)
Marcel Poelker044b82243d25
diff --git a/frontend/src/scenes/session-recordings/playlist/Playlist.tsx b/frontend/src/scenes/session-recordings/playlist/Playlist.tsxindex 2a615e714a9b..9216a6ecf678 100644--- a/frontend/src/scenes/session-recordings/playlist/Playlist.tsx+++ b/frontend/src/scenes/session-recordings/playlist/Playlist.tsx@@ -320,9 +320,9 @@ export function Playlist({<LemonTableLoader loading={sessionRecordingsResponseLoading} /></div>{selectedRecordingOutsideFilters && (- <LemonBanner type="info" className="m-2 text-xs">- The selected recording doesn't match the current filters. It's shown because it was- opened from a direct link.+ <LemonBanner type="warning" className="m-2">+ The recording you have open doesn't match the current filters. It stays in the list+ until you close it.</LemonBanner>)}<div className="overflow-y-auto flex-1 min-h-0" onScroll={handleScroll} ref={contentRef}>diff --git a/frontend/src/scenes/session-recordings/playlist/SessionRecordingPreview.tsx b/frontend/src/scenes/session-recordings/playlist/SessionRecordingPreview.tsxindex a0875b8ea562..5817d594abd3 100644--- a/frontend/src/scenes/session-recordings/playlist/SessionRecordingPreview.tsx+++ b/frontend/src/scenes/session-recordings/playlist/SessionRecordingPreview.tsx@@ -13,7 +13,7 @@ import {IconLive,IconPlusSmall,} from '@posthog/icons'-import { LemonButton, Spinner } from '@posthog/lemon-ui'+import { LemonButton, LemonTag, Spinner } from '@posthog/lemon-ui'import { PropertyIcon } from 'lib/components/PropertyIcon/PropertyIcon'import { TZLabel } from 'lib/components/TZLabel'@@ -363,8 +363,15 @@ const SessionRecordingPreviewBase = memo({selectable && <ItemCheckbox recording={recording} />}<div className="grow overflow-hidden flex flex-col gap-y-2 ml-1"><div className="flex items-center justify-between gap-x-0.5">- <div className="flex overflow-hidden font-medium ph-no-capture">+ <div className="flex overflow-hidden items-center gap-x-1 font-medium ph-no-capture"><span className="truncate">{asDisplay(recording.person)}</span>+ {recording.matches_filters === false && (+ <Tooltip title="This recording is listed only because it's open. It doesn't match the current filters.">+ <LemonTag type="warning" size="small" className="shrink-0">+ Doesn't match filters+ </LemonTag>+ </Tooltip>+ )}</div>{playlistTimestampFormat === TimestampFormat.Relative ? (@@ -454,6 +461,9 @@ const SessionRecordingPreviewBase = memo(},(prevProps, nextProps) =>prevProps.recording.id === nextProps.recording.id &&+ // The row renders matches_filters, and the same recording flips in and out of matching+ // as filters change around an open player, so comparing only the id would keep it stale.+ prevProps.recording.matches_filters === nextProps.recording.matches_filters &&prevProps.isActive === nextProps.isActive &&prevProps.selectable === nextProps.selectable &&prevProps.order === nextProps.order@@ -474,6 +484,9 @@ export const SessionRecordingPreview = memo(},(prevProps, nextProps) =>prevProps.recording.id === nextProps.recording.id &&+ // The row renders matches_filters, and the same recording flips in and out of matching+ // as filters change around an open player, so comparing only the id would keep it stale.+ prevProps.recording.matches_filters === nextProps.recording.matches_filters &&prevProps.isActive === nextProps.isActive &&prevProps.selectable === nextProps.selectable &&prevProps.order === nextProps.orderdiff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.pyindex c969aa251f37..16b64d502d9b 100644--- a/posthog/session_recordings/session_recording_api.py+++ b/posthog/session_recordings/session_recording_api.py@@ -2006,6 +2006,12 @@ def _load_recording_if_matches_filters(Check if a specific recording matches the current filters (ignoring pagination).Returns the recording if it matches, None otherwise."""+ # An explicit id set is itself a filter: callers that pass session_ids (pinned recordings,+ # comment search, the experiment recordings tab's session buckets) are asking for that set+ # and nothing else, so an id outside it does not match however well it fits the rest.+ if query.session_ids is not None and session_id not in query.session_ids:+ return None+prepend_check_query = query.model_copy(update={"session_ids": [session_id],@@ -2084,27 +2090,24 @@ def list_recordings_from_query(timer = ServerTimingsGathered()- # If session_recording_id is provided, add it to session_ids to fetch it along with the rest+ # An explicitly requested recording gets the same treatment whatever else the query asks for.+ # Folding it into session_ids instead would load it straight from Postgres by id, which skips+ # both the match check (so it is never flagged) and, for a recording not yet persisted to S3,+ # the guarantee that it comes back at all.if session_recording_id_to_prepend:- if all_session_ids:- all_session_ids = [session_recording_id_to_prepend] + [- sid for sid in all_session_ids if sid != session_recording_id_to_prepend- ]- else:- # We need to fetch this specific recording alongside the filtered results- with timer("load_prepend_recording"):- prepend_recording = _load_recording_if_matches_filters(- session_recording_id_to_prepend,- query,- team,- allow_event_property_expansion,- )- if prepend_recording is None:- # The recording was explicitly requested (e.g. a shared link) but doesn't match- # the current filters - include it anyway so the link still opens it- prepend_recording = _load_selected_recording_ignoring_filters(session_recording_id_to_prepend, team)- if prepend_recording:- recordings.append(prepend_recording)+ with timer("load_prepend_recording"):+ prepend_recording = _load_recording_if_matches_filters(+ session_recording_id_to_prepend,+ query,+ team,+ allow_event_property_expansion,+ )+ if prepend_recording is None:+ # The recording was explicitly requested (e.g. a shared link) but doesn't match+ # the current filters - include it anyway so the link still opens it+ prepend_recording = _load_selected_recording_ignoring_filters(session_recording_id_to_prepend, team)+ if prepend_recording:+ recordings.append(prepend_recording)if all_session_ids:with timer("load_persisted_recordings"), tracer.start_as_current_span("load_persisted_recordings"):@@ -2168,12 +2171,13 @@ def list_recordings_from_query(recordings_from_clickhouse = SessionRecording.get_or_build_from_clickhouse(team, ch_session_recordings)recordings = recordings + recordings_from_clickhouse- # If we have specified session_ids we need to sort them by the order they were specified- if all_session_ids:- recordings = sorted(- recordings,- key=lambda x: cast(list[str], all_session_ids).index(x.session_id),- )+ # If we have specified session_ids we need to sort them by the order they were specified. This sits+ # outside the ClickHouse branch because a request whose ids are all already persisted skips that+ # branch entirely, and it needs the caller's ordering just the same. An explicitly requested+ # recording outside the set sorts first, which is where prepending already put it.+ if all_session_ids:+ ordering = {session_id: index for index, session_id in enumerate(all_session_ids)}+ recordings = sorted(recordings, key=lambda x: ordering.get(x.session_id, -1))# Deduplicate recordings by session_id (if session_recording_id was fetched separately and also in results)if session_recording_id_to_prepend:diff --git a/posthog/session_recordings/test/test_session_recordings.py b/posthog/session_recordings/test/test_session_recordings.pyindex 2c2b3c264b4a..411211b55d9d 100644--- a/posthog/session_recordings/test/test_session_recordings.py+++ b/posthog/session_recordings/test/test_session_recordings.py@@ -1,4 +1,5 @@import os+import jsonfrom datetime import UTC, datetime, timedeltafrom typing import castfrom urllib.parse import urlencode@@ -583,6 +584,26 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)any_user = self.client.get(f"/api/projects/{self.team.id}/session_recordings?hide_viewed_recordings=any-user")assert self._result_ids(any_user) == ["unviewed"]+ @parameterized.expand([("from_clickhouse", False), ("persisted_to_s3", True)])+ def test_session_ids_results_follow_the_requested_order(self, _name: str, persisted: bool):+ base_time = (now() - relativedelta(days=1)).replace(microsecond=0)+ for index, session_id in enumerate(["alpha", "beta", "gamma"]):+ self.produce_replay_summary("user1", session_id, base_time + relativedelta(seconds=index * 10))+ if persisted:+ SessionRecording.objects.create(+ team=self.team, session_id=session_id, full_recording_v2_path=f"s3://bucket/{session_id}"+ )++ # Pinned collections and the experiment tab's session buckets both rely on the response+ # keeping the order they asked for, which is not the list's own recency ordering. Once every+ # requested recording is persisted there is nothing left to look up in ClickHouse, so the+ # ordering has to survive skipping that branch.+ requested = ["gamma", "alpha", "beta"]+ response = self.client.get(+ f"/api/projects/{self.team.id}/session_recordings?session_ids={json.dumps(requested)}"+ )+ assert self._result_ids(response) == requested+def test_hide_viewed_recordings_does_not_apply_to_explicit_session_ids(self):base_time = (now() - relativedelta(days=1)).replace(microsecond=0)self.produce_replay_summary("u1", "viewed", base_time)@@ -2108,6 +2129,38 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest){"recent_session": True}, # must be in results, with expected matches_filters["no_such_session"], # must NOT be in results),+ (+ "recording_outside_supplied_session_ids_is_included_but_flagged",+ # The caller supplies an explicit session_ids set (how the experiment recordings tab+ # sends bucket results) and asks for a recording that isn't in it.+ {+ "recordings": [+ {"session_id": "bucket_session", "days_ago": 1},+ {"session_id": "open_session", "days_ago": 1},+ ],+ "date_from": "-3d",+ "session_ids": ["bucket_session"],+ "session_recording_id": "open_session",+ },+ {"bucket_session": True, "open_session": False},+ [], # must NOT be in results+ ),+ (+ "recording_inside_supplied_session_ids_is_not_flagged",+ # The same shape, except the requested recording is part of the supplied set, so it+ # is a genuine member of the list rather than a retained selection.+ {+ "recordings": [+ {"session_id": "bucket_session", "days_ago": 1},+ {"session_id": "open_session", "days_ago": 1},+ ],+ "date_from": "-3d",+ "session_ids": ["bucket_session", "open_session"],+ "session_recording_id": "open_session",+ },+ {"bucket_session": True, "open_session": True},+ [], # must NOT be in results+ ),])def test_session_recording_id_respects_filters(@@ -2138,6 +2191,8 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)params["limit"] = config["limit"]if "session_recording_id" in config:params["session_recording_id"] = config["session_recording_id"]+ if "session_ids" in config:+ params["session_ids"] = json.dumps(config["session_ids"])params_string = urlencode(params)response = self.client.get(f"/api/projects/{self.team.id}/session_recordings?{params_string}")