: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): read the recordings list once per playlist open (#96802)
Marcel Poelker142ea4b88d4b
diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.tsindex d6223c32e98e..75e18890ff64 100644--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts@@ -24,7 +24,10 @@ import { playlistFiltersLogic } from './playlistFiltersLogic'import {DEFAULT_RECORDING_FILTERS,DEFAULT_RECORDING_FILTERS_ORDER_BY,+ LIST_MEMO_WINDOW_MS,+ type SessionRecordingPlaylistLogicProps,asUniversalFilters,+ clearMemoizedListResponses,convertLegacyFiltersToUniversalFilters,convertUniversalFiltersToRecordingsQuery,getDefaultFilters,@@ -168,6 +171,8 @@ describe('sessionRecordingsPlaylistLogic', () => {})initKeaTests()featureFlagLogic.mount()+ // The list memo is module state, so it survives the kea context these tests reset+ clearMemoizedListResponses()})afterEach(() => {@@ -1036,13 +1041,14 @@ describe('sessionRecordingsPlaylistLogic', () => {expect(onRecordingSelected.mock.calls).toEqual([[aRecording.id]])// A reload that keeps the same recording on top doesn't move the player, so it must- // not be reported as another open.+ // not be reported as another open. Each reload here forces the read, because the+ // parameters do not change and the memo would otherwise answer it.const listSpy = jest.spyOn(api.recordings, 'list').mockResolvedValueOnce({ results: listOfSessionRecordings, has_next: false } as Awaited<ReturnType<typeof api.recordings.list>>)- logic.actions.loadSessionRecordings()+ logic.actions.loadSessionRecordings(undefined, undefined, true)await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess'])expect(onRecordingSelected.mock.calls).toEqual([[aRecording.id]])@@ -1057,7 +1063,7 @@ describe('sessionRecordingsPlaylistLogic', () => {listSpy.mockResolvedValueOnce({ results: [newestRecording], has_next: false } as Awaited<ReturnType<typeof api.recordings.list>>)- logic.actions.loadSessionRecordings()+ logic.actions.loadSessionRecordings(undefined, undefined, true)await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess'])expect(onRecordingSelected.mock.calls).toEqual([[aRecording.id], ['newest']])})@@ -1093,13 +1099,14 @@ describe('sessionRecordingsPlaylistLogic', () => {// A facet can match nothing: the player unloads into the empty state. When the next// reload brings the same recording back, it autoplays afresh — a new open, not a- // re-select of something still on screen.+ // re-select of something still on screen. Each reload here forces the read, because+ // the parameters do not change and the memo would otherwise answer it.const listSpy = jest.spyOn(api.recordings, 'list').mockResolvedValueOnce({ results: [], has_next: false } as Awaited<ReturnType<typeof api.recordings.list>>)- logic.actions.loadSessionRecordings()+ logic.actions.loadSessionRecordings(undefined, undefined, true)await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()expect(logic.values.sessionRecordings).toEqual([])expect(logic.values.activeSessionRecordingId).toBeUndefined()@@ -1108,7 +1115,7 @@ describe('sessionRecordingsPlaylistLogic', () => {listSpy.mockResolvedValueOnce({ results: listOfSessionRecordings, has_next: false } as Awaited<ReturnType<typeof api.recordings.list>>)- logic.actions.loadSessionRecordings()+ logic.actions.loadSessionRecordings(undefined, undefined, true)await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()expect(onRecordingSelected.mock.calls).toEqual([[aRecording.id], [aRecording.id]])})@@ -1316,28 +1323,380 @@ describe('sessionRecordingsPlaylistLogic', () => {describe('rehydrating persisted filters', () => {const props = { logicKey: 'persist_regression', personUUID: 'persist_regression', updateSearchParams: false }- it('resets a malformed persisted filters value to defaults on mount', async () => {+ afterEach(() => {+ jest.restoreAllMocks()+ })++ // Leaves `storedFilters` in the persist slot the given props rehydrate from, so the next+ // mount reads them - exactly what a stored entry does in production.+ const persistFilters = (+ logicProps: SessionRecordingPlaylistLogicProps,+ storedFilters: Record<string, any>+ ): void => {// A first mount writes the persist key. Discover its exact name rather than hardcoding// kea-localstorage's prefix/path format.- const seed = sessionRecordingsPlaylistLogic(props)+ const seed = sessionRecordingsPlaylistLogic(logicProps)seed.mount()const filtersKey = Object.keys(localStorage).find(- (k) => k.includes('persist_regression') && k.endsWith('.filters')+ (k) => k.includes(logicProps.logicKey!) && k.endsWith('.filters'))expect(typeof filtersKey).toBe('string')seed.unmount()- // Poison the persisted entry, then reset the kea context so the reducer rehydrates from- // storage on the next build - exactly what a stale localStorage entry does in production.- localStorage.setItem(filtersKey!, JSON.stringify({ filter_group: 'not-a-group', duration: 'nope' }))+ localStorage.setItem(filtersKey!, JSON.stringify(storedFilters))initKeaTests()featureFlagLogic.mount()+ }++ it('resets a malformed persisted filters value to defaults on mount', async () => {+ persistFilters(props, { filter_group: 'not-a-group', duration: 'nope' })logic = sessionRecordingsPlaylistLogic(props)logic.mount()expect(logic.values.filters).toEqual(getDefaultFilters('persist_regression'))})++ it('reads the caller filters, not the persisted ones, on a scoped mount', async () => {+ // The caller scopes the list by date and leaves the rest of the filters to the viewer+ const scopedProps = {+ logicKey: 'caller_scoped',+ updateSearchParams: false,+ filters: {+ date_from: '-7d',+ duration: DEFAULT_RECORDING_FILTERS.duration,+ filter_group: DEFAULT_RECORDING_FILTERS.filter_group,+ },+ }+ persistFilters(scopedProps, {+ ...DEFAULT_RECORDING_FILTERS,+ date_from: '-30d',+ filter_test_accounts: true,+ })+ const listSpy = jest+ .spyOn(api.recordings, 'list')+ .mockImplementation(+ () =>+ Promise.resolve({ results: [aRecording], has_next: false } as unknown) as ReturnType<+ typeof api.recordings.list+ >+ )++ logic = sessionRecordingsPlaylistLogic(scopedProps)+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()++ // one read, scoped to the caller, and the viewer's own key survives the merge+ expect(listSpy).toHaveBeenCalledTimes(1)+ expect(listSpy).toHaveBeenCalledWith(+ expect.objectContaining({ date_from: '-7d', filter_test_accounts: true })+ )+ })++ it('drops a persisted absolute date_to when the caller passes a relative date_from', async () => {+ const scopedProps = {+ logicKey: 'caller_scoped_dates',+ updateSearchParams: false,+ filters: {+ date_from: '-7d',+ duration: DEFAULT_RECORDING_FILTERS.duration,+ filter_group: DEFAULT_RECORDING_FILTERS.filter_group,+ },+ }+ // Every key the caller sets already matches, so only the transform `setFilters` runs on+ // a relative date_from makes this mount differ from what is stored.+ persistFilters(scopedProps, {+ ...DEFAULT_RECORDING_FILTERS,+ date_from: '-7d',+ date_to: '2024-01-01',+ })+ const listSpy = jest+ .spyOn(api.recordings, 'list')+ .mockImplementation(+ () =>+ Promise.resolve({ results: [aRecording], has_next: false } as unknown) as ReturnType<+ typeof api.recordings.list+ >+ )++ logic = sessionRecordingsPlaylistLogic(scopedProps)+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()++ expect(listSpy).toHaveBeenCalledTimes(1)+ expect(listSpy).toHaveBeenCalledWith(expect.objectContaining({ date_from: '-7d', date_to: null }))+ })++ it('applies the caller filters and the pinned ones in one load, as no viewer edit', async () => {+ const pinnedFilters = {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: 'events',+ name: 'All events',+ properties: [{ key: "$group_0 = 'scoped-group'", type: 'hogql' }],+ } as ActionFilter,+ ],+ }+ const scopedProps = {+ logicKey: 'caller_scoped_pinned',+ updateSearchParams: false,+ pinnedFilters,+ filters: {+ date_from: '-7d',+ duration: DEFAULT_RECORDING_FILTERS.duration,+ filter_group: DEFAULT_RECORDING_FILTERS.filter_group,+ },+ }+ // The stored group holds no pinned filter, so the pinned merge is pending at mount+ persistFilters(scopedProps, { ...DEFAULT_RECORDING_FILTERS, date_from: '-30d' })+ const listSpy = jest+ .spyOn(api.recordings, 'list')+ .mockImplementation(+ () =>+ Promise.resolve({ results: [aRecording], has_next: false } as unknown) as ReturnType<+ typeof api.recordings.list+ >+ )++ logic = sessionRecordingsPlaylistLogic(scopedProps)+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()++ expect(listSpy).toHaveBeenCalledTimes(1)+ expect(listSpy).toHaveBeenCalledWith(expect.objectContaining({ date_from: '-7d' }))+ // props applied at mount are not viewer edits, so the read carries no filter edit+ expect(listSpy.mock.calls[0][0]).not.toHaveProperty('user_modified_filters')+ const firstGroup = logic.values.filters.filter_group.values[0] as any+ expect(firstGroup.values).toContainEqual(pinnedFilters.values[0])+ })++ // A viewer's own filter edit has to survive a remount, or narrowing the range inside the+ // experiment Recordings tab is lost on every tab switch.+ it('keeps a filter the viewer set across a remount of a scoped playlist', async () => {+ const scopedProps = {+ logicKey: 'caller_scoped_viewer_edit',+ updateSearchParams: false,+ filters: {+ date_from: '-7d',+ duration: DEFAULT_RECORDING_FILTERS.duration,+ filter_group: DEFAULT_RECORDING_FILTERS.filter_group,+ filter_test_accounts: true,+ },+ }+ const listSpy = jest+ .spyOn(api.recordings, 'list')+ .mockImplementation(+ () =>+ Promise.resolve({ results: [aRecording], has_next: false } as unknown) as ReturnType<+ typeof api.recordings.list+ >+ )++ const firstMount = sessionRecordingsPlaylistLogic(scopedProps)+ firstMount.mount()+ await expectLogic(firstMount).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()++ // the viewer narrows the date range from the filter bar+ await expectLogic(firstMount, () => {+ firstMount.actions.setFilters({ date_from: '-30d', date_to: null })+ })+ .toDispatchActions(['loadSessionRecordingsSuccess'])+ .toFinishAllListeners()+ firstMount.unmount()++ listSpy.mockClear()+ // the remount asks for the same rows, so clear the memo to leave the read visible+ clearMemoizedListResponses()++ const secondMount = sessionRecordingsPlaylistLogic(scopedProps)+ secondMount.mount()+ await expectLogic(secondMount).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()++ // one read, the viewer's range survives, and the caller's other keys still apply+ expect(listSpy).toHaveBeenCalledTimes(1)+ expect(listSpy).toHaveBeenCalledWith(+ expect.objectContaining({ date_from: '-30d', filter_test_accounts: true })+ )++ secondMount.unmount()+ })++ // A saved filter set arrives as one whole-object dispatch, so it would otherwise claim the+ // two keys a caller scopes with and unscope the list on the next mount.+ it('never marks the keys a caller scopes with as viewer edits', async () => {+ logic = sessionRecordingsPlaylistLogic({ logicKey: 'caller_owned_keys', updateSearchParams: false })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()++ await expectLogic(logic, () => {+ logic.actions.setFilters({+ ...DEFAULT_RECORDING_FILTERS,+ date_from: '-30d',+ session_ids: ['a-session'],+ experiment_exposure: { experiment_id: 1, variant: 'test' },+ })+ }).toFinishAllListeners()++ expect(logic.values.viewerFilterKeys).toContain('date_from')+ expect(logic.values.viewerFilterKeys).not.toContain('session_ids')+ expect(logic.values.viewerFilterKeys).not.toContain('experiment_exposure')+ })++ it('takes a key back when the caller filters change', async () => {+ const scopedProps = {+ logicKey: 'caller_scoped_props_change',+ updateSearchParams: false,+ filters: {+ date_from: '-7d',+ duration: DEFAULT_RECORDING_FILTERS.duration,+ filter_group: DEFAULT_RECORDING_FILTERS.filter_group,+ },+ }+ const listSpy = jest+ .spyOn(api.recordings, 'list')+ .mockImplementation(+ () =>+ Promise.resolve({ results: [aRecording], has_next: false } as unknown) as ReturnType<+ typeof api.recordings.list+ >+ )++ logic = sessionRecordingsPlaylistLogic(scopedProps)+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()++ await expectLogic(logic, () => {+ logic.actions.setFilters({ date_from: '-30d', date_to: null })+ })+ .toDispatchActions(['loadSessionRecordingsSuccess'])+ .toFinishAllListeners()+ expect(logic.values.viewerFilterKeys).toContain('date_from')++ // the caller's own range moves, so it owns that key again+ sessionRecordingsPlaylistLogic({+ ...scopedProps,+ filters: { ...scopedProps.filters, date_from: '-14d' },+ })+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()++ expect(logic.values.viewerFilterKeys).not.toContain('date_from')+ expect(logic.values.viewerFilterKeys).toContain('date_to')+ expect(listSpy).toHaveBeenLastCalledWith(expect.objectContaining({ date_from: '-14d' }))+ })++ // The experiment tab recomputes its whole filter object on every variant and watch card, so+ // a props change must only carry the keys that moved.+ it('leaves a viewer key alone when another caller key changes', async () => {+ const scopedProps = {+ logicKey: 'caller_scoped_partial_props_change',+ updateSearchParams: false,+ filters: {+ date_from: '-7d',+ duration: DEFAULT_RECORDING_FILTERS.duration,+ filter_group: DEFAULT_RECORDING_FILTERS.filter_group,+ },+ }+ const listSpy = jest+ .spyOn(api.recordings, 'list')+ .mockImplementation(+ () =>+ Promise.resolve({ results: [aRecording], has_next: false } as unknown) as ReturnType<+ typeof api.recordings.list+ >+ )++ logic = sessionRecordingsPlaylistLogic(scopedProps)+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()++ await expectLogic(logic, () => {+ logic.actions.setFilters({ date_from: '-30d', date_to: null })+ })+ .toDispatchActions(['loadSessionRecordingsSuccess'])+ .toFinishAllListeners()++ // the caller narrows to a variant, which recomputes the whole object+ const experimentExposure = { experiment_id: 1, variant: 'test' }+ sessionRecordingsPlaylistLogic({+ ...scopedProps,+ filters: { ...scopedProps.filters, experiment_exposure: experimentExposure },+ })+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()++ expect(logic.values.filters.date_from).toEqual('-30d')+ expect(logic.values.viewerFilterKeys).toContain('date_from')+ expect(listSpy).toHaveBeenLastCalledWith(+ expect.objectContaining({ date_from: '-30d', experiment_exposure: experimentExposure })+ )+ })++ it('clears the viewer keys on reset, so the next mount is fully caller-scoped', async () => {+ const scopedProps = {+ logicKey: 'caller_scoped_reset',+ updateSearchParams: false,+ filters: {+ date_from: '-7d',+ duration: DEFAULT_RECORDING_FILTERS.duration,+ filter_group: DEFAULT_RECORDING_FILTERS.filter_group,+ },+ }+ const listSpy = jest+ .spyOn(api.recordings, 'list')+ .mockImplementation(+ () =>+ Promise.resolve({ results: [aRecording], has_next: false } as unknown) as ReturnType<+ typeof api.recordings.list+ >+ )++ const firstMount = sessionRecordingsPlaylistLogic(scopedProps)+ firstMount.mount()+ await expectLogic(firstMount).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()++ await expectLogic(firstMount, () => {+ firstMount.actions.setFilters({ date_from: '-30d', date_to: null })+ })+ .toDispatchActions(['loadSessionRecordingsSuccess'])+ .toFinishAllListeners()+ await expectLogic(firstMount, () => {+ firstMount.actions.resetFilters()+ })+ .toDispatchActions(['loadSessionRecordingsSuccess'])+ .toFinishAllListeners()+ expect(firstMount.values.viewerFilterKeys).toEqual([])+ firstMount.unmount()++ listSpy.mockClear()+ clearMemoizedListResponses()++ const secondMount = sessionRecordingsPlaylistLogic(scopedProps)+ secondMount.mount()+ await expectLogic(secondMount).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()++ expect(listSpy).toHaveBeenLastCalledWith(expect.objectContaining({ date_from: '-7d' }))++ secondMount.unmount()+ })++ it('reads the persisted filters once when the caller sets none', async () => {+ persistFilters(props, { ...DEFAULT_RECORDING_FILTERS, date_from: '-14d' })+ const listSpy = jest+ .spyOn(api.recordings, 'list')+ .mockImplementation(+ () =>+ Promise.resolve({ results: [aRecording], has_next: false } as unknown) as ReturnType<+ typeof api.recordings.list+ >+ )++ logic = sessionRecordingsPlaylistLogic(props)+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()++ expect(listSpy).toHaveBeenCalledTimes(1)+ expect(listSpy).toHaveBeenCalledWith(expect.objectContaining({ date_from: '-14d' }))+ })})describe('set filters', () => {@@ -1435,6 +1794,16 @@ describe('sessionRecordingsPlaylistLogic', () => {describe('deduping identical list requests', () => {const listResponse = { results: [aRecording], has_next: false }+ // The memo window is measured with `performance.now`, so a test moves the clock rather+ // than waiting on it. Returns a function that adds to the clock.+ const mockClock = (): ((ms: number) => void) => {+ let now = 0+ jest.spyOn(performance, 'now').mockImplementation(() => now)+ return (ms: number) => {+ now += ms+ }+ }+afterEach(() => {jest.restoreAllMocks()})@@ -1443,6 +1812,7 @@ describe('sessionRecordingsPlaylistLogic', () => {// in-flight guard, which cannot match a request that no call has issued yet. This case// guards the debounce: shorten or drop it and same-tick duplicates come back.it('leaves the debounce to collapse two loads dispatched in the same tick', async () => {+ const advanceClock = mockClock()const listSpy = jest.spyOn(api.recordings, 'list').mockImplementation(@@ -1455,6 +1825,8 @@ describe('sessionRecordingsPlaylistLogic', () => {// let the load afterMount kicks off settle, so only the two below are countedawait expectLogic(sameTickLogic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()listSpy.mockClear()+ // move past the memo window, so the debounce is the only thing left to collapse them+ advanceClock(LIST_MEMO_WINDOW_MS + 1)await expectLogic(sameTickLogic, () => {sameTickLogic.actions.loadSessionRecordings()@@ -1564,6 +1936,162 @@ describe('sessionRecordingsPlaylistLogic', () => {selectionLogic.unmount()})++ // The measured duplicates arrive a second or two after the first response landed, so the+ // in-flight guard cannot match them. These cases cover the memo that does.+ it('reads once when a load repeats a request whose response landed inside the memo window', async () => {+ const advanceClock = mockClock()+ const listSpy = jest+ .spyOn(api.recordings, 'list')+ .mockImplementation(+ () => Promise.resolve(listResponse as unknown) as ReturnType<typeof api.recordings.list>+ )++ const memoLogic = sessionRecordingsPlaylistLogic({ logicKey: 'dedupe-memo' })+ memoLogic.mount()+ await expectLogic(memoLogic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()+ listSpy.mockClear()++ advanceClock(LIST_MEMO_WINDOW_MS - 1)+ await expectLogic(memoLogic, () => {+ memoLogic.actions.loadSessionRecordings()+ })+ .toDispatchActions(['loadSessionRecordingsSuccess'])+ .toNotHaveDispatchedActions(['reportRecordingsListFetched'])+ .toFinishAllListeners()++ expect(listSpy).not.toHaveBeenCalled()+ expect(memoLogic.values.sessionRecordings).toEqual([aRecording])++ memoLogic.unmount()+ })++ it('reads again when a load repeats a request the memo window no longer covers', async () => {+ const advanceClock = mockClock()+ const listSpy = jest+ .spyOn(api.recordings, 'list')+ .mockImplementation(+ () => Promise.resolve(listResponse as unknown) as ReturnType<typeof api.recordings.list>+ )++ const staleMemoLogic = sessionRecordingsPlaylistLogic({ logicKey: 'dedupe-memo-expired' })+ staleMemoLogic.mount()+ await expectLogic(staleMemoLogic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()+ listSpy.mockClear()++ advanceClock(LIST_MEMO_WINDOW_MS + 1)+ await expectLogic(staleMemoLogic, () => {+ staleMemoLogic.actions.loadSessionRecordings()+ })+ .toDispatchActions(['loadSessionRecordingsSuccess'])+ .toFinishAllListeners()++ expect(listSpy).toHaveBeenCalledTimes(1)++ staleMemoLogic.unmount()+ })++ it('reads again when the refresh button repeats a request inside the memo window', async () => {+ const advanceClock = mockClock()+ const listSpy = jest+ .spyOn(api.recordings, 'list')+ .mockImplementation(+ () => Promise.resolve(listResponse as unknown) as ReturnType<typeof api.recordings.list>+ )++ const refreshLogic = sessionRecordingsPlaylistLogic({ logicKey: 'force-refresh-memo' })+ refreshLogic.mount()+ await expectLogic(refreshLogic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()+ listSpy.mockClear()++ advanceClock(LIST_MEMO_WINDOW_MS - 1)+ await expectLogic(refreshLogic, () => {+ refreshLogic.actions.loadAllRecordings()+ })+ .toDispatchActions(['loadSessionRecordingsSuccess'])+ .toFinishAllListeners()++ expect(listSpy).toHaveBeenCalledTimes(1)++ refreshLogic.unmount()+ })++ // An embedded playlist unmounts with its tab, so most repeats arrive on a fresh logic+ // instance. The memo has to outlive the one that issued the read.+ it('reads once when a remount inside the memo window repeats the request', async () => {+ const advanceClock = mockClock()+ const listSpy = jest+ .spyOn(api.recordings, 'list')+ .mockImplementation(+ () => Promise.resolve(listResponse as unknown) as ReturnType<typeof api.recordings.list>+ )++ const firstMount = sessionRecordingsPlaylistLogic({ logicKey: 'dedupe-remount' })+ firstMount.mount()+ await expectLogic(firstMount).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()+ firstMount.unmount()++ advanceClock(LIST_MEMO_WINDOW_MS - 1)+ const secondMount = sessionRecordingsPlaylistLogic({ logicKey: 'dedupe-remount' })+ secondMount.mount()+ await expectLogic(secondMount).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()++ expect(listSpy).toHaveBeenCalledTimes(1)+ expect(secondMount.values.sessionRecordings).toEqual([aRecording])++ secondMount.unmount()+ })++ it('reads again when a remount repeats a request the memo window no longer covers', async () => {+ const advanceClock = mockClock()+ const listSpy = jest+ .spyOn(api.recordings, 'list')+ .mockImplementation(+ () => Promise.resolve(listResponse as unknown) as ReturnType<typeof api.recordings.list>+ )++ const firstMount = sessionRecordingsPlaylistLogic({ logicKey: 'dedupe-remount-expired' })+ firstMount.mount()+ await expectLogic(firstMount).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()+ firstMount.unmount()++ advanceClock(LIST_MEMO_WINDOW_MS + 1)+ const secondMount = sessionRecordingsPlaylistLogic({ logicKey: 'dedupe-remount-expired' })+ secondMount.mount()+ await expectLogic(secondMount).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()++ expect(listSpy).toHaveBeenCalledTimes(2)++ secondMount.unmount()+ })++ it('reads again for a changed filter inside the memo window', async () => {+ const advanceClock = mockClock()+ const listSpy = jest+ .spyOn(api.recordings, 'list')+ .mockImplementation(+ () => Promise.resolve(listResponse as unknown) as ReturnType<typeof api.recordings.list>+ )++ const changedFilterLogic = sessionRecordingsPlaylistLogic({ logicKey: 'dedupe-memo-changed' })+ changedFilterLogic.mount()+ await expectLogic(changedFilterLogic)+ .toDispatchActions(['loadSessionRecordingsSuccess'])+ .toFinishAllListeners()+ listSpy.mockClear()++ advanceClock(LIST_MEMO_WINDOW_MS - 1)+ await expectLogic(changedFilterLogic, () => {+ changedFilterLogic.actions.setFilters({ filter_test_accounts: true })+ })+ .toDispatchActions(['loadSessionRecordingsSuccess'])+ .toFinishAllListeners()++ expect(listSpy).toHaveBeenCalledTimes(1)+ expect(listSpy).toHaveBeenCalledWith(expect.objectContaining({ filter_test_accounts: true }))++ changedFilterLogic.unmount()+ })})describe('convertUniversalFiltersToRecordingsQuery', () => {diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.tsindex f64dcf38ff14..a2651f42ea6b 100644--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts@@ -173,6 +173,39 @@ export const defaultRecordingDurationFilter: RecordingDurationFilter = {export const MAX_SELECTED_RECORDINGS = 20export const DELETE_CONFIRMATION_TEXT = 'delete'+// How long a landed list response answers a repeat of the same request. Two seconds is shorter+// than the gap the duplicates arrive in, and five seconds gives a person clicking around rows+// they would call stale, so three seconds covers the repeats and keeps the rows fresh.+export const LIST_MEMO_WINDOW_MS = 3000++/**+ * The list responses that landed inside `LIST_MEMO_WINDOW_MS`, keyed by team and request.+ *+ * This outlives the logic on purpose. An embedded playlist unmounts with the tab or the page that+ * holds it, so most repeats arrive on a fresh logic instance and a per-instance memo would miss+ * them. The team id is part of the key because the request parameters do not carry it, and a team+ * switch must never answer from another team's rows.+ */+const landedListResponses = new Map<string, { response: RecordingsQueryResponse; completedAt: number }>()++const memoizedListResponse = (memoKey: string): RecordingsQueryResponse | undefined => {+ const landed = landedListResponses.get(memoKey)+ return landed && performance.now() - landed.completedAt < LIST_MEMO_WINDOW_MS ? landed.response : undefined+}++const memoizeListResponse = (memoKey: string, response: RecordingsQueryResponse, completedAt: number): void => {+ // Drop what the window no longer covers, so a long session cannot grow the map.+ for (const [key, landed] of landedListResponses) {+ if (completedAt - landed.completedAt >= LIST_MEMO_WINDOW_MS) {+ landedListResponses.delete(key)+ }+ }+ landedListResponses.set(memoKey, { response, completedAt })+}++/** The memo outlives a kea context, so a test has to start from an empty one. */+export const clearMemoizedListResponses = (): void => landedListResponses.clear()+const getDefaultFilterTestAccounts = (): boolean => {const stored = localStorage.getItem('default_filter_test_accounts')return stored === 'true'@@ -479,7 +512,8 @@ export interface SessionRecordingPlaylistLogicProps {/*** The most recent recordings list request this logic issued. `promise` is dropped once the response* lands, so only a live request can be waited on, while `selectedRecordingId` outlives it and- * records which recording the server was already asked to include.+ * records which recording the server was already asked to include. What the request returned goes+ * to `landedListResponses` instead, which outlives the logic.*/interface IssuedListRequest {key: string@@ -489,6 +523,31 @@ interface IssuedListRequest {const isRelativeDate = (x: RecordingUniversalFilters['date_from']): boolean => !!x && x.startsWith('-')+/**+ * Filter keys a caller scopes the list with, so they never count as viewer edits. A saved filter set+ * carries `experiment_exposure` through a whole-object dispatch, and marking it would unscope the+ * experiment tab's list. `session_ids` is how that tab's watch cards scope the list, and the viewer+ * can clear them from the list header, so the same holds.+ */+const CALLER_OWNED_FILTER_KEYS: string[] = ['experiment_exposure', 'session_ids']++/** The filters state `setFilters` produces, so a caller can compare before it dispatches. */+const applyFilterUpdate = (+ state: RecordingUniversalFilters,+ update: Partial<RecordingUniversalFilters>,+ pinnedFilters?: UniversalFiltersGroup+): RecordingUniversalFilters => {+ const newState = {+ ...state,+ date_to: update.date_from && isRelativeDate(update.date_from) ? null : state.date_to,+ ...update,+ }+ if (pinnedFilters) {+ newState.filter_group = mergePinnedFilters(newState.filter_group, pinnedFilters)+ }+ return newState+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface sessionRecordingsPlaylistLogicValues {deletedRecordingIds: Set<string> // deletedRecordingsLogic@@ -539,6 +598,7 @@ export interface sessionRecordingsPlaylistLogicValues {showSettings: booleantotalFiltersCount: numberunusableEventsInFilter: string[]+ viewerFilterKeys: string[]visiblePinnedRecordings: SessionRecordingType[]}@@ -760,8 +820,12 @@ export interface sessionRecordingsPlaylistLogicActions {setDeleteConfirmationText: (deleteConfirmationText: string) => {deleteConfirmationText: string}- setFilters: (filters: Partial<RecordingUniversalFilters>) => {+ setFilters: (+ filters: Partial<RecordingUniversalFilters>,+ userModified?: boolean+ ) => {filters: Partial<RecordingUniversalFilters>+ userModified: boolean}setIsAddToCollectionModalOpen: (isAddToCollectionModalOpen: boolean) => {isAddToCollectionModalOpen: boolean@@ -902,7 +966,12 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic})),actions({- setFilters: (filters: Partial<RecordingUniversalFilters>) => ({ filters }),+ // `userModified` is false for filters that come from props rather than from the viewer,+ // so the load they trigger reports no filter edit.+ setFilters: (filters: Partial<RecordingUniversalFilters>, userModified: boolean = true) => ({+ filters,+ userModified,+ }),setShowFilters: (showFilters: boolean) => ({ showFilters }),setShowSettings: (showSettings: boolean) => ({ showSettings }),resetFilters: true,@@ -960,7 +1029,19 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogicactions.loadPinnedRecordings()}if (props.filters && !objectsEqual(props.filters, oldProps.filters)) {- actions.setFilters(props.filters)+ // A caller can recompute the whole object - the experiment tab does on every variant or+ // watch card - so dispatch only the keys whose value moved. The rest would overwrite a+ // viewer's own edit and take back their ownership of a key the caller never changed.+ const changedFilters = Object.fromEntries(+ Object.entries(props.filters).filter(+ ([filterKey, value]) =>+ !oldProps.filters ||+ !objectsEqual(value, oldProps.filters[filterKey as keyof RecordingUniversalFilters])+ )+ ) as Partial<RecordingUniversalFilters>+ if (Object.keys(changedFilters).length) {+ actions.setFilters(changedFilters, false)+ }}}),@@ -1047,22 +1128,28 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogicparams.after = undefined}- // Each list request is a full ClickHouse read, so two identical ones in flight- // read the same rows twice. The debounce below cannot prevent the second: it- // discards the earlier *result*, but a request already past it has reached the- // server, and cancellation does not reach the query layer. So a request that- // matches one in flight waits for that response instead of issuing its own.+ // Each list request is a full ClickHouse read, so two identical ones read the+ // same rows twice. The debounce below cannot prevent the second: it discards+ // the earlier *result*, but a request already past it has reached the server,+ // and cancellation does not reach the query layer. So a repeat waits for a+ // request this logic still has in flight, or answers from the response+ // `landedListResponses` holds for a few seconds after it landed.// The comparison ignores `user_modified_filters` because the server only feeds// it to an analytics event, so it does not change which rows are read.const requestKey = JSON.stringify({ ...params, user_modified_filters: undefined })+ const memoKey = `${getCurrentTeamId()}__${requestKey}`const lastRequest: IssuedListRequest | undefined = cache.listRequest+ // `forceRefetch` skips both paths, because the caller asks for fresh rows.+ const memoizedResponse = forceRefetch ? undefined : memoizedListResponse(memoKey)const requestInFlight =- !forceRefetch && lastRequest && lastRequest.key === requestKey ? lastRequest.promise : undefined+ !forceRefetch && lastRequest?.key === requestKey ? lastRequest.promise : undefinedlet response: RecordingsQueryResponse- if (requestInFlight) {- // This call issued no request, so it has no fetch to report. The call that- // did issue it reports the one read both calls answer from.+ // The first two branches issue no request, so they have no fetch to report.+ // The call that did issue it reports the one read they all answer from.+ if (memoizedResponse) {+ response = memoizedResponse+ } else if (requestInFlight) {response = await requestInFlight} else {await breakpoint(400) // Debounce for lots of quick filter changes@@ -1087,9 +1174,12 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogicthrow e}// The response is here, so nothing can wait on this request any more. The- // entry stays, because it records the recording the server was asked for.+ // entry stays, because it records the recording the server was asked for,+ // and the rows go to the memo a repeat answers from.+ const completedAt = performance.now()request.promise = undefined- const loadTimeMs = performance.now() - startTime+ memoizeListResponse(memoKey, response, completedAt)+ const loadTimeMs = completedAt - startTimeactions.reportRecordingsListFetched(loadTimeMs,@@ -1198,15 +1288,7 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogicreturn getDefaultFilters(props.personUUID, props.pinnedFilters)}- const newState = {- ...state,- date_to: filters.date_from && isRelativeDate(filters.date_from) ? null : state.date_to,- ...filters,- }- if (props.pinnedFilters) {- newState.filter_group = mergePinnedFilters(newState.filter_group, props.pinnedFilters)- }- return newState+ return applyFilterUpdate(state, filters, props.pinnedFilters)} catch (e) {posthog.captureException(e)return getDefaultFilters(props.personUUID, props.pinnedFilters)@@ -1215,6 +1297,31 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogicresetFilters: () => getDefaultFilters(props.personUUID, props.pinnedFilters),},],+ /**+ * The filter keys the viewer set themselves. The filter bar dispatches one narrow partial per+ * control, so the payload keys of a viewer-modified `setFilters` are the provenance. It+ * persists next to `filters` so a caller reapplying its own scope at mount leaves what the+ * viewer chose alone.+ */+ viewerFilterKeys: [+ [] as string[],+ { persist: true, prefix: `${getCurrentTeamId()}__${key}` },+ {+ setFilters: (state, { filters, userModified }) => {+ const keys = Object.keys(filters)+ if (!userModified) {+ // A caller writing a key takes it back, so a filter it now owns reapplies.+ const kept = state.filter((viewerKey) => !keys.includes(viewerKey))+ return kept.length === state.length ? state : kept+ }+ const added = keys.filter(+ (viewerKey) => !state.includes(viewerKey) && !CALLER_OWNED_FILTER_KEYS.includes(viewerKey)+ )+ return added.length ? [...state, ...added] : state+ },+ resetFilters: () => [],+ },+ ],showFilters: [true,{@@ -1395,7 +1502,8 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogicif (values.featureFlags[FEATURE_FLAGS.REPLAY_RECOMMENDED_RECORDINGS_FILTER_EXPERIMENT] === 'test') {actions.loadSessionRecordings()} else {- actions.setFilters({ recommended_only: false })+ // The flag decides this one, so it is not a viewer edit.+ actions.setFilters({ recommended_only: false }, false)}},loadAllRecordings: () => {@@ -1404,8 +1512,8 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogicactions.loadSessionRecordings(undefined, undefined, true)actions.loadPinnedRecordings()},- setFilters: ({ filters }) => {- actions.loadSessionRecordings(undefined, filters)+ setFilters: ({ filters, userModified }) => {+ actions.loadSessionRecordings(undefined, userModified ? filters : undefined)props.onFiltersChange?.(values.filters)actions.loadEventsHaveSessionId()},@@ -2190,20 +2298,25 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic}if (quickEventFilter || quickPersonFilter) {- actions.setFilters({- filter_group: {- type: FilterLogicalOperator.And,- values: [- {- type: FilterLogicalOperator.And,- values: [- ...(quickEventFilter ? [quickEventFilter] : []),- ...(quickPersonFilter ? [quickPersonFilter] : []),- ],- },- ],+ // A link carries these, not a control the viewer moved in this list, so they do not+ // become viewer keys. The URL keeps them for as long as it holds them.+ actions.setFilters(+ {+ filter_group: {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: FilterLogicalOperator.And,+ values: [+ ...(quickEventFilter ? [quickEventFilter] : []),+ ...(quickPersonFilter ? [quickPersonFilter] : []),+ ],+ },+ ],+ },},- })+ false+ )return}@@ -2224,7 +2337,9 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic}if (Object.keys(updatedFilters).length > 0) {- actions.setFilters({ ...values.filters, ...updatedFilters })+ // This payload carries the whole set, most of it from defaults rather than from+ // the URL, so it claims no viewer keys.+ actions.setFilters({ ...values.filters, ...updatedFilters }, false)}}}@@ -2252,15 +2367,8 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogicvalues.filters.recommended_only &&values.featureFlags[FEATURE_FLAGS.REPLAY_RECOMMENDED_RECORDINGS_FILTER_EXPERIMENT] !== 'test') {- actions.setFilters({ recommended_only: false })- }-- if (props.pinnedFilters) {- const merged = mergePinnedFilters(values.filters.filter_group, props.pinnedFilters)- if (!equal(merged, values.filters.filter_group)) {- actions.setFilters({ filter_group: merged })- return- }+ // The flag decides this one, so it is not a viewer edit.+ actions.setFilters({ recommended_only: false }, false)}// If updateSearchParams is enabled and URL has filters different from current state,@@ -2279,6 +2387,32 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic}}+ // A caller scopes the list with `props.filters`, pins filters into it with+ // `props.pinnedFilters`, or both. The filters reducer persists, so kea rehydrates the stored+ // value over `props.filters` and the first read would carry a filter set the caller never+ // asked for. Reapply what the caller owns in one dispatch, and let the `setFilters` listener+ // issue the one load. A key the viewer set themselves stays theirs, so a scoped list opens+ // scoped without dropping the range or the property they chose. This sits after the URL+ // branch, so a shared link still wins.+ if (props.filters || props.pinnedFilters) {+ const callerFilters: Partial<RecordingUniversalFilters> = { ...props.filters }+ for (const viewerKey of values.viewerFilterKeys) {+ delete callerFilters[viewerKey as keyof RecordingUniversalFilters]+ }+ if (props.pinnedFilters) {+ // Pinned filters are the caller's either way, so they merge over whichever group+ // survived above.+ callerFilters.filter_group = mergePinnedFilters(+ callerFilters.filter_group ?? values.filters.filter_group,+ props.pinnedFilters+ )+ }+ if (!equal(applyFilterUpdate(values.filters, callerFilters, props.pinnedFilters), values.filters)) {+ actions.setFilters(callerFilters, false)+ return+ }+ }+actions.loadSessionRecordings()}),])