Skip to content

: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.

fix: move hide replay filtering on the backend (#60664)

Christian Raffertydbd0b8e59de6
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 444125b3aa69..f9c0d00b7214 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -35440,6 +35440,11 @@
},
"type": "array"
},
+ "hide_viewed_recordings": {
+ "description": "Exclude recordings already viewed by the current user ('current-user'), by any team member ('any-user'), or none (default). Applied server-side so pagination and the result cursor operate on the filtered set.",
+ "enum": ["current-user", "any-user", null],
+ "type": ["string", "null"]
+ },
"kind": {
"const": "RecordingsQuery",
"type": "string"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index aad45c2dfd67..58ac407e1358 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -606,6 +606,8 @@ export interface RecordingsQuery extends DataNode<RecordingsQueryResponse> {
* */
operand?: FilterLogicalOperator
session_ids?: string[]
+ /** Exclude recordings already viewed by the current user ('current-user'), by any team member ('any-user'), or none (default). Applied server-side so pagination and the result cursor operate on the filtered set. */
+ hide_viewed_recordings?: 'current-user' | 'any-user' | null
/** If provided, this recording will be fetched and prepended to the results, even if it doesn't match the filters */
session_recording_id?: string
person_uuid?: string
diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
index 60d119ee158e..b0333dfbd751 100644
--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
@@ -691,12 +691,15 @@ describe('sessionRecordingsPlaylistLogic', () => {
.toDispatchActions(['loadSessionRecordingsSuccess'])
.toMatchValues({ otherRecordings: [aRecording, bRecording] })
- // mark abc as viewed so it becomes "hidden" when hideViewedRecordings is on
+ // turning on hide-viewed refetches from the server, so mark abc viewed afterwards
+ playerSettingsLogic.actions.setHideViewedRecordings('current-user')
+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess'])
+
+ // mark abc as viewed so it becomes "hidden" — selecting then deselecting leaves it viewed
logic.actions.setSelectedRecordingId('abc')
await expectLogic(logic).toFinishAllListeners()
// deselect so selectedRecordingId exclusion doesn't interfere
logic.actions.setSelectedRecordingId(null)
- playerSettingsLogic.actions.setHideViewedRecordings('current-user')
// abc is now hidden (viewed but not selected)
await expectLogic(logic).toMatchValues({
@@ -711,6 +714,30 @@ describe('sessionRecordingsPlaylistLogic', () => {
})
})
+ it('sends hide_viewed_recordings to the backend when the player setting is set', async () => {
+ playerSettingsLogic.mount()
+ const listSpy = jest.spyOn(api.recordings, 'list')
+
+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess'])
+
+ playerSettingsLogic.actions.setHideViewedRecordings('current-user')
+ await expectLogic(logic).toDispatchActions(['loadSessionRecordings', 'loadSessionRecordingsSuccess'])
+
+ expect(listSpy).toHaveBeenLastCalledWith(
+ expect.objectContaining({ hide_viewed_recordings: 'current-user' })
+ )
+ })
+
+ it('omits hide_viewed_recordings when the player setting is off', async () => {
+ playerSettingsLogic.mount()
+ const listSpy = jest.spyOn(api.recordings, 'list')
+
+ logic.actions.loadSessionRecordings()
+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess'])
+
+ expect(listSpy).toHaveBeenLastCalledWith(expect.objectContaining({ hide_viewed_recordings: undefined }))
+ })
+
it('bulk delete only marks successfully deleted recordings', async () => {
jest.spyOn(api.recordings, 'bulkDeleteRecordings').mockResolvedValue({
success: true,
diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts
index 05a9d4acad4c..ec57d8471337 100644
--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts
+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts
@@ -675,6 +675,9 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic
limit: convertedQuery.limit ?? RECORDINGS_LIMIT,
// If a recording is selected from URL, ensure it's always included in results
session_recording_id: values.selectedRecordingId ?? undefined,
+ // Hide viewed recordings is filtered server-side so pagination operates on the
+ // filtered set; the client-side otherRecordings filter remains as a backstop.
+ hide_viewed_recordings: values.hideViewedRecordings || undefined,
}
if (values.allowEventPropertyExpansion) {
@@ -1172,7 +1175,9 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic
},
setHideViewedRecordings: () => {
- actions.maybeLoadSessionRecordings('older')
+ // Filtering happens server-side, so toggling the filter changes the result set entirely.
+ // Reset and refetch from the first page rather than paginating onto the stale cursor.
+ actions.loadSessionRecordings()
},
handleBulkAddToPlaylist: async ({ short_id }: { short_id: string }) => {
await lemonToast.promise(
diff --git a/posthog/schema.py b/posthog/schema.py
index 2393fba72a11..28033495818e 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -4288,6 +4288,12 @@ class RecordingPropertyFilter(BaseModel):
value: list[str | float | bool] | str | float | bool | None = None
+class HideViewedRecordings(Enum):
+ CURRENT_USER = "current-user"
+ ANY_USER = "any-user"
+ NONE_TYPE_NONE = None
+
+
class RedditAdsDefaultSources(StrEnum):
REDDIT = "reddit"
@@ -23246,6 +23252,14 @@ class RecordingsQuery(BaseModel):
]
| None
) = None
+ hide_viewed_recordings: HideViewedRecordings | None = Field(
+ default=None,
+ description=(
+ "Exclude recordings already viewed by the current user ('current-user'), by"
+ " any team member ('any-user'), or none (default). Applied server-side so"
+ " pagination and the result cursor operate on the filtered set."
+ ),
+ )
kind: Literal["RecordingsQuery"] = "RecordingsQuery"
limit: int | None = None
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
diff --git a/posthog/session_recordings/queries/session_recording_list_from_query.py b/posthog/session_recordings/queries/session_recording_list_from_query.py
index 5068e387046f..7aa85715ea03 100644
--- a/posthog/session_recordings/queries/session_recording_list_from_query.py
+++ b/posthog/session_recordings/queries/session_recording_list_from_query.py
@@ -123,6 +123,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
allow_event_property_expansion: bool = False,
max_execution_time: int | None = None,
extra_having_predicates: list[ast.Expr] | None = None,
+ session_ids_to_exclude: list[str] | None = None,
**_,
):
# TRICKY: we need to make sure we init test account filters only once,
@@ -184,6 +185,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
self._allow_event_property_expansion = allow_event_property_expansion
self._max_execution_time = max_execution_time
self._extra_having_predicates = extra_having_predicates or []
+ self._session_ids_to_exclude = session_ids_to_exclude
@tracer.start_as_current_span("SessionRecordingListFromQuery.run")
def run(self) -> SessionRecordingQueryResult:
@@ -299,6 +301,17 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
)
)
+ # 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.
+ if self._session_ids_to_exclude:
+ exprs.append(
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.NotIn,
+ left=ast.Field(chain=["session_id"]),
+ right=ast.Constant(value=self._session_ids_to_exclude),
+ )
+ )
+
query_date_from = self.query_date_range.date_from()
if query_date_from:
exprs.append(
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.py
index 85ab85eef665..bd2d6b367ec7 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
@@ -4784,3 +4784,80 @@ class TestClickhouseSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseT
self.assertEqual(len(result2.results), 2)
self.assertTrue(result2.has_more_recording)
+
+ def _produce_sessions(self, base_session_id: str, count: int) -> list[str]:
+ session_ids = []
+ for i in range(count):
+ session_id = f"{base_session_id}-{i}"
+ session_ids.append(session_id)
+ produce_replay_summary(
+ session_id=session_id,
+ team_id=self.team.pk,
+ first_timestamp=self.base_time + relativedelta(seconds=i * 10),
+ last_timestamp=self.base_time + relativedelta(seconds=i * 10 + 30),
+ )
+ return session_ids
+
+ def test_session_ids_to_exclude_removes_those_sessions(self):
+ session_ids = self._produce_sessions(f"exclude-{uuid4()}", 3)
+
+ query = RecordingsQuery.model_validate({"limit": 10})
+ result = SessionRecordingListFromQuery(
+ query=query,
+ team=self.team,
+ hogql_query_modifiers=None,
+ session_ids_to_exclude=[session_ids[1]],
+ ).run()
+
+ assert sorted(r["session_id"] for r in result.results) == sorted([session_ids[0], session_ids[2]])
+
+ @parameterized.expand([("empty_list", []), ("none", None)])
+ def test_session_ids_to_exclude_no_op_when_empty(self, _name: str, exclude):
+ session_ids = self._produce_sessions(f"no-exclude-{uuid4()}", 3)
+
+ query = RecordingsQuery.model_validate({"limit": 10})
+ result = SessionRecordingListFromQuery(
+ query=query,
+ team=self.team,
+ hogql_query_modifiers=None,
+ session_ids_to_exclude=exclude,
+ ).run()
+
+ assert sorted(r["session_id"] for r in result.results) == sorted(session_ids)
+
+ def test_session_ids_to_exclude_is_and_combined_with_or_operand(self):
+ # Even with an OR operand the exclusion must always be AND'd, otherwise it could be OR'd away.
+ session_ids = self._produce_sessions(f"exclude-or-{uuid4()}", 2)
+
+ query = RecordingsQuery.model_validate({"limit": 10, "operand": "OR"})
+ instance = SessionRecordingListFromQuery(
+ query=query,
+ team=self.team,
+ hogql_query_modifiers=None,
+ session_ids_to_exclude=[session_ids[0]],
+ )
+ # the printer renders NOT IN as the function form notin(...), and it must sit inside the
+ # top-level and(...) so the OR operand can't cancel the exclusion
+ printed_query = self._print_query(instance.get_query())
+ assert "notin(s.session_id" in printed_query.lower()
+
+ result = instance.run()
+ assert [r["session_id"] for r in result.results] == [session_ids[1]]
+
+ def test_session_ids_to_exclude_paginates_over_filtered_set(self):
+ # Sessions are produced oldest-to-newest; with DESC order the two newest are excluded, so a
+ # page of size 2 must still surface the older unexcluded sessions rather than an empty page.
+ session_ids = self._produce_sessions(f"exclude-page-{uuid4()}", 4)
+ newest_two = session_ids[2:]
+ oldest_two = session_ids[:2]
+
+ query = RecordingsQuery.model_validate({"limit": 2, "order": "start_time", "order_direction": "DESC"})
+ result = SessionRecordingListFromQuery(
+ query=query,
+ team=self.team,
+ hogql_query_modifiers=None,
+ session_ids_to_exclude=newest_two,
+ ).run()
+
+ assert sorted(r["session_id"] for r in result.results) == sorted(oldest_two)
+ assert result.has_more_recording is False
diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.py
index ff09925065d1..3da5e19e206a 100644
--- a/posthog/session_recordings/session_recording_api.py
+++ b/posthog/session_recordings/session_recording_api.py
@@ -46,6 +46,7 @@ from temporalio.service import RPCError, RPCStatusCode
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_random_exponential
from posthog.schema import (
+ HideViewedRecordings,
MatchedRecordingEvent,
MatchingEventsResponse,
ProductIntentContext,
@@ -1988,11 +1989,22 @@ def list_recordings_from_query(
query_for_list = query.model_copy(update=query_updates)
+ # Resolve the "hide viewed recordings" filter into a server-side exclusion set, so pagination
+ # and the cursor operate on the filtered set. Skip when explicit session_ids are requested
+ # (pinned recordings, comment search) since those are intentional and shouldn't be hidden.
+ session_ids_to_exclude: list[str] = []
+ if query_for_list.session_ids is None:
+ with timer("load_viewed_recordings_to_exclude"):
+ session_ids_to_exclude = _viewed_session_ids_to_exclude(
+ query_for_list.hide_viewed_recordings, user, team
+ )
+
query_result = SessionRecordingListFromQuery(
query=query_for_list,
team=team,
hogql_query_modifiers=None,
allow_event_property_expansion=allow_event_property_expansion,
+ session_ids_to_exclude=session_ids_to_exclude,
).run()
ch_session_recordings = query_result.results
@@ -2093,6 +2105,42 @@ def current_user_viewed(recording_ids_in_list: list[str], user: User | None, tea
return viewed_session_recordings
+# The exclusion list is inlined into the ClickHouse query, so an unbounded set (e.g. a large team in
+# 'any-user' mode) could exceed max_query_size and make the query fail or run slowly. Cap it; the
+# client-side filter still hides any viewed recordings beyond the cap.
+MAX_VIEWED_SESSION_IDS_TO_EXCLUDE = 10_000
+
+
+def _viewed_session_ids_to_exclude(
+ hide_viewed_recordings: HideViewedRecordings | None, user: User | None, team: Team
+) -> list[str]:
+ """
+ Resolve the "hide viewed recordings" filter into the set of session_ids to exclude server-side,
+ so pagination and the result cursor operate on the already-filtered set.
+
+ - 'current-user': recordings this user has viewed (empty when there is no user, e.g. Celery callers)
+ - 'any-user': recordings any team member has viewed
+
+ Not bounded by date: SessionRecordingViewed only stores the view time (created_at), which does not
+ correspond to the recording's start_time, so a date bound would exclude/include the wrong rows.
+ Bounded by count: see MAX_VIEWED_SESSION_IDS_TO_EXCLUDE. Ordered by session_id so the truncation
+ is deterministic across paginated requests rather than returning an arbitrary slice each time.
+ """
+ queryset = SessionRecordingViewed.objects.filter(team=team)
+ if hide_viewed_recordings == HideViewedRecordings.CURRENT_USER:
+ if not user:
+ return []
+ queryset = queryset.filter(user=user)
+ elif hide_viewed_recordings != HideViewedRecordings.ANY_USER:
+ return []
+
+ return list(
+ queryset.values_list("session_id", flat=True)
+ .distinct()
+ .order_by("session_id")[:MAX_VIEWED_SESSION_IDS_TO_EXCLUDE]
+ )
+
+
def create_openai_messages(system_content: str, user_content: str) -> list[ChatCompletionMessageParam]:
"""Helper function to create properly typed OpenAI messages."""
return [
diff --git a/posthog/session_recordings/test/test_session_recordings.py b/posthog/session_recordings/test/test_session_recordings.py
index b4d1b7ac9070..606d4f279e12 100644
--- a/posthog/session_recordings/test/test_session_recordings.py
+++ b/posthog/session_recordings/test/test_session_recordings.py
@@ -573,6 +573,82 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
("test_viewed_state_of_session_recording_version-1", True),
]
+ def _result_ids(self, response) -> list[str]:
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ return [r["id"] for r in response.json()["results"]]
+
+ def test_hide_viewed_recordings_current_user_excludes_viewed_server_side(self):
+ base_time = (now() - relativedelta(days=1)).replace(microsecond=0)
+ self.produce_replay_summary("u1", "viewed", base_time)
+ self.produce_replay_summary("u1", "unviewed", base_time + relativedelta(seconds=30))
+ SessionRecordingViewed.objects.create(team=self.team, user=self.user, session_id="viewed")
+
+ without_filter = self.client.get(f"/api/projects/{self.team.id}/session_recordings")
+ assert sorted(self._result_ids(without_filter)) == ["unviewed", "viewed"]
+
+ with_filter = self.client.get(
+ f"/api/projects/{self.team.id}/session_recordings?hide_viewed_recordings=current-user"
+ )
+ assert self._result_ids(with_filter) == ["unviewed"]
+
+ def test_hide_viewed_recordings_any_user_excludes_team_viewed_server_side(self):
+ other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
+ base_time = (now() - relativedelta(days=1)).replace(microsecond=0)
+ self.produce_replay_summary("u1", "viewed-by-other", base_time)
+ self.produce_replay_summary("u1", "unviewed", base_time + relativedelta(seconds=30))
+ SessionRecordingViewed.objects.create(team=self.team, user=other_user, session_id="viewed-by-other")
+
+ # current-user mode keeps it (this user hasn't viewed it)
+ current_user = self.client.get(
+ f"/api/projects/{self.team.id}/session_recordings?hide_viewed_recordings=current-user"
+ )
+ assert sorted(self._result_ids(current_user)) == ["unviewed", "viewed-by-other"]
+
+ # any-user mode excludes it
+ 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"]
+
+ 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)
+ SessionRecordingViewed.objects.create(team=self.team, user=self.user, session_id="viewed")
+
+ # Pinned recordings request explicit session_ids; hide-viewed must not strip them.
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/session_recordings"
+ f'?hide_viewed_recordings=current-user&session_ids=["viewed"]'
+ )
+ assert self._result_ids(response) == ["viewed"]
+
+ def test_hide_viewed_recordings_still_prepends_selected_recording(self):
+ base_time = (now() - relativedelta(days=1)).replace(microsecond=0)
+ self.produce_replay_summary("u1", "viewed", base_time)
+ self.produce_replay_summary("u1", "unviewed", base_time + relativedelta(seconds=30))
+ SessionRecordingViewed.objects.create(team=self.team, user=self.user, session_id="viewed")
+
+ # The explicitly-selected recording is prepended even though it's viewed.
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/session_recordings"
+ f"?hide_viewed_recordings=current-user&session_recording_id=viewed"
+ )
+ assert sorted(self._result_ids(response)) == ["unviewed", "viewed"]
+
+ def test_hide_viewed_recordings_paginates_over_filtered_set(self):
+ # The two newest recordings are viewed; with a page size of 2 and the filter on, the first page
+ # must still surface the older unviewed recordings rather than returning an empty page.
+ base_time = (now() - relativedelta(days=1)).replace(microsecond=0)
+ self.produce_replay_summary("u1", "unviewed-old", base_time)
+ self.produce_replay_summary("u1", "unviewed-mid", base_time + relativedelta(seconds=20))
+ self.produce_replay_summary("u1", "viewed-newer", base_time + relativedelta(seconds=40))
+ self.produce_replay_summary("u1", "viewed-newest", base_time + relativedelta(seconds=60))
+ SessionRecordingViewed.objects.create(team=self.team, user=self.user, session_id="viewed-newer")
+ SessionRecordingViewed.objects.create(team=self.team, user=self.user, session_id="viewed-newest")
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/session_recordings?hide_viewed_recordings=current-user&limit=2"
+ )
+ assert self._result_ids(response) == ["unviewed-mid", "unviewed-old"]
+
def test_setting_viewed_state_of_session_recording(self):
Person.objects.create(
team=self.team,
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 81a79d18c484..3cd56a95b97d 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -18652,6 +18652,14 @@ export namespace Schemas {
results: HeatmapResponseItem[];
}
+ export type HideViewedRecordings = typeof HideViewedRecordings[keyof typeof HideViewedRecordings];
+
+
+ export const HideViewedRecordings = {
+ CurrentUser: 'current-user',
+ AnyUser: 'any-user',
+ } as const;
+
/**
* Variable: {key, type: string|number|boolean, default}.
*/
@@ -20140,6 +20148,8 @@ export namespace Schemas {
events?: RecordingsQueryEvents;
filter_test_accounts?: boolean | null;
having_predicates?: (EventPropertyFilter | PersonPropertyFilter | ElementPropertyFilter | EventMetadataPropertyFilter | SessionPropertyFilter | CohortPropertyFilter | RecordingPropertyFilter | LogEntryPropertyFilter | GroupPropertyFilter | FeaturePropertyFilter | FlagPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter | DataWarehousePropertyFilter | DataWarehousePersonPropertyFilter | ErrorTrackingIssueFilter | LogPropertyFilter | SpanPropertyFilter | RevenueAnalyticsPropertyFilter | WorkflowVariablePropertyFilter)[] | null;
+ /** Exclude recordings already viewed by the current user ('current-user'), by any team member ('any-user'), or none (default). Applied server-side so pagination and the result cursor operate on the filtered set. */
+ hide_viewed_recordings?: HideViewedRecordings | null;
kind?: 'RecordingsQuery';
limit?: number | null;
/** Modifiers used when performing the query */