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(replay): respect funnel drop-off context when viewing recordings (#62971)

Arno Hillen9edd07647ec2
diff --git a/frontend/src/scenes/session-recordings/playlist/Playlist.test.tsx b/frontend/src/scenes/session-recordings/playlist/Playlist.test.tsx
new file mode 100644
index 000000000000..c164280c8c96
--- /dev/null
+++ b/frontend/src/scenes/session-recordings/playlist/Playlist.test.tsx
@@ -0,0 +1,92 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { BindLogic, Provider } from 'kea'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { Playlist } from './Playlist'
+import { sessionRecordingsPlaylistLogic } from './sessionRecordingsPlaylistLogic'
+
+jest.mock('scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed', () => ({
+ RecordingsUniversalFiltersEmbedButton: () => <div data-attr="mock-filters-embed-button" />,
+}))
+
+jest.mock('scenes/notebooks/AddToNotebook/DraggableToNotebook', () => ({
+ DraggableToNotebook: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+}))
+
+jest.mock('scenes/session-recordings/playlist/SessionRecordingsPlaylistSettings', () => ({
+ SessionRecordingsPlaylistTopSettings: () => <div data-attr="mock-top-settings" />,
+}))
+
+jest.mock('scenes/session-recordings/playlist/SessionRecordingPreview', () => ({
+ SessionRecordingPreview: () => <div data-attr="mock-recording-preview" />,
+}))
+
+jest.mock('./SessionRecordingsPlaylistTroubleshooting', () => ({
+ SessionRecordingsPlaylistTroubleshooting: () => <div data-attr="mock-troubleshooting" />,
+}))
+
+describe('Playlist', () => {
+ let logic: ReturnType<typeof sessionRecordingsPlaylistLogic.build>
+
+ const logicProps = { logicKey: 'playlist-component-test', updateSearchParams: false }
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/environments/:team_id/session_recordings': { results: [], has_next: false },
+ '/api/environments/:team_id/session_recordings/properties': { results: [] },
+ },
+ })
+ initKeaTests()
+ logic = sessionRecordingsPlaylistLogic(logicProps)
+ logic.mount()
+ })
+
+ afterEach(() => {
+ cleanup()
+ logic.unmount()
+ localStorage.clear()
+ })
+
+ function renderPlaylist(): ReturnType<typeof render> {
+ return render(
+ <Provider>
+ <BindLogic logic={sessionRecordingsPlaylistLogic} props={logicProps}>
+ <Playlist />
+ </BindLogic>
+ </Provider>
+ )
+ }
+
+ it('does not show the selected sessions banner when no session_ids filter is set', () => {
+ renderPlaylist()
+
+ expect(screen.queryByText(/Only showing/)).not.toBeInTheDocument()
+ expect(screen.queryByText('Show all recordings')).not.toBeInTheDocument()
+ })
+
+ it('shows the selected sessions banner and clears session_ids via "Show all recordings"', async () => {
+ logic.actions.setFilters({ session_ids: ['s1', 's2'] })
+
+ renderPlaylist()
+
+ expect(screen.getByText('Only showing 2 selected recordings')).toBeInTheDocument()
+
+ await waitFor(() => {
+ expect(logic.values.sessionRecordingsResponseLoading).toBe(false)
+ })
+
+ // LemonBanner renders the action twice (wide and narrow responsive variants)
+ userEvent.click(screen.getAllByRole('button', { name: 'Show all recordings' })[0])
+
+ await waitFor(() => {
+ expect(logic.values.filters.session_ids).toBeUndefined()
+ })
+ expect(screen.queryByText(/Only showing/)).not.toBeInTheDocument()
+ })
+})
diff --git a/frontend/src/scenes/session-recordings/playlist/Playlist.tsx b/frontend/src/scenes/session-recordings/playlist/Playlist.tsx
index 5776f8bdb49f..142f62761bca 100644
--- a/frontend/src/scenes/session-recordings/playlist/Playlist.tsx
+++ b/frontend/src/scenes/session-recordings/playlist/Playlist.tsx
@@ -19,7 +19,7 @@ import {
import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'
import { useResizeBreakpoints } from 'lib/hooks/useResizeObserver'
import { LemonTableLoader } from 'lib/lemon-ui/LemonTable/LemonTableLoader'
-import { range } from 'lib/utils'
+import { pluralize, range } from 'lib/utils'
import { DraggableToNotebook } from 'scenes/notebooks/AddToNotebook/DraggableToNotebook'
import { useNotebookNode } from 'scenes/notebooks/Nodes/NotebookNodeContext'
import { RecordingsUniversalFiltersEmbedButton } from 'scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed'
@@ -259,6 +259,19 @@ export function Playlist({
</DraggableToNotebook>
</div>
)}
+ {!!filters?.session_ids?.length && (
+ <LemonBanner
+ type="info"
+ className="mb-2"
+ action={{
+ children: 'Show all recordings',
+ onClick: () => setFilters({ session_ids: undefined }),
+ loading: !!sessionRecordingsResponseLoading,
+ }}
+ >
+ Only showing {pluralize(filters.session_ids.length, 'selected recording')}
+ </LemonBanner>
+ )}
<div
ref={playlistRef}
data-attr="session-recordings-playlist"
diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
index 31f31c4e5889..07645c4dbe09 100644
--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
@@ -130,7 +130,7 @@ describe('sessionRecordingsPlaylistLogic', () => {
]
} else if (
(searchParams.get('having_predicates')?.length || 0) > 0 &&
- JSON.parse(searchParams.get('having_predicates') || '[]')[0]['value'] === 600
+ JSON.parse(searchParams.get('having_predicates') || '[]')[0]?.['value'] === 600
) {
return [
200,
@@ -716,6 +716,67 @@ describe('sessionRecordingsPlaylistLogic', () => {
})
})
+ describe('session_ids filter', () => {
+ const emptyFilterGroup = {
+ type: FilterLogicalOperator.And,
+ values: [{ type: FilterLogicalOperator.And, values: [] }],
+ }
+
+ it('reads session_ids from the URL, layers them over defaults and passes them to the query', async () => {
+ const listSpy = jest.spyOn(api.recordings, 'list')
+
+ router.actions.push('/replay/home', {
+ filters: {
+ session_ids: ['s1', 's2'],
+ date_from: '-7d',
+ filter_group: emptyFilterGroup,
+ duration: [],
+ },
+ })
+
+ await expectLogic(logic)
+ .toDispatchActions(['setFilters', 'loadSessionRecordings', 'loadSessionRecordingsSuccess'])
+ .toMatchValues({
+ filters: expect.objectContaining({
+ session_ids: ['s1', 's2'],
+ date_from: '-7d',
+ }),
+ })
+
+ expect(convertUniversalFiltersToRecordingsQuery(logic.values.filters)).toEqual(
+ expect.objectContaining({ session_ids: ['s1', 's2'] })
+ )
+ expect(listSpy).toHaveBeenLastCalledWith(
+ expect.objectContaining({ session_ids: ['s1', 's2'], date_from: '-7d' })
+ )
+ })
+
+ it('clears session_ids via setFilters and reloads the list', async () => {
+ router.actions.push('/replay/home', {
+ filters: {
+ session_ids: ['s1', 's2'],
+ date_from: '-7d',
+ filter_group: emptyFilterGroup,
+ duration: [],
+ },
+ })
+ await expectLogic(logic)
+ .toDispatchActions(['setFilters', 'loadSessionRecordingsSuccess'])
+ .toMatchValues({
+ filters: expect.objectContaining({ session_ids: ['s1', 's2'] }),
+ })
+
+ const listSpy = jest.spyOn(api.recordings, 'list')
+
+ await expectLogic(logic, () => {
+ logic.actions.setFilters({ session_ids: undefined })
+ }).toDispatchActions(['setFilters', 'loadSessionRecordings', 'loadSessionRecordingsSuccess'])
+
+ expect(logic.values.filters.session_ids).toBeUndefined()
+ expect(listSpy).toHaveBeenLastCalledWith(expect.objectContaining({ session_ids: undefined }))
+ })
+ })
+
describe('deleting recordings', () => {
it('otherRecordings filters out deleted recording ids', async () => {
await expectLogic(logic)
diff --git a/frontend/src/scenes/trends/persons-modal/personsModalLogic.test.ts b/frontend/src/scenes/trends/persons-modal/personsModalLogic.test.ts
index 1b97893e4f29..f767271dfb12 100644
--- a/frontend/src/scenes/trends/persons-modal/personsModalLogic.test.ts
+++ b/frontend/src/scenes/trends/persons-modal/personsModalLogic.test.ts
@@ -411,6 +411,189 @@ describe('personsModalLogic', () => {
})
})
+ describe('funnel step scoping', () => {
+ const funnelSeries = [
+ { kind: NodeKind.EventsNode, event: 'step one' },
+ { kind: NodeKind.EventsNode, event: 'step two' },
+ {
+ kind: NodeKind.EventsNode,
+ event: 'step three',
+ properties: [
+ {
+ key: 'tab',
+ value: 'public',
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Event,
+ },
+ ],
+ },
+ ]
+
+ const setupFunnelStepLogic = ({
+ funnelStep,
+ matchedRecordings = [],
+ series = funnelSeries,
+ }: {
+ funnelStep?: number
+ matchedRecordings?: Array<{ session_id: string; events: any[] }>
+ series?: any[]
+ }): void => {
+ logic = personsModalLogic({
+ query: {
+ kind: NodeKind.FunnelsActorsQuery,
+ source: {
+ kind: NodeKind.FunnelsQuery,
+ series,
+ dateRange: { date_from: '-7d', date_to: '2024-05-01' },
+ },
+ ...(funnelStep !== undefined ? { funnelStep } : {}),
+ includeRecordings: true,
+ } as any,
+ url: '/api/environments/1/persons?',
+ additionalSelect: { matched_recordings: 'matched_recordings' },
+ })
+ logic.mount()
+ logic.actions.loadActorsSuccess({
+ results: [
+ {
+ count: 1,
+ people: [
+ {
+ type: 'person',
+ id: 'person-1',
+ distinct_ids: ['user-1'],
+ is_identified: true,
+ properties: {},
+ created_at: '2024-01-01',
+ matched_recordings: matchedRecordings,
+ value_at_data_point: null,
+ },
+ ],
+ },
+ ],
+ missing_persons: 0,
+ })
+ }
+
+ const getInnerFilterValues = (): any[] => {
+ const outerGroup = logic.values.recordingFilters.filter_group
+ const innerGroup = outerGroup?.values?.[0]
+ return innerGroup && 'values' in innerGroup ? (innerGroup.values as any[]) : []
+ }
+
+ it('includes the funnel date range when session IDs are available for a drop-off step', () => {
+ setupFunnelStepLogic({
+ funnelStep: -3,
+ matchedRecordings: [{ session_id: 'session-1', events: [] }],
+ })
+ expectLogic(logic).toMatchValues({
+ recordingFilters: {
+ session_ids: ['session-1'],
+ filter_group: {
+ type: FilterLogicalOperator.And,
+ values: [{ type: FilterLogicalOperator.And, values: [] }],
+ },
+ duration: [],
+ date_from: '-7d',
+ date_to: '2024-05-01',
+ },
+ })
+ })
+
+ it('only filters on completed steps in the fallback path for a drop-off step', () => {
+ setupFunnelStepLogic({ funnelStep: -3 })
+ const innerValues = getInnerFilterValues()
+ expect(innerValues).toEqual([
+ expect.objectContaining({ id: 'step one', type: 'events' }),
+ expect.objectContaining({ id: 'step two', type: 'events' }),
+ ])
+ expect(innerValues).not.toEqual(expect.arrayContaining([expect.objectContaining({ id: 'step three' })]))
+ expect(logic.values.recordingFilters.date_from).toEqual('-7d')
+ expect(logic.values.recordingFilters.date_to).toEqual('2024-05-01')
+ })
+
+ it.each([
+ { scenario: 'drop-off at step 2', funnelStep: -2, expectedEvents: ['step one'] },
+ {
+ scenario: 'conversion through step 3',
+ funnelStep: 3,
+ expectedEvents: ['step one', 'step two', 'step three'],
+ },
+ {
+ scenario: 'no funnel step',
+ funnelStep: undefined,
+ expectedEvents: ['step one', 'step two', 'step three'],
+ },
+ ])('filters on $expectedEvents for $scenario', ({ funnelStep, expectedEvents }) => {
+ setupFunnelStepLogic({ funnelStep })
+ expect(getInnerFilterValues().map((filter) => filter.id)).toEqual(expectedEvents)
+ })
+
+ it('includes action steps in the fallback path', () => {
+ setupFunnelStepLogic({
+ funnelStep: -3,
+ series: [
+ { kind: NodeKind.EventsNode, event: 'step one' },
+ { kind: NodeKind.ActionsNode, id: 42, name: 'Sign up' },
+ { kind: NodeKind.EventsNode, event: 'step three' },
+ ],
+ })
+ expect(getInnerFilterValues()).toEqual([
+ expect.objectContaining({ id: 'step one', type: 'events' }),
+ expect.objectContaining({ id: 42, name: 'Sign up', type: 'actions' }),
+ ])
+ })
+ })
+
+ it('keeps all series filters and the date range for the trends fallback path', () => {
+ logic = personsModalLogic({
+ query: {
+ kind: NodeKind.InsightActorsQuery,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [
+ { kind: NodeKind.EventsNode, event: '$pageview' },
+ { kind: NodeKind.EventsNode, event: 'sign_up' },
+ ],
+ dateRange: { date_from: '-14d' },
+ },
+ includeRecordings: true,
+ },
+ url: '/api/environments/1/persons?',
+ additionalSelect: { matched_recordings: 'matched_recordings' },
+ })
+ logic.mount()
+
+ logic.actions.loadActorsSuccess({
+ results: [
+ {
+ count: 1,
+ people: [
+ {
+ type: 'person',
+ id: 'person-1',
+ distinct_ids: ['user-1'],
+ is_identified: true,
+ properties: {},
+ created_at: '2024-01-01',
+ matched_recordings: [],
+ value_at_data_point: null,
+ },
+ ],
+ },
+ ],
+ missing_persons: 0,
+ })
+
+ const filters = logic.values.recordingFilters
+ const innerValues = (filters.filter_group as any)?.values?.[0]?.values
+ expect(innerValues).toEqual([
+ expect.objectContaining({ id: '$pageview', type: 'events' }),
+ expect.objectContaining({ id: 'sign_up', type: 'events' }),
+ ])
+ expect(filters.date_from).toEqual('-14d')
+ })
+
it('falls back to event filters when no session IDs are available', () => {
logic = personsModalLogic({
query: {
diff --git a/frontend/src/scenes/trends/persons-modal/personsModalLogic.ts b/frontend/src/scenes/trends/persons-modal/personsModalLogic.ts
index 3b65d154463c..0d4994c2400b 100644
--- a/frontend/src/scenes/trends/persons-modal/personsModalLogic.ts
+++ b/frontend/src/scenes/trends/persons-modal/personsModalLogic.ts
@@ -570,6 +570,21 @@ export const personsModalLogic = kea<personsModalLogicType>([
// Scope recordings to the selected funnel breakdown value (e.g. country = "NL").
const funnelBreakdownFilter = buildFunnelBreakdownFilter(source)
+ // The actual insight query (with series, properties, etc.) is nested at source.source
+ let insightQuery = source
+ if ('source' in source && source.source) {
+ insightQuery = source.source as any
+ }
+
+ let date_from = propertiesTimelineFilter?.date_from
+ let date_to = propertiesTimelineFilter?.date_to
+
+ if ('dateRange' in insightQuery && insightQuery.dateRange) {
+ const dateRange = insightQuery.dateRange as any
+ date_from = dateRange.date_from || date_from
+ date_to = dateRange.date_to || date_to
+ }
+
// If we have session IDs from matched_recordings, use them directly for efficient lookup
if (sessionIds.length > 0) {
return {
@@ -584,35 +599,49 @@ export const personsModalLogic = kea<personsModalLogicType>([
],
},
duration: [],
+ date_from,
+ date_to,
}
}
// For non-funnel queries or funnels without session IDs, use filter-based approach
const filters: UniversalFilterValue[] = []
- // The actual insight query (with series, properties, etc.) is nested at source.source
- let insightQuery = source
- if ('source' in source && source.source) {
- insightQuery = source.source as any
- }
-
// Extract events from the insight query series
if ('series' in insightQuery && Array.isArray(insightQuery.series)) {
- insightQuery.series.forEach((series) => {
+ // drop-off actors (negative funnelStep) only completed the steps before the
+ // drop-off, so only those can be required as event filters
+ let seriesToFilterOn: any[] = insightQuery.series
+ if (source.kind === NodeKind.FunnelsActorsQuery && typeof source.funnelStep === 'number') {
+ const completedStepCount =
+ source.funnelStep > 0 ? source.funnelStep : Math.abs(source.funnelStep) - 1
+ seriesToFilterOn = insightQuery.series.slice(0, completedStepCount)
+ }
+ seriesToFilterOn.forEach((series) => {
+ let entityFilter: any = null
if ('event' in series && series.event) {
- const eventFilter: any = {
+ entityFilter = {
id: series.event,
name: series.event,
type: 'events',
}
+ } else if (series.kind === NodeKind.ActionsNode && series.id != null) {
+ // action steps have an action id, not an event name
+ entityFilter = {
+ id: series.id,
+ name: series.name,
+ type: 'actions',
+ }
+ }
+ if (entityFilter) {
if (
'properties' in series &&
Array.isArray(series.properties) &&
series.properties.length > 0
) {
- eventFilter.properties = series.properties
+ entityFilter.properties = series.properties
}
- filters.push(eventFilter)
+ filters.push(entityFilter)
}
})
}
@@ -642,16 +671,6 @@ export const personsModalLogic = kea<personsModalLogicType>([
filters.push(...insightQuery.properties)
}
- // Extract date range from insight query
- let date_from = propertiesTimelineFilter?.date_from
- let date_to = propertiesTimelineFilter?.date_to
-
- if ('dateRange' in insightQuery && insightQuery.dateRange) {
- const dateRange = insightQuery.dateRange as any
- date_from = dateRange.date_from || date_from
- date_to = dateRange.date_to || date_to
- }
-
// Build the result for non-funnel or fallback cases
return {
filter_group: {
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 7aa85715ea03..5a1cbee0b901 100644
--- a/posthog/session_recordings/queries/session_recording_list_from_query.py
+++ b/posthog/session_recordings/queries/session_recording_list_from_query.py
@@ -2,6 +2,7 @@ from datetime import UTC, datetime, timedelta
from typing import Any, Literal, Union, cast
import structlog
+from dateutil.relativedelta import relativedelta
from opentelemetry import trace
from posthog.schema import (
@@ -124,8 +125,10 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
max_execution_time: int | None = None,
extra_having_predicates: list[ast.Expr] | None = None,
session_ids_to_exclude: list[str] | None = None,
+ bypass_date_window_for_session_ids: bool = False,
**_,
):
+ self._bypass_date_window_for_session_ids = bypass_date_window_for_session_ids
# TRICKY: we need to make sure we init test account filters only once,
# otherwise we'll end up with a lot of duplicated test account filters in the query
expanded_query = query.model_copy(deep=True)
@@ -312,25 +315,44 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
)
)
- query_date_from = self.query_date_range.date_from()
- if query_date_from:
+ # 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=query_date_from),
+ 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),
+ 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] = []
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 f739a99bb6df..8a7ac313dbf2 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
@@ -913,6 +913,158 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
],
)
+ def _an_old_recording(self) -> str:
+ user = "test_session_ids_date_window-user"
+ Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})
+
+ ten_days_ago = self.an_hour_ago - relativedelta(days=10)
+ old_session_id = str(uuid4())
+ produce_replay_summary(
+ session_id=old_session_id,
+ team_id=self.team.pk,
+ first_timestamp=ten_days_ago,
+ last_timestamp=ten_days_ago + relativedelta(minutes=5),
+ distinct_id=user,
+ )
+ return old_session_id
+
+ def _filter_recordings_with_bypass(self, query: dict) -> list[str]:
+ result = SessionRecordingListFromQuery(
+ query=RecordingsQuery.model_validate(query),
+ team=self.team,
+ hogql_query_modifiers=None,
+ bypass_date_window_for_session_ids=True,
+ ).run()
+ return sorted(r["session_id"] for r in result.results)
+
+ @parameterized.expand(
+ [
+ ("default_date_range", None, False),
+ ("explicit_narrow_date_range", "-1d", False),
+ ("window_covering_the_recording", "-30d", True),
+ ]
+ )
+ def test_session_ids_apply_date_window_by_default(
+ self, _name: str, date_from: str | None, expect_found: bool
+ ) -> None:
+ old_session_id = self._an_old_recording()
+
+ query: dict = {"session_ids": [old_session_id]}
+ if date_from is not None:
+ query["date_from"] = date_from
+
+ self._assert_query_matches_session_ids(query, [old_session_id] if expect_found else [])
+
+ @parameterized.expand(
+ [
+ ("default_date_range", None),
+ ("explicit_narrow_date_range", "-1d"),
+ ]
+ )
+ def test_bypass_returns_explicitly_selected_sessions_regardless_of_date_window(
+ self, _name: str, date_from: str | None
+ ) -> None:
+ old_session_id = self._an_old_recording()
+
+ query: dict = {"session_ids": [old_session_id]}
+ if date_from is not None:
+ query["date_from"] = date_from
+
+ assert self._filter_recordings_with_bypass(query) == [old_session_id]
+
+ def test_date_window_still_excludes_old_recordings_without_session_ids(self) -> None:
+ self._an_old_recording()
+
+ self._assert_query_matches_session_ids(None, [])
+
+ def test_bypass_does_not_apply_to_session_ids_derived_from_comment_search(self) -> None:
+ old_session_id = self._an_old_recording()
+
+ # comment-derived session_ids are not user-selected, so the date range still applies
+ comment_query = {
+ "session_ids": [old_session_id],
+ "comment_text": {
+ "key": "comment_text",
+ "type": "recording",
+ "operator": "icontains",
+ "value": "anything",
+ },
+ }
+ assert self._filter_recordings_with_bypass(comment_query) == []
+
+ @parameterized.expand(
+ [
+ ("default", False),
+ ("with_bypass", True),
+ ]
+ )
+ def test_empty_session_ids_list_still_matches_nothing(self, _name: str, bypass: bool) -> None:
+ self._an_old_recording()
+
+ result = SessionRecordingListFromQuery(
+ query=RecordingsQuery(session_ids=[]),
+ team=self.team,
+ hogql_query_modifiers=None,
+ bypass_date_window_for_session_ids=bypass,
+ ).run()
+ assert result.results == []
+
+ def test_retention_bound_cannot_hide_live_recordings(self) -> None:
+ # anything older than the 5y bound is past every retention period, so never viewable
+ user = "test_retention_bound-user"
+ Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})
+
+ six_years_ago = self.an_hour_ago - relativedelta(years=6)
+ ancient_session_id = str(uuid4())
+ produce_replay_summary(
+ session_id=ancient_session_id,
+ team_id=self.team.pk,
+ first_timestamp=six_years_ago,
+ last_timestamp=six_years_ago + relativedelta(minutes=5),
+ distinct_id=user,
+ retention_period_days=1826,
+ )
+
+ assert self._filter_recordings_with_bypass({"session_ids": [ancient_session_id]}) == []
+
+ @parameterized.expand(
+ [
+ ("default_window_excludes_events", None, False),
+ ("wide_window_includes_events", "-30d", True),
+ ]
+ )
+ def test_event_filters_bound_session_ids_queries_by_date_even_with_bypass(
+ self, _name: str, date_from: str | None, expect_found: bool
+ ) -> None:
+ # event subqueries scan within the date range even when bypassing
+ user = "test_session_ids_event_window-user"
+ Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})
+
+ ten_days_ago = self.an_hour_ago - relativedelta(days=10)
+ old_session_id = str(uuid4())
+ create_event(
+ team=self.team,
+ distinct_id=user,
+ timestamp=ten_days_ago,
+ properties={"$session_id": old_session_id, "$window_id": str(uuid4())},
+ )
+ produce_replay_summary(
+ session_id=old_session_id,
+ team_id=self.team.pk,
+ first_timestamp=ten_days_ago,
+ last_timestamp=ten_days_ago + relativedelta(minutes=5),
+ distinct_id=user,
+ )
+
+ query: dict = {
+ "session_ids": [old_session_id],
+ "events": [{"id": "$pageview", "type": "events", "order": 0, "name": "$pageview"}],
+ }
+ if date_from is not None:
+ query["date_from"] = date_from
+
+ assert self._filter_recordings_with_bypass(query) == ([old_session_id] if expect_found else [])
+
@snapshot_clickhouse_queries
def test_event_filter_with_active_sessions(
self,
diff --git a/posthog/session_recordings/queries/test/test_recordings_query_runner.py b/posthog/session_recordings/queries/test/test_recordings_query_runner.py
index 4bbcab4b6fe5..d516de3e6486 100644
--- a/posthog/session_recordings/queries/test/test_recordings_query_runner.py
+++ b/posthog/session_recordings/queries/test/test_recordings_query_runner.py
@@ -1,6 +1,8 @@
from freezegun import freeze_time
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, snapshot_clickhouse_queries
+from parameterized import parameterized
+
from posthog.schema import RecordingsQuery, SessionRecordingType, SnapshotSource
from posthog.clickhouse.client import sync_execute
@@ -87,6 +89,23 @@ class TestRecordingsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert "session-new" in session_ids
assert "session-old" not in session_ids
+ @parameterized.expand(
+ [
+ ("narrow_window_excludes", "-1d", []),
+ ("covering_window_includes", "-10d", ["session-old"]),
+ ]
+ )
+ def test_session_ids_respect_date_window(self, _name: str, date_from: str, expected: list[str]):
+ # within the 30d retention, so only the date window can exclude it
+ self._produce_replay("session-old", first_timestamp="2020-12-25T12:00:00", last_timestamp="2020-12-25T12:10:00")
+
+ runner = RecordingsQueryRunner(
+ query=RecordingsQuery(session_ids=["session-old"], date_from=date_from), team=self.team
+ )
+ response = runner.calculate()
+
+ assert [r.id for r in response.results] == expected
+
@snapshot_clickhouse_queries
def test_generates_valid_hogql(self):
self._produce_replay("session-1")
diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.py
index 70ee19079568..6d6788e31e3a 100644
--- a/posthog/session_recordings/session_recording_api.py
+++ b/posthog/session_recordings/session_recording_api.py
@@ -890,6 +890,9 @@ class SessionRecordingViewSet(
cast(User, request.user),
team=self.team,
allow_event_property_expansion=allow_event_property_expansion,
+ # show explicitly selected sessions (e.g. a funnel drop-off handoff)
+ # even outside the date range
+ bypass_date_window_for_session_ids=True,
)
with tracer.start_as_current_span("make_response"):
@@ -1987,7 +1990,11 @@ def _load_selected_recording_ignoring_filters(session_id: str, team: Team) -> Se
# TODO i guess this becomes the query runner for our _internal_ use of RecordingsQuery
def list_recordings_from_query(
- query: RecordingsQuery, user: User | None, team: Team, allow_event_property_expansion: bool = False
+ query: RecordingsQuery,
+ user: User | None,
+ team: Team,
+ allow_event_property_expansion: bool = False,
+ bypass_date_window_for_session_ids: bool = False,
) -> tuple[list[SessionRecording], bool, str, str | None]:
"""
As we can store recordings in S3 or in Clickhouse we need to do a few things here
@@ -2082,6 +2089,7 @@ def list_recordings_from_query(
hogql_query_modifiers=None,
allow_event_property_expansion=allow_event_property_expansion,
session_ids_to_exclude=session_ids_to_exclude,
+ bypass_date_window_for_session_ids=bypass_date_window_for_session_ids,
).run()
ch_session_recordings = query_result.results
diff --git a/posthog/session_recordings/test/test_session_recording_playlist.py b/posthog/session_recordings/test/test_session_recording_playlist.py
index 4565b0327a8b..9b76e5d086d3 100644
--- a/posthog/session_recordings/test/test_session_recording_playlist.py
+++ b/posthog/session_recordings/test/test_session_recording_playlist.py
@@ -725,6 +725,72 @@ class TestSessionRecordingPlaylist(APIBaseTest, QueryMatchingTest):
assert len(result["results"]) == 1
assert result["results"][0]["id"] == session_one
+ def test_collection_recordings_keep_one_year_search_bound(self) -> None:
+ # long retention keeps the old recording alive, so only the collections -1y bound excludes it
+ playlist = SessionRecordingPlaylist.objects.create(
+ team=self.team, name="collection", created_by=self.user, type="collection"
+ )
+
+ recent_session = f"recent-{uuid4()}"
+ over_a_year_old_session = f"over-a-year-old-{uuid4()}"
+ three_days_ago = (datetime.now() - timedelta(days=3)).replace(tzinfo=UTC)
+ over_a_year_ago = (datetime.now() - timedelta(days=400)).replace(tzinfo=UTC)
+
+ for session_id, timestamp in [(recent_session, three_days_ago), (over_a_year_old_session, over_a_year_ago)]:
+ produce_replay_summary(
+ team_id=self.team.id,
+ session_id=session_id,
+ distinct_id="123",
+ first_timestamp=timestamp,
+ last_timestamp=timestamp,
+ retention_period_days=1826,
+ )
+ self.client.post(
+ f"/api/projects/{self.team.id}/session_recording_playlists/{playlist.short_id}/recordings/{session_id}"
+ )
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/session_recording_playlists/{playlist.short_id}/recordings"
+ )
+ assert response.status_code == status.HTTP_200_OK
+ assert {x["id"] for x in response.json()["results"]} == {recent_session}
+
+ @parameterized.expand(
+ [
+ ("narrow_window_excludes", "-1d", False),
+ ("covering_window_includes", "-30d", True),
+ ]
+ )
+ def test_filters_playlist_pinned_recordings_respect_date_params(
+ self, _name: str, date_from: str, expect_found: bool
+ ) -> None:
+ # legacy filters playlists can still carry pinned items
+ playlist = SessionRecordingPlaylist.objects.create(
+ team=self.team, name="legacy filters with pins", created_by=self.user, type="filters"
+ )
+
+ old_session = f"old-{uuid4()}"
+ ten_days_ago = (datetime.now() - timedelta(days=10)).replace(tzinfo=UTC)
+ produce_replay_summary(
+ team_id=self.team.id,
+ session_id=old_session,
+ distinct_id="123",
+ first_timestamp=ten_days_ago,
+ last_timestamp=ten_days_ago,
+ )
+ # pinning via the API is collection-only, so create the legacy rows directly
+ recording, _ = SessionRecording.objects.get_or_create(
+ session_id=old_session, team=self.team, defaults={"deleted": False}
+ )
+ SessionRecordingPlaylistItem.objects.create(playlist=playlist, recording=recording)
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/session_recording_playlists/{playlist.short_id}/recordings",
+ data={"date_from": date_from},
+ )
+ assert response.status_code == status.HTTP_200_OK
+ assert {x["id"] for x in response.json()["results"]} == ({old_session} if expect_found else set())
+
def test_add_remove_static_playlist_items(self):
playlist1 = SessionRecordingPlaylist.objects.create(
team=self.team,
diff --git a/posthog/session_recordings/test/test_session_recordings.py b/posthog/session_recordings/test/test_session_recordings.py
index 36d9c852099c..a11be9e71153 100644
--- a/posthog/session_recordings/test/test_session_recordings.py
+++ b/posthog/session_recordings/test/test_session_recordings.py
@@ -1085,6 +1085,26 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)
assert response_data["results"][1]["id"] == "2"
assert response_data["results"][2]["id"] == "3"
+ def test_session_ids_filter_returns_recordings_outside_default_date_range(self):
+ with freeze_time("2020-09-13T12:26:40.000Z"):
+ Person.objects.create(
+ team=self.team,
+ distinct_ids=["user"],
+ properties={"$some_prop": "something", "email": "[email protected]"},
+ )
+ # outside the default date range
+ self.produce_replay_summary("user", "old-session", now() - relativedelta(days=10))
+
+ params_string = urlencode({"session_ids": '["old-session"]'})
+ response = self.client.get(f"/api/projects/{self.team.id}/session_recordings?{params_string}")
+ assert response.status_code == status.HTTP_200_OK
+ assert [r["id"] for r in response.json()["results"]] == ["old-session"]
+
+ # without explicit session_ids the default date range still hides it
+ response = self.client.get(f"/api/projects/{self.team.id}/session_recordings")
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["results"] == []
+
def test_empty_list_session_ids_filter_returns_no_recordings(self):
with freeze_time("2020-09-13T12:26:40.000Z"):
Person.objects.create(