: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): clamp seeks to the first renderable position when a full snapshot is missing (#62709)
Tue Haulundbca3e394be66
diff --git a/common/replay-shared/src/index.ts b/common/replay-shared/src/index.tsindex c00ed4653b0c..fd8d06141533 100644--- a/common/replay-shared/src/index.ts+++ b/common/replay-shared/src/index.ts@@ -44,7 +44,7 @@ export { createSegments, mergeInactiveSegments, mapSnapshotsToWindowId } from '.// snapshot storeexport { SnapshotStore } from './snapshot-store/SnapshotStore'-export type { SourceEntry, LoadBatch, SourceLoadingState, Mode } from './snapshot-store/types'+export type { SourceEntry, LoadBatch, SourceLoadingState, Mode, FullSnapshotRef } from './snapshot-store/types'// canvas replayexport type { CanvasPluginErrorHandler } from './canvas/canvas-plugin'diff --git a/common/replay-shared/src/snapshot-store/SnapshotStore.ts b/common/replay-shared/src/snapshot-store/SnapshotStore.tsindex c985f358ba05..ba10385f17b3 100644--- a/common/replay-shared/src/snapshot-store/SnapshotStore.ts+++ b/common/replay-shared/src/snapshot-store/SnapshotStore.ts@@ -1,7 +1,7 @@import { EventType, eventWithTime } from 'posthog-js/rrweb-types'import { RecordingSnapshot, SessionRecordingSnapshotSource } from '../types'-import { SourceEntry, SourceLoadingState } from './types'+import { FullSnapshotRef, SourceEntry, SourceLoadingState } from './types'export class SnapshotStore {private entries: SourceEntry[] = []@@ -32,7 +32,7 @@ export class SnapshotStore {index,state: 'unloaded' as const,processedSnapshots: null,- fullSnapshotTimestamps: [],+ fullSnapshots: [],metaTimestamps: [],startMs: source.start_timestamp ? new Date(source.start_timestamp).getTime() : 0,endMs: source.end_timestamp ? new Date(source.end_timestamp).getTime() : 0,@@ -61,11 +61,11 @@ export class SnapshotStore {processedSnapshots.sort((a, b) => a.timestamp - b.timestamp)- const fullSnapshotTimestamps: number[] = []+ const fullSnapshots: FullSnapshotRef[] = []const metaTimestamps: number[] = []for (const snap of processedSnapshots) {if (snap.type === EventType.FullSnapshot) {- fullSnapshotTimestamps.push(snap.timestamp)+ fullSnapshots.push({ timestamp: snap.timestamp, windowId: snap.windowId })}if (snap.type === EventType.Meta) {metaTimestamps.push(snap.timestamp)@@ -74,7 +74,7 @@ export class SnapshotStore {entry.state = 'loaded'entry.processedSnapshots = processedSnapshots- entry.fullSnapshotTimestamps = fullSnapshotTimestamps+ entry.fullSnapshots = fullSnapshotsentry.metaTimestamps = metaTimestampsthis.bump()}@@ -138,7 +138,7 @@ export class SnapshotStore {return Math.max(0, this.entries.length - 1)}- canPlayAt(ts: number): boolean {+ canPlayAt(ts: number, windowId?: number): boolean {if (this.entries.length === 0) {return false}@@ -147,7 +147,7 @@ export class SnapshotStore {return false}- const fullSnapshotInfo = this.findNearestFullSnapshot(ts)+ const fullSnapshotInfo = this.findNearestFullSnapshot(ts, windowId)if (!fullSnapshotInfo) {return false}@@ -165,14 +165,23 @@ export class SnapshotStore {return true}- findNearestFullSnapshot(ts: number): { sourceIndex: number; timestamp: number } | null {+ /**+ * Returns the latest loaded FullSnapshot at or before `ts`, or null if none.+ * When `windowId` is given, only FullSnapshots captured in that window count —+ * rrweb renders one window at a time, so another window's FullSnapshot cannot+ * make this window's events renderable.+ */+ findNearestFullSnapshot(ts: number, windowId?: number): { sourceIndex: number; timestamp: number } | null {let bestTs = -1let bestSourceIndex = -1for (const entry of this.entries) {- for (const fullTs of entry.fullSnapshotTimestamps) {- if (fullTs <= ts && fullTs > bestTs) {- bestTs = fullTs+ for (const fullSnapshot of entry.fullSnapshots) {+ if (windowId !== undefined && fullSnapshot.windowId !== windowId) {+ continue+ }+ if (fullSnapshot.timestamp <= ts && fullSnapshot.timestamp > bestTs) {+ bestTs = fullSnapshot.timestampbestSourceIndex = entry.index}}@@ -184,29 +193,50 @@ export class SnapshotStore {return { sourceIndex: bestSourceIndex, timestamp: bestTs }}+ /**+ * Returns all loaded FullSnapshots at or after `ts`, sorted by timestamp.+ * Used to recover playback when the data before `ts` has no FullSnapshot to+ * render from (e.g. the initial full snapshot was lost at capture time).+ */+ fullSnapshotsAfter(ts: number): (FullSnapshotRef & { sourceIndex: number })[] {+ const result: (FullSnapshotRef & { sourceIndex: number })[] = []+ for (const entry of this.entries) {+ for (const fullSnapshot of entry.fullSnapshots) {+ if (fullSnapshot.timestamp >= ts) {+ result.push({ ...fullSnapshot, sourceIndex: entry.index })+ }+ }+ }+ return result.sort((a, b) => a.timestamp - b.timestamp)+ }+syncFullSnapshotTimestamps(processedSnapshots: RecordingSnapshot[]): boolean {let changed = falsefor (const entry of this.entries) {if (entry.state !== 'loaded') {continue}- const timestamps: number[] = []+ const fullSnapshots: FullSnapshotRef[] = []for (const snap of processedSnapshots) {if (snap.type === EventType.FullSnapshot &&snap.timestamp >= entry.startMs &&snap.timestamp <= entry.endMs) {- timestamps.push(snap.timestamp)+ fullSnapshots.push({ timestamp: snap.timestamp, windowId: snap.windowId })}}- timestamps.sort((a, b) => a - b)+ fullSnapshots.sort((a, b) => a.timestamp - b.timestamp)if (- timestamps.length > 0 &&- (timestamps.length !== entry.fullSnapshotTimestamps.length ||- timestamps.some((t, j) => t !== entry.fullSnapshotTimestamps[j]))+ fullSnapshots.length > 0 &&+ (fullSnapshots.length !== entry.fullSnapshots.length ||+ fullSnapshots.some(+ (fs, j) =>+ fs.timestamp !== entry.fullSnapshots[j].timestamp ||+ fs.windowId !== entry.fullSnapshots[j].windowId+ ))) {- entry.fullSnapshotTimestamps = timestamps+ entry.fullSnapshots = fullSnapshotschanged = true}}diff --git a/common/replay-shared/src/snapshot-store/types.ts b/common/replay-shared/src/snapshot-store/types.tsindex 204f5c1c6c00..3cc7a6d1a9ea 100644--- a/common/replay-shared/src/snapshot-store/types.ts+++ b/common/replay-shared/src/snapshot-store/types.ts@@ -1,11 +1,16 @@import { RecordingSnapshot, SessionRecordingSnapshotSource } from '../types'+export interface FullSnapshotRef {+ timestamp: number+ windowId: number+}+export interface SourceEntry {source: SessionRecordingSnapshotSourceindex: numberstate: 'unloaded' | 'loaded'processedSnapshots: RecordingSnapshot[] | null- fullSnapshotTimestamps: number[]+ fullSnapshots: FullSnapshotRef[]metaTimestamps: number[]startMs: numberendMs: number@@ -13,7 +18,7 @@ export interface SourceEntry {export interface LoadBatch {sourceIndices: number[]- reason: 'seek_target' | 'seek_backward' | 'seek_gap_fill' | 'buffer_ahead' | 'load_all'+ reason: 'seek_target' | 'seek_backward' | 'seek_gap_fill' | 'seek_forward' | 'buffer_ahead' | 'load_all'}export interface SourceLoadingState {@@ -22,4 +27,7 @@ export interface SourceLoadingState {state: 'unloaded' | 'loaded'}-export type Mode = { kind: 'buffer_ahead' } | { kind: 'seek'; targetTimestamp: number } | { kind: 'load_all' }+export type Mode =+ | { kind: 'buffer_ahead' }+ | { kind: 'seek'; targetTimestamp: number; targetWindowId?: number }+ | { kind: 'load_all' }diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.tsindex d8367408881a..99bffeb4823d 100644--- a/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.ts+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.ts@@ -235,7 +235,7 @@ export const sessionRecordingDataCoordinatorLogic = kea<sessionRecordingDataCoor}// Release raw snapshot arrays from the store — only the metadata- // (fullSnapshotTimestamps, metaTimestamps, state) is still needed.+ // (fullSnapshots, metaTimestamps, state) is still needed.values.snapshotStore.clearSnapshotData()actions.setProcessedSnapshots(result)@@ -413,12 +413,12 @@ export const sessionRecordingDataCoordinatorLogic = kea<sessionRecordingDataCoorreturn false}- const anyWindowMissingFullSnapshot = !Object.values(windowsHaveFullSnapshot).some((x) => x)- const everyWindowMissingFullSnapshot = !Object.values(windowsHaveFullSnapshot).every((x) => x)+ const noWindowHasFullSnapshot = !Object.values(windowsHaveFullSnapshot).some((x) => x)+ const someWindowMissingFullSnapshot = !Object.values(windowsHaveFullSnapshot).every((x) => x)const recordingAgeMs = now().diff(start, 'millisecond')- if (everyWindowMissingFullSnapshot) {+ if (noWindowHasFullSnapshot) {// video is definitely unplayableposthog.capture('recording_has_no_full_snapshot', {watchedSession: sessionRecordingId,@@ -426,7 +426,7 @@ export const sessionRecordingDataCoordinatorLogic = kea<sessionRecordingDataCoorteamName: currentTeam?.name,recordingAgeMs,})- } else if (anyWindowMissingFullSnapshot) {+ } else if (someWindowMissingFullSnapshot) {posthog.capture('recording_window_missing_full_snapshot', {watchedSession: sessionRecordingId,teamID: currentTeam?.id,@@ -435,7 +435,7 @@ export const sessionRecordingDataCoordinatorLogic = kea<sessionRecordingDataCoor})}- return everyWindowMissingFullSnapshot+ return noWindowHasFullSnapshot},],diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.test.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.test.tsindex ba1510e34aed..283e99ea2016 100644--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.test.ts+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.test.ts@@ -14,7 +14,7 @@ import { makeLogger } from 'scenes/session-recordings/player/utils/player-logginimport { urls } from 'scenes/urls'import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'-import { ExporterFormat, RecordingSegment } from '~/types'+import { ExporterFormat, RecordingSegment, RecordingSnapshot } from '~/types'import { deletedRecordingsLogic } from '../deletedRecordingsLogic'import { sessionRecordingEventUsageLogic } from '../sessionRecordingEventUsageLogic'@@ -411,6 +411,157 @@ describe('sessionRecordingPlayerLogic', () => {})})+ describe('seek renderability clamping', () => {+ // Mock recording meta: start=1682952380877+ const START = 1682952380877+ const LATE_FS_TS = START + 300000++ // Fresh blob keys ('8'/'9') — re-using the default mocks' key '0' would make+ // setSources silently inherit the entry already loaded from the mocks instead+ // of the snapshots seeded here+ const SOURCE_A = {+ source: 'blob_v2',+ blob_key: '8',+ start_timestamp: new Date(START).toISOString(),+ end_timestamp: new Date(START + 60000).toISOString(),+ }+ const SOURCE_B = {+ source: 'blob_v2',+ blob_key: '9',+ start_timestamp: new Date(START + 60000).toISOString(),+ end_timestamp: new Date(LATE_FS_TS + 60000).toISOString(),+ }++ const makeSnapshot = (timestamp: number, type: EventType): RecordingSnapshot =>+ ({ timestamp, type, windowId: 1, data: {} }) as unknown as RecordingSnapshot++ const inc = (timestamp: number): RecordingSnapshot => makeSnapshot(timestamp, EventType.IncrementalSnapshot)+ const fs = (timestamp: number): RecordingSnapshot => makeSnapshot(timestamp, EventType.FullSnapshot)++ // Seeds the snapshot store and the coordinator's processed snapshots (which+ // segments derive from) directly, bypassing the network loading machinery.+ // Passing null leaves that source unloaded.+ const seedRecording = (+ firstSourceSnapshots: RecordingSnapshot[] | null,+ secondSourceSnapshots: RecordingSnapshot[]+ ): void => {+ const dataLogic = snapshotDataLogic({ sessionRecordingId: '2' })+ dataLogic.actions.loadSnapshotSourcesSuccess([SOURCE_A, SOURCE_B] as any)+ const store = dataLogic.cache.store+ const processed: RecordingSnapshot[] = []+ if (firstSourceSnapshots) {+ store.markLoaded(0, firstSourceSnapshots)+ processed.push(...firstSourceSnapshots)+ }+ store.markLoaded(1, secondSourceSnapshots)+ processed.push(...secondSourceSnapshots)+ dataLogic.actions.storeUpdated()+ sessionRecordingDataCoordinatorLogic({ sessionRecordingId: '2' }).actions.setProcessedSnapshots(processed)+ }++ beforeEach(async () => {+ await expectLogic(logic)+ .toDispatchActions([snapshotDataLogic({ sessionRecordingId: '2' }).actionTypes.loadSnapshotSources])+ .toFinishAllListeners()+ })++ // assertions below run synchronously after the seek dispatch — kea listeners+ // run synchronously up to their first await, and draining listeners instead+ // would let the animation loop advance the playhead past the asserted value++ it.each([+ {+ description: 'clamps a seek into a dead zone forward to the next full snapshot',+ firstSourceSnapshots: [inc(START), inc(START + 1000)],+ secondSourceSnapshots: [fs(LATE_FS_TS)],+ seekTo: START + 1000,+ expectedTimestamp: LATE_FS_TS,+ expectedError: null,+ expectsClampEvent: true,+ },+ {+ // the seek target lies beyond the first source, so the scheduler enters+ // seek mode — the unplayable verdict must still win over buffering+ description: 'errors when fully loaded and no full snapshot exists anywhere',+ firstSourceSnapshots: [inc(START), inc(START + 1000)],+ secondSourceSnapshots: [inc(START + 61000), inc(START + 62000)],+ seekTo: START + 61500,+ expectedTimestamp: START + 61500,+ expectedError: 'noPlayableFullSnapshot',+ expectsClampEvent: false,+ },+ {+ description: 'does not interfere when a full snapshot exists before the seek position',+ firstSourceSnapshots: [fs(START), inc(START + 1000)],+ secondSourceSnapshots: [inc(LATE_FS_TS)],+ seekTo: START + 1000,+ expectedTimestamp: START + 1000,+ expectedError: null,+ expectsClampEvent: false,+ },+ ])(+ '$description',+ ({+ firstSourceSnapshots,+ secondSourceSnapshots,+ seekTo,+ expectedTimestamp,+ expectedError,+ expectsClampEvent,+ }) => {+ seedRecording(firstSourceSnapshots, secondSourceSnapshots)+ const captureSpy = jest.spyOn(posthog, 'capture')+ captureSpy.mockClear()+ logic.actions.setPause()++ logic.actions.seekToTimestamp(seekTo)++ expect(logic.values.currentTimestamp).toBe(expectedTimestamp)+ expect(logic.values.playerError).toBe(expectedError)+ const clampCalls = captureSpy.mock.calls.filter(+ ([eventName]) => eventName === 'recording player seek clamped to next full snapshot'+ )+ expect(clampCalls).toHaveLength(expectsClampEvent ? 1 : 0)+ if (expectsClampEvent) {+ expect(clampCalls[0][1]).toMatchObject({+ seekTimestamp: seekTo,+ clampedToTimestamp: expectedTimestamp,+ })+ }+ }+ )++ it('does not clamp or capture when a null currentTimestamp is forwarded during player init', () => {+ // Some callers (e.g. the setPlayer listener) forward currentTimestamp+ // while it still holds its initial null — that must not be coerced to 0+ // and clamped to the FullSnapshot with telemetry on every player init+ seedRecording([inc(START), inc(START + 1000)], [fs(LATE_FS_TS)])+ const captureSpy = jest.spyOn(posthog, 'capture')+ captureSpy.mockClear()++ logic.actions.seekToTimestamp(null as unknown as number)++ const clampCalls = captureSpy.mock.calls.filter(+ ([eventName]) => eventName === 'recording player seek clamped to next full snapshot'+ )+ expect(clampCalls).toHaveLength(0)+ expect(logic.values.currentTimestamp).not.toBe(LATE_FS_TS)+ })++ it('buffers while earlier data that could contain a full snapshot is still loading', () => {+ // The first source is unloaded — it could still contain the window's+ // FullSnapshot, so a seek into the second source's FullSnapshot-less data+ // must buffer, not clamp+ seedRecording(null, [inc(START + 61000), inc(START + 62000)])++ logic.actions.seekToTimestamp(START + 61500)++ expect(logic.values.isBuffering).toBe(true)+ expect(logic.values.playerError).toBeNull()+ expect(logic.values.currentTimestamp).toBe(START + 61500)+ })+ })+describe('delete session recording', () => {const mockedDeleteRecording = deleteRecordingMock as jest.MockedFunction<typeof deleteRecordingMock>diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.tsindex 9ec7b098e297..135c3ba175ac 100644--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts@@ -26,6 +26,7 @@ import {COMMON_REPLAYER_CONFIG,CanvasReplayerPlugin,CorsPlugin,+ SnapshotStore,createHLSPlayerPlugin,} from '@posthog/replay-shared'@@ -143,6 +144,25 @@ export interface SessionRecordingPlayerLogicProps extends SessionRecordingDataCoconst ReplayIframeDatakeyPrefix = 'ph_replay_fixed_heatmap_'+// Positions less than this far before the next FullSnapshot are treated as+// renderable: recordings routinely start a few ms before their first+// FullSnapshot (the recording start is min(event start, snapshot start)) and+// rrweb handles that fine — clamping would only add telemetry noise and an+// extra seek on nearly every playback.+const MIN_CLAMPABLE_DEAD_ZONE_MS = 1000++export type SeekRenderability =+ // a FullSnapshot exists at or before the timestamp for its window+ | { kind: 'renderable' }+ // no FullSnapshot exists at or before the timestamp — the earliest recoverable+ // position is this later FullSnapshot+ | { kind: 'clampToFullSnapshot'; timestamp: number }+ // not determinable yet — data that could contain a FullSnapshot is still loading+ | { kind: 'waitingForData' }+ // everything is loaded and no FullSnapshot exists anywhere at or after the+ // timestamp — playback there can never work+ | { kind: 'unplayable' }+// weights should add up to 1const smoothingWeights = [0.07,@@ -475,7 +495,14 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(connect((props: SessionRecordingPlayerLogicProps) => ({values: [snapshotDataLogic(props),- ['snapshotsLoaded', 'snapshotsLoading', 'snapshotSources', 'isWaitingForPlayableFullSnapshot'],+ [+ 'snapshotsLoaded',+ 'snapshotsLoading',+ 'snapshotSources',+ 'isWaitingForPlayableFullSnapshot',+ 'snapshotStore',+ 'allSourcesLoaded',+ ],sessionRecordingDataCoordinatorLogic(props),['urls',@@ -1056,6 +1083,53 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(},],+ // rrweb can only render from a FullSnapshot at or before the playhead, in the+ // same window. This resolves whether a timestamp is renderable and, if not,+ // how playback can recover (e.g. when the initial full snapshot was lost at+ // capture time, the recording is only playable from a later FullSnapshot).+ seekRenderability: [+ (s) => [s.segmentForTimestamp, s.snapshotStore, s.allSourcesLoaded],+ (+ segmentForTimestamp: (timestamp?: number) => RecordingSegment | null,+ snapshotStore: SnapshotStore,+ allSourcesLoaded: boolean+ ) => {+ return (timestamp: number): SeekRenderability => {+ const segment = segmentForTimestamp(timestamp)+ if (segment?.kind !== 'window' || segment.windowId === undefined) {+ // gap and buffer segments are handled by the existing buffering machinery+ return { kind: 'renderable' }+ }+ if (snapshotStore.findNearestFullSnapshot(timestamp, segment.windowId)) {+ return { kind: 'renderable' }+ }+ // The window has no FullSnapshot at or before this position. That is+ // only definitive once everything before the position has loaded — an+ // earlier unloaded source could still contain one.+ const targetIndex = snapshotStore.getSourceIndexForTimestamp(timestamp)+ if (targetIndex === null) {+ // no sources yet — initial load paths handle this+ return { kind: 'renderable' }+ }+ if (snapshotStore.getUnloadedIndicesInRange(0, targetIndex).length > 0) {+ return { kind: 'waitingForData' }+ }+ // Recover at the first later FullSnapshot that can render the segment+ // it lands in. A FullSnapshot whose landing segment belongs to another+ // window is no use — seeking there would be just as unrenderable.+ const recoveryTarget = snapshotStore+ .fullSnapshotsAfter(timestamp)+ .find((fs) => segmentForTimestamp(fs.timestamp)?.windowId === fs.windowId)+ if (recoveryTarget) {+ return recoveryTarget.timestamp - timestamp < MIN_CLAMPABLE_DEAD_ZONE_MS+ ? { kind: 'renderable' }+ : { kind: 'clampToFullSnapshot', timestamp: recoveryTarget.timestamp }+ }+ return allSourcesLoaded ? { kind: 'unplayable' } : { kind: 'waitingForData' }+ }+ },+ ],+debugSnapshots: [(s) => [s.sessionPlayerData, s.debugSettings],(sessionPlayerData: SessionPlayerData, debugSettings): eventWithTime[] => {@@ -1493,14 +1567,29 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(values.player?.replayer?.setConfig({ speed: values.playerSpeed })},checkBufferingCompleted: () => {- // If buffering has completed, resume last playing state- if (values.currentTimestamp === undefined) {+ // If buffering has completed, resume last playing state.+ // Gates on the raw isBuffering reducer rather than currentPlayerState ===+ // BUFFER — other states (e.g. SKIP while skipping inactivity) outrank+ // BUFFER in that selector and would otherwise mask the exit forever.+ // == null also catches the null that currentTimestamp holds before+ // playback initializes — seeking to it would derail the initial load+ if (values.currentTimestamp == null || !values.isBuffering) {return}const isBufferingSegment = values.segmentForTimestamp(values.currentTimestamp)?.kind === 'buffer'- const isBuffering = isBufferingSegment || values.isWaitingForPlayableFullSnapshot-- if (values.currentPlayerState === SessionPlayerState.BUFFER && !isBuffering) {+ const renderability = values.seekRenderability(values.currentTimestamp)+ // A definitive verdict ends buffering even while the scheduler is still in+ // seek mode for this position — the re-seek below clamps forward to the+ // next FullSnapshot or errors if the position can never play+ const hasDefinitiveVerdict =+ renderability.kind === 'clampToFullSnapshot' || renderability.kind === 'unplayable'+ const stillBuffering =+ !hasDefinitiveVerdict &&+ (isBufferingSegment ||+ values.isWaitingForPlayableFullSnapshot ||+ renderability.kind === 'waitingForData')++ if (!stillBuffering) {actions.endBuffer()actions.seekToTimestamp(values.currentTimestamp, values.playingState === SessionPlayerState.PLAY)}@@ -1690,16 +1779,37 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(}},seekToTimestamp: ({ timestamp, forcePlay }, breakpoint) => {+ // If the data before `timestamp` definitively has no FullSnapshot to render+ // from (e.g. the initial full snapshot was lost at capture time), clamp the+ // seek forward to the first renderable position instead of letting the+ // player get stuck on an unrenderable frame.+ // Despite the action's typing, some callers forward currentTimestamp while+ // it still holds its initial null — seekRenderability would coerce that to+ // 0 and clamp every normal recording to its first FullSnapshot, firing+ // spurious telemetry on every player init.+ const renderability: SeekRenderability =+ timestamp == null ? { kind: 'renderable' } : values.seekRenderability(timestamp)+ if (renderability.kind === 'clampToFullSnapshot' && renderability.timestamp !== timestamp) {+ posthog.capture('recording player seek clamped to next full snapshot', {+ sessionId: values.sessionRecordingId,+ seekTimestamp: timestamp,+ clampedToTimestamp: renderability.timestamp,+ })+ actions.seekToTimestamp(renderability.timestamp, forcePlay)+ return+ }+actions.stopAnimation()actions.pauseIframePlayback()cache.pausedMediaElements = []- actions.setCurrentTimestamp(timestamp)- actions.setTargetTimestamp(timestamp)// Check if we're seeking to a new segmentconst segment = values.segmentForTimestamp(timestamp)+ actions.setCurrentTimestamp(timestamp)+ actions.setTargetTimestamp(timestamp, segment?.kind === 'window' ? segment.windowId : undefined)+// End-of-recording detection — independent of segment type so that// findSegmentForTimestamp can safely return a real segment for// past-end timestamps (needed for the image exporter to boot the@@ -1718,8 +1828,24 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(actions.setCurrentSegment(segment)}- // If next time is greater than last buffered time, set to buffering- else if (segment?.kind === 'buffer' || values.isWaitingForPlayableFullSnapshot) {+ // Everything is loaded and there is no FullSnapshot that could render this+ // position — playback here can never work, so buffering would be pointless.+ // Checked before the buffering branch: the scheduler may still be in seek+ // mode for this very target (making isWaitingForPlayableFullSnapshot true),+ // but no amount of loading changes a definitive verdict.+ else if (renderability.kind === 'unplayable') {+ values.player?.replayer?.pause()+ actions.setPlayerError('noPlayableFullSnapshot')+ }++ // If next time is greater than last buffered time, set to buffering.+ // Also buffer while we can't yet tell whether this position has a+ // FullSnapshot to render from — playing would freeze on a blank frame.+ else if (+ segment?.kind === 'buffer' ||+ values.isWaitingForPlayableFullSnapshot ||+ renderability.kind === 'waitingForData'+ ) {values.player?.replayer?.pause()actions.startBuffer()actions.clearPlayerError()@@ -1943,7 +2069,10 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(// Throttled position update for loading scheduler (every 5s)if (shouldUpdatePlaybackPosition(newTimestamp, cache.lastPlaybackPositionUpdate)) {cache.lastPlaybackPositionUpdate = newTimestamp- actions.updatePlaybackPosition(newTimestamp)+ actions.updatePlaybackPosition(+ newTimestamp,+ values.currentSegment?.kind === 'window' ? values.currentSegment.windowId : undefined+ )}cache.disposables.add(() => {diff --git a/frontend/src/scenes/session-recordings/player/snapshot-store/LoadingScheduler.test.ts b/frontend/src/scenes/session-recordings/player/snapshot-store/LoadingScheduler.test.tsindex 53c9a8ce72f2..788e81c690dc 100644--- a/frontend/src/scenes/session-recordings/player/snapshot-store/LoadingScheduler.test.ts+++ b/frontend/src/scenes/session-recordings/player/snapshot-store/LoadingScheduler.test.ts@@ -118,6 +118,42 @@ describe('LoadingScheduler', () => {expect(maxIdx).toBe(29)})+ it('scans forward beyond the buffer window when nothing renderable is known', () => {+ // Playhead at the start, buffer window fully loaded, but no FullSnapshot+ // anywhere — e.g. the initial full snapshot was lost at capture time+ const loaded = Array.from({ length: 30 }, (_, i) => i)+ const store = createLoadedStore(50, loaded, [])+ const scheduler = new LoadingScheduler()++ const batch = scheduler.getNextBatch(store, 10, tsForMinute(0))+ expect(batch?.reason).toBe('seek_forward')+ expect(batch?.sourceIndices).toEqual([30, 31, 32, 33, 34, 35, 36, 37, 38, 39])+ })++ it('does not scan beyond the buffer window when the playhead is renderable', () => {+ const loaded = Array.from({ length: 30 }, (_, i) => i)+ const store = createLoadedStore(50, loaded, [0])+ const scheduler = new LoadingScheduler()++ expect(scheduler.getNextBatch(store, 10, tsForMinute(0))).toBeNull()+ })++ it('scans forward when the playhead window has no FullSnapshot even though another window does', () => {+ // The FullSnapshot at source 0 belongs to window 2 — it can't render+ // window-1 content at the playhead, so the scan must still fire+ const store = new SnapshotStore()+ store.setSources(makeSources(50))+ for (let i = 0; i < 30; i++) {+ const ts = tsForMinute(i)+ store.markLoaded(i, i === 0 ? [makeFullSnapshot(ts, 2), makeSnapshot(ts + 100)] : [makeSnapshot(ts)])+ }+ const scheduler = new LoadingScheduler()++ const batch = scheduler.getNextBatch(store, 10, tsForMinute(0), 1)+ expect(batch?.reason).toBe('seek_forward')+ expect(batch?.sourceIndices).toEqual([30, 31, 32, 33, 34, 35, 36, 37, 38, 39])+ })+it('does not load backward from playback position', () => {// Sources 0-9 unloaded, 10-19 loadedconst store = createLoadedStore(@@ -225,6 +261,74 @@ describe('LoadingScheduler', () => {expect(scheduler.currentMode).toEqual({ kind: 'buffer_ahead' })expect(batch).toBeNull()})++ it('searches forward when no FullSnapshot exists at or before the target', () => {+ // Everything up to source 17 loaded without any FullSnapshot, 18-19 unloaded+ const loaded = Array.from({ length: 18 }, (_, i) => i)+ const store = createLoadedStore(20, loaded, [])+ const scheduler = new LoadingScheduler()+ scheduler.seekTo(tsForMinute(10))++ const batch = scheduler.getNextBatch(store, 10)+ expect(batch?.reason).toBe('seek_forward')+ expect(batch?.sourceIndices).toEqual([18, 19])+ expect(scheduler.isSeeking).toBe(true)+ })++ it('stops searching forward once a later FullSnapshot is known', () => {+ // No FullSnapshot before the target, but one is loaded at source 18+ const allIndices = Array.from({ length: 20 }, (_, i) => i)+ const store = createLoadedStore(20, allIndices, [18])+ const scheduler = new LoadingScheduler()+ scheduler.seekTo(tsForMinute(10))++ // The player recovers by clamping the seek to the later FullSnapshot,+ // so the scheduler gives up this seek instead of loading more+ const batch = scheduler.getNextBatch(store, 10)+ expect(scheduler.currentMode).toEqual({ kind: 'buffer_ahead' })+ expect(batch).toBeNull()+ })++ it('keeps searching forward when the only later FullSnapshot belongs to another window', () => {+ // Sources 0-18 loaded; the FullSnapshot at source 18 belongs to window 2,+ // which can't render a window-1 target — source 19 must still be scanned+ const store = new SnapshotStore()+ store.setSources(makeSources(20))+ for (let i = 0; i < 19; i++) {+ const ts = tsForMinute(i)+ store.markLoaded(i, i === 18 ? [makeFullSnapshot(ts, 2), makeSnapshot(ts + 100)] : [makeSnapshot(ts)])+ }+ const scheduler = new LoadingScheduler()+ scheduler.seekTo(tsForMinute(10), 1)++ const batch = scheduler.getNextBatch(store, 10)+ expect(batch?.reason).toBe('seek_forward')+ expect(batch?.sourceIndices).toEqual([19])+ })++ it('only counts FullSnapshots of the target window when targetWindowId is passed', () => {+ // FullSnapshot at source 5 belongs to window 2; sources 0-2 unloaded+ const loaded = Array.from({ length: 17 }, (_, i) => i + 3)+ const store = new SnapshotStore()+ store.setSources(makeSources(20))+ for (const i of loaded) {+ const ts = tsForMinute(i)+ store.markLoaded(i, i === 5 ? [makeFullSnapshot(ts, 2), makeSnapshot(ts + 100)] : [makeSnapshot(ts)])+ }++ // Window-agnostic seek is satisfied by window 2's FullSnapshot+ const agnosticScheduler = new LoadingScheduler()+ agnosticScheduler.seekTo(tsForMinute(10))+ expect(agnosticScheduler.getNextBatch(store, 10)?.reason).not.toBe('seek_backward')+ expect(agnosticScheduler.isSeeking).toBe(false)++ // A seek targeting window 1 must keep searching backward for window 1's FullSnapshot+ const windowAwareScheduler = new LoadingScheduler()+ windowAwareScheduler.seekTo(tsForMinute(10), 1)+ const batch = windowAwareScheduler.getNextBatch(store, 10)+ expect(batch?.reason).toBe('seek_backward')+ expect(batch?.sourceIndices).toEqual([0, 1, 2])+ })})describe('buffer ahead after seek', () => {diff --git a/frontend/src/scenes/session-recordings/player/snapshot-store/LoadingScheduler.ts b/frontend/src/scenes/session-recordings/player/snapshot-store/LoadingScheduler.tsindex 16ef14002d3f..ab3e97dfcfbb 100644--- a/frontend/src/scenes/session-recordings/player/snapshot-store/LoadingScheduler.ts+++ b/frontend/src/scenes/session-recordings/player/snapshot-store/LoadingScheduler.ts@@ -10,8 +10,8 @@ export class LoadingScheduler {private seekRangeEnd: number | null = nullprivate seekRangeStart: number | null = null- seekTo(targetTimestamp: number): void {- this.mode = { kind: 'seek', targetTimestamp }+ seekTo(targetTimestamp: number, targetWindowId?: number): void {+ this.mode = { kind: 'seek', targetTimestamp, targetWindowId }this.seekRangeEnd = nullthis.seekRangeStart = null}@@ -31,7 +31,8 @@ export class LoadingScheduler {getNextBatch(store: SnapshotStore,batchSize: number = DEFAULT_BATCH_SIZE,- playbackPosition?: number+ playbackPosition?: number,+ playbackWindowId?: number): LoadBatch | null {if (store.sourceCount === 0) {return null@@ -45,7 +46,7 @@ export class LoadingScheduler {return this.getLoadAllBatch(store, batchSize)}- return this.getBufferAheadBatch(store, batchSize, playbackPosition)+ return this.getBufferAheadBatch(store, batchSize, playbackPosition, playbackWindowId)}get isSeeking(): boolean {@@ -57,6 +58,7 @@ export class LoadingScheduler {return null}const targetTs = this.mode.targetTimestamp+ const targetWindowId = this.mode.targetWindowId// Step 1: Load window around target if not loaded.const targetIndex = store.getSourceIndexForTimestamp(targetTs)@@ -85,13 +87,13 @@ export class LoadingScheduler {}// Step 2: If can play, clear seek and switch to buffer_ahead- if (store.canPlayAt(targetTs)) {+ if (store.canPlayAt(targetTs, targetWindowId)) {this.clearSeek()return this.getBufferAheadBatch(store, batchSize)}// Step 3: Need FullSnapshot. Find nearest and fill gap.- const nearestFull = store.findNearestFullSnapshot(targetTs)+ const nearestFull = store.findNearestFullSnapshot(targetTs, targetWindowId)if (nearestFull) {// Fill gap between FullSnapshot source and the start of our loaded rangeconst gapIndices = store.getUnloadedIndicesInRange(nearestFull.sourceIndex, targetIndex)@@ -126,12 +128,40 @@ export class LoadingScheduler {}this.seekRangeStart = 0- // Step 5: Exhausted backward search without finding a FullSnapshot. Give up.+ // Step 5: Backward search exhausted — no FullSnapshot exists at or before+ // the target, so playback there can only start from one after it (the+ // player clamps the seek to it once known). Keep loading forward until a+ // FullSnapshot for the target's window is found or everything is loaded —+ // another window's FullSnapshot can't render the target.+ const hasRecoveryCandidate = store+ .fullSnapshotsAfter(targetTs)+ .some((fs) => targetWindowId === undefined || fs.windowId === targetWindowId)+ if (!hasRecoveryCandidate) {+ const forwardIndices = store.getUnloadedIndicesInRange(+ (this.seekRangeEnd ?? targetIndex) + 1,+ store.sourceCount - 1+ )+ if (forwardIndices.length > 0) {+ const batch = this.truncateToContiguous(forwardIndices.slice(0, batchSize))+ this.seekRangeEnd = Math.max(this.seekRangeEnd ?? 0, batch[batch.length - 1])+ return {+ sourceIndices: batch,+ reason: 'seek_forward',+ }+ }+ }++ // Step 6: Nothing left to load that could satisfy this seek. Give up.this.clearSeek()return this.getBufferAheadBatch(store, batchSize)}- private getBufferAheadBatch(store: SnapshotStore, batchSize: number, playbackPosition?: number): LoadBatch | null {+ private getBufferAheadBatch(+ store: SnapshotStore,+ batchSize: number,+ playbackPosition?: number,+ playbackWindowId?: number+ ): LoadBatch | null {let anchorIndex: numberif (playbackPosition !== undefined) {const idx = store.getSourceIndexForTimestamp(playbackPosition)@@ -152,6 +182,24 @@ export class LoadingScheduler {}}+ // The playhead has nothing to render from (no FullSnapshot at or before it+ // for its window, e.g. lost at capture time) — the player can't progress to+ // pull the buffer window along, so keep scanning forward beyond it until+ // everything is loaded. The player clamps to a recovery FullSnapshot (moving+ // the playhead and ending the scan) as soon as one it can use appears.+ if (+ playbackPosition !== undefined &&+ store.findNearestFullSnapshot(playbackPosition, playbackWindowId) === null+ ) {+ const forwardIndices = store.getUnloadedIndicesInRange(bufferEnd + 1, store.sourceCount - 1)+ if (forwardIndices.length > 0) {+ return {+ sourceIndices: this.truncateToContiguous(forwardIndices.slice(0, batchSize)),+ reason: 'seek_forward',+ }+ }+ }+return null}diff --git a/frontend/src/scenes/session-recordings/player/snapshot-store/SnapshotStore.test.ts b/frontend/src/scenes/session-recordings/player/snapshot-store/SnapshotStore.test.tsindex 93d24fc4e6ce..9d544ff754e8 100644--- a/frontend/src/scenes/session-recordings/player/snapshot-store/SnapshotStore.test.ts+++ b/frontend/src/scenes/session-recordings/player/snapshot-store/SnapshotStore.test.ts@@ -88,7 +88,7 @@ describe('SnapshotStore', () => {expect(store.getEntry(2)?.state).toBe('unloaded')expect(store.getEntry(3)?.state).toBe('unloaded')expect(store.getEntry(4)?.state).toBe('unloaded')- expect(store.getEntry(0)?.fullSnapshotTimestamps).toEqual([1000])+ expect(store.getEntry(0)?.fullSnapshots).toEqual([{ timestamp: 1000, windowId: 1 }])})it('preserves loaded snapshots through source growth', () => {@@ -114,7 +114,7 @@ describe('SnapshotStore', () => {expect(store.getEntry(1)?.state).toBe('loaded')expect(store.getEntry(0)?.state).toBe('unloaded')- expect(store.getEntry(1)?.fullSnapshotTimestamps).toEqual([ts])+ expect(store.getEntry(1)?.fullSnapshots).toEqual([{ timestamp: ts, windowId: 1 }])})it('extracts Meta timestamps', () => {@@ -328,6 +328,60 @@ describe('SnapshotStore', () => {const result = store.findNearestFullSnapshot(target)expect(result).toEqual({ sourceIndex: 1, timestamp: fs2 })})++ it('only counts FullSnapshots of the given window when windowId is passed', () => {+ const store = new SnapshotStore()+ store.setSources(makeSources(3))++ const fs1 = new Date(Date.UTC(2023, 7, 11, 12, 1, 10)).getTime()+ const fs2 = new Date(Date.UTC(2023, 7, 11, 12, 1, 40)).getTime()++ store.markLoaded(1, [makeFullSnapshot(fs1, 1), makeFullSnapshot(fs2, 2)])++ const target = new Date(Date.UTC(2023, 7, 11, 12, 2, 0)).getTime()+ expect(store.findNearestFullSnapshot(target, 1)).toEqual({ sourceIndex: 1, timestamp: fs1 })+ expect(store.findNearestFullSnapshot(target, 2)).toEqual({ sourceIndex: 1, timestamp: fs2 })+ expect(store.findNearestFullSnapshot(target, 3)).toBeNull()+ })+ })++ describe('fullSnapshotsAfter', () => {+ it('returns empty array when no FullSnapshots exist', () => {+ const store = new SnapshotStore()+ store.setSources(makeSources(3))+ store.markLoaded(0, [makeSnapshot(1000)])++ expect(store.fullSnapshotsAfter(0)).toEqual([])+ })++ it('returns FullSnapshots at or after the target, sorted by timestamp', () => {+ const store = new SnapshotStore()+ store.setSources(makeSources(5))++ const fs1 = new Date(Date.UTC(2023, 7, 11, 12, 1, 30)).getTime()+ const fs3 = new Date(Date.UTC(2023, 7, 11, 12, 3, 30)).getTime()++ store.markLoaded(3, [makeFullSnapshot(fs3, 2)])+ store.markLoaded(1, [makeFullSnapshot(fs1, 1)])++ expect(store.fullSnapshotsAfter(fs1)).toEqual([+ { timestamp: fs1, windowId: 1, sourceIndex: 1 },+ { timestamp: fs3, windowId: 2, sourceIndex: 3 },+ ])+ })++ it('excludes FullSnapshots before the target', () => {+ const store = new SnapshotStore()+ store.setSources(makeSources(5))++ const fs1 = new Date(Date.UTC(2023, 7, 11, 12, 1, 30)).getTime()+ const fs3 = new Date(Date.UTC(2023, 7, 11, 12, 3, 30)).getTime()++ store.markLoaded(1, [makeFullSnapshot(fs1)])+ store.markLoaded(3, [makeFullSnapshot(fs3)])++ expect(store.fullSnapshotsAfter(fs1 + 1)).toEqual([{ timestamp: fs3, windowId: 1, sourceIndex: 3 }])+ })})describe('syncFullSnapshotTimestamps', () => {diff --git a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsxindex 58237573b99a..5d8ef9f416f1 100644--- a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx+++ b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx@@ -67,8 +67,8 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([stopPolling: true,setPollingInterval: (intervalMs: number) => ({ intervalMs }),resetPollingInterval: true,- setTargetTimestamp: (timestamp: number | null) => ({ timestamp }),- updatePlaybackPosition: (timestamp: number) => ({ timestamp }),+ setTargetTimestamp: (timestamp: number | null, windowId?: number) => ({ timestamp, windowId }),+ updatePlaybackPosition: (timestamp: number, windowId?: number) => ({ timestamp, windowId }),setPlayerActive: (active: boolean) => ({ active }),loadAllSources: true,// dispatch after any mutation to cache.store or cache.scheduler —@@ -224,12 +224,13 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([],})),listeners(({ values, actions, cache, props }) => ({- setTargetTimestamp: ({ timestamp }) => {+ setTargetTimestamp: ({ timestamp, windowId }) => {if (!cache.scheduler || !cache.store) {return}if (timestamp !== null) {cache.playbackPosition = timestamp+ cache.playbackWindowId = windowIdconst currentMode = cache.scheduler.currentMode// Don't interrupt load_all (e.g. during export)@@ -238,12 +239,16 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([return}// Don't re-seek to the same target- if (currentMode.kind === 'seek' && currentMode.targetTimestamp === timestamp) {+ if (+ currentMode.kind === 'seek' &&+ currentMode.targetTimestamp === timestamp &&+ currentMode.targetWindowId === windowId+ ) {return}// If we can already play at this position (data is loaded), no need to seek —// this handles segment transitions during normal forward playback- if (cache.store.canPlayAt(timestamp)) {+ if (cache.store.canPlayAt(timestamp, windowId)) {actions.loadNextSnapshotSource()return}@@ -258,14 +263,15 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([return}- cache.scheduler.seekTo(timestamp)+ cache.scheduler.seekTo(timestamp, windowId)actions.storeUpdated()actions.loadNextSnapshotSource()}},- updatePlaybackPosition: ({ timestamp }) => {+ updatePlaybackPosition: ({ timestamp, windowId }) => {cache.playbackPosition = timestamp+ cache.playbackWindowId = windowId// Trigger loading if the buffer ahead needs fillingactions.loadNextSnapshotSource()},@@ -439,7 +445,7 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([// mutating the store. Kea can't see that, so dispatch storeUpdated// to invalidate selectors that read scheduler state (#53893).const wasSeeking = cache.scheduler.currentMode.kind === 'seek'- const batch = cache.scheduler.getNextBatch(cache.store, 10, cache.playbackPosition)+ const batch = cache.scheduler.getNextBatch(cache.store, 10, cache.playbackPosition, cache.playbackWindowId)if (wasSeeking && cache.scheduler.currentMode.kind !== 'seek') {actions.storeUpdated()}@@ -521,7 +527,7 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([if (mode.kind !== 'seek') {return false}- return !cache.store.canPlayAt(mode.targetTimestamp)+ return !cache.store.canPlayAt(mode.targetTimestamp, mode.targetWindowId)},],