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): stop the recordings list issuing duplicate requests (#96102)

Marcel Poelker6e74316644f2
diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
index 72c8b6c6bd3e..5f176793416c 100644
--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
@@ -1433,6 +1433,140 @@ describe('sessionRecordingsPlaylistLogic', () => {
})
})
+ describe('deduping identical list requests', () => {
+ const listResponse = { results: [aRecording], has_next: false }
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ // Two loads in one tick are collapsed by the 400ms `breakpoint` debounce, not by the
+ // 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 listSpy = jest
+ .spyOn(api.recordings, 'list')
+ .mockImplementation(
+ () => Promise.resolve(listResponse as unknown) as ReturnType<typeof api.recordings.list>
+ )
+
+ const sameTickLogic = sessionRecordingsPlaylistLogic({ logicKey: 'dedupe-same-tick' })
+ sameTickLogic.mount()
+
+ // let the load afterMount kicks off settle, so only the two below are counted
+ await expectLogic(sameTickLogic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()
+ listSpy.mockClear()
+
+ await expectLogic(sameTickLogic, () => {
+ sameTickLogic.actions.loadSessionRecordings()
+ sameTickLogic.actions.loadSessionRecordings()
+ })
+ .toDispatchActions(['loadSessionRecordingsSuccess'])
+ .toFinishAllListeners()
+
+ expect(listSpy).toHaveBeenCalledTimes(1)
+
+ sameTickLogic.unmount()
+ })
+
+ it('reads once when a load repeats one that is past the debounce and awaiting the response', async () => {
+ let resolveList: (value: unknown) => void = () => {}
+ const pendingList = new Promise((resolve) => {
+ resolveList = resolve
+ })
+ let markIssued: () => void = () => {}
+ const requestIssued = new Promise<void>((resolve) => {
+ markIssued = resolve
+ })
+ const listSpy = jest.spyOn(api.recordings, 'list').mockImplementation(() => {
+ markIssued()
+ return pendingList as ReturnType<typeof api.recordings.list>
+ })
+
+ const inFlightLogic = sessionRecordingsPlaylistLogic({ logicKey: 'dedupe-in-flight' })
+ inFlightLogic.mount()
+
+ // the load afterMount kicks off is now past the debounce and awaiting the response
+ await requestIssued
+
+ inFlightLogic.actions.loadSessionRecordings()
+ resolveList(listResponse)
+
+ await expectLogic(inFlightLogic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()
+
+ expect(listSpy).toHaveBeenCalledTimes(1)
+ expect(inFlightLogic.values.sessionRecordings).toEqual([aRecording])
+
+ inFlightLogic.unmount()
+ })
+
+ it('reads again when the refresh button repeats a request already in flight', async () => {
+ let resolveList: (value: unknown) => void = () => {}
+ const pendingList = new Promise((resolve) => {
+ resolveList = resolve
+ })
+ let markIssued: () => void = () => {}
+ const requestIssued = new Promise<void>((resolve) => {
+ markIssued = resolve
+ })
+ const listSpy = jest.spyOn(api.recordings, 'list').mockImplementation(() => {
+ markIssued()
+ return pendingList as ReturnType<typeof api.recordings.list>
+ })
+
+ const refreshLogic = sessionRecordingsPlaylistLogic({ logicKey: 'force-refresh' })
+ refreshLogic.mount()
+
+ // the load afterMount kicks off is now past the debounce and awaiting the response
+ await requestIssued
+
+ refreshLogic.actions.loadAllRecordings()
+ resolveList(listResponse)
+
+ await expectLogic(refreshLogic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()
+
+ expect(listSpy).toHaveBeenCalledTimes(2)
+
+ refreshLogic.unmount()
+ })
+
+ it('reads once for a selected recording the list does not hold', async () => {
+ const listSpy = jest
+ .spyOn(api.recordings, 'list')
+ .mockImplementation(
+ () =>
+ Promise.resolve({ results: [], has_next: false } as unknown) as ReturnType<
+ typeof api.recordings.list
+ >
+ )
+
+ const selectionLogic = sessionRecordingsPlaylistLogic({ logicKey: 'dedupe-selection' })
+ selectionLogic.mount()
+ await expectLogic(selectionLogic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()
+
+ // the list does not hold the selection, so the first pick asks the server to include it
+ await expectLogic(selectionLogic, () => {
+ selectionLogic.actions.setSelectedRecordingId('missing-recording')
+ })
+ .toDispatchActions(['loadSessionRecordings', 'loadSessionRecordingsSuccess'])
+ .toFinishAllListeners()
+ expect(listSpy).toHaveBeenLastCalledWith(
+ expect.objectContaining({ session_recording_id: 'missing-recording' })
+ )
+
+ listSpy.mockClear()
+
+ // that request answered without the recording, so picking it again reads nothing new
+ await expectLogic(selectionLogic, () => {
+ selectionLogic.actions.setSelectedRecordingId('missing-recording')
+ }).toFinishAllListeners()
+
+ expect(listSpy).not.toHaveBeenCalled()
+
+ selectionLogic.unmount()
+ })
+ })
+
describe('convertUniversalFiltersToRecordingsQuery', () => {
it('passes the visited_page filter as a recording property', () => {
const result = convertUniversalFiltersToRecordingsQuery({
diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts
index 85a3e16ab4dd..3d48fc144602 100644
--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts
+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts
@@ -479,6 +479,17 @@ export interface SessionRecordingPlaylistLogicProps {
onPinnedChange?: (recording: SessionRecordingType, pinned: boolean) => void
}
+/**
+ * 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.
+ */
+interface IssuedListRequest {
+ key: string
+ selectedRecordingId: RecordingsQuery['session_recording_id']
+ promise: Promise<RecordingsQueryResponse> | undefined
+}
+
const isRelativeDate = (x: RecordingUniversalFilters['date_from']): boolean => !!x && x.startsWith('-')
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -665,9 +676,11 @@ export interface sessionRecordingsPlaylistLogicActions {
}
loadSessionRecordings: (
direction?: 'newer' | 'older',
- userModifiedFilters?: Record<string, any>
+ userModifiedFilters?: Record<string, any>,
+ forceRefetch?: boolean
) => {
direction: 'newer' | 'older' | undefined
+ forceRefetch: boolean | undefined
userModifiedFilters: Record<string, any> | undefined
}
loadSessionRecordingsFailure: (
@@ -700,6 +713,7 @@ export interface sessionRecordingsPlaylistLogicActions {
},
payload?: {
direction: 'newer' | 'older' | undefined
+ forceRefetch: boolean | undefined
userModifiedFilters: Record<string, any> | undefined
}
) => {
@@ -725,6 +739,7 @@ export interface sessionRecordingsPlaylistLogicActions {
}
payload?: {
direction: 'newer' | 'older' | undefined
+ forceRefetch: boolean | undefined
userModifiedFilters: Record<string, any> | undefined
}
}
@@ -897,9 +912,15 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic
}),
loadAllRecordings: true,
loadPinnedRecordings: true,
- loadSessionRecordings: (direction?: 'newer' | 'older', userModifiedFilters?: Record<string, any>) => ({
+ loadSessionRecordings: (
+ direction?: 'newer' | 'older',
+ userModifiedFilters?: Record<string, any>,
+ /** Issue the request even when an identical one is already in flight. */
+ forceRefetch?: boolean
+ ) => ({
direction,
userModifiedFilters,
+ forceRefetch,
}),
maybeLoadSessionRecordings: (direction?: 'newer' | 'older') => ({ direction }),
loadNext: true,
@@ -936,7 +957,7 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic
}
}),
- loaders(({ props, values, actions }) => ({
+ loaders(({ props, values, actions, cache }) => ({
eventsHaveSessionId: [
{} as Record<string, boolean>,
{
@@ -970,7 +991,7 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic
order_direction: RecordingsQuery['order_direction']
},
{
- loadSessionRecordings: async ({ direction, userModifiedFilters }, breakpoint) => {
+ loadSessionRecordings: async ({ direction, userModifiedFilters, forceRefetch }, breakpoint) => {
// Captured before the awaits: `values` reads throw if this logic unmounts
// mid-flight, and the fetch report must carry the filters the request was
// built from, not whatever they are once the response lands.
@@ -1019,23 +1040,62 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic
params.after = undefined
}
- await breakpoint(400) // Debounce for lots of quick filter changes
+ // 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.
+ // 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 lastRequest: IssuedListRequest | undefined = cache.listRequest
+ const requestInFlight =
+ !forceRefetch && lastRequest && lastRequest.key === requestKey ? lastRequest.promise : undefined
+
+ let 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.
+ response = await requestInFlight
+ } else {
+ await breakpoint(400) // Debounce for lots of quick filter changes
- const startTime = performance.now()
- const response = await api.recordings.list(params)
- const loadTimeMs = performance.now() - startTime
+ const promise = api.recordings.list(params)
+ const request: IssuedListRequest = {
+ key: requestKey,
+ selectedRecordingId: params.session_recording_id,
+ promise,
+ }
+ cache.listRequest = request
- actions.reportRecordingsListFetched(
- loadTimeMs,
- filters,
- defaultRecordingDurationFilter,
- {
- resultCount: response.results.length,
- hasNext: response.has_next,
- isFirstPage: !direction,
- },
- props.analyticsSource
- )
+ const startTime = performance.now()
+ try {
+ response = await promise
+ } catch (e) {
+ // A read that failed says nothing about what the server holds, so drop
+ // the entry and let the next request for these parameters go out.
+ if (cache.listRequest === request) {
+ cache.listRequest = undefined
+ }
+ throw 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.
+ request.promise = undefined
+ const loadTimeMs = performance.now() - startTime
+
+ actions.reportRecordingsListFetched(
+ loadTimeMs,
+ filters,
+ defaultRecordingDurationFilter,
+ {
+ resultCount: response.results.length,
+ hasNext: response.has_next,
+ isFirstPage: !direction,
+ },
+ props.analyticsSource
+ )
+ }
// Must run after the fetch report (superseded and abandoned fetches still
// count toward load-time metrics) and before the `values` reads below
@@ -1322,7 +1382,9 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic
return {
loadAllRecordings: () => {
- actions.loadSessionRecordings()
+ // The manual refresh asks for fresh rows, so it re-reads even when an identical
+ // request is in flight.
+ actions.loadSessionRecordings(undefined, undefined, true)
actions.loadPinnedRecordings()
},
setFilters: ({ filters }) => {
@@ -1547,9 +1609,16 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic
const recordingIndex = values.sessionRecordings.findIndex((s) => s.id === values.selectedRecordingId)
- // If recording not found in current list, reload with the new selected recording
- // The backend will automatically include it via session_recording_id parameter
- if (recordingIndex === -1 && values.selectedRecordingId) {
+ // A recording the list does not hold needs a request carrying session_recording_id,
+ // which makes the server include it. Once a request asked for this recording, a
+ // second one reads the whole first page again and adds nothing: that request is
+ // either still in flight, or it already answered without the recording.
+ const lastRequest: IssuedListRequest | undefined = cache.listRequest
+ if (
+ recordingIndex === -1 &&
+ values.selectedRecordingId &&
+ lastRequest?.selectedRecordingId !== values.selectedRecordingId
+ ) {
actions.loadSessionRecordings()
}
@@ -1713,7 +1782,9 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic
if (shortId) {
handleLoadCollectionRecordings(shortId)
} else {
- actions.loadSessionRecordings()
+ // The request parameters do not change here, but the rows the server
+ // returns do, so re-read even when an identical request is in flight.
+ actions.loadSessionRecordings(undefined, undefined, true)
}
} catch (e) {
posthog.captureException(e)
@@ -1741,7 +1812,9 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic
if (shortId) {
handleLoadCollectionRecordings(shortId)
} else {
- actions.loadSessionRecordings()
+ // The request parameters do not change here, but the rows the server
+ // returns do, so re-read even when an identical request is in flight.
+ actions.loadSessionRecordings(undefined, undefined, true)
}
} catch (e) {
posthog.captureException(e)