: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): overhaul player buffering, seeking, and snapshot loading (#67972)
Tue Haulundaaa2ccb38d72
diff --git a/common/replay-shared/src/index.test.ts b/common/replay-shared/src/index.test.tsindex 00f46d86320a..11c070e9af48 100644--- a/common/replay-shared/src/index.test.ts+++ b/common/replay-shared/src/index.test.ts@@ -76,7 +76,8 @@ describe('@posthog/replay-shared', () => {expect(store.sourceCount).toBe(1)expect(store.getUnloadedIndicesInRange(0, 0)).toEqual([0])- store.markLoaded(0, [])+ store.markFetched(0, [])+ store.markProcessed([0])expect(store.getUnloadedIndicesInRange(0, 0)).toEqual([])})})diff --git a/common/replay-shared/src/index.ts b/common/replay-shared/src/index.tsindex fd8d06141533..dfccb61fd5e3 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, FullSnapshotRef } from './snapshot-store/types'+export type { SourceEntry, LoadBatch, SourceLoadingState, FullSnapshotRef } from './snapshot-store/types'// canvas replayexport type { CanvasPluginErrorHandler } from './canvas/canvas-plugin'diff --git a/common/replay-shared/src/segmenter.ts b/common/replay-shared/src/segmenter.tsindex 38c5bf1a845d..5f185f1ed517 100644--- a/common/replay-shared/src/segmenter.ts+++ b/common/replay-shared/src/segmenter.ts@@ -44,7 +44,9 @@ export const createSegments = (start: number | null,end: number | null,trackedWindow: number | null | undefined,- snapshotsByWindowId: Record<number, eventWithTime[]>+ snapshotsByWindowId: Record<number, eventWithTime[]>,+ // whether every source covering [startTs, endTs] has loaded; null = unknown, keep the default kind+ isRangeLoaded: (startTimestamp: number, endTimestamp: number) => boolean | null = () => null): RecordingSegment[] => {let segments: RecordingSegment[] = []let activeSegment!: Partial<RecordingSegment>@@ -137,8 +139,9 @@ export const createSegments = (// Offset the window ID check so we look for a subsequent segmentconst preferredWindowId = trackedWindow ?? previousSegment.windowIdconst windowId = findWindowIdForTimestamp(startTimestamp + 1, preferredWindowId)+ // A "gap" whose sources haven't loaded yet is pending data, not real inactivity — classify it as buffer so the player waits instead of skipping.const gapSegment: Partial<RecordingSegment> = {- kind: 'gap',+ kind: isRangeLoaded(startTimestamp, endTimestamp) === false ? 'buffer' : 'gap',startTimestamp,endTimestamp,windowId,@@ -159,9 +162,11 @@ export const createSegments = (const endTimestamp = endif (!latestTimestamp || latestTimestamp < endTimestamp) {+ const startTimestamp = latestTimestamp ? latestTimestamp + 1 : start+ // The trailing region is pending data by default, but once its sources are all loaded it is just trailing inactivity.segments.push({- kind: 'buffer',- startTimestamp: latestTimestamp ? latestTimestamp + 1 : start,+ kind: isRangeLoaded(startTimestamp, endTimestamp) === true ? 'gap' : 'buffer',+ startTimestamp,endTimestamp: endTimestamp,isActive: false,} as RecordingSegment)@@ -171,7 +176,7 @@ export const createSegments = (const firstTimestamp = segments[0]?.startTimestampif (firstTimestamp && firstTimestamp > start) {segments.unshift({- kind: 'gap',+ kind: isRangeLoaded(start, firstTimestamp) === false ? 'buffer' : 'gap',startTimestamp: start,endTimestamp: firstTimestamp,isActive: false,diff --git a/common/replay-shared/src/snapshot-processing/process-all-snapshots.ts b/common/replay-shared/src/snapshot-processing/process-all-snapshots.tsindex 8517394a347f..bc788adbc089 100644--- a/common/replay-shared/src/snapshot-processing/process-all-snapshots.ts+++ b/common/replay-shared/src/snapshot-processing/process-all-snapshots.ts@@ -8,7 +8,7 @@ import {SessionRecordingSnapshotSource,SessionRecordingSnapshotSourceResponse,} from '../types'-import { isEmptyObject, isObject } from '../utils'+import { isObject } from '../utils'import { CHROME_EXTENSION_DENY_LIST, stripChromeExtensionDataFromNode } from './chrome-extension-stripping'import { chunkMutationSnapshot } from './chunk-large-mutations'import { decompressEvent } from './decompress'@@ -117,7 +117,8 @@ export async function processAllSnapshots(sessionRecordingId: string,telemetry: ReplayTelemetry = noOpTelemetry): Promise<RecordingSnapshot[]> {- if (!sources || !snapshotsBySource || isEmptyObject(snapshotsBySource)) {+ // No isEmptyObject early-return: a pass with no new input must still rebuild the full result from processingCache, or previously processed sources get wiped downstream.+ if (!sources || !snapshotsBySource) {return []}diff --git a/common/replay-shared/src/snapshot-store/SnapshotStore.ts b/common/replay-shared/src/snapshot-store/SnapshotStore.tsindex ba10385f17b3..41ca0c835679 100644--- a/common/replay-shared/src/snapshot-store/SnapshotStore.ts+++ b/common/replay-shared/src/snapshot-store/SnapshotStore.ts@@ -1,4 +1,4 @@-import { EventType, eventWithTime } from 'posthog-js/rrweb-types'+import { EventType } from 'posthog-js/rrweb-types'import { RecordingSnapshot, SessionRecordingSnapshotSource } from '../types'import { FullSnapshotRef, SourceEntry, SourceLoadingState } from './types'@@ -6,8 +6,6 @@ import { FullSnapshotRef, SourceEntry, SourceLoadingState } from './types'export class SnapshotStore {private entries: SourceEntry[] = []private _version = 0- private mergedSnapshotsCache: RecordingSnapshot[] | null = null- private snapshotsByWindowIdCache: Record<number, eventWithTime[]> | null = nullget version(): number {return this._version@@ -33,7 +31,6 @@ export class SnapshotStore {state: 'unloaded' as const,processedSnapshots: null,fullSnapshots: [],- metaTimestamps: [],startMs: source.start_timestamp ? new Date(source.start_timestamp).getTime() : 0,endMs: source.end_timestamp ? new Date(source.end_timestamp).getTime() : 0,}@@ -53,66 +50,42 @@ export class SnapshotStore {return this.entries[index]}- markLoaded(sourceIndex: number, processedSnapshots: RecordingSnapshot[]): void {+ // Raw data has arrived but hasn't been through snapshot processing yet — playable state ('loaded') is granted by markProcessed.+ markFetched(sourceIndex: number, snapshots: RecordingSnapshot[]): void {const entry = this.entries[sourceIndex]if (!entry) {return}- processedSnapshots.sort((a, b) => a.timestamp - b.timestamp)+ snapshots.sort((a, b) => a.timestamp - b.timestamp)const fullSnapshots: FullSnapshotRef[] = []- const metaTimestamps: number[] = []- for (const snap of processedSnapshots) {+ for (const snap of snapshots) {if (snap.type === EventType.FullSnapshot) {fullSnapshots.push({ timestamp: snap.timestamp, windowId: snap.windowId })}- if (snap.type === EventType.Meta) {- metaTimestamps.push(snap.timestamp)- }}- entry.state = 'loaded'- entry.processedSnapshots = processedSnapshots+ entry.state = 'fetched'+ entry.processedSnapshots = snapshotsentry.fullSnapshots = fullSnapshots- entry.metaTimestamps = metaTimestampsthis.bump()}- getAllLoadedSnapshots(): RecordingSnapshot[] {- if (this.mergedSnapshotsCache) {- return this.mergedSnapshotsCache- }-- const result: RecordingSnapshot[] = []- for (const entry of this.entries) {- if (entry.state === 'loaded' && entry.processedSnapshots) {- for (const snap of entry.processedSnapshots) {- result.push(snap)- }+ // Flips fetched sources to loaded once a processing pass has covered them.+ markProcessed(sourceIndexes: number[]): boolean {+ let changed = false+ for (const sourceIndex of sourceIndexes) {+ const entry = this.entries[sourceIndex]+ if (entry?.state === 'fetched') {+ entry.state = 'loaded'+ changed = true}}- this.mergedSnapshotsCache = result- return result- }-- getSnapshotsByWindowId(): Record<number, eventWithTime[]> {- if (this.snapshotsByWindowIdCache) {- return this.snapshotsByWindowIdCache- }-- const snapshots = this.getAllLoadedSnapshots()-- const result: Record<number, eventWithTime[]> = {}- for (const snapshot of snapshots) {- const windowId = (snapshot as RecordingSnapshot).windowId- if (!(windowId in result)) {- result[windowId] = []- }- result[windowId].push(snapshot)+ if (changed) {+ this.bump()}- this.snapshotsByWindowIdCache = result- return result+ return changed}/**@@ -126,27 +99,28 @@ export class SnapshotStore {if (this.entries.length === 0) {return null}- for (let i = 0; i < this.entries.length; i++) {- const entry = this.entries[i]- if (ts >= entry.startMs && ts <= entry.endMs) {- return i- }- if (ts < entry.startMs) {- return Math.max(0, i - 1)+ // Binary search over startMs (sources arrive time-ordered): positions inside a range resolve to it, positions in inter-source gaps or past the ends resolve to the nearest source.+ let low = 0+ let high = this.entries.length - 1+ let candidate = -1+ while (low <= high) {+ const mid = (low + high) >> 1+ if (this.entries[mid].startMs <= ts) {+ candidate = mid+ low = mid + 1+ } else {+ high = mid - 1}}- return Math.max(0, this.entries.length - 1)+ return Math.max(0, candidate)}canPlayAt(ts: number, windowId?: number): boolean {if (this.entries.length === 0) {return false}- // Timestamp is beyond all known source data — can't play yet- if (ts > this.entries[this.entries.length - 1].endMs) {- return false- }+ // Positions beyond the last source resolve to it, so a fully-loaded tail can render its last frame without first fetching the whole recording.const fullSnapshotInfo = this.findNearestFullSnapshot(ts, windowId)if (!fullSnapshotInfo) {return false@@ -176,6 +150,10 @@ export class SnapshotStore {let bestSourceIndex = -1for (const entry of this.entries) {+ // entries past `ts` can't hold a FullSnapshot at or before it (refs never precede their entry's start, except entry 0's)+ if (entry.index > 0 && entry.startMs > ts) {+ break+ }for (const fullSnapshot of entry.fullSnapshots) {if (windowId !== undefined && fullSnapshot.windowId !== windowId) {continue@@ -193,6 +171,35 @@ export class SnapshotStore {return { sourceIndex: bestSourceIndex, timestamp: bestTs }}+ // Whether every source covering [startTs, endTs] has been processed; null = unknown (no sources yet), callers keep their default.+ isRangeLoaded(startTs: number, endTs: number): boolean | null {+ if (this.entries.length === 0) {+ return null+ }+ const startIndex = this.getSourceIndexForTimestamp(startTs)+ const endIndex = this.getSourceIndexForTimestamp(endTs)+ if (startIndex === null || endIndex === null) {+ return null+ }+ return this.getUnloadedIndicesInRange(startIndex, endIndex).length === 0+ }++ // Allocation-free existence check for the load planner's recovery scan.+ hasFullSnapshotAfter(ts: number, windowId?: number): boolean {+ for (const entry of this.entries) {+ for (const fullSnapshot of entry.fullSnapshots) {+ if (fullSnapshot.timestamp >= ts && (windowId === undefined || fullSnapshot.windowId === windowId)) {+ return true+ }+ }+ }+ return false+ }++ get hasLoadedAnySource(): boolean {+ return this.entries.some((entry) => entry.state === 'loaded')+ }+/*** Returns all loaded FullSnapshots at or after `ts`, sorted by timestamp.* Used to recover playback when the data before `ts` has no FullSnapshot to@@ -211,30 +218,34 @@ export class SnapshotStore {}syncFullSnapshotTimestamps(processedSnapshots: RecordingSnapshot[]): boolean {+ // Bucketed by nearest source (not by [startMs, endMs] range) so a synthesized FullSnapshot whose timestamp falls between two sources' metadata ranges is still indexed somewhere.+ const buckets = new Map<number, FullSnapshotRef[]>()+ for (const snap of processedSnapshots) {+ if (snap.type !== EventType.FullSnapshot) {+ continue+ }+ const sourceIndex = this.getSourceIndexForTimestamp(snap.timestamp)+ if (sourceIndex === null) {+ continue+ }+ const bucket = buckets.get(sourceIndex) ?? []+ bucket.push({ timestamp: snap.timestamp, windowId: snap.windowId })+ buckets.set(sourceIndex, bucket)+ }+let changed = falsefor (const entry of this.entries) {if (entry.state !== 'loaded') {continue}- const fullSnapshots: FullSnapshotRef[] = []- for (const snap of processedSnapshots) {- if (- snap.type === EventType.FullSnapshot &&- snap.timestamp >= entry.startMs &&- snap.timestamp <= entry.endMs- ) {- fullSnapshots.push({ timestamp: snap.timestamp, windowId: snap.windowId })- }- }- fullSnapshots.sort((a, b) => a.timestamp - b.timestamp)+ const fullSnapshots = (buckets.get(entry.index) ?? []).sort((a, b) => a.timestamp - b.timestamp)if (- fullSnapshots.length > 0 &&- (fullSnapshots.length !== entry.fullSnapshots.length ||- fullSnapshots.some(- (fs, j) =>- fs.timestamp !== entry.fullSnapshots[j].timestamp ||- fs.windowId !== entry.fullSnapshots[j].windowId- ))+ fullSnapshots.length !== entry.fullSnapshots.length ||+ fullSnapshots.some(+ (fs, j) =>+ fs.timestamp !== entry.fullSnapshots[j].timestamp ||+ fs.windowId !== entry.fullSnapshots[j].windowId+ )) {entry.fullSnapshots = fullSnapshotschanged = true@@ -246,20 +257,31 @@ export class SnapshotStore {return changed}+ // Deliberately does not bump(): consumers should keep their memoized view, since only loaded-state metadata stays meaningful and fetched entries keep their still-unprocessed raw data.clearSnapshotData(): void {for (const entry of this.entries) {- entry.processedSnapshots = null+ if (entry.state === 'loaded') {+ entry.processedSnapshots = null+ }}- this.mergedSnapshotsCache = null- this.snapshotsByWindowIdCache = null}+ // "Not yet playable" — fetched-but-unprocessed sources count; use for renderability, not for planning fetches.getUnloadedIndicesInRange(start: number, end: number): number[] {+ return this.indicesInRange(start, end, (state) => state !== 'loaded')+ }++ // "Not yet requested" — what the load planner still needs to fetch from the network.+ getUnfetchedIndicesInRange(start: number, end: number): number[] {+ return this.indicesInRange(start, end, (state) => state === 'unloaded')+ }++ private indicesInRange(start: number, end: number, matches: (state: SourceEntry['state']) => boolean): number[] {const result: number[] = []const clampedStart = Math.max(0, start)const clampedEnd = Math.min(this.entries.length - 1, end)for (let i = clampedStart; i <= clampedEnd; i++) {- if (this.entries[i]?.state !== 'loaded') {+ if (matches(this.entries[i]?.state ?? 'unloaded')) {result.push(i)}}@@ -272,7 +294,5 @@ export class SnapshotStore {private bump(): void {this._version++- this.mergedSnapshotsCache = null- this.snapshotsByWindowIdCache = null}}diff --git a/common/replay-shared/src/snapshot-store/types.ts b/common/replay-shared/src/snapshot-store/types.tsindex 3cc7a6d1a9ea..cecbf1a2d030 100644--- a/common/replay-shared/src/snapshot-store/types.ts+++ b/common/replay-shared/src/snapshot-store/types.ts@@ -8,10 +8,9 @@ export interface FullSnapshotRef {export interface SourceEntry {source: SessionRecordingSnapshotSourceindex: number- state: 'unloaded' | 'loaded'+ state: 'unloaded' | 'fetched' | 'loaded'processedSnapshots: RecordingSnapshot[] | nullfullSnapshots: FullSnapshotRef[]- metaTimestamps: number[]startMs: numberendMs: number}@@ -24,10 +23,5 @@ export interface LoadBatch {export interface SourceLoadingState {startMs: numberendMs: number- state: 'unloaded' | 'loaded'+ state: 'unloaded' | 'fetched' | 'loaded'}--export type Mode =- | { kind: 'buffer_ahead' }- | { kind: 'seek'; targetTimestamp: number; targetWindowId?: number }- | { kind: 'load_all' }diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 84df267c0fd4..9cfb2eb00447 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1383,7 +1383,7 @@ snapshots:components-playerinspector--with-logs-filter--dark:hash: v1.k794b7964.4a27837802248b94d5c146c18b6962bfc713ce40ec3da10a23d4fc89639cf794.PRcX4NksDqdhgKXU-BTlmrZ4mkRVcQIAlLsj5nbUq9Icomponents-playerinspector--with-logs-filter--light:- hash: v1.k794b7964.97c396a5d41b78e6f653cdcb59a7e59dce49c44d08a9c3903dd69324eb20fdd6.UcFWQBXiTFaua5umBEqB8d8UUCI6aLN4cXg2abaVyJ0+ hash: v1.k794b7964.6a9ed3bc4517e86c66a587197537ef454d902596d2d78e151de1d26541444ca7.999h6vfa3n6nYUoAkRrCg0mD3k_wWQEf9wxjCbeImZMcomponents-playerinspector--with-logs-filter-upsell--dark:hash: v1.k794b7964.5e4afe863e34df7278c0dd092946adfd396ee778f0cd0a41e5e3f5e1771a9601.SBOdVp0jJnn1w2H4fMR-3Vf2ac00QSBFQjsl93AbcYAcomponents-playerinspector--with-logs-filter-upsell--light:@@ -4733,9 +4733,9 @@ snapshots:replay-tabs-home-success--filters-expanded-lots-of-results-narrow--light:hash: v1.k794b7964.48e7a6fa73c1452938b82fe8b24408b6c35be4016ec89c4d467f09b55db46fe3.c0tQ-HVvuPwToQeoCVCRgdTQ36ubOXRYIhab78RiW6kreplay-tabs-home-success--recent-recordings--dark:- hash: v1.k794b7964.750afbb731b81643c73711d2357a200d265ed788560862fd1871d4c98b7a69a5.tBas-hmcgaFiodJ0IPksAyLMEwSRUm-Aw-E6Y2QTft8+ hash: v1.k794b7964.a0021cf27fc31617f6b8aefb81f566da3d40284ba2ba4e3060a596f058bf95e3.DiUSK9Y0hFIN0tJItKpMnVqBn0TfKolrZ1lsI3FF3J8replay-tabs-home-success--recent-recordings--light:- hash: v1.k794b7964.27b10042eb0d0e279be639adee5057da11e0eca6891cc4d2acc3261cb52a0d81.vuSjUeMK51PkxV4HPbiO0Lo4j5nOLFUpkxws6NxeJ58+ hash: v1.k794b7964.594cbac0c6c0faa26249e102c90835f11fa21a87ae377287ced1f62198172e9e.Fx7rXwIa3GhsN6ApZXqkyDA9zsNJJVs3EbZgRXOKOSMreplay-tabs-home-success--recent-recordings-empty--dark:hash: v1.k794b7964.9202b201349e799c65d2110f96efa6610473f09a31c00908a2cf580d671171ee.hXoNZ1khtqFx65a4cdiLrd4HfWykWHTOv_-m09ut4xUreplay-tabs-home-success--recent-recordings-empty--light:diff --git a/frontend/src/scenes/session-recordings/player/__snapshots__/sessionRecordingPlayerLogic.test.ts.snap b/frontend/src/scenes/session-recordings/player/__snapshots__/sessionRecordingPlayerLogic.test.ts.snapindex 1509b895d7c7..bddc759a1516 100644--- a/frontend/src/scenes/session-recordings/player/__snapshots__/sessionRecordingPlayerLogic.test.ts.snap+++ b/frontend/src/scenes/session-recordings/player/__snapshots__/sessionRecordingPlayerLogic.test.ts.snap@@ -23,7 +23,6 @@ exports[`sessionRecordingPlayerLogic loading session core loads metadata and sna"durationMs": 11868,"endTimestamp": 1682952392745,"isActive": false,- "isLoading": false,"kind": "buffer","startTimestamp": 1682952380877,},@@ -58,7 +57,6 @@ exports[`sessionRecordingPlayerLogic loading session core loads metadata and sna"durationMs": 11868,"endTimestamp": 1682952392745,"isActive": false,- "isLoading": false,"kind": "buffer","startTimestamp": 1682952380877,},diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.blobv2.test.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.blobv2.test.tsindex fd1d5dd74d8d..398c73619b05 100644--- a/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.blobv2.test.ts+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.blobv2.test.ts@@ -57,6 +57,9 @@ describe('sessionRecordingDataCoordinatorLogic blobby v2', () => {return new HttpResponse(keyZero)} else if (key === '1') {return new HttpResponse(keyOne)+ } else if (start_blob_key === '2' && end_blob_key === '2') {+ // a heartbeat blob with no snapshots+ return new HttpResponse('')} else if (start_blob_key === '0' && end_blob_key === '1') {return new HttpResponse(`${keyZero}\n${keyOne}`)}@@ -86,6 +89,39 @@ describe('sessionRecordingDataCoordinatorLogic blobby v2', () => {jest.spyOn(api, 'create')})+ describe('processing after live source growth', () => {+ it('an empty heartbeat blob does not wipe the processed stream', async () => {+ await expectLogic(logic, () => {+ logic.actions.loadSnapshots()+ })+ .toDispatchActions([snapshotLogic.actionTypes.loadSnapshotsForSourceSuccess, 'setProcessedSnapshots'])+ .toFinishAllListeners()++ const processedBefore = logic.values.snapshots.length+ expect(processedBefore).toBeGreaterThan(0)++ // a live recording appends a blob that contains no snapshots, after earlier raw data was released+ const HEARTBEAT_SOURCE: SessionRecordingSnapshotSource = {+ source: 'blob_v2',+ start_timestamp: '2025-05-18T03:52:00.000000Z',+ end_timestamp: '2025-05-18T03:52:10.000000Z',+ blob_key: '2',+ }+ await expectLogic(logic, () => {+ snapshotLogic.actions.loadSnapshotSourcesSuccess([+ BLOB_V2_SOURCE_ZERO,+ BLOB_V2_SOURCE_ONE,+ HEARTBEAT_SOURCE,+ ])+ })+ .toDispatchActions([snapshotLogic.actionTypes.loadSnapshotsForSourceSuccess, 'setProcessedSnapshots'])+ .toFinishAllListeners()++ expect(logic.values.snapshots.length).toBe(processedBefore)+ expect(snapshotLogic.cache.store.getEntry(2)?.state).toBe('loaded')+ })+ })+describe('loading session core', () => {it('loads all data', async () => {await expectLogic(logic, () => {diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.tsindex e2863b5c27ce..004005f3d4b8 100644--- a/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.ts+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.ts@@ -32,7 +32,6 @@ import type { sessionRecordingDataCoordinatorLogicType } from './sessionRecordinimport { sessionRecordingMetaLogic } from './sessionRecordingMetaLogic'import { posthogTelemetry } from './snapshot-processing/process-all-snapshots'import { snapshotDataLogic } from './snapshotDataLogic'-import { convertSegmentKinds } from './utils/segment-kind-conversion'import { createSegments, mapSnapshotsToWindowId } from './utils/segmenter'export interface SessionRecordingDataCoordinatorLogicProps {@@ -218,10 +217,15 @@ export const sessionRecordingDataCoordinatorLogic = kea<sessionRecordingDataCoorconst sources = values.snapshotSourcesconst snapshotsBySource = {} as Record<string, { snapshots: RecordingSnapshot[] }>+ // fetched sources this pass will cover — promoted to loaded on completion, including empty ones that contribute no snapshots+ const coveredIndexes: number[] = []if (sources) {for (let i = 0; i < sources.length; i++) {const entry = values.snapshotStore.getEntry(i)- if (entry?.state === 'loaded' && entry.processedSnapshots?.length) {+ if (entry?.state === 'fetched') {+ coveredIndexes.push(i)+ }+ if (entry?.state !== 'unloaded' && entry?.processedSnapshots?.length) {snapshotsBySource[keyForSource(sources[i])] = {snapshots: entry.processedSnapshots,}@@ -229,27 +233,42 @@ export const sessionRecordingDataCoordinatorLogic = kea<sessionRecordingDataCoor}}- const result = await processAllSnapshots(- sources,- snapshotsBySource,- cache.processingCache,- values.viewportForTimestamp,- props.sessionRecordingId,- posthogTelemetry- )+ let result: RecordingSnapshot[]+ try {+ result = await processAllSnapshots(+ sources,+ snapshotsBySource,+ cache.processingCache,+ values.viewportForTimestamp,+ props.sessionRecordingId,+ posthogTelemetry+ )+ } catch (error) {+ // A processing throw on the final batch would otherwise leave fetched sources unplayable forever (nothing re-triggers processing), so retry with backoff.+ posthog.captureException(error)+ cache.processingFailureCount = (cache.processingFailureCount ?? 0) + 1+ if (cache.processingFailureCount <= 3) {+ await breakpoint(cache.processingFailureCount * 1000)+ actions.processSnapshotsAsync()+ }+ return+ }+ cache.processingFailureCount = 0breakpoint()+ // Promotion is what makes these sources count as playable — the oracle, segments, and planner all key on it, so it must land with the processed snapshots.+ const promoted = values.snapshotStore.markProcessed(coveredIndexes)// processAllSnapshots may synthesize full snapshots (e.g. for mobile recordings).- // Sync them back to the store so canPlayAt() and LoadingScheduler work correctly.- if (values.snapshotStore.syncFullSnapshotTimestamps(result)) {- actions.storeUpdated()- }+ // Sync them back to the store so canPlayAt() and the load planner work correctly.+ const synced = values.snapshotStore.syncFullSnapshotTimestamps(result)- // Release raw snapshot arrays from the store — only the metadata- // (fullSnapshots, metaTimestamps, state) is still needed.+ // Release raw snapshot arrays from the store — only the metadata (fullSnapshots, state) is still needed.values.snapshotStore.clearSnapshotData()+ if (promoted || synced) {+ actions.storeUpdated()+ }actions.setProcessedSnapshots(result)},@@ -261,7 +280,7 @@ export const sessionRecordingDataCoordinatorLogic = kea<sessionRecordingDataCoor}},})),- selectors(({ cache }) => ({+ selectors(() => ({snapshots: [(s) => [s.processedSnapshots],(processedSnapshots: RecordingSnapshot[]): RecordingSnapshot[] => {@@ -318,7 +337,6 @@ export const sessionRecordingDataCoordinatorLogic = kea<sessionRecordingDataCoors.end,s.trackedWindow,s.snapshotsByWindowId,- s.isLoadingSnapshots,s.snapshotStore,s.storeVersion,],@@ -328,11 +346,11 @@ export const sessionRecordingDataCoordinatorLogic = kea<sessionRecordingDataCoorend: Dayjs | null,trackedWindow: number | null,snapshotsByWindowId: Record<number, eventWithTime[]>,- isLoadingSnapshots: boolean,snapshotStore: SnapshotStore): RecordingSegment[] => {- const segments = createSegments(snapshots || [], start, end, trackedWindow, snapshotsByWindowId)- return convertSegmentKinds(segments, snapshotStore, isLoadingSnapshots)+ return createSegments(snapshots || [], start, end, trackedWindow, snapshotsByWindowId, (s, e) =>+ snapshotStore.isRangeLoaded(s, e)+ )},],@@ -363,19 +381,21 @@ export const sessionRecordingDataCoordinatorLogic = kea<sessionRecordingDataCoorwindowIdForTimestamp: [(s) => [s.segments],- (segments) =>- (timestamp: number): number | undefined => {- cache.windowIdForTimestamp = cache.windowIdForTimestamp || {}- if (cache.windowIdForTimestamp[timestamp] !== undefined) {- return cache.windowIdForTimestamp[timestamp]+ (segments) => {+ // memoized per segments recompute — segments reshape as data loads, so a logic-lifetime cache would pin stale window attributions+ const memo: Record<number, number | undefined> = {}+ return (timestamp: number): number | undefined => {+ if (timestamp in memo) {+ return memo[timestamp]}const matchingWindowId = segments.find((segment) => segment.startTimestamp <= timestamp && segment.endTimestamp >= timestamp)?.windowId- cache.windowIdForTimestamp[timestamp] = matchingWindowId+ memo[timestamp] = matchingWindowIdreturn matchingWindowId- },+ }+ },],urls: [@@ -498,7 +518,7 @@ export const sessionRecordingDataCoordinatorLogic = kea<sessionRecordingDataCooreffectiveSourceLoadingStates: [(s) => [s.sourceLoadingStates, s.segments],(states: SourceLoadingState[], segments: RecordingSegment[]): SourceLoadingState[] => {- let lastNonGapState: 'loaded' | 'unloaded' = 'unloaded'+ let lastNonGapState: SourceLoadingState['state'] = 'unloaded'return states.map((s) => {const inGap = !segments.some((seg) => seg.kind !== 'gap' && seg.startTimestamp < s.endMs && seg.endTimestamp > s.startMs@@ -583,7 +603,6 @@ export const sessionRecordingDataCoordinatorLogic = kea<sessionRecordingDataCoor],})),beforeUnmount(({ cache, actions, values }) => {- cache.windowIdForTimestamp = undefinedcache.processingCache = undefined// Force clear processedSnapshots to release memory immediately// This breaks the reference chain in selector memoization cachediff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.test.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.test.tsindex 143f9bab24ee..a7ffb239e943 100644--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.test.ts+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.test.ts@@ -26,6 +26,7 @@ import {setupSessionRecordingTest,} from './__mocks__/test-setup'import { findNewEvents, findSegmentForTimestamp, stripRrwebScriptShims } from './sessionRecordingPlayerLogic'+import { markLoaded } from './snapshot-store/test-utils'import { snapshotDataLogic } from './snapshotDataLogic'import { deleteRecording as deleteRecordingMock } from './utils/playerUtils'@@ -433,14 +434,33 @@ describe('sessionRecordingPlayerLogic', () => {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 makeSnapshot = (+ timestamp: number,+ type: EventType,+ windowId: number = 1,+ data: Record<string, any> = {}+ ): RecordingSnapshot => ({ timestamp, type, windowId, data }) as unknown as RecordingSnapshotconst inc = (timestamp: number): RecordingSnapshot => makeSnapshot(timestamp, EventType.IncrementalSnapshot)const fs = (timestamp: number): RecordingSnapshot => makeSnapshot(timestamp, EventType.FullSnapshot)- // second-window incremental for the multi-window case+ // second-window events for the multi-window casesconst w2inc = (timestamp: number): RecordingSnapshot =>- ({ timestamp, type: EventType.IncrementalSnapshot, windowId: 2, data: {} }) as unknown as RecordingSnapshot+ makeSnapshot(timestamp, EventType.IncrementalSnapshot, 2)+ const w2fs = (timestamp: number): RecordingSnapshot => makeSnapshot(timestamp, EventType.FullSnapshot, 2)+ // an ACTIVE first-window event, so the segmenter splits a real window-1 segment before it+ const w1move = (timestamp: number): RecordingSnapshot =>+ makeSnapshot(timestamp, EventType.IncrementalSnapshot, 1, { source: IncrementalSource.MouseMove })++ // one-minute-per-source blob fixtures matching the store test helpers+ const makeBlobSources = (+ blobKeys: string[]+ ): { source: string; blob_key: string; start_timestamp: string; end_timestamp: string }[] =>+ blobKeys.map((blobKey, index) => ({+ source: 'blob_v2',+ blob_key: blobKey,+ start_timestamp: new Date(START + index * 60000).toISOString(),+ end_timestamp: new Date(START + (index + 1) * 60000).toISOString(),+ }))// Seeds the snapshot store and the coordinator's processed snapshots (which// segments derive from) directly, bypassing the network loading machinery.@@ -454,10 +474,10 @@ describe('sessionRecordingPlayerLogic', () => {const store = dataLogic.cache.storeconst processed: RecordingSnapshot[] = []if (firstSourceSnapshots) {- store.markLoaded(0, firstSourceSnapshots)+ markLoaded(store, 0, firstSourceSnapshots)processed.push(...firstSourceSnapshots)}- store.markLoaded(1, secondSourceSnapshots)+ markLoaded(store, 1, secondSourceSnapshots)processed.push(...secondSourceSnapshots)dataLogic.actions.storeUpdated()sessionRecordingDataCoordinatorLogic({ sessionRecordingId: '2' }).actions.setProcessedSnapshots(processed)@@ -552,6 +572,150 @@ describe('sessionRecordingPlayerLogic', () => {expect(logic.values.currentTimestamp).not.toBe(LATE_FS_TS)})+ it("re-targets the loader when a window-blind seek is satisfied by another window's full snapshot", async () => {+ const dataLogic = snapshotDataLogic({ sessionRecordingId: '2' })+ const coordinator = sessionRecordingDataCoordinatorLogic({ sessionRecordingId: '2' })+ const sources = makeBlobSources(['10', '11', '12', '13', '14', '15'])+ const seekTarget = START + 250000++ dataLogic.actions.loadSnapshotSourcesSuccess(sources as any)+ const store = dataLogic.cache.store+ // a loaded tail keeps the recording end past the seek target, which sits in unloaded territory with no known windowId+ const tail = [inc(START + 295000)]+ markLoaded(store, 5, tail)+ dataLogic.actions.storeUpdated()+ coordinator.actions.setProcessedSnapshots(tail)+ logic.actions.setPause()++ logic.actions.seekToTimestamp(seekTarget)+ expect(logic.values.isBuffering).toBe(true)++ // the seek window arrives: window 2's FullSnapshot satisfies the window-blind canPlayAt while window 1's FullSnapshot sits in the still-unloaded first source+ const arrived = [+ inc(START + 65000),+ inc(START + 125000),+ inc(START + 185000),+ w2fs(START + 245000),+ inc(START + 248000),+ inc(START + 252000),+ ]+ await expectLogic(dataLogic, () => {+ markLoaded(store, 1, [arrived[0]])+ markLoaded(store, 2, [arrived[1]])+ markLoaded(store, 3, [arrived[2]])+ markLoaded(store, 4, arrived.slice(3))+ dataLogic.actions.storeUpdated()+ coordinator.actions.setProcessedSnapshots([...arrived, ...tail])+ }).toDispatchActions([+ (action) =>+ action.type === dataLogic.actionTypes.loadSnapshotsForSource &&+ action.payload.sources?.[0]?.blob_key === '10',+ ])++ expect(logic.values.isBuffering).toBe(true)+ expect(logic.values.playerError).toBeNull()+ })++ it('clamps to a recovery full snapshot even when a preceding gap owns its boundary timestamp', () => {+ // Window 2's recovery FullSnapshot at +70s sits right after window-1 activity, so the micro-gap ending at its timestamp is attributed to window 1 and that inferred windowId must not veto the only usable recovery point.+ seedRecording(+ [fs(START), inc(START + 1000)],+ [+ w2inc(START + 61000),+ w2inc(START + 62000),+ w1move(START + 63000),+ w1move(START + 64000),+ w2fs(START + 70000),+ w2inc(START + 71000),+ w1move(START + 75000),+ ]+ )+ logic.actions.setPause()++ logic.actions.seekToTimestamp(START + 61500)++ expect(logic.values.playerError).toBeNull()+ expect(logic.values.currentTimestamp).toBe(START + 70000)+ })++ it('keeps buffering instead of over-clamping while sources before the recovery point are unloaded', () => {+ const dataLogic = snapshotDataLogic({ sessionRecordingId: '2' })+ const sources = makeBlobSources(['20', '21', '22'])+ dataLogic.actions.loadSnapshotSourcesSuccess(sources as any)+ const store = dataLogic.cache.store+ // window 1 has no FullSnapshot in its loaded head; the unloaded middle source could still contain one earlier than the loaded island's+ const head = [inc(START), inc(START + 1000)]+ const island = [fs(START + 130000), inc(START + 131000)]+ markLoaded(store, 0, head)+ markLoaded(store, 2, island)+ dataLogic.actions.storeUpdated()+ sessionRecordingDataCoordinatorLogic({ sessionRecordingId: '2' }).actions.setProcessedSnapshots([+ ...head,+ ...island,+ ])+ logic.actions.setPause()++ logic.actions.seekToTimestamp(START + 500)++ expect(logic.values.isBuffering).toBe(true)+ expect(logic.values.currentTimestamp).toBe(START + 500)+ })++ it('re-derives a stale current segment when segments reshape under a paused playhead', async () => {+ const coordinator = sessionRecordingDataCoordinatorLogic({ sessionRecordingId: '2' })+ const initial = [fs(START), inc(START + 1000), inc(START + 11000)]+ seedRecording(initial, [])+ logic.actions.setPause()++ logic.actions.seekToTimestamp(START + 5000)+ expect(logic.values.currentSegment?.kind).toBe('gap')++ // processing later synthesizes activity around the playhead, reshaping the gap into a window segment+ const reshaped = [fs(START), inc(START + 1000), w1move(START + 4900), inc(START + 5100), inc(START + 11000)]+ await expectLogic(logic, () => {+ coordinator.actions.setProcessedSnapshots(reshaped)+ }).toFinishAllListeners()++ expect(logic.values.currentSegment).toMatchObject({ kind: 'window', windowId: 1 })+ })++ it('does not recommit the current segment when only its boundaries drift', async () => {+ const coordinator = sessionRecordingDataCoordinatorLogic({ sessionRecordingId: '2' })+ seedRecording([fs(START), inc(START + 1000), inc(START + 11000)], [])+ logic.actions.setPause()++ logic.actions.seekToTimestamp(START + 5000)+ expect(logic.values.currentSegment).toMatchObject({ kind: 'gap', windowId: 1 })++ // live recordings drift segment boundaries on every poll; recommitting would re-seek rrweb each time+ coordinator.actions.setProcessedSnapshots([fs(START), inc(START + 1000), inc(START + 13000)])+ await new Promise((r) => setTimeout(r, 400))++ // the stale boundary is retained, proving no recommit (and no rrweb re-seek) happened+ expect(logic.values.currentSegment).toMatchObject({ kind: 'gap', endTimestamp: START + 11000 })+ })++ it('revives a dead loading chain from syncPlayerState while still buffering', async () => {+ const dataLogic = snapshotDataLogic({ sessionRecordingId: '2' })+ seedRecording(null, [inc(START + 61000), inc(START + 62000)])+ logic.actions.setPause()++ // an inactive player swallows the seek-time load kick, leaving the chain dead the same way repeated fetch failures do+ dataLogic.cache.playerActive = false+ logic.actions.seekToTimestamp(START + 61500)+ expect(logic.values.isBuffering).toBe(true)+ dataLogic.cache.playerActive = true++ // the periodic buffering re-check must restart loading, not just re-derive the verdict+ await expectLogic(dataLogic, () => {+ logic.actions.syncPlayerState()+ }).toDispatchActions([+ (action) =>+ action.type === dataLogic.actionTypes.loadSnapshotsForSource &&+ action.payload.sources?.[0]?.blob_key === '8',+ ])+ })+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@@ -604,9 +768,9 @@ describe('sessionRecordingPlayerLogic', () => {})it('flips a stuck still-ingesting recording to the terminal error once grace lapses', () => {- // The afterMount BUFFERING_REEVALUATION_INTERVAL_MS interval re-runs checkBufferingCompleted;+ // The afterMount BUFFERING_REEVALUATION_INTERVAL_MS interval re-runs syncPlayerState;// this asserts that payload directly (no timer): a recording buffering on waitingForIngestion- // transitions to the terminal error the next time checkBufferingCompleted runs after the grace+ // transitions to the terminal error the next time syncPlayerState runs after the grace// period has elapsed — without any new snapshot data arriving.const graceSpy = jest.spyOn(sessionRecordingDataCoordinatorLogicModule, 'isWithinIngestionGracePeriod')@@ -621,7 +785,7 @@ describe('sessionRecordingPlayerLogic', () => {// grace lapses, no new data arrives — the periodic nudge re-reads the now-definitive// verdict and surfaces the terminal errorgraceSpy.mockReturnValue(false)- logic.actions.checkBufferingCompleted()+ logic.actions.syncPlayerState()expect(logic.values.playerError).toBe('noPlayableFullSnapshot')} finally {diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.tsindex 9521d5924639..7075c40f0c01 100644--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts@@ -160,15 +160,7 @@ const MIN_CLAMPABLE_DEAD_ZONE_MS = 1000// marker); below it the dead-zone clamp handles things silently and a warning would be noiseconst LATE_FULL_SNAPSHOT_THRESHOLD_MS = 20000-// While buffering on a still-ingesting recording we may receive no new events to re-trigger a-// verdict re-evaluation: source polling can back off, and the grace check reads wall-clock time,-// which isn't reactive. Re-run checkBufferingCompleted on this cadence so a recording stuck-// buffering past the ingestion grace period still transitions to the terminal error rather than-// sitting on "Still processing…" forever. A tick is inert unless buffering has genuinely-// completed: checkBufferingCompleted early-returns when not buffering, and while still-// legitimately buffering it only ends buffering on a definitive verdict — so a mid-buffer tick-// never yanks the playhead. Cheap either way. The cadence is a deliberate safety-net interval,-// not a tuned value: worst case is ~2 min of "Still processing…" after grace has already lapsed.+// Safety-net cadence for re-running syncPlayerState while buffering, since neither backed-off source polling nor the non-reactive wall-clock grace check re-triggers verdict re-evaluation on its own.const BUFFERING_REEVALUATION_INTERVAL_MS = 120000export type SeekRenderability =@@ -188,9 +180,7 @@ export type SeekRenderability =| { kind: 'unplayable' }// Non-definitive verdicts where more data could still make the position renderable — playback-// should buffer and keep polling rather than play or error. Centralized so the buffer-entry-// (seekToTimestamp) and buffer-exit (checkBufferingCompleted) checks can't drift if a new-// still-loading kind is added.+// should buffer and keep polling rather than play or error.export function isAwaitingMoreData(renderability: SeekRenderability): boolean {return renderability.kind === 'waitingForData' || renderability.kind === 'waitingForIngestion'}@@ -527,14 +517,7 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(connect((props: SessionRecordingPlayerLogicProps) => ({values: [snapshotDataLogic(props),- [- 'snapshotsLoaded',- 'snapshotsLoading',- 'snapshotSources',- 'isWaitingForPlayableFullSnapshot',- 'snapshotStore',- 'allSourcesLoaded',- ],+ ['snapshotsLoaded', 'snapshotsLoading', 'snapshotSources', 'snapshotStore', 'allSourcesLoaded'],sessionRecordingDataCoordinatorLogic(props),['urls',@@ -606,14 +589,13 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(seekToStart: true,showSeekIndicator: (direction: 'forward' | 'backward', seconds: number) => ({ direction, seconds }),hideSeekIndicator: true,- resolvePlayerState: true,updateAnimation: true,stopAnimation: true,pauseIframePlayback: true,restartIframePlayback: true,setCurrentSegment: (segment: RecordingSegment) => ({ segment }),setRootFrame: (frame: HTMLDivElement | null) => ({ frame }),- checkBufferingCompleted: true,+ syncPlayerState: (forcePlay: boolean = false, reposition: boolean = false) => ({ forcePlay, reposition }),initializePlayerFromStart: true,incrementErrorCount: true,caughtAssetErrorFromIframe: (errorDetails: ResourceErrorDetails) => ({ errorDetails }),@@ -1069,6 +1051,9 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(}const snapshots = sessionPlayerData.snapshotsByWindowId[currentSegment.windowId]+ if (!snapshots?.length) {+ return+ }return Math.max(0, timestamp - snapshots[0].timestamp)}@@ -1084,6 +1069,9 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(return}const snapshots = sessionPlayerData.snapshotsByWindowId[currentSegment.windowId]+ if (!snapshots?.length) {+ return+ }return snapshots[0].timestamp + time}},@@ -1127,33 +1115,54 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(allSourcesLoaded: boolean,sessionPlayerData: SessionPlayerData) => {- return (timestamp: number): SeekRenderability => {+ // Whether any segment containing the FullSnapshot's timestamp belongs to its window; boundary timestamps are shared with the preceding (micro-)gap, whose inferred windowId must not veto a usable recovery point.+ const rendersOwnSegment = (fs: { timestamp: number; windowId: number }): boolean => {+ for (const seg of sessionPlayerData.segments) {+ if (seg.startTimestamp > fs.timestamp) {+ break+ }+ if (seg.windowId === fs.windowId && fs.timestamp <= seg.endTimestamp) {+ return true+ }+ }+ return false+ }+ const computeRenderability = (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' }+ // Gap and buffer positions render once their underlying source has loaded; until then they are still waiting on data.+ return snapshotStore.isRangeLoaded(timestamp, timestamp) === false+ ? { kind: 'waitingForData' }+ : { 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 thisreturn { kind: 'renderable' }}+ const nearestFull = snapshotStore.findNearestFullSnapshot(timestamp, segment.windowId)+ if (nearestFull) {+ // Renderable means a FullSnapshot for this window exists at or before the position AND everything between them is loaded — the same contract the loader satisfies.+ return snapshotStore.getUnloadedIndicesInRange(nearestFull.sourceIndex, targetIndex).length ===+ 0+ ? { kind: 'renderable' }+ : { kind: 'waitingForData' }+ }+ // No FullSnapshot at or before this position for its window — only definitive once everything earlier has loaded, since an unloaded source could still contain one.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)+ const recoveryTarget = snapshotStore.fullSnapshotsAfter(timestamp).find(rendersOwnSegment)if (recoveryTarget) {+ // An unloaded source between the position and the recovery point could still contain an earlier FullSnapshot, so the clamp target isn't final yet.+ if (+ snapshotStore.getUnloadedIndicesInRange(targetIndex, recoveryTarget.sourceIndex).length > 0+ ) {+ return { kind: 'waitingForData' }+ }return recoveryTarget.timestamp - timestamp < MIN_CLAMPABLE_DEAD_ZONE_MS? { kind: 'renderable' }: { kind: 'clampToFullSnapshot', timestamp: recoveryTarget.timestamp }@@ -1168,6 +1177,20 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(? { kind: 'waitingForIngestion' }: { kind: 'unplayable' }}++ // The oracle runs per animation frame and several times per data arrival, so memoize the last verdict; the closure (and memo) is rebuilt whenever any input changes.+ let memoTimestamp: number | null = null+ let memoVerdict: SeekRenderability | null = null+ return (timestamp: number): SeekRenderability => {+ if (timestamp === memoTimestamp && memoVerdict) {+ return memoVerdict+ }+ const verdict = computeRenderability(timestamp)+ // waitingForIngestion reads the wall clock (ingestion grace), so it must be recomputed every call or the lapse to 'unplayable' never happens+ memoTimestamp = verdict.kind === 'waitingForIngestion' ? null : timestamp+ memoVerdict = verdict+ return verdict+ }},],@@ -1208,7 +1231,7 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(// The grace check reads wall-clock `now()` at call time, so this value is intentionally// stale between recomputes — it only re-derives when seekRenderability/currentTimestamp// change, not when the grace period elapses. That's fine: it only drives the overlay- // message, and the buffer machinery (seekToTimestamp, checkBufferingCompleted) re-reads+ // message, and the buffer machinery (seekToTimestamp, syncPlayerState) re-reads// seekRenderability fresh at event time, so the actual ERROR transition isn't gated on it.// The afterMount BUFFERING_REEVALUATION_INTERVAL_MS nudge guarantees that re-read happens// even when no events fire, so a stuck-buffering recording still flips once grace lapses.@@ -1640,9 +1663,7 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(}// Otherwise keep existing player visible (last valid frame)}- if (values.currentTimestamp !== undefined) {- actions.seekToTimestamp(values.currentTimestamp, values.playingState === SessionPlayerState.PLAY)- }+ actions.syncPlayerState(values.playingState === SessionPlayerState.PLAY, true)},setSkipInactivitySetting: ({ skipInactivitySetting }) => {if (!values.currentSegment?.isActive && skipInactivitySetting) {@@ -1657,30 +1678,65 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(syncPlayerSpeed: () => {values.player?.replayer?.setConfig({ speed: values.playerSpeed })},- checkBufferingCompleted: () => {- // 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) {+ // The single map from (position, verdict, play intent) to player state — seeks call it with reposition=true, while data arrivals and the safety tick call it without, making it a pure buffering reconciler that never touches a healthily playing replayer.+ syncPlayerState: ({ forcePlay, reposition }) => {+ // The null check also catches the null that currentTimestamp holds before playback initializes — acting on it would derail the initial load.+ const timestamp = values.currentTimestamp+ if (timestamp == null) {return}- const isBufferingSegment = values.segmentForTimestamp(values.currentTimestamp)?.kind === 'buffer'- 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 || isAwaitingMoreData(renderability))-- if (!stillBuffering) {+ // 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.+ if (!reposition && !values.isBuffering) {+ return+ }+ const segment = values.segmentForTimestamp(timestamp)+ const renderability = values.seekRenderability(timestamp)++ // Everything is loaded and no FullSnapshot could render this position — playback here can never work, so buffering would be pointless.+ if (renderability.kind === 'unplayable') {actions.endBuffer()- actions.seekToTimestamp(values.currentTimestamp, values.playingState === SessionPlayerState.PLAY)+ values.player?.replayer?.pause()+ actions.setPlayerError('noPlayableFullSnapshot')+ return+ }++ // A clamp verdict arriving mid-buffer moves the playhead — route through the seek path, which owns clamp resolution and its telemetry.+ if (renderability.kind === 'clampToFullSnapshot' && renderability.timestamp !== timestamp) {+ actions.seekToTimestamp(timestamp, forcePlay || values.playingState === SessionPlayerState.PLAY)+ return+ }++ // Buffer while the position's data is pending; waitingForIngestion lands here too, polling for late sources instead of showing the terminal error.+ if (segment?.kind === 'buffer' || isAwaitingMoreData(renderability)) {+ values.player?.replayer?.pause()+ actions.startBuffer()+ actions.clearPlayerError()+ // Re-target the (window-blind) loader with the segment's windowId, or it may consider a seek satisfied by another window's FullSnapshot and never load what this position needs.+ if (+ renderability.kind === 'waitingForData' &&+ segment?.kind === 'window' &&+ segment.windowId !== undefined+ ) {+ actions.setTargetTimestamp(timestamp, segment.windowId)+ }+ // Also the only revival path for a loading chain killed by repeated fetch failures.+ actions.loadNextSnapshotSource()+ return+ }++ // endBuffer first, so the pause/play decision below reads the user's play intent rather than the buffering state that outranks it.+ actions.endBuffer()+ actions.stopAnimation()+ if (!forcePlay && values.currentPlayerState === SessionPlayerState.PAUSE) {+ // NOTE: when we show a preview pane, this branch runs+ // in very large recordings this call to pause+ // can consume 100% CPU and freeze the entire page+ values.player?.replayer?.pause(values.toRRWebPlayerTime(timestamp))+ actions.clearPlayerError()+ } else {+ values.player?.replayer?.play(values.toRRWebPlayerTime(timestamp))+ actions.updateAnimation()+ actions.clearPlayerError()}},initializePlayerFromStart: () => {@@ -1701,12 +1757,12 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(if (searchParams.fullscreen) {actions.setIsFullScreen(true)}- if (searchParams.timestamp) {- const desiredStartTime = Number(searchParams.timestamp)- actions.seekToTimestamp(desiredStartTime, true)- } else if (searchParams.t) {- const desiredStartTime = Number(searchParams.t) * 1000- actions.seekToTime(desiredStartTime)+ const timestampParam = Number(searchParams.timestamp)+ const tParam = Number(searchParams.t) * 1000+ if (searchParams.timestamp && Number.isFinite(timestampParam)) {+ actions.seekToTimestamp(timestampParam, true)+ } else if (searchParams.t && Number.isFinite(tParam)) {+ actions.seekToTime(tParam)} else {actions.setSkipToFirstMatchingEvent(true)}@@ -1724,8 +1780,12 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(const currentEvents = values.player?.replayer?.service.state.context.events ?? []const eventsToAdd: eventWithTime[] = []- if (values.isWaitingForPlayableFullSnapshot) {- actions.checkBufferingCompleted()+ // While the playhead's position is still waiting on data, only re-check buffering — the seek machinery will feed the replayer once the position is renderable.+ if (+ values.currentTimestamp != null &&+ isAwaitingMoreData(values.seekRenderability(values.currentTimestamp))+ ) {+ actions.syncPlayerState()breakpoint()return}@@ -1749,6 +1809,8 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(values.player?.replayer?.addEvent(eventsToAdd[i])if (performance.now() - lastYield > YIELD_AFTER_MS) {await new Promise<void>((r) => setTimeout(r, 0))+ // a newer sync run computed its own event diff — cancel here or both runs add the same tail twice+ breakpoint()lastYield = performance.now()}}@@ -1757,7 +1819,20 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(if (!values.currentTimestamp) {actions.initializePlayerFromStart()}- actions.checkBufferingCompleted()++ // Segments can reshape under a stale currentSegment (e.g. a trailing buffer resolving into real window segments), so re-derive it on kind/windowId changes only — re-committing on the constant boundary drift of live recordings would trigger a full rrweb re-seek per poll.+ if (values.currentTimestamp != null && values.currentSegment) {+ const freshSegment = values.segmentForTimestamp(values.currentTimestamp)+ if (+ freshSegment &&+ (freshSegment.kind !== values.currentSegment.kind ||+ freshSegment.windowId !== values.currentSegment.windowId)+ ) {+ actions.setCurrentSegment(freshSegment)+ }+ }++ actions.syncPlayerState()// If snapshot data arrived but the replayer hasn't been created yet,// try initializing it now. This handles the race condition where@@ -1872,24 +1947,20 @@ 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) {+ // If the data before `timestamp` definitively has no FullSnapshot to render from (e.g. lost at capture time), clamp the seek forward to the first renderable position instead of sticking on an unrenderable frame.+ // Despite the action's typing, some callers forward currentTimestamp while it still holds its initial null, which seekRenderability would coerce to 0 and clamp every normal recording to its first FullSnapshot.+ let target = timestamp+ for (let hops = 0; target != null && hops < 10; hops++) {+ const renderability = values.seekRenderability(target)+ if (renderability.kind !== 'clampToFullSnapshot' || renderability.timestamp === target) {+ break+ }posthog.capture('recording player seek clamped to next full snapshot', {sessionId: values.sessionRecordingId,- seekTimestamp: timestamp,+ seekTimestamp: target,clampedToTimestamp: renderability.timestamp,})- actions.seekToTimestamp(renderability.timestamp, forcePlay)- return+ target = renderability.timestamp}actions.stopAnimation()@@ -1898,10 +1969,10 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(cache.pausedMediaElements = []// Check if we're seeking to a new segment- const segment = values.segmentForTimestamp(timestamp)+ const segment = values.segmentForTimestamp(target)- actions.setCurrentTimestamp(timestamp)- actions.setTargetTimestamp(timestamp, segment?.kind === 'window' ? segment.windowId : undefined)+ actions.setCurrentTimestamp(target)+ actions.setTargetTimestamp(target, segment?.kind === 'window' ? segment.windowId : undefined)// End-of-recording detection — independent of segment type so that// findSegmentForTimestamp can safely return a real segment for@@ -1914,57 +1985,14 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(// pause the player before tryInitReplayer has created the// rrweb wrapper. Natural playback progression still triggers// endReached via updateAnimation.- const isPastEnd = values.sessionPlayerData.end && timestamp > values.sessionPlayerData.end.valueOf()+ const isPastEnd = values.sessionPlayerData.end && target > values.sessionPlayerData.end.valueOf()if (isPastEnd) {actions.setEndReached(true)} else if (segment && !objectsEqual(segment, values.currentSegment)) {+ // setCurrentSegment ends in its own syncPlayerState once the replayer is set up for the segmentactions.setCurrentSegment(segment)- }-- // 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.- // `waitingForIngestion` lands here too: a recent recording missing its- // FullSnapshot is still ingesting, so buffer and keep polling for late- // sources rather than showing the terminal error.- else if (- segment?.kind === 'buffer' ||- values.isWaitingForPlayableFullSnapshot ||- isAwaitingMoreData(renderability)- ) {- values.player?.replayer?.pause()- actions.startBuffer()- actions.clearPlayerError()-- // if we're buffering, then be careful to ensure we're loading data- actions.loadNextSnapshotSource()- }-- // If not forced to play and if last playing state was pause, pause- else if (!forcePlay && values.currentPlayerState === SessionPlayerState.PAUSE) {- // NOTE: when we show a preview pane, this branch runs- // in very large recordings this call to pause- // can consume 100% CPU and freeze the entire page- values.player?.replayer?.pause(values.toRRWebPlayerTime(timestamp))- actions.endBuffer()- actions.clearPlayerError()- }- // Otherwise play- else {- values.player?.replayer?.play(values.toRRWebPlayerTime(timestamp))- actions.updateAnimation()- actions.endBuffer()- actions.clearPlayerError()+ } else {+ actions.syncPlayerState(forcePlay, true)}breakpoint()@@ -2124,13 +2152,20 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(}if (newTimestamp == undefined) {- // no newTimestamp is unexpected, bail out+ // No frame timestamp yet (e.g. the replayer exists but hasn't started its timer) — keep the loop alive so stuck-recovery can engage, instead of dying silently.+ cache.disposables.add(() => {+ const timerId = requestAnimationFrame(actions.updateAnimation)+ return () => cancelAnimationFrame(timerId)+ }, 'animationTimer')return}// If we are beyond the current segment then move to the next oneif (values.currentSegment && newTimestamp > values.currentSegment.endTimestamp) {- const nextSegment = values.segmentForTimestamp(newTimestamp)+ // findSegmentForTimestamp clamps past-end timestamps to the nearest segment (for stale-link boot seeks), so end-of-recording must be detected against the recording end, not a null segment.+ const isPastEnd =+ values.sessionPlayerData.end && newTimestamp > values.sessionPlayerData.end.valueOf()+ const nextSegment = isPastEnd ? null : values.segmentForTimestamp(newTimestamp)if (nextSegment) {// NOTE: confusingly this setCurrentTimestamp call is essential to playback@@ -2458,16 +2493,6 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(actions.syncSnapshotsWithPlayer()}},- isWaitingForPlayableFullSnapshot: (isWaiting: boolean, wasWaiting: boolean | undefined) => {- // Force a buffering re-check when the scheduler gives up on seek- // without loading new snapshots. checkBufferingCompleted normally- // fires via syncSnapshotsWithPlayer on new data, but a silent- // seek → buffer_ahead transition delivers none, so the player- // would stay stuck in BUFFER without this listener (#53893).- if (wasWaiting && !isWaiting) {- actions.checkBufferingCompleted()- }- },timestampChangeTracking: (value) => {if (value.timestampMatchesPrevious < 10) {return@@ -2569,7 +2594,7 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(// error once the grace period lapses — but only on a re-read of seekRenderability, which// otherwise happens solely on incoming events. Paused on hidden tabs by the plugin.cache.disposables.add(() => {- const intervalId = setInterval(() => actions.checkBufferingCompleted(), BUFFERING_REEVALUATION_INTERVAL_MS)+ const intervalId = setInterval(() => actions.syncPlayerState(), BUFFERING_REEVALUATION_INTERVAL_MS)return () => clearInterval(intervalId)}, 'bufferingReevaluation')diff --git a/frontend/src/scenes/session-recordings/player/snapshot-store/LoadingScheduler.ts b/frontend/src/scenes/session-recordings/player/snapshot-store/LoadingScheduler.tsdeleted file mode 100644index ab3e97dfcfbb..000000000000--- a/frontend/src/scenes/session-recordings/player/snapshot-store/LoadingScheduler.ts+++ /dev/null@@ -1,230 +0,0 @@-import { LoadBatch, Mode, SnapshotStore } from '@posthog/replay-shared'--const DEFAULT_BATCH_SIZE = 10-const BUFFER_AHEAD_SOURCES = 30-const SEEK_WINDOW_BEHIND = 3-const SEEK_WINDOW_AHEAD = 7--export class LoadingScheduler {- private mode: Mode = { kind: 'buffer_ahead' }- private seekRangeEnd: number | null = null- private seekRangeStart: number | null = null-- seekTo(targetTimestamp: number, targetWindowId?: number): void {- this.mode = { kind: 'seek', targetTimestamp, targetWindowId }- this.seekRangeEnd = null- this.seekRangeStart = null- }-- clearSeek(): void {- this.mode = { kind: 'buffer_ahead' }- }-- loadAll(): void {- this.mode = { kind: 'load_all' }- }-- get currentMode(): Mode {- return this.mode- }-- getNextBatch(- store: SnapshotStore,- batchSize: number = DEFAULT_BATCH_SIZE,- playbackPosition?: number,- playbackWindowId?: number- ): LoadBatch | null {- if (store.sourceCount === 0) {- return null- }-- if (this.mode.kind === 'seek') {- return this.getSeekBatch(store, batchSize)- }-- if (this.mode.kind === 'load_all') {- return this.getLoadAllBatch(store, batchSize)- }-- return this.getBufferAheadBatch(store, batchSize, playbackPosition, playbackWindowId)- }-- get isSeeking(): boolean {- return this.mode.kind === 'seek'- }-- private getSeekBatch(store: SnapshotStore, batchSize: number): LoadBatch | null {- if (this.mode.kind !== 'seek') {- 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)- if (targetIndex === null) {- return null- }- const windowStart = Math.max(0, targetIndex - SEEK_WINDOW_BEHIND)- const windowEnd = Math.min(store.sourceCount - 1, targetIndex + SEEK_WINDOW_AHEAD)-- const unloadedInWindow = store.getUnloadedIndicesInRange(windowStart, windowEnd)- if (unloadedInWindow.length > 0) {- this.seekRangeStart = windowStart- this.seekRangeEnd = windowEnd- return {- sourceIndices: this.truncateToContiguous(unloadedInWindow.slice(0, batchSize)),- reason: 'seek_target',- }- }-- // Ensure range tracking is set- if (this.seekRangeStart === null) {- this.seekRangeStart = windowStart- }- if (this.seekRangeEnd === null) {- this.seekRangeEnd = windowEnd- }-- // Step 2: If can play, clear seek and switch to buffer_ahead- 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, targetWindowId)- if (nearestFull) {- // Fill gap between FullSnapshot source and the start of our loaded range- const gapIndices = store.getUnloadedIndicesInRange(nearestFull.sourceIndex, targetIndex)- if (gapIndices.length > 0) {- // Load the unloaded sources closest to target first (from the end of the gap)- const batch = this.truncateToContiguous(gapIndices.slice(-batchSize))- this.seekRangeStart = Math.min(this.seekRangeStart ?? batch[0], batch[0])- return {- sourceIndices: batch,- reason: 'seek_gap_fill',- }- }- }-- // Step 4: No FullSnapshot found yet, search backward.- // Loop through ranges to skip over already-loaded sections.- let currentStart = this.seekRangeStart ?? targetIndex- while (currentStart > 0) {- const searchStart = Math.max(0, currentStart - batchSize)- const searchEnd = currentStart - 1-- const backwardIndices = store.getUnloadedIndicesInRange(searchStart, searchEnd)- if (backwardIndices.length > 0) {- this.seekRangeStart = searchStart- return {- sourceIndices: this.truncateToContiguous(backwardIndices.slice(0, batchSize)),- reason: 'seek_backward',- }- }- // All sources in this range are loaded — advance past them- currentStart = searchStart- }- this.seekRangeStart = 0-- // 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,- playbackWindowId?: number- ): LoadBatch | null {- let anchorIndex: number- if (playbackPosition !== undefined) {- const idx = store.getSourceIndexForTimestamp(playbackPosition)- if (idx === null) {- return null- }- anchorIndex = idx- } else {- anchorIndex = this.seekRangeEnd ?? 0- }-- const bufferEnd = Math.min(store.sourceCount - 1, anchorIndex + BUFFER_AHEAD_SOURCES - 1)- const aheadIndices = store.getUnloadedIndicesInRange(anchorIndex, bufferEnd)- if (aheadIndices.length > 0) {- return {- sourceIndices: this.truncateToContiguous(aheadIndices.slice(0, batchSize)),- reason: 'buffer_ahead',- }- }-- // 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- }-- private getLoadAllBatch(store: SnapshotStore, batchSize: number): LoadBatch | null {- const unloaded = store.getUnloadedIndicesInRange(0, store.sourceCount - 1)- if (unloaded.length === 0) {- return null- }- return {- sourceIndices: this.truncateToContiguous(unloaded.slice(0, batchSize)),- reason: 'load_all',- }- }-- private truncateToContiguous(indices: number[]): number[] {- if (indices.length <= 1) {- return indices- }- const result = [indices[0]]- for (let i = 1; i < indices.length; i++) {- if (indices[i] !== indices[i - 1] + 1) {- break- }- result.push(indices[i])- }- return result- }-}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 9d544ff754e8..929509447837 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@@ -4,6 +4,8 @@ import { SnapshotStore } from '@posthog/replay-shared'import { RecordingSnapshot, SessionRecordingSnapshotSource } from '~/types'+import { markLoaded } from './test-utils'+function makeSource(index: number,startMin: number = index,@@ -76,8 +78,8 @@ describe('SnapshotStore', () => {it('preserves loaded entries when sources grow', () => {const store = new SnapshotStore()store.setSources(makeSources(3))- store.markLoaded(0, [makeFullSnapshot(1000)])- store.markLoaded(1, [makeSnapshot(2000)])+ markLoaded(store, 0, [makeFullSnapshot(1000)])+ markLoaded(store, 1, [makeSnapshot(2000)])// Live recording adds 2 new sourcesstore.setSources(makeSources(5))@@ -94,99 +96,38 @@ describe('SnapshotStore', () => {it('preserves loaded snapshots through source growth', () => {const store = new SnapshotStore()store.setSources(makeSources(2))- store.markLoaded(0, [makeFullSnapshot(1000)])+ markLoaded(store, 0, [makeFullSnapshot(1000)])store.setSources(makeSources(3))- expect(store.getAllLoadedSnapshots()).toHaveLength(1)- expect(store.getAllLoadedSnapshots()[0].timestamp).toBe(1000)+ expect(store.getEntry(0)?.processedSnapshots).toHaveLength(1)+ expect(store.getEntry(0)?.processedSnapshots?.[0].timestamp).toBe(1000)})})- describe('markLoaded', () => {+ describe('markFetched + markProcessed seeding', () => {it('marks source as loaded and extracts FullSnapshot timestamps', () => {const store = new SnapshotStore()store.setSources(makeSources(3))const ts = new Date(Date.UTC(2023, 7, 11, 12, 1, 30)).getTime()const snaps = [makeFullSnapshot(ts), makeSnapshot(ts + 100)]- store.markLoaded(1, snaps)+ markLoaded(store, 1, snaps)expect(store.getEntry(1)?.state).toBe('loaded')expect(store.getEntry(0)?.state).toBe('unloaded')expect(store.getEntry(1)?.fullSnapshots).toEqual([{ timestamp: ts, windowId: 1 }])})- it('extracts Meta timestamps', () => {- const store = new SnapshotStore()- store.setSources(makeSources(1))-- const ts = 1000- const metaSnap = {- timestamp: ts,- windowId: 1,- type: EventType.Meta,- data: {},- } as unknown as RecordingSnapshot- store.markLoaded(0, [metaSnap])-- expect(store.getEntry(0)?.metaTimestamps).toEqual([ts])- })-it('bumps version', () => {const store = new SnapshotStore()store.setSources(makeSources(1))const v0 = store.version- store.markLoaded(0, [makeSnapshot(1000)])+ markLoaded(store, 0, [makeSnapshot(1000)])expect(store.version).toBeGreaterThan(v0)})})- describe('getAllLoadedSnapshots', () => {- it('returns empty array when nothing loaded', () => {- const store = new SnapshotStore()- store.setSources(makeSources(3))- expect(store.getAllLoadedSnapshots()).toEqual([])- })-- it('merges snapshots from multiple sources in source order', () => {- const store = new SnapshotStore()- store.setSources(makeSources(3))-- const ts0a = new Date(Date.UTC(2023, 7, 11, 12, 0, 10)).getTime()- const ts0b = new Date(Date.UTC(2023, 7, 11, 12, 0, 50)).getTime()- const ts2 = new Date(Date.UTC(2023, 7, 11, 12, 2, 30)).getTime()-- store.markLoaded(0, [makeSnapshot(ts0b), makeSnapshot(ts0a)])- store.markLoaded(2, [makeSnapshot(ts2)])-- const all = store.getAllLoadedSnapshots()- expect(all.map((s) => s.timestamp)).toEqual([ts0a, ts0b, ts2])- })-- it('caches result until version changes', () => {- const store = new SnapshotStore()- store.setSources(makeSources(1))- store.markLoaded(0, [makeSnapshot(100)])-- const first = store.getAllLoadedSnapshots()- const second = store.getAllLoadedSnapshots()- expect(first).toBe(second) // same reference- })- })-- describe('getSnapshotsByWindowId', () => {- it('groups snapshots by windowId', () => {- const store = new SnapshotStore()- store.setSources(makeSources(1))- store.markLoaded(0, [makeSnapshot(100, 1), makeSnapshot(200, 2), makeSnapshot(300, 1)])-- const byWindow = store.getSnapshotsByWindowId()- expect(byWindow[1]?.length).toBe(2)- expect(byWindow[2]?.length).toBe(1)- })- })-describe('getSourceIndexForTimestamp', () => {it.each([{ description: 'timestamp in first source', minute: 0, second: 30, expected: 0 },@@ -231,8 +172,8 @@ describe('SnapshotStore', () => {it('returns false when no FullSnapshot exists', () => {const store = new SnapshotStore()store.setSources(makeSources(3))- store.markLoaded(0, [makeSnapshot(1000)])- store.markLoaded(1, [makeSnapshot(2000)])+ markLoaded(store, 0, [makeSnapshot(1000)])+ markLoaded(store, 1, [makeSnapshot(2000)])const ts = new Date(Date.UTC(2023, 7, 11, 12, 1, 30)).getTime()expect(store.canPlayAt(ts)).toBe(false)@@ -243,9 +184,9 @@ describe('SnapshotStore', () => {store.setSources(makeSources(5))const fsTs = new Date(Date.UTC(2023, 7, 11, 12, 0, 30)).getTime()- store.markLoaded(0, [makeFullSnapshot(fsTs)])- store.markLoaded(1, [makeSnapshot(fsTs + 60000)])- store.markLoaded(2, [makeSnapshot(fsTs + 120000)])+ markLoaded(store, 0, [makeFullSnapshot(fsTs)])+ markLoaded(store, 1, [makeSnapshot(fsTs + 60000)])+ markLoaded(store, 2, [makeSnapshot(fsTs + 120000)])const targetTs = new Date(Date.UTC(2023, 7, 11, 12, 2, 30)).getTime()expect(store.canPlayAt(targetTs)).toBe(true)@@ -256,9 +197,9 @@ describe('SnapshotStore', () => {store.setSources(makeSources(10))const fsTs = new Date(Date.UTC(2023, 7, 11, 12, 0, 30)).getTime()- store.markLoaded(0, [makeFullSnapshot(fsTs)])+ markLoaded(store, 0, [makeFullSnapshot(fsTs)])// Source 1-4 NOT loaded (gap)- store.markLoaded(5, [makeSnapshot(fsTs + 300000)])+ markLoaded(store, 5, [makeSnapshot(fsTs + 300000)])const targetTs = new Date(Date.UTC(2023, 7, 11, 12, 5, 30)).getTime()expect(store.canPlayAt(targetTs)).toBe(false)@@ -270,24 +211,28 @@ describe('SnapshotStore', () => {const fsTs = new Date(Date.UTC(2023, 7, 11, 12, 1, 10)).getTime()const targetTs = new Date(Date.UTC(2023, 7, 11, 12, 1, 50)).getTime()- store.markLoaded(0, [makeSnapshot(1000)])- store.markLoaded(1, [makeFullSnapshot(fsTs), makeSnapshot(targetTs)])+ markLoaded(store, 0, [makeSnapshot(1000)])+ markLoaded(store, 1, [makeFullSnapshot(fsTs), makeSnapshot(targetTs)])expect(store.canPlayAt(targetTs)).toBe(true)})- it('returns false when timestamp is beyond all source data', () => {+ it('resolves timestamps beyond all source data to the loaded tail', () => {const store = new SnapshotStore()store.setSources(makeSources(5))const fsTs = new Date(Date.UTC(2023, 7, 11, 12, 0, 30)).getTime()- for (let i = 0; i < 5; i++) {- store.markLoaded(i, i === 0 ? [makeFullSnapshot(fsTs)] : [makeSnapshot(fsTs + i * 60000)])- }-- // All sources loaded, but timestamp is beyond the last source's endMsconst beyondTs = new Date(Date.UTC(2023, 7, 11, 13, 0, 0)).getTime()++ // Tail not loaded yet: a beyond-end position cannot render+ markLoaded(store, 0, [makeFullSnapshot(fsTs)])expect(store.canPlayAt(beyondTs)).toBe(false)++ // Fully loaded: a beyond-end position renders the last frame without loading anything else+ for (let i = 1; i < 5; i++) {+ markLoaded(store, i, [makeSnapshot(fsTs + i * 60000)])+ }+ expect(store.canPlayAt(beyondTs)).toBe(true)})})@@ -295,7 +240,7 @@ describe('SnapshotStore', () => {it('returns null when no FullSnapshots exist', () => {const store = new SnapshotStore()store.setSources(makeSources(3))- store.markLoaded(0, [makeSnapshot(1000)])+ markLoaded(store, 0, [makeSnapshot(1000)])expect(store.findNearestFullSnapshot(2000)).toBeNull()})@@ -307,8 +252,8 @@ describe('SnapshotStore', () => {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)])+ markLoaded(store, 1, [makeFullSnapshot(fs1)])+ markLoaded(store, 3, [makeFullSnapshot(fs3)])const target = new Date(Date.UTC(2023, 7, 11, 12, 4, 0)).getTime()const result = store.findNearestFullSnapshot(target)@@ -322,7 +267,7 @@ describe('SnapshotStore', () => {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), makeFullSnapshot(fs2)])+ markLoaded(store, 1, [makeFullSnapshot(fs1), makeFullSnapshot(fs2)])const target = new Date(Date.UTC(2023, 7, 11, 12, 2, 0)).getTime()const result = store.findNearestFullSnapshot(target)@@ -336,7 +281,7 @@ describe('SnapshotStore', () => {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)])+ markLoaded(store, 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 })@@ -349,7 +294,7 @@ describe('SnapshotStore', () => {it('returns empty array when no FullSnapshots exist', () => {const store = new SnapshotStore()store.setSources(makeSources(3))- store.markLoaded(0, [makeSnapshot(1000)])+ markLoaded(store, 0, [makeSnapshot(1000)])expect(store.fullSnapshotsAfter(0)).toEqual([])})@@ -361,8 +306,8 @@ describe('SnapshotStore', () => {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)])+ markLoaded(store, 3, [makeFullSnapshot(fs3, 2)])+ markLoaded(store, 1, [makeFullSnapshot(fs1, 1)])expect(store.fullSnapshotsAfter(fs1)).toEqual([{ timestamp: fs1, windowId: 1, sourceIndex: 1 },@@ -377,20 +322,43 @@ describe('SnapshotStore', () => {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)])+ markLoaded(store, 1, [makeFullSnapshot(fs1)])+ markLoaded(store, 3, [makeFullSnapshot(fs3)])expect(store.fullSnapshotsAfter(fs1 + 1)).toEqual([{ timestamp: fs3, windowId: 1, sourceIndex: 3 }])})})+ describe('fetched lifecycle', () => {+ it('fetched sources are not playable until a processing pass promotes them', () => {+ const store = new SnapshotStore()+ store.setSources(makeSources(2))+ const fsTs = new Date(Date.UTC(2023, 7, 11, 12, 0, 30)).getTime()++ store.markFetched(0, [makeFullSnapshot(fsTs), makeSnapshot(fsTs + 100)])+ store.markFetched(1, [makeSnapshot(fsTs + 60000)])++ // fetched data is indexed but not renderable, and not refetchable either+ expect(store.canPlayAt(fsTs + 100)).toBe(false)+ expect(store.allLoaded).toBe(false)+ expect(store.getUnloadedIndicesInRange(0, 1)).toEqual([0, 1])+ expect(store.getUnfetchedIndicesInRange(0, 1)).toEqual([])++ expect(store.markProcessed([0, 1])).toBe(true)++ expect(store.canPlayAt(fsTs + 100)).toBe(true)+ expect(store.allLoaded).toBe(true)+ expect(store.getUnloadedIndicesInRange(0, 1)).toEqual([])+ })+ })+describe('syncFullSnapshotTimestamps', () => {it('syncs synthetic full snapshot timestamps from processed results', () => {const store = new SnapshotStore()store.setSources(makeSources(3))const snapTs = new Date(Date.UTC(2023, 7, 11, 12, 0, 30)).getTime()- store.markLoaded(0, [makeSnapshot(snapTs)])+ markLoaded(store, 0, [makeSnapshot(snapTs)])expect(store.findNearestFullSnapshot(snapTs)).toBeNull()@@ -406,7 +374,7 @@ describe('SnapshotStore', () => {store.setSources(makeSources(3))const snapTs = new Date(Date.UTC(2023, 7, 11, 12, 0, 30)).getTime()- store.markLoaded(0, [makeSnapshot(snapTs)])+ markLoaded(store, 0, [makeSnapshot(snapTs)])expect(store.canPlayAt(snapTs)).toBe(false)@@ -415,6 +383,24 @@ describe('SnapshotStore', () => {expect(store.canPlayAt(snapTs)).toBe(true)})+ it('indexes synthesized full snapshots that fall between source metadata ranges', () => {+ const store = new SnapshotStore()+ const iso = (second: number): string => new Date(Date.UTC(2023, 7, 11, 12, 0, second)).toISOString()+ const at = (second: number): number => new Date(Date.UTC(2023, 7, 11, 12, 0, second)).getTime()+ store.setSources([+ { source: 'blob_v2', blob_key: 'a', start_timestamp: iso(0), end_timestamp: iso(50) },+ { source: 'blob_v2', blob_key: 'b', start_timestamp: iso(56), end_timestamp: iso(110) },+ ] as any)+ markLoaded(store, 0, [makeSnapshot(at(10))])+ markLoaded(store, 1, [makeSnapshot(at(70))])++ // mobile processing synthesizes a FullSnapshot at screenshot.timestamp - 1, which can land between blob ranges+ const changed = store.syncFullSnapshotTimestamps([makeFullSnapshot(at(55))])++ expect(changed).toBe(true)+ expect(store.findNearestFullSnapshot(at(70))).toMatchObject({ timestamp: at(55) })+ })+it.each([{description: 'returns false when timestamps are unchanged',@@ -430,7 +416,7 @@ describe('SnapshotStore', () => {const fsTs = new Date(Date.UTC(2023, 7, 11, 12, 0, 30)).getTime()if (loadSource) {- store.markLoaded(0, [makeFullSnapshot(fsTs)])+ markLoaded(store, 0, [makeFullSnapshot(fsTs)])}const versionBefore = store.version@@ -475,7 +461,7 @@ describe('SnapshotStore', () => {const store = new SnapshotStore()store.setSources(makeSources(5))for (const i of loadedIndices) {- store.markLoaded(i, [makeSnapshot(1000 + i)])+ markLoaded(store, i, [makeSnapshot(1000 + i)])}expect(store.getUnloadedIndicesInRange(start, end)).toEqual(expected)})@@ -485,7 +471,7 @@ describe('SnapshotStore', () => {it('returns state for each source', () => {const store = new SnapshotStore()store.setSources(makeSources(3))- store.markLoaded(1, [makeSnapshot(2000)])+ markLoaded(store, 1, [makeSnapshot(2000)])const states = store.getSourceStates()expect(states).toHaveLength(3)@@ -499,15 +485,15 @@ describe('SnapshotStore', () => {it('is false when not all sources are loaded', () => {const store = new SnapshotStore()store.setSources(makeSources(3))- store.markLoaded(0, [makeSnapshot(1000)])+ markLoaded(store, 0, [makeSnapshot(1000)])expect(store.allLoaded).toBe(false)})it('is true when all sources are loaded', () => {const store = new SnapshotStore()store.setSources(makeSources(2))- store.markLoaded(0, [makeSnapshot(1000)])- store.markLoaded(1, [makeSnapshot(2000)])+ markLoaded(store, 0, [makeSnapshot(1000)])+ markLoaded(store, 1, [makeSnapshot(2000)])expect(store.allLoaded).toBe(true)})@@ -525,10 +511,10 @@ describe('SnapshotStore', () => {store.setSources(makeSources(3))versions.push(store.version)- store.markLoaded(0, [makeSnapshot(1000)])+ markLoaded(store, 0, [makeSnapshot(1000)])versions.push(store.version)- store.markLoaded(1, [makeSnapshot(2000)])+ markLoaded(store, 1, [makeSnapshot(2000)])versions.push(store.version)// Each version should be strictly increasingdiff --git a/frontend/src/scenes/session-recordings/player/snapshot-store/integration.test.ts b/frontend/src/scenes/session-recordings/player/snapshot-store/integration.test.tsindex cbf717d382bf..0bbc65381db4 100644--- a/frontend/src/scenes/session-recordings/player/snapshot-store/integration.test.ts+++ b/frontend/src/scenes/session-recordings/player/snapshot-store/integration.test.ts@@ -4,9 +4,9 @@ import { LoadBatch, SnapshotStore } from '@posthog/replay-shared'import { RecordingSegment, RecordingSnapshot, SessionRecordingSnapshotSource } from '~/types'-import { convertSegmentKinds } from '../utils/segment-kind-conversion'import { createSegments, mapSnapshotsToWindowId } from '../utils/segmenter'-import { LoadingScheduler } from './LoadingScheduler'+import { SeekTarget, planNextBatch } from './planNextBatch'+import { allLoadedSnapshots, markLoaded } from './test-utils'// Each source represents 1 minute of recordingfunction makeSources(count: number): SessionRecordingSnapshotSource[] {@@ -37,16 +37,16 @@ function makeFullSnapshot(timestamp: number, windowId: number = 1): RecordingSna/*** Simulates what snapshotDataLogic does in a loop:- * get next batch → "load" each source → repeat.+ * plan next batch → "load" each source → repeat.** The snapshotFactory controls what snapshots each source produces.* Returns the sequence of batches that were loaded.*/function runLoadingLoop(store: SnapshotStore,- scheduler: LoadingScheduler,opts: {snapshotFactory: (sourceIndex: number) => RecordingSnapshot[]+ target?: SeekTargetbatchSize?: numberplaybackPosition?: numbermaxIterations?: number@@ -57,7 +57,11 @@ function runLoadingLoop(let iterations = 0while (iterations++ < maxIterations) {- const batch = scheduler.getNextBatch(store, opts.batchSize ?? 5, opts.playbackPosition)+ const batch = planNextBatch(+ store,+ { target: opts.target ?? null, loadAll: false, playbackPosition: opts.playbackPosition },+ opts.batchSize ?? 5+ )if (!batch) {break}@@ -66,20 +70,19 @@ function runLoadingLoop(for (const idx of batch.sourceIndices) {const snaps = opts.snapshotFactory(idx)- store.markLoaded(idx, snaps)+ markLoaded(store, idx, snaps)}}return batches}-describe('SnapshotStore + LoadingScheduler integration', () => {+describe('SnapshotStore + planNextBatch integration', () => {it('loads a short recording from start to buffer limit', () => {const store = new SnapshotStore()- const scheduler = new LoadingScheduler()store.setSources(makeSources(10))- const batches = runLoadingLoop(store, scheduler, {+ const batches = runLoadingLoop(store, {snapshotFactory: (i) =>i === 0? [makeFullSnapshot(tsForMinute(i)), makeSnapshot(tsForMinute(i) + 100)]@@ -98,17 +101,14 @@ describe('SnapshotStore + LoadingScheduler integration', () => {it('seek loads window and buffers ahead, does not load backward', () => {const store = new SnapshotStore()- const scheduler = new LoadingScheduler()store.setSources(makeSources(50))- // Seek to minute 30- scheduler.seekTo(tsForMinute(30))-- const batches = runLoadingLoop(store, scheduler, {+ const batches = runLoadingLoop(store, {snapshotFactory: (i) =>i === 28? [makeFullSnapshot(tsForMinute(i)), makeSnapshot(tsForMinute(i) + 100)]: [makeSnapshot(tsForMinute(i))],+ target: { timestamp: tsForMinute(30) },batchSize: 10,})@@ -131,35 +131,31 @@ describe('SnapshotStore + LoadingScheduler integration', () => {it('seek resolves quickly when a FullSnapshot exists near the target', () => {const store = new SnapshotStore()- const scheduler = new LoadingScheduler()store.setSources(makeSources(30))- // Seek to minute 15- scheduler.seekTo(tsForMinute(15))-// FullSnapshot at source 12 (near the seek window)- const batches = runLoadingLoop(store, scheduler, {+ const target = { timestamp: tsForMinute(15) }+ const batches = runLoadingLoop(store, {snapshotFactory: (i) =>i === 12? [makeFullSnapshot(tsForMinute(i)), makeSnapshot(tsForMinute(i) + 100)]: [makeSnapshot(tsForMinute(i))],+ target,batchSize: 10,})- const reasons = batches.map((b) => b.reason)-- expect(reasons[0]).toBe('seek_target')+ expect(batches[0].reason).toBe('seek_target')expect(store.canPlayAt(tsForMinute(15))).toBe(true)- expect(scheduler.currentMode).toEqual({ kind: 'buffer_ahead' })+ // A satisfied target no longer produces seek batches+ expect(planNextBatch(store, { target, loadAll: false })?.reason ?? null).not.toBe('seek_target')})it('buffer ahead stops at BUFFER_AHEAD_SOURCES limit', () => {const store = new SnapshotStore()- const scheduler = new LoadingScheduler()store.setSources(makeSources(100))// Start from beginning, no seek- const batches = runLoadingLoop(store, scheduler, {+ const batches = runLoadingLoop(store, {snapshotFactory: (i) =>i === 0? [makeFullSnapshot(tsForMinute(i)), makeSnapshot(tsForMinute(i) + 100)]@@ -184,11 +180,10 @@ describe('SnapshotStore + LoadingScheduler integration', () => {it('sliding window: advancing playback position loads more ahead', () => {const store = new SnapshotStore()- const scheduler = new LoadingScheduler()store.setSources(makeSources(100))// Load initial buffer at position 0- runLoadingLoop(store, scheduler, {+ runLoadingLoop(store, {snapshotFactory: (i) =>i === 0? [makeFullSnapshot(tsForMinute(i)), makeSnapshot(tsForMinute(i) + 100)]@@ -202,7 +197,7 @@ describe('SnapshotStore + LoadingScheduler integration', () => {).length// Advance playback to minute 20 — should load more ahead- const newBatches = runLoadingLoop(store, scheduler, {+ const newBatches = runLoadingLoop(store, {snapshotFactory: (i) => [makeSnapshot(tsForMinute(i))],batchSize: 10,playbackPosition: tsForMinute(20),@@ -218,92 +213,58 @@ describe('SnapshotStore + LoadingScheduler integration', () => {it('second seek after first seek was partially resolved', () => {const store = new SnapshotStore()- const scheduler = new LoadingScheduler()store.setSources(makeSources(30))// Start seeking to minute 10- scheduler.seekTo(tsForMinute(10))- const firstBatch = scheduler.getNextBatch(store, 10)!+ const firstBatch = planNextBatch(store, { target: { timestamp: tsForMinute(10) }, loadAll: false }, 10)!expect(firstBatch.reason).toBe('seek_target')// Load the first seek batchfor (const idx of firstBatch.sourceIndices) {- store.markLoaded(idx, [makeSnapshot(tsForMinute(idx))])+ markLoaded(store, idx, [makeSnapshot(tsForMinute(idx))])}- // Before seek resolves, user seeks to minute 25 instead- scheduler.seekTo(tsForMinute(25))- expect(scheduler.currentMode).toEqual({ kind: 'seek', targetTimestamp: tsForMinute(25) })-- // New seek should load around minute 25- const secondBatch = scheduler.getNextBatch(store, 10)!+ // Before the first seek resolves, user seeks to minute 25 instead+ const secondBatch = planNextBatch(store, { target: { timestamp: tsForMinute(25) }, loadAll: false }, 10)!expect(secondBatch.reason).toBe('seek_target')expect(secondBatch.sourceIndices.some((i) => i >= 23)).toBe(true)})- it('getAllLoadedSnapshots returns sorted data across multiple load rounds', () => {- const store = new SnapshotStore()- const scheduler = new LoadingScheduler()- store.setSources(makeSources(10))-- // Seek to minute 8 — loads sources 6-9 first- scheduler.seekTo(tsForMinute(8))- const seekBatch = scheduler.getNextBatch(store, 10)!- for (const idx of seekBatch.sourceIndices) {- store.markLoaded(idx, [makeSnapshot(tsForMinute(idx))])- }-- // Then load sources 0-5 via backward search- const nextBatch = scheduler.getNextBatch(store, 10)!- for (const idx of nextBatch.sourceIndices) {- store.markLoaded(idx, [idx === 0 ? makeFullSnapshot(tsForMinute(idx)) : makeSnapshot(tsForMinute(idx))])- }-- // Merged snapshots should be sorted regardless of load order- const allSnapshots = store.getAllLoadedSnapshots()- for (let i = 1; i < allSnapshots.length; i++) {- expect(allSnapshots[i].timestamp).toBeGreaterThanOrEqual(allSnapshots[i - 1].timestamp)- }- })-- it('scheduler returns contiguous batches, skipping loaded gaps', () => {+ it('returns contiguous batches, skipping loaded gaps', () => {const store = new SnapshotStore()- const scheduler = new LoadingScheduler()store.setSources(makeSources(20))- // Pre-load sources 3-6 so the scheduler skips them+ // Pre-load sources 3-6 so the planner skips themfor (let i = 3; i <= 6; i++) {- store.markLoaded(i, [makeSnapshot(tsForMinute(i))])+ markLoaded(store, i, [makeSnapshot(tsForMinute(i))])}// First batch: contiguous [0,1,2] — stops at the loaded gap- const batch = scheduler.getNextBatch(store, 10, tsForMinute(0))!+ const batch = planNextBatch(store, { target: null, loadAll: false, playbackPosition: tsForMinute(0) }, 10)!expect(batch.reason).toBe('buffer_ahead')expect(batch.sourceIndices).toEqual([0, 1, 2])// Load the batchfor (const idx of batch.sourceIndices) {- store.markLoaded(idx, [idx === 0 ? makeFullSnapshot(tsForMinute(idx)) : makeSnapshot(tsForMinute(idx))])+ markLoaded(store, idx, [idx === 0 ? makeFullSnapshot(tsForMinute(idx)) : makeSnapshot(tsForMinute(idx))])}// Next batch picks up from source 7 (first unloaded after the gap)- const nextBatch = scheduler.getNextBatch(store, 10, tsForMinute(0))!+ const nextBatch = planNextBatch(store, { target: null, loadAll: false, playbackPosition: tsForMinute(0) }, 10)!expect(nextBatch.sourceIndices[0]).toBe(7)})it('seek with backward search converges', () => {const store = new SnapshotStore()- const scheduler = new LoadingScheduler()store.setSources(makeSources(55))// Seek to middle with FullSnapshot at source 25- scheduler.seekTo(tsForMinute(30))-- const batches = runLoadingLoop(store, scheduler, {+ const batches = runLoadingLoop(store, {snapshotFactory: (i) =>i === 25? [makeFullSnapshot(tsForMinute(i)), makeSnapshot(tsForMinute(i) + 100)]: [makeSnapshot(tsForMinute(i))],+ target: { timestamp: tsForMinute(30) },batchSize: 10,playbackPosition: tsForMinute(30),maxIterations: 20,@@ -315,11 +276,10 @@ describe('SnapshotStore + LoadingScheduler integration', () => {it('live source growth mid-loading preserves progress and continues', () => {const store = new SnapshotStore()- const scheduler = new LoadingScheduler()store.setSources(makeSources(5))// Load the first 5 sources- runLoadingLoop(store, scheduler, {+ runLoadingLoop(store, {snapshotFactory: (i) =>i === 0? [makeFullSnapshot(tsForMinute(i)), makeSnapshot(tsForMinute(i) + 100)]@@ -328,7 +288,7 @@ describe('SnapshotStore + LoadingScheduler integration', () => {})expect(store.allLoaded).toBe(true)- const snapshotCountBefore = store.getAllLoadedSnapshots().length+ const snapshotCountBefore = allLoadedSnapshots(store).length// Live recording adds 3 new sourcesstore.setSources(makeSources(8))@@ -340,10 +300,10 @@ describe('SnapshotStore + LoadingScheduler integration', () => {expect(store.getEntry(i)?.state).toBe('loaded')}// Previously loaded snapshots still present- expect(store.getAllLoadedSnapshots().length).toBe(snapshotCountBefore)+ expect(allLoadedSnapshots(store).length).toBe(snapshotCountBefore)- // Scheduler picks up the new unloaded sources- const newBatches = runLoadingLoop(store, scheduler, {+ // The planner picks up the new unloaded sources+ const newBatches = runLoadingLoop(store, {snapshotFactory: (i) => [makeSnapshot(tsForMinute(i))],batchSize: 5,})@@ -353,20 +313,7 @@ describe('SnapshotStore + LoadingScheduler integration', () => {expect(store.allLoaded).toBe(true)})- it('seek to position 0 in buffer_ahead mode does not enter seek mode', () => {- const store = new SnapshotStore()- const scheduler = new LoadingScheduler()- store.setSources(makeSources(10))-- // Scheduler starts in buffer_ahead — requesting batches at position 0- // should stay in buffer_ahead, not switch to seek- const batch = scheduler.getNextBatch(store, 5, tsForMinute(0))- expect(batch?.reason).toBe('buffer_ahead')- expect(batch?.sourceIndices[0]).toBe(0)- expect(scheduler.currentMode).toEqual({ kind: 'buffer_ahead' })- })-- describe('SnapshotStore + segment conversion', () => {+ describe('SnapshotStore + segment kind derivation', () => {function makeActiveSnapshot(timestamp: number, windowId: number = 1): RecordingSnapshot {return {timestamp,@@ -377,30 +324,30 @@ describe('SnapshotStore + LoadingScheduler integration', () => {}function buildSegments(store: SnapshotStore, sourceCount: number): RecordingSegment[] {- const snapshots = store.getAllLoadedSnapshots()+ const snapshots = allLoadedSnapshots(store)const snapshotsByWindowId = mapSnapshotsToWindowId(snapshots)const start = { valueOf: () => tsForMinute(0) } as anyconst end = { valueOf: () => tsForMinute(sourceCount) } as any- return createSegments(snapshots, start, end, undefined, snapshotsByWindowId)+ return createSegments(snapshots, start, end, undefined, snapshotsByWindowId, (a, b) =>+ store.isRangeLoaded(a, b)+ )}it('forward seek leaves unloaded region — gaps convert to buffer', () => {const store = new SnapshotStore()- const scheduler = new LoadingScheduler()store.setSources(makeSources(50))// Seek to minute 30, loading sources around it- scheduler.seekTo(tsForMinute(30))- runLoadingLoop(store, scheduler, {+ runLoadingLoop(store, {snapshotFactory: (i) =>i === 28? [makeFullSnapshot(tsForMinute(i)), makeActiveSnapshot(tsForMinute(i) + 100)]: [makeActiveSnapshot(tsForMinute(i))],+ target: { timestamp: tsForMinute(30) },batchSize: 10,})- const rawSegments = buildSegments(store, 50)- const converted = convertSegmentKinds(rawSegments, store, false)+ const converted = buildSegments(store, 50)// Segments covering the unloaded region (minutes 0-27) should be buffer, not gapconst earlySegments = converted.filter((s) => s.startTimestamp < tsForMinute(27))@@ -420,11 +367,10 @@ describe('SnapshotStore + LoadingScheduler integration', () => {store.setSources(makeSources(10))for (let i = 0; i < 10; i++) {- store.markLoaded(i, [i === 0 ? makeFullSnapshot(tsForMinute(i)) : makeActiveSnapshot(tsForMinute(i))])+ markLoaded(store, i, [i === 0 ? makeFullSnapshot(tsForMinute(i)) : makeActiveSnapshot(tsForMinute(i))])}- const rawSegments = buildSegments(store, 10)- const converted = convertSegmentKinds(rawSegments, store, false)+ const converted = buildSegments(store, 10)// No buffer segments should remain — everything is loadedexpect(converted.some((s) => s.kind === 'buffer')).toBe(false)@@ -436,15 +382,15 @@ describe('SnapshotStore + LoadingScheduler integration', () => {// Load all 10 sourcesfor (let i = 0; i < 10; i++) {- store.markLoaded(i, [i === 0 ? makeFullSnapshot(tsForMinute(i)) : makeActiveSnapshot(tsForMinute(i))])+ markLoaded(store, i, [i === 0 ? makeFullSnapshot(tsForMinute(i)) : makeActiveSnapshot(tsForMinute(i))])}- const beforeGrowth = convertSegmentKinds(buildSegments(store, 10), store, false)+ const beforeGrowth = buildSegments(store, 10)expect(beforeGrowth.some((s) => s.kind === 'buffer')).toBe(false)// Live growth: 5 new sources arrivestore.setSources(makeSources(15))- const afterGrowth = convertSegmentKinds(buildSegments(store, 15), store, true)+ const afterGrowth = buildSegments(store, 15)// The new region (minutes 10-14) should have buffer segmentsconst newRegionSegments = afterGrowth.filter((s) => s.endTimestamp > tsForMinute(10))@@ -455,16 +401,15 @@ describe('SnapshotStore + LoadingScheduler integration', () => {describe('getUnloadedIndicesInRange detects gaps for segment conversion', () => {it('reports unloaded sources in a region skipped by forward seek', () => {const store = new SnapshotStore()- const scheduler = new LoadingScheduler()store.setSources(makeSources(50))// Seek forward to minute 30, loading sources 27-49- scheduler.seekTo(tsForMinute(30))- runLoadingLoop(store, scheduler, {+ runLoadingLoop(store, {snapshotFactory: (i) =>i === 28? [makeFullSnapshot(tsForMinute(i)), makeSnapshot(tsForMinute(i) + 100)]: [makeSnapshot(tsForMinute(i))],+ target: { timestamp: tsForMinute(30) },batchSize: 10,})@@ -484,7 +429,7 @@ describe('SnapshotStore + LoadingScheduler integration', () => {// Load all sourcesfor (let i = 0; i < 10; i++) {- store.markLoaded(i, [i === 0 ? makeFullSnapshot(tsForMinute(i)) : makeSnapshot(tsForMinute(i))])+ markLoaded(store, i, [i === 0 ? makeFullSnapshot(tsForMinute(i)) : makeSnapshot(tsForMinute(i))])}// All loaded — gaps here are real inactivity, not pending datadiff --git a/frontend/src/scenes/session-recordings/player/snapshot-store/LoadingScheduler.test.ts b/frontend/src/scenes/session-recordings/player/snapshot-store/planNextBatch.test.tssimilarity index 51%rename from frontend/src/scenes/session-recordings/player/snapshot-store/LoadingScheduler.test.tsrename to frontend/src/scenes/session-recordings/player/snapshot-store/planNextBatch.test.tsindex 788e81c690dc..dd8f026bfcf4 100644--- a/frontend/src/scenes/session-recordings/player/snapshot-store/LoadingScheduler.test.ts+++ b/frontend/src/scenes/session-recordings/player/snapshot-store/planNextBatch.test.ts@@ -4,7 +4,8 @@ import { SnapshotStore } from '@posthog/replay-shared'import { RecordingSnapshot, SessionRecordingSnapshotSource } from '~/types'-import { LoadingScheduler } from './LoadingScheduler'+import { LoadPlanInput, planNextBatch } from './planNextBatch'+import { markLoaded } from './test-utils'function makeSources(count: number): SessionRecordingSnapshotSource[] {return Array.from({ length: count }, (_, i) => ({@@ -49,83 +50,58 @@ function createLoadedStore(const snaps = fullSnapshotIndices.includes(i)? [makeFullSnapshot(ts), makeSnapshot(ts + 100)]: [makeSnapshot(ts)]- store.markLoaded(i, snaps)+ markLoaded(store, i, snaps)}return store}-describe('LoadingScheduler', () => {- describe('buffer ahead', () => {- it('starts in buffer_ahead mode', () => {- const scheduler = new LoadingScheduler()- expect(scheduler.currentMode).toEqual({ kind: 'buffer_ahead' })- })+function plan(+ store: SnapshotStore,+ input: Partial<LoadPlanInput> = {},+ batchSize?: number+): ReturnType<typeof planNextBatch> {+ return planNextBatch(store, { target: null, loadAll: false, ...input }, batchSize)+}- it('loads ahead from anchor position', () => {+describe('planNextBatch', () => {+ describe('buffer ahead', () => {+ it('loads ahead from the start without a position', () => {const store = createLoadedStore(10, [])- const scheduler = new LoadingScheduler()-- const batch = scheduler.getNextBatch(store, 3)- expect(batch).toEqual({- sourceIndices: [0, 1, 2],- reason: 'buffer_ahead',- })+ expect(plan(store, {}, 3)).toEqual({ sourceIndices: [0, 1, 2], reason: 'buffer_ahead' })})it('loads ahead from playback position', () => {const store = createLoadedStore(50, [])- const scheduler = new LoadingScheduler()-- const batch = scheduler.getNextBatch(store, 5, tsForMinute(20))+ const batch = plan(store, { playbackPosition: tsForMinute(20) }, 5)expect(batch?.reason).toBe('buffer_ahead')expect(batch?.sourceIndices[0]).toBe(20)})it('skips already loaded sources', () => {const store = createLoadedStore(10, [0, 1, 2])- const scheduler = new LoadingScheduler()-- const batch = scheduler.getNextBatch(store, 3)- expect(batch).toEqual({- sourceIndices: [3, 4, 5],- reason: 'buffer_ahead',- })+ expect(plan(store, {}, 3)).toEqual({ sourceIndices: [3, 4, 5], reason: 'buffer_ahead' })})it('returns null when all sources ahead are loaded', () => {const store = createLoadedStore(3, [0, 1, 2])- const scheduler = new LoadingScheduler()-- expect(scheduler.getNextBatch(store)).toBeNull()+ expect(plan(store)).toBeNull()})it('returns null when store is empty', () => {- const store = new SnapshotStore()- const scheduler = new LoadingScheduler()-- expect(scheduler.getNextBatch(store)).toBeNull()+ expect(plan(new SnapshotStore())).toBeNull()})it('respects buffer limit', () => {const store = createLoadedStore(100, [])- const scheduler = new LoadingScheduler()-- // With playback at 0, should buffer ahead up to BUFFER_AHEAD_SOURCES (30)- // i.e. indices 0-29 inclusive- const batch = scheduler.getNextBatch(store, 100, tsForMinute(0))- expect(batch?.sourceIndices.length).toBeLessThanOrEqual(100)- const maxIdx = Math.max(...batch!.sourceIndices)- expect(maxIdx).toBe(29)+ const batch = plan(store, { playbackPosition: tsForMinute(0) }, 100)+ expect(Math.max(...batch!.sourceIndices)).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+ // Buffer window fully loaded but no FullSnapshot anywhere, e.g. the initial full snapshot was lost at capture timeconst loaded = Array.from({ length: 30 }, (_, i) => i)const store = createLoadedStore(50, loaded, [])- const scheduler = new LoadingScheduler()-- const batch = scheduler.getNextBatch(store, 10, tsForMinute(0))+ const batch = plan(store, { playbackPosition: tsForMinute(0) })expect(batch?.reason).toBe('seek_forward')expect(batch?.sourceIndices).toEqual([30, 31, 32, 33, 34, 35, 36, 37, 38, 39])})@@ -133,23 +109,26 @@ describe('LoadingScheduler', () => {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(plan(store, { playbackPosition: tsForMinute(0) })).toBeNull()+ })- expect(scheduler.getNextBatch(store, 10, tsForMinute(0))).toBeNull()+ it('does not sweep the recording when the playhead is parked just before the first FullSnapshot', () => {+ // A paused-at-start mount parks the playhead epsilon before its window's first FullSnapshot, and the loaded later FullSnapshot is already the clamp target+ const loaded = Array.from({ length: 30 }, (_, i) => i)+ const store = createLoadedStore(50, loaded, [0])+ expect(plan(store, { playbackPosition: tsForMinute(0) - 50 })).toBeNull()+ expect(plan(store, { playbackPosition: tsForMinute(0) - 50, playbackWindowId: 1 })).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+ // The FullSnapshot at source 0 belongs to window 2 and can't render window-1 content at the playhead, so the scan must still fireconst 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)])+ markLoaded(store, i, i === 0 ? [makeFullSnapshot(ts, 2), makeSnapshot(ts + 100)] : [makeSnapshot(ts)])}- const scheduler = new LoadingScheduler()-- const batch = scheduler.getNextBatch(store, 10, tsForMinute(0), 1)+ const batch = plan(store, { playbackPosition: tsForMinute(0), playbackWindowId: 1 })expect(batch?.reason).toBe('seek_forward')expect(batch?.sourceIndices).toEqual([30, 31, 32, 33, 34, 35, 36, 37, 38, 39])})@@ -160,27 +139,14 @@ describe('LoadingScheduler', () => {20,Array.from({ length: 10 }, (_, i) => i + 10))- const scheduler = new LoadingScheduler()-- // Playback at minute 15 — should not try to load 0-9- const batch = scheduler.getNextBatch(store, 10, tsForMinute(15))- expect(batch).toBeNull()+ expect(plan(store, { playbackPosition: tsForMinute(15) })).toBeNull()})})- describe('seek mode', () => {- it('enters seek mode on seekTo', () => {- const scheduler = new LoadingScheduler()- scheduler.seekTo(tsForMinute(5))- expect(scheduler.currentMode).toEqual({ kind: 'seek', targetTimestamp: tsForMinute(5) })- })-- it('loads window around target on first batch', () => {+ describe('seek target', () => {+ it('loads the window around the target first', () => {const store = createLoadedStore(20, [])- const scheduler = new LoadingScheduler()- scheduler.seekTo(tsForMinute(10))-- const batch = scheduler.getNextBatch(store, 11)+ const batch = plan(store, { target: { timestamp: tsForMinute(10) } }, 11)expect(batch?.reason).toBe('seek_target')// Window: [target-3, target+7] = [7, 17]expect(batch?.sourceIndices[0]).toBe(7)@@ -192,10 +158,7 @@ describe('LoadingScheduler', () => {{ targetMinute: 19, expectedEnd: 19, description: 'clamped at recording end' },])('window is $description', ({ targetMinute, expectedStart, expectedEnd }) => {const store = createLoadedStore(20, [])- const scheduler = new LoadingScheduler()- scheduler.seekTo(tsForMinute(targetMinute))-- const batch = scheduler.getNextBatch(store, 20)!+ const batch = plan(store, { target: { timestamp: tsForMinute(targetMinute) } }, 20)!if (expectedStart !== undefined) {expect(batch.sourceIndices[0]).toBe(expectedStart)}@@ -204,24 +167,17 @@ describe('LoadingScheduler', () => {}})- it('clears seek and buffers ahead when canPlayAt is true', () => {+ it('ignores a satisfied target and buffers ahead instead', () => {const loaded = Array.from({ length: 13 }, (_, i) => i)const store = createLoadedStore(20, loaded, [0])- const scheduler = new LoadingScheduler()- scheduler.seekTo(tsForMinute(5))-- const batch = scheduler.getNextBatch(store, 10)- expect(scheduler.currentMode).toEqual({ kind: 'buffer_ahead' })+ const batch = plan(store, { target: { timestamp: tsForMinute(5) } })expect(batch?.reason).toBe('buffer_ahead')})it('fills gap between FullSnapshot and target', () => {const loaded = [0, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]const store = createLoadedStore(20, loaded, [0])- const scheduler = new LoadingScheduler()- scheduler.seekTo(tsForMinute(10))-- const batch = scheduler.getNextBatch(store, 10)+ const batch = plan(store, { target: { timestamp: tsForMinute(10) } })expect(batch?.reason).toBe('seek_gap_fill')expect(batch?.sourceIndices).toContain(1)expect(batch?.sourceIndices).toContain(4)@@ -230,10 +186,7 @@ describe('LoadingScheduler', () => {it('searches backward when no FullSnapshot found', () => {const loaded = [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]const store = createLoadedStore(20, loaded, [])- const scheduler = new LoadingScheduler()- scheduler.seekTo(tsForMinute(10))-- const batch = scheduler.getNextBatch(store, 10)+ const batch = plan(store, { target: { timestamp: tsForMinute(10) } })expect(batch?.reason).toBe('seek_backward')expect(batch?.sourceIndices.every((i) => i < 8)).toBe(true)})@@ -242,132 +195,98 @@ describe('LoadingScheduler', () => {// Sources 3-7 loaded (no FullSnapshot), 0-2 unloaded, target window 8-17 loadedconst loaded = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]const store = createLoadedStore(20, loaded, [])- const scheduler = new LoadingScheduler()- scheduler.seekTo(tsForMinute(10))-- // Should skip over 3-7 (loaded) and find 0-2 (unloaded)- const batch = scheduler.getNextBatch(store, 10)+ const batch = plan(store, { target: { timestamp: tsForMinute(10) } })expect(batch?.reason).toBe('seek_backward')expect(batch?.sourceIndices).toEqual([0, 1, 2])})- it('gives up and falls to buffer_ahead when backward search exhausted', () => {+ it('returns null when everything is loaded and nothing can satisfy the target', () => {const allIndices = Array.from({ length: 20 }, (_, i) => i)const store = createLoadedStore(20, allIndices, [])- const scheduler = new LoadingScheduler()- scheduler.seekTo(tsForMinute(10))-- const batch = scheduler.getNextBatch(store, 10)- expect(scheduler.currentMode).toEqual({ kind: 'buffer_ahead' })- expect(batch).toBeNull()+ expect(plan(store, { target: { timestamp: tsForMinute(10) } })).toBeNull()})it('searches forward when no FullSnapshot exists at or before the target', () => {// Everything up to source 17 loaded without any FullSnapshot, 18-19 unloadedconst 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)+ const batch = plan(store, { target: { timestamp: tsForMinute(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+ // No FullSnapshot before the target, but one is loaded at source 18 —+ // the player recovers by clamping the seek to it, so nothing more is neededconst 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()+ expect(plan(store, { target: { timestamp: tsForMinute(10) } })).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+ // Sources 0-18 are loaded but the FullSnapshot at source 18 belongs to window 2 and can't render a window-1 target, so source 19 must still be scannedconst 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)])+ markLoaded(store, 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)+ const batch = plan(store, { target: { timestamp: tsForMinute(10), windowId: 1 } })expect(batch?.reason).toBe('seek_forward')expect(batch?.sourceIndices).toEqual([19])})- it('only counts FullSnapshots of the target window when targetWindowId is passed', () => {+ it('only counts FullSnapshots of the target window when a windowId is given', () => {// FullSnapshot at source 5 belongs to window 2; sources 0-2 unloadedconst 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)])+ markLoaded(store, 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 window-agnostic target is satisfied by window 2's FullSnapshot — nothing to fetch+ expect(plan(store, { target: { timestamp: tsForMinute(10) } })).toBeNull()- // 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)+ // A window-1 target must keep searching backward for window 1's FullSnapshot+ const batch = plan(store, { target: { timestamp: tsForMinute(10), windowId: 1 } })expect(batch?.reason).toBe('seek_backward')expect(batch?.sourceIndices).toEqual([0, 1, 2])})- })- describe('buffer ahead after seek', () => {- it('buffers ahead from seek range end', () => {+ it('buffers ahead from the target once the seek is satisfied', () => {const loaded = Array.from({ length: 16 }, (_, i) => i)const store = createLoadedStore(20, loaded, [0])- const scheduler = new LoadingScheduler()- scheduler.seekTo(tsForMinute(8))-- // Seek resolves → buffers ahead from seekRangeEnd- const batch = scheduler.getNextBatch(store, 5)- expect(scheduler.currentMode).toEqual({ kind: 'buffer_ahead' })+ const batch = plan(store, { target: { timestamp: tsForMinute(8) } }, 5)expect(batch?.reason).toBe('buffer_ahead')expect(batch?.sourceIndices).toEqual([16, 17, 18, 19])})- it('does not load backward after seek', () => {+ it('does not load backward once the seek is satisfied', () => {// Sources 3-19 loaded with FullSnapshot at 3, sources 0-2 unloadedconst loaded = Array.from({ length: 17 }, (_, i) => i + 3)const store = createLoadedStore(20, loaded, [3])- const scheduler = new LoadingScheduler()- scheduler.seekTo(tsForMinute(8))-- // Seek resolves. No forward to load, no backward loading → null- const batch = scheduler.getNextBatch(store, 10)- expect(batch).toBeNull()+ expect(plan(store, { target: { timestamp: tsForMinute(8) } })).toBeNull()})})- describe('clearSeek', () => {- it('switches back to buffer_ahead mode', () => {- const scheduler = new LoadingScheduler()- scheduler.seekTo(tsForMinute(5))- scheduler.clearSeek()- expect(scheduler.currentMode).toEqual({ kind: 'buffer_ahead' })+ describe('fetched sources', () => {+ it('does not re-request fetched-but-unprocessed sources', () => {+ const store = new SnapshotStore()+ store.setSources(makeSources(3))+ for (let i = 0; i < 3; i++) {+ store.markFetched(i, [makeSnapshot(tsForMinute(i))])+ }++ // nothing to fetch even though nothing is playable yet — processing, not the network, is what's pending+ expect(plan(store, { target: { timestamp: tsForMinute(1) } })).toBeNull()+ expect(plan(store, { playbackPosition: tsForMinute(0) })).toBeNull()+ expect(plan(store, { loadAll: true })).toBeNull()})})- describe('truncateToContiguous', () => {+ describe('truncation to contiguous ranges', () => {it.each([{ description: 'stops at loaded source in the middle', loaded: [5], expected: [3, 4] },{ description: 'stops at two loaded sources', loaded: [5, 6], expected: [3, 4] },@@ -375,9 +294,7 @@ describe('LoadingScheduler', () => {])('$description', ({ loaded, expected }) => {// Sources 0-9, pre-load 0-2 so buffer_ahead starts at 3const store = createLoadedStore(10, [0, 1, 2, ...loaded])- const scheduler = new LoadingScheduler()-- const batch = scheduler.getNextBatch(store, 10, tsForMinute(0))+ const batch = plan(store, { playbackPosition: tsForMinute(0) })expect(batch?.sourceIndices).toEqual(expected)})})@@ -385,63 +302,28 @@ describe('LoadingScheduler', () => {describe('load all', () => {it('loads all unloaded sources from the beginning', () => {const store = createLoadedStore(10, [3, 4, 5])- const scheduler = new LoadingScheduler()- scheduler.loadAll()-- expect(scheduler.currentMode).toEqual({ kind: 'load_all' })- const batch = scheduler.getNextBatch(store, 5)- expect(batch).toEqual({- sourceIndices: [0, 1, 2],- reason: 'load_all',- })+ expect(plan(store, { loadAll: true }, 5)).toEqual({ sourceIndices: [0, 1, 2], reason: 'load_all' })})it('skips loaded sources and finds next contiguous unloaded batch', () => {const store = createLoadedStore(10, [0, 1, 2, 5, 6])- const scheduler = new LoadingScheduler()- scheduler.loadAll()-- const batch = scheduler.getNextBatch(store, 5)- expect(batch?.sourceIndices).toEqual([3, 4])+ expect(plan(store, { loadAll: true }, 5)?.sourceIndices).toEqual([3, 4])})it('returns null when all sources are loaded', () => {const allLoaded = Array.from({ length: 10 }, (_, i) => i)const store = createLoadedStore(10, allLoaded)- const scheduler = new LoadingScheduler()- scheduler.loadAll()-- expect(scheduler.getNextBatch(store, 10)).toBeNull()+ expect(plan(store, { loadAll: true })).toBeNull()})- it('ignores playback position', () => {+ it('overrides seek targets and playback position', () => {const store = createLoadedStore(50, [])- const scheduler = new LoadingScheduler()- scheduler.loadAll()-- // Even with playback at source 40, load_all starts from the beginning- const batch = scheduler.getNextBatch(store, 5, tsForMinute(40))+ const batch = plan(+ store,+ { loadAll: true, target: { timestamp: tsForMinute(30) }, playbackPosition: tsForMinute(40) },+ 5+ )expect(batch?.sourceIndices).toEqual([0, 1, 2, 3, 4])})})-- describe('isSeeking', () => {- it('is false in buffer_ahead mode', () => {- const scheduler = new LoadingScheduler()- expect(scheduler.isSeeking).toBe(false)- })-- it('is true after seekTo', () => {- const scheduler = new LoadingScheduler()- scheduler.seekTo(tsForMinute(5))- expect(scheduler.isSeeking).toBe(true)- })-- it('is false after clearSeek', () => {- const scheduler = new LoadingScheduler()- scheduler.seekTo(tsForMinute(5))- scheduler.clearSeek()- expect(scheduler.isSeeking).toBe(false)- })- })})diff --git a/frontend/src/scenes/session-recordings/player/snapshot-store/planNextBatch.ts b/frontend/src/scenes/session-recordings/player/snapshot-store/planNextBatch.tsnew file mode 100644index 000000000000..94cecd9e7730--- /dev/null+++ b/frontend/src/scenes/session-recordings/player/snapshot-store/planNextBatch.ts@@ -0,0 +1,138 @@+import { LoadBatch, SnapshotStore } from '@posthog/replay-shared'++const DEFAULT_BATCH_SIZE = 10+const BUFFER_AHEAD_SOURCES = 30+const SEEK_WINDOW_BEHIND = 3+const SEEK_WINDOW_AHEAD = 7++export interface SeekTarget {+ timestamp: number+ windowId?: number+}++export interface LoadPlanInput {+ // the position the player wants to render but cannot yet — ignored once the store can play it+ target: SeekTarget | null+ loadAll: boolean+ playbackPosition?: number+ playbackWindowId?: number+}++// Pure planner: recomputed from scratch on every call, so it carries no cursors or modes and converges because the store's loaded set only grows.+export function planNextBatch(+ store: SnapshotStore,+ { target, loadAll, playbackPosition, playbackWindowId }: LoadPlanInput,+ batchSize: number = DEFAULT_BATCH_SIZE+): LoadBatch | null {+ if (store.sourceCount === 0) {+ return null+ }++ if (loadAll) {+ const unloaded = store.getUnfetchedIndicesInRange(0, store.sourceCount - 1)+ if (unloaded.length === 0) {+ return null+ }+ return { sourceIndices: truncateToContiguous(unloaded.slice(0, batchSize)), reason: 'load_all' }+ }++ if (target && !store.canPlayAt(target.timestamp, target.windowId)) {+ const seekBatch = planSeekBatch(store, target, batchSize)+ if (seekBatch) {+ return seekBatch+ }+ }++ return planBufferAheadBatch(store, batchSize, playbackPosition ?? target?.timestamp, playbackWindowId)+}++function planSeekBatch(store: SnapshotStore, { timestamp, windowId }: SeekTarget, batchSize: number): LoadBatch | null {+ const targetIndex = store.getSourceIndexForTimestamp(timestamp)+ if (targetIndex === null) {+ return null+ }+ const windowStart = Math.max(0, targetIndex - SEEK_WINDOW_BEHIND)+ const windowEnd = Math.min(store.sourceCount - 1, targetIndex + SEEK_WINDOW_AHEAD)++ // Step 1: load the window around the target.+ const unloadedInWindow = store.getUnfetchedIndicesInRange(windowStart, windowEnd)+ if (unloadedInWindow.length > 0) {+ return { sourceIndices: truncateToContiguous(unloadedInWindow.slice(0, batchSize)), reason: 'seek_target' }+ }++ // Step 2: fill the span between the nearest usable FullSnapshot and the target, closest to the target first.+ const nearestFull = store.findNearestFullSnapshot(timestamp, windowId)+ if (nearestFull) {+ const gapIndices = store.getUnfetchedIndicesInRange(nearestFull.sourceIndex, targetIndex)+ if (gapIndices.length > 0) {+ return { sourceIndices: truncateToContiguous(gapIndices.slice(-batchSize)), reason: 'seek_gap_fill' }+ }+ return null+ }++ // Step 3: no FullSnapshot at or before the target is loaded — hunt backward, closest sources first.+ const backwardIndices = store.getUnfetchedIndicesInRange(0, windowStart - 1)+ if (backwardIndices.length > 0) {+ return { sourceIndices: truncateToContiguous(backwardIndices.slice(-batchSize)), reason: 'seek_backward' }+ }++ // Step 4: nothing before the target can help, so recovery must come from a later FullSnapshot in the target's window — keep loading forward until one is known.+ if (!store.hasFullSnapshotAfter(timestamp, windowId)) {+ const forwardIndices = store.getUnfetchedIndicesInRange(windowEnd + 1, store.sourceCount - 1)+ if (forwardIndices.length > 0) {+ return { sourceIndices: truncateToContiguous(forwardIndices.slice(0, batchSize)), reason: 'seek_forward' }+ }+ }++ return null+}++function planBufferAheadBatch(+ store: SnapshotStore,+ batchSize: number,+ playbackPosition?: number,+ playbackWindowId?: number+): LoadBatch | null {+ let anchorIndex = 0+ if (playbackPosition !== undefined) {+ const index = store.getSourceIndexForTimestamp(playbackPosition)+ if (index === null) {+ return null+ }+ anchorIndex = index+ }++ const bufferEnd = Math.min(store.sourceCount - 1, anchorIndex + BUFFER_AHEAD_SOURCES - 1)+ const aheadIndices = store.getUnfetchedIndicesInRange(anchorIndex, bufferEnd)+ if (aheadIndices.length > 0) {+ return { sourceIndices: truncateToContiguous(aheadIndices.slice(0, batchSize)), reason: 'buffer_ahead' }+ }++ // A playhead with no usable FullSnapshot before it and none loaded after it can't progress to pull the buffer window along, so scan forward until a recovery FullSnapshot is known (with a later one already loaded the player clamps to it, and a paused-at-start playhead parked epsilon-before its window's first FullSnapshot must not sweep the whole recording).+ if (+ playbackPosition !== undefined &&+ store.findNearestFullSnapshot(playbackPosition, playbackWindowId) === null &&+ !store.hasFullSnapshotAfter(playbackPosition, playbackWindowId)+ ) {+ const forwardIndices = store.getUnfetchedIndicesInRange(bufferEnd + 1, store.sourceCount - 1)+ if (forwardIndices.length > 0) {+ return { sourceIndices: truncateToContiguous(forwardIndices.slice(0, batchSize)), reason: 'seek_forward' }+ }+ }++ return null+}++function truncateToContiguous(indices: number[]): number[] {+ if (indices.length <= 1) {+ return indices+ }+ const result = [indices[0]]+ for (let i = 1; i < indices.length; i++) {+ if (indices[i] !== indices[i - 1] + 1) {+ break+ }+ result.push(indices[i])+ }+ return result+}diff --git a/frontend/src/scenes/session-recordings/player/snapshot-store/test-utils.ts b/frontend/src/scenes/session-recordings/player/snapshot-store/test-utils.tsnew file mode 100644index 000000000000..dad14c6bcbd1--- /dev/null+++ b/frontend/src/scenes/session-recordings/player/snapshot-store/test-utils.ts@@ -0,0 +1,20 @@+import { SnapshotStore } from '@posthog/replay-shared'++import { RecordingSnapshot } from '~/types'++// One-shot fetched+processed seeding for tests that don't exercise the processing pipeline; production code must go through markFetched + markProcessed.+export function markLoaded(store: SnapshotStore, sourceIndex: number, snapshots: RecordingSnapshot[]): void {+ store.markFetched(sourceIndex, snapshots)+ store.markProcessed([sourceIndex])+}++export function allLoadedSnapshots(store: SnapshotStore): RecordingSnapshot[] {+ const result: RecordingSnapshot[] = []+ for (let i = 0; i < store.sourceCount; i++) {+ const entry = store.getEntry(i)+ if (entry?.state !== 'unloaded' && entry?.processedSnapshots) {+ result.push(...entry.processedSnapshots)+ }+ }+ return result.sort((a, b) => a.timestamp - b.timestamp)+}diff --git a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.store.test.ts b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.store.test.tsindex 6ad3b41300ac..de3d6413b36a 100644--- a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.store.test.ts+++ b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.store.test.ts@@ -6,6 +6,7 @@ import { EventType } from 'posthog-js/rrweb-types'import { RecordingSnapshot, SessionRecordingSnapshotSource } from '~/types'import { setupSessionRecordingTest } from './__mocks__/test-setup'+import { allLoadedSnapshots, markLoaded } from './snapshot-store/test-utils'import { snapshotDataLogic } from './snapshotDataLogic'const SOURCE_A: SessionRecordingSnapshotSource = {@@ -122,11 +123,11 @@ describe('snapshotDataLogic (store-based loading)', () => {.toFinishAllListeners()const store = logic.values.snapshotStore!- const allSnaps = store.getAllLoadedSnapshots()+ const allSnaps = allLoadedSnapshots(store)expect(allSnaps.length).toBeGreaterThan(0)})- it('marks sources as loaded after bucketing', async () => {+ it('marks sources as fetched, not loaded, after bucketing', async () => {mountLogic()await expectLogic(logic, () => {@@ -135,8 +136,10 @@ describe('snapshotDataLogic (store-based loading)', () => {.toDispatchActions(['loadSnapshotsForSourceSuccess']).toFinishAllListeners()+ // playable state is granted by the coordinator's processing pass, which isn't mounted hereconst states = logic.values.sourceLoadingStates- expect(states.some((s) => s.state === 'loaded')).toBe(true)+ expect(states.some((s) => s.state === 'fetched')).toBe(true)+ expect(states.some((s) => s.state === 'loaded')).toBe(false)})})@@ -164,14 +167,14 @@ describe('snapshotDataLogic (store-based loading)', () => {const store = logic.values.snapshotStore!store.setSources([SOURCE_A])- store.markLoaded(0, [makeFullSnapshot(tsMs(0, 0)), makeSnapshot(tsMs(0, 30))])+ markLoaded(store, 0, [makeFullSnapshot(tsMs(0, 0)), makeSnapshot(tsMs(0, 30))])await expectLogic(logic, () => {logic.actions.setTargetTimestamp(tsMs(0, 15))}).toDispatchActions(['loadNextSnapshotSource'])- // Should NOT be in seek mode — data is already available- expect(logic.values.isWaitingForPlayableFullSnapshot).toBe(false)+ // The satisfied target is recorded but must not trigger any fetch+ expect(logic.values.seekTarget).toEqual({ timestamp: tsMs(0, 15), windowId: undefined })})it('does not override load_all mode', async () => {@@ -190,87 +193,7 @@ describe('snapshotDataLogic (store-based loading)', () => {logic.actions.setTargetTimestamp(tsMs(2))await expectLogic(logic).toDispatchActions(['loadNextSnapshotSource'])- expect(logic.values.isWaitingForPlayableFullSnapshot).toBe(false)- })-- it('does not enter seek for source 0 when already in buffer_ahead', async () => {- mountLogic()-- logic.actions.loadSnapshotSourcesSuccess([SOURCE_A, SOURCE_B])- await expectLogic(logic).toFinishAllListeners()-- logic.values.snapshotStore!.setSources([SOURCE_A, SOURCE_B])-- await expectLogic(logic, () => {- logic.actions.setTargetTimestamp(tsMs(0, 0))- }).toDispatchActions(['loadNextSnapshotSource'])-- expect(logic.values.isWaitingForPlayableFullSnapshot).toBe(false)- })-- it('re-evaluates isWaitingForPlayableFullSnapshot after silent seek clear (#53893 Bug B)', async () => {- // Regression test for the stale-selector half of #53893.- //- // When LoadingScheduler.getSeekBatch silently clears seek mode- // (step 5: backward search exhausted, no full snapshot found),- // it mutates cache.scheduler.currentMode directly. The store's- // version doesn't bump because no data is added. Without the- // storeUpdated dispatch on that transition and a selector- // dependency that tracks it, isWaitingForPlayableFullSnapshot- // stays cached at `true` — poisoning the next seekToTimestamp.- //- // This exercise uses the step-5 path specifically because it's- // the case where mode changes WITHOUT any store mutation, so- // we can isolate the selector-reactivity half of the fix from- // the step-2 path (where markLoaded would also bump the- // selector's storeVersion dependency and mask a regression).- mountLogic()-- // Pre-load sources as loaded-but-empty. state='loaded' means- // no seek batch will try to load them, and empty snapshots mean- // no full snapshot exists anywhere → canPlayAt is always false- // and the backward search in getSeekBatch step 4/5 will exhaust.- const store = logic.values.snapshotStore!- store.setSources([SOURCE_A, SOURCE_B])- store.markLoaded(0, [])- store.markLoaded(1, [])-- // Tell Kea about the sources. setSources preserves loaded- // entries by blob_key, and loadNextSnapshotSource sees- // everything as loaded → no loader dispatches.- logic.actions.loadSnapshotSourcesSuccess([SOURCE_A, SOURCE_B])- await expectLogic(logic).toFinishAllListeners()-- // Directly put the scheduler in seek mode. setTargetTimestamp- // would work too, but it's fiddly to arrange the early-return- // checks in this state — direct seekTo is cleaner.- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const scheduler = (logic as any).cache.scheduler as {- seekTo: (ts: number) => void- currentMode: { kind: string }- }- scheduler.seekTo(tsMs(0, 30))-- // Pre-read: seek mode + no full snapshot → true, CACHED.- expect(logic.values.isWaitingForPlayableFullSnapshot).toBe(true)-- // Trigger getSeekBatch. Step 1 finds nothing unloaded (all- // loaded), step 2 canPlayAt=false (no full snapshot), step 3- // findNearestFullSnapshot=null, step 4 backward search has- // nothing unloaded, step 5 exhausted → clearSeek. Mode flips- // to buffer_ahead WITHOUT any store mutation — this is the- // isolation point that catches Bug B.- logic.actions.loadNextSnapshotSource()- await expectLogic(logic).toFinishAllListeners()-- // Sanity: scheduler actually exited seek mode.- expect(scheduler.currentMode.kind).toBe('buffer_ahead')-- // Without the fix (no storeUpdated dispatch on silent clearSeek,- // or selector depending on storeVersion instead of storeUpdateCount),- // this returns a stale `true` because nothing in Kea's- // reactivity graph changed while the mode flipped.- expect(logic.values.isWaitingForPlayableFullSnapshot).toBe(false)+ expect(logic.values.loadAllMode).toBe(true)})it('enters seek mode when called before sources load (past-end URL regression #53893)', async () => {@@ -292,23 +215,11 @@ describe('snapshotDataLogic (store-based loading)', () => {// Pre-condition: store is mounted but has no sources yet.expect(logic.values.snapshotStore!.sourceCount).toBe(0)- // Force memoization at false so the test catches a missing storeUpdated- // after scheduler.seekTo (per review feedback on #53893).- expect(logic.values.isWaitingForPlayableFullSnapshot).toBe(false)-logic.actions.setTargetTimestamp(tsMs(5, 0))await expectLogic(logic).toFinishAllListeners()- // With the fix: getSourceIndexForTimestamp returns null for- // the empty store, so targetIndex === 0 is false and the- // optimization doesn't fire. scheduler.seekTo runs and the- // storeUpdated dispatch on the wasSeeking transition ensures- // the selector re-evaluates. canPlayAt is false (no data),- // so isWaitingForPlayableFullSnapshot is true.- //- // Without the fix: scheduler stays in buffer_ahead, selector- // returns false, player has no signal to keep buffering.- expect(logic.values.isWaitingForPlayableFullSnapshot).toBe(true)+ // The target must survive until sources arrive so the planner can seek to it+ expect(logic.values.seekTarget).toEqual({ timestamp: tsMs(5, 0), windowId: undefined })})})@@ -385,12 +296,32 @@ describe('snapshotDataLogic (store-based loading)', () => {const store = logic.values.snapshotStore!store.setSources([SOURCE_A])- store.markLoaded(0, [makeFullSnapshot(tsMs(0, 0))])+ markLoaded(store, 0, [makeFullSnapshot(tsMs(0, 0))])await expectLogic(logic, () => {logic.actions.loadNextSnapshotSource()}).toDispatchActions(['maybeStartPolling'])})++ it('re-arms the next poll after a poll returns unchanged sources', async () => {+ // polling-enabled instance, unlike the shared harness+ logic = snapshotDataLogic({ sessionRecordingId: 'store-test-polling' })+ logic.mount()++ // pre-seed the store as fully loaded so no snapshot fetch starts+ const store = logic.values.snapshotStore!+ store.setSources([SOURCE_A])+ markLoaded(store, 0, [makeFullSnapshot(tsMs(0, 0))])++ await expectLogic(logic, () => {+ logic.actions.loadSnapshotSourcesSuccess([SOURCE_A])+ }).toDispatchActions(['maybeStartPolling', 'startPolling'])++ // a poll response with the same source list must close this cycle and arm the next one+ await expectLogic(logic, () => {+ logic.actions.loadSnapshotSourcesSuccess([SOURCE_A])+ }).toDispatchActions(['stopPolling', 'maybeStartPolling', 'startPolling'])+ })})describe('selectors', () => {@@ -400,7 +331,7 @@ describe('snapshotDataLogic (store-based loading)', () => {const store = logic.values.snapshotStore!store.setSources([SOURCE_A])- store.markLoaded(0, [makeFullSnapshot(tsMs(0, 0))])+ markLoaded(store, 0, [makeFullSnapshot(tsMs(0, 0))])expect(logic.values.snapshotsLoading).toBe(false)})@@ -412,7 +343,7 @@ describe('snapshotDataLogic (store-based loading)', () => {expect(logic.values.allSourcesLoaded).toBe(false)})- it('becomes true once all sources have been marked loaded', () => {+ it('becomes true only once fetched sources have been processed', () => {mountLogic()const store = logic.values.snapshotStore!@@ -421,25 +352,19 @@ describe('snapshotDataLogic (store-based loading)', () => {// Trigger selector re-evaluation with a source setlogic.actions.loadSnapshotSourcesSuccess([SOURCE_A, SOURCE_B])- // Not yet — no data loaded- store.markLoaded(0, [makeFullSnapshot(tsMs(0, 0))])- logic.actions.loadSnapshotsForSourceSuccess({ sources: [SOURCE_A] })+ // Fetched data alone is not playable+ store.markFetched(0, [makeFullSnapshot(tsMs(0, 0))])+ store.markFetched(1, [makeSnapshot(tsMs(1, 0))])+ logic.actions.storeUpdated()expect(logic.values.allSourcesLoaded).toBe(false)- // Now mark the second source- store.markLoaded(1, [makeSnapshot(tsMs(1, 0))])- logic.actions.loadSnapshotsForSourceSuccess({ sources: [SOURCE_B] })+ // A processing pass promotes them+ store.markProcessed([0, 1])+ logic.actions.storeUpdated()expect(logic.values.allSourcesLoaded).toBe(true)})})- describe('isWaitingForPlayableFullSnapshot', () => {- it('is false when not seeking', () => {- mountLogic()- expect(logic.values.isWaitingForPlayableFullSnapshot).toBe(false)- })- })-describe('storeVersion', () => {it('increments when store mutates', () => {mountLogic()@@ -491,7 +416,7 @@ describe('snapshotDataLogic (store-based loading)', () => {const store = logic.values.snapshotStore!expect(store.sourceCount).toBe(3)- expect(store.getAllLoadedSnapshots().length).toBeGreaterThan(0)+ expect(allLoadedSnapshots(store).length).toBeGreaterThan(0)})})@@ -509,8 +434,8 @@ describe('snapshotDataLogic (store-based loading)', () => {const store = logic.values.snapshotStore!expect(store.sourceCount).toBe(1)- expect(store.allLoaded).toBe(true)- expect(store.getAllLoadedSnapshots()).toHaveLength(3)+ expect(store.getSourceStates()[0].state).toBe('fetched')+ expect(allLoadedSnapshots(store)).toHaveLength(3)})it('makes snapshots available via coordinator selector', async () => {@@ -525,7 +450,7 @@ describe('snapshotDataLogic (store-based loading)', () => {.toFinishAllListeners()const store = logic.values.snapshotStore!- const loaded = store.getAllLoadedSnapshots()+ const loaded = allLoadedSnapshots(store)expect(loaded).toHaveLength(2)expect(loaded[0].type).toBe(EventType.FullSnapshot)})diff --git a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsxindex 5d8ef9f416f1..b77e25c05d98 100644--- a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx+++ b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx@@ -21,7 +21,7 @@ import {SnapshotSourceType,} from '~/types'-import { LoadingScheduler } from './snapshot-store/LoadingScheduler'+import { SeekTarget, planNextBatch } from './snapshot-store/planNextBatch'import type { snapshotDataLogicType } from './snapshotDataLogicType'const DEFAULT_V2_POLLING_INTERVAL_MS: number = 10000@@ -35,14 +35,7 @@ export interface SnapshotLogicProps {accessToken?: string}-// Reactivity note (#53893): `cache.store` (SnapshotStore) and `cache.scheduler`-// (LoadingScheduler) live outside Kea. Their mutations are invisible to-// selectors unless `storeUpdated()` is dispatched. Any listener that-// mutates either — scheduler.seekTo, scheduler.clearSeek, store.markLoaded,-// store.setSources — MUST dispatch `storeUpdated()` afterwards. Any selector-// that reads `cache.scheduler.currentMode` or `cache.store` state MUST depend-// on `storeUpdateCount` (not `storeVersion`, which only bumps on data mutations-// and would memoize to stale values across pure mode transitions).+// Reactivity note (#53893): `cache.store` (SnapshotStore) lives outside Kea, so any listener that mutates it (markFetched, setSources) MUST dispatch `storeUpdated()` afterwards, and any selector reading it MUST depend on `storeVersion`.export const snapshotDataLogic = kea<snapshotDataLogicType>([path((key) => ['scenes', 'session-recordings', 'snapshotLogic', key]),props({} as SnapshotLogicProps),@@ -71,8 +64,7 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([updatePlaybackPosition: (timestamp: number, windowId?: number) => ({ timestamp, windowId }),setPlayerActive: (active: boolean) => ({ active }),loadAllSources: true,- // dispatch after any mutation to cache.store or cache.scheduler —- // these live outside Kea's reactivity and need explicit invalidation+ // dispatch after any mutation to cache.store — it lives outside Kea's reactivity and needs explicit invalidationstoreUpdated: true,}),reducers(() => ({@@ -82,6 +74,19 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([storeUpdated: (state: number) => state + 1,},],+ seekTarget: [+ null as SeekTarget | null,+ {+ setTargetTimestamp: (_: SeekTarget | null, { timestamp, windowId }) =>+ timestamp === null ? null : { timestamp, windowId },+ },+ ],+ loadAllMode: [+ false,+ {+ loadAllSources: () => true,+ },+ ],loadingSources: [[] as Pick<SessionRecordingSnapshotSource, 'source' | 'blob_key' | 'start_timestamp' | 'end_timestamp'>[],{@@ -223,50 +228,19 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([},],})),- listeners(({ values, actions, cache, props }) => ({- setTargetTimestamp: ({ timestamp, windowId }) => {- if (!cache.scheduler || !cache.store) {+ listeners(({ values, actions, cache, props, selectors }) => ({+ setTargetTimestamp: ({ timestamp, windowId }, _breakpoint, __, previousState) => {+ if (timestamp === null) {return}- if (timestamp !== null) {- cache.playbackPosition = timestamp- cache.playbackWindowId = windowId-- const currentMode = cache.scheduler.currentMode- // Don't interrupt load_all (e.g. during export)- if (currentMode.kind === 'load_all') {- actions.loadNextSnapshotSource()- return- }- // Don't re-seek to the same target- 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, windowId)) {- actions.loadNextSnapshotSource()- return- }- // Don't enter seek mode when at source 0 and already in buffer_ahead mode —- // buffer_ahead loading already starts from the beginning. An empty store- // returns null here, which naturally falls through to scheduler.seekTo —- // that's required for ?t=<past-end> URLs that arrive before sources load- // (see #53893).- const targetIndex = cache.store.getSourceIndexForTimestamp(timestamp)- if (targetIndex === 0 && currentMode.kind === 'buffer_ahead') {- actions.loadNextSnapshotSource()- return- }-- cache.scheduler.seekTo(timestamp, windowId)- actions.storeUpdated()- actions.loadNextSnapshotSource()+ cache.playbackPosition = timestamp+ cache.playbackWindowId = windowId+ const previousTarget = selectors.seekTarget(previousState)+ if (previousTarget?.timestamp !== timestamp || previousTarget?.windowId !== windowId) {+ // A genuinely new target grants fresh retries after the permanent-failure cap.+ cache.loadFailureCount = 0}+ actions.loadNextSnapshotSource()},updatePlaybackPosition: ({ timestamp, windowId }) => {@@ -284,18 +258,21 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([},loadAllSources: () => {- if (cache.scheduler) {- cache.scheduler.loadAll()- actions.loadNextSnapshotSource()- }+ actions.loadNextSnapshotSource()+ },++ // Sources can become playable (promotion) without any new fetch completing, and polling only arms once everything is loaded — so the poll gate re-checks on every store mutation; it is fully guarded and inert mid-fetch.+ storeUpdated: () => {+ actions.maybeStartPolling()},setSnapshots: ({ snapshots }: { snapshots: RecordingSnapshot[] }) => {if (cache.store) {const fileSource = { source: SnapshotSourceType.file } as SessionRecordingSnapshotSourcecache.store.setSources([fileSource])- cache.store.markLoaded(0, snapshots)+ cache.store.markFetched(0, snapshots)cache.pendingBatch = { snapshots, sources: [fileSource] }+ actions.storeUpdated()}// Set sources first, then trigger the success action@@ -326,20 +303,19 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([cache.previousSourceKeys = currentSourceKeys+ // Close the poll cycle on both branches, or maybeStartPolling's isPolling gate blocks every future poll after the first unchanged response.+ actions.stopPolling()if (sourcesChanged) {actions.resetPollingInterval()cache.lastSourcesChangeTime = Date.now()- actions.stopPolling()+ cache.store?.setSources(snapshotSources)+ actions.storeUpdated()} else {const currentInterval = values.pollingIntervalconst newInterval = Math.min(currentInterval * 2, MAX_V2_POLLING_INTERVAL_MS)actions.setPollingInterval(newInterval)}- if (sourcesChanged) {- cache.store?.setSources(snapshotSources)- }-actions.loadNextSnapshotSource()},@@ -391,7 +367,8 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([buckets.get(sourceEntries[seIdx].sourceIndex)?.push(snap)}for (const se of sourceEntries) {- cache.store?.markLoaded(se.sourceIndex, buckets.get(se.sourceIndex)!)+ // fetched, not loaded — sources become playable only once a processing pass promotes them+ cache.store?.markFetched(se.sourceIndex, buckets.get(se.sourceIndex)!)}actions.storeUpdated()@@ -408,6 +385,10 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([},maybeStartPolling: () => {+ // file playback has no recording id and nothing server-side to poll+ if (!props.sessionRecordingId) {+ return+ }if (props.blobV2PollingDisabled || !values.allSourcesLoaded || values.isPolling || document.hidden) {return}@@ -438,17 +419,15 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([return}- if (!cache.scheduler || !cache.store) {+ if (!cache.store) {return}- // getNextBatch may flip the scheduler out of seek mode without- // 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, cache.playbackWindowId)- if (wasSeeking && cache.scheduler.currentMode.kind !== 'seek') {- actions.storeUpdated()- }+ const batch = planNextBatch(cache.store, {+ target: values.seekTarget,+ loadAll: values.loadAllMode,+ playbackPosition: cache.playbackPosition,+ playbackWindowId: cache.playbackWindowId,+ })if (!batch) {actions.maybeStartPolling()return@@ -463,11 +442,10 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([selectors(({ cache }) => ({snapshotsLoading: [(s) => [s.snapshotSourcesLoading, s.snapshotsForSourceLoading, s.storeVersion],- (snapshotSourcesLoading: boolean, snapshotsForSourceLoading: boolean): boolean => {- return (- (cache.store?.getAllLoadedSnapshots().length ?? 0) === 0 &&- (snapshotSourcesLoading || snapshotsForSourceLoading)- )+ (snapshotSourcesLoading: boolean, snapshotsForSourceLoading: boolean, _storeVersion: number): boolean => {+ // Keyed on loaded-source state (not snapshot arrays, which the coordinator releases after processing), so a fully-watchable recording doesn't flap back to loading during source polls.+ const hasLoadedAnySource = cache.store?.hasLoadedAnySource ?? false+ return !hasLoadedAnySource && (snapshotSourcesLoading || snapshotsForSourceLoading)},],@@ -481,8 +459,8 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([],allSourcesLoaded: [- (s) => [s.snapshotSources, s.storeUpdateCount],- (snapshotSources): boolean => {+ (s) => [s.snapshotSources, s.storeVersion],+ (snapshotSources, _storeVersion: number): boolean => {if (!snapshotSources || snapshotSources.length === 0) {return false}@@ -513,24 +491,6 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([},],- isWaitingForPlayableFullSnapshot: [- // Depends on storeUpdateCount (not storeVersion) because this- // selector reads scheduler state, which can mutate without- // bumping store.version — storeVersion would memoize to a- // stale value. storeUpdateCount invalidates on every storeUpdated.- (s) => [s.storeUpdateCount],- (): boolean => {- if (!cache.scheduler || !cache.store) {- return false- }- const mode = cache.scheduler.currentMode- if (mode.kind !== 'seek') {- return false- }- return !cache.store.canPlayAt(mode.targetTimestamp, mode.targetWindowId)- },- ],-isRecordingDeleted: [(s) => [s.snapshotLoadError],(snapshotLoadError): boolean => {@@ -561,7 +521,6 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([afterMount(({ actions, cache }) => {cache.playerActive = truecache.store = new SnapshotStore()- cache.scheduler = new LoadingScheduler()actions.storeUpdated()cache.disposables.add(() => {@@ -583,11 +542,11 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([beforeUnmount(({ cache }) => {cache.playerActive = falsecache.store = undefined- cache.scheduler = undefinedcache.pendingBatch = undefinedcache.previousSourceKeys = undefinedcache.lastSourcesChangeTime = undefinedcache.playbackPosition = undefined+ cache.playbackWindowId = undefinedcache.loadFailureCount = undefined}),])diff --git a/frontend/src/scenes/session-recordings/player/utils/resolve-frame-timestamp.test.ts b/frontend/src/scenes/session-recordings/player/utils/resolve-frame-timestamp.test.tsindex 457e0fc21027..6b08b5373572 100644--- a/frontend/src/scenes/session-recordings/player/utils/resolve-frame-timestamp.test.ts+++ b/frontend/src/scenes/session-recordings/player/utils/resolve-frame-timestamp.test.ts@@ -77,7 +77,7 @@ describe('resolveFrameTimestamp', () => {segmentKind: 'gap' as const,prev: state(0, undefined),expectedTs: 500 + FPS_1X,- expectedStuck: 0,+ expectedStuck: 1,expectedAdvance: true,},{@@ -87,7 +87,7 @@ describe('resolveFrameTimestamp', () => {segmentKind: 'gap' as const,prev: state(0, undefined),expectedTs: undefined,- expectedStuck: 0,+ expectedStuck: 1,expectedAdvance: true,},{@@ -97,7 +97,7 @@ describe('resolveFrameTimestamp', () => {segmentKind: 'window' as const,prev: state(0, undefined),expectedTs: undefined,- expectedStuck: 0,+ expectedStuck: 1,expectedAdvance: false,},{@@ -137,7 +137,7 @@ describe('resolveFrameTimestamp', () => {segmentKind: 'buffer' as const,prev: state(0, undefined),expectedTs: undefined,- expectedStuck: 0,+ expectedStuck: 1,expectedAdvance: false,},{@@ -147,7 +147,7 @@ describe('resolveFrameTimestamp', () => {segmentKind: undefined,prev: state(0, undefined),expectedTs: undefined,- expectedStuck: 0,+ expectedStuck: 1,expectedAdvance: false,},])('$name', ({ rrwebTs, currentTs, segmentKind, prev, expectedTs, expectedStuck, expectedAdvance }) => {@@ -253,8 +253,8 @@ describe('resolveFrameTimestamp', () => {expect(result.resolvedTimestamp).toBeCloseTo(currentTs + FPS_1X, 1)currentTs = result.resolvedTimestamp!frameState = result.newState- // stuck counter stays at 0 because undefined !== undefined doesn't increment- expect(frameState.stuckFrames).toBe(0)+ // Repeated undefined rrweb times match the previous frame, so the stuck counter climbs; the gap rule drives the advance regardless.+ expect(frameState.stuckFrames).toBe(i + 1)}})})diff --git a/frontend/src/scenes/session-recordings/player/utils/resolve-frame-timestamp.ts b/frontend/src/scenes/session-recordings/player/utils/resolve-frame-timestamp.tsindex 276571cc30ed..dad4a8dff68e 100644--- a/frontend/src/scenes/session-recordings/player/utils/resolve-frame-timestamp.ts+++ b/frontend/src/scenes/session-recordings/player/utils/resolve-frame-timestamp.ts@@ -18,8 +18,9 @@ export function resolveFrameTimestamp(roughAnimationFPS: number,previousState: FrameState): FrameResult {+ // An undefined rrweb time (replayer constructed but not yet started) counts as stuck too, or the manual-advance recovery below could never engage for it.let stuckFrames: number- if (rrwebTimestamp !== undefined && rrwebTimestamp === previousState.lastAnimTimestamp) {+ if (rrwebTimestamp === previousState.lastAnimTimestamp) {stuckFrames = previousState.stuckFrames + 1} else {stuckFrames = 0diff --git a/frontend/src/scenes/session-recordings/player/utils/segment-kind-conversion.test.ts b/frontend/src/scenes/session-recordings/player/utils/segment-kind-conversion.test.tsdeleted file mode 100644index b5fc159e1ee8..000000000000--- a/frontend/src/scenes/session-recordings/player/utils/segment-kind-conversion.test.ts+++ /dev/null@@ -1,147 +0,0 @@-import { SnapshotStore } from '@posthog/replay-shared'--import { RecordingSegment, SessionRecordingSnapshotSource } from '~/types'--import { convertSegmentKinds } from './segment-kind-conversion'--function makeSources(count: number): SessionRecordingSnapshotSource[] {- return Array.from({ length: count }, (_, i) => ({- source: 'blob_v2' as const,- blob_key: String(i),- start_timestamp: new Date(Date.UTC(2023, 7, 11, 12, i, 0)).toISOString(),- end_timestamp: new Date(Date.UTC(2023, 7, 11, 12, i + 1, 0)).toISOString(),- }))-}--function tsForMinute(minute: number): number {- return new Date(Date.UTC(2023, 7, 11, 12, minute, 30)).getTime()-}--function makeSegment(overrides: Partial<RecordingSegment> & Pick<RecordingSegment, 'kind'>): RecordingSegment {- return {- startTimestamp: tsForMinute(5),- endTimestamp: tsForMinute(10),- durationMs: tsForMinute(10) - tsForMinute(5),- isActive: false,- ...overrides,- }-}--function storeWithSources(count: number, loadedIndices: number[] = []): SnapshotStore {- const store = new SnapshotStore()- store.setSources(makeSources(count))- for (const i of loadedIndices) {- store.markLoaded(i, [])- }- return store-}--function allLoaded(count: number): number[] {- return Array.from({ length: count }, (_, i) => i)-}--describe('convertSegmentKinds', () => {- it.each([- {- name: 'buffer + all sources loaded → gap (true inactivity)',- segment: makeSegment({ kind: 'buffer' }),- store: storeWithSources(20, allLoaded(20)),- isLoading: false,- expectedKind: 'gap',- expectedIsLoading: undefined,- },- {- name: 'buffer + some sources unloaded → buffer with isLoading',- segment: makeSegment({ kind: 'buffer' }),- store: storeWithSources(20, [0, 1, 2]),- isLoading: true,- expectedKind: 'buffer',- expectedIsLoading: true,- },- {- name: 'buffer + store has 0 sources (early load) → buffer with isLoading',- segment: makeSegment({ kind: 'buffer' }),- store: new SnapshotStore(),- isLoading: false,- expectedKind: 'buffer',- expectedIsLoading: false,- },- {- name: 'gap + some sources unloaded → buffer (the seek-back bug fix)',- segment: makeSegment({ kind: 'gap' }),- store: storeWithSources(20, [0, 1, 2]),- isLoading: true,- expectedKind: 'buffer',- expectedIsLoading: true,- },- {- name: 'gap + all sources loaded → gap (true inactivity)',- segment: makeSegment({ kind: 'gap' }),- store: storeWithSources(20, allLoaded(20)),- isLoading: false,- expectedKind: 'gap',- expectedIsLoading: undefined,- },- {- name: 'window (active) → unchanged regardless of store state',- segment: makeSegment({ kind: 'window', isActive: true, windowId: 1 }),- store: storeWithSources(20, [0, 1, 2]),- isLoading: true,- expectedKind: 'window',- expectedIsLoading: undefined,- },- {- name: 'window (inactive) → unchanged regardless of store state',- segment: makeSegment({ kind: 'window', isActive: false, windowId: 1 }),- store: storeWithSources(20, allLoaded(20)),- isLoading: false,- expectedKind: 'window',- expectedIsLoading: undefined,- },- ])('$name', ({ segment, store, isLoading, expectedKind, expectedIsLoading }) => {- const [result] = convertSegmentKinds([segment], store, isLoading)- expect(result.kind).toBe(expectedKind)- expect(result.isLoading).toBe(expectedIsLoading)- })-- it('gap spanning partial unload — single unloaded source in range converts to buffer', () => {- const store = new SnapshotStore()- store.setSources(makeSources(20))- // Load all except source 7- for (let i = 0; i < 20; i++) {- if (i !== 7) {- store.markLoaded(i, [])- }- }-- const segment = makeSegment({- kind: 'gap',- startTimestamp: tsForMinute(3),- endTimestamp: tsForMinute(12),- })-- const [result] = convertSegmentKinds([segment], store, true)- expect(result.kind).toBe('buffer')- expect(result.isLoading).toBe(true)- })-- it('processes multiple segments with mixed kinds independently', () => {- const store = storeWithSources(20, allLoaded(20))- const segments = [- makeSegment({ kind: 'buffer' }),- makeSegment({ kind: 'window', isActive: true, windowId: 1 }),- makeSegment({ kind: 'gap' }),- ]- const result = convertSegmentKinds(segments, store, false)- expect(result.map((s) => s.kind)).toEqual(['gap', 'window', 'gap'])- })-- it('isLoading propagates current loading state to buffer segments', () => {- const emptyStore = new SnapshotStore()- const notLoading = convertSegmentKinds([makeSegment({ kind: 'buffer' })], emptyStore, false)- expect(notLoading[0].isLoading).toBe(false)-- const loading = convertSegmentKinds([makeSegment({ kind: 'buffer' })], emptyStore, true)- expect(loading[0].isLoading).toBe(true)- })-})diff --git a/frontend/src/scenes/session-recordings/player/utils/segment-kind-conversion.ts b/frontend/src/scenes/session-recordings/player/utils/segment-kind-conversion.tsdeleted file mode 100644index fb112d92fe18..000000000000--- a/frontend/src/scenes/session-recordings/player/utils/segment-kind-conversion.ts+++ /dev/null@@ -1,40 +0,0 @@-import { SnapshotStore } from '@posthog/replay-shared'--import { RecordingSegment } from '~/types'--export function convertSegmentKinds(- segments: RecordingSegment[],- snapshotStore: SnapshotStore,- isLoadingSnapshots: boolean-): RecordingSegment[] {- return segments.map((segment) => {- if (snapshotStore.sourceCount > 0) {- const startIdx = snapshotStore.getSourceIndexForTimestamp(segment.startTimestamp)- const endIdx = snapshotStore.getSourceIndexForTimestamp(segment.endTimestamp)- if (startIdx !== null && endIdx !== null) {- const hasUnloaded = snapshotStore.getUnloadedIndicesInRange(startIdx, endIdx).length > 0-- if (segment.kind === 'buffer' && !hasUnloaded) {- // All sources covering this buffer range are already loaded —- // the data isn't pending, it's a gap with no events.- return { ...segment, kind: 'gap' as const }- }-- if (segment.kind === 'gap' && hasUnloaded) {- // This looks like a gap but has unloaded sources — it's actually- // a region where data hasn't been fetched yet. Convert to buffer- // so the player pauses and waits for data instead of skipping.- return { ...segment, kind: 'buffer' as const, isLoading: isLoadingSnapshots }- }- }- }-- if (segment.kind === 'buffer') {- return {- ...segment,- isLoading: isLoadingSnapshots,- }- }- return segment- })-}diff --git a/frontend/src/scenes/session-recordings/player/utils/segmenter.ts b/frontend/src/scenes/session-recordings/player/utils/segmenter.tsindex 8e370385e9c7..cc0634532739 100644--- a/frontend/src/scenes/session-recordings/player/utils/segmenter.ts+++ b/frontend/src/scenes/session-recordings/player/utils/segmenter.ts@@ -13,13 +13,15 @@ export const createSegments = (start: Dayjs | null,end: Dayjs | null,trackedWindow: number | null | undefined,- snapshotsByWindowId: Record<number, eventWithTime[]>+ snapshotsByWindowId: Record<number, eventWithTime[]>,+ isRangeLoaded?: (startTimestamp: number, endTimestamp: number) => boolean | null): RecordingSegment[] => {return _createSegments(snapshots,start?.valueOf() ?? null,end?.valueOf() ?? null,trackedWindow,- snapshotsByWindowId+ snapshotsByWindowId,+ isRangeLoaded)}diff --git a/frontend/src/scenes/session-recordings/player/utils/snapshot-sync.ts b/frontend/src/scenes/session-recordings/player/utils/snapshot-sync.tsindex 9083db04f484..140c07c082ab 100644--- a/frontend/src/scenes/session-recordings/player/utils/snapshot-sync.ts+++ b/frontend/src/scenes/session-recordings/player/utils/snapshot-sync.ts@@ -2,7 +2,7 @@ const POSITION_UPDATE_INTERVAL_MS = 5000/*** Determines whether the playback position should be reported to the- * LoadingScheduler so it can slide its buffer window forward.+ * load planner so it can slide its buffer window forward.*/export function shouldUpdatePlaybackPosition(newTimestamp: number, lastUpdateTimestamp: number | undefined): boolean {return !lastUpdateTimestamp || newTimestamp - lastUpdateTimestamp > POSITION_UPDATE_INTERVAL_MSdiff --git a/playwright/package.json b/playwright/package.jsonindex 4b639e2ba675..4f9cfcc5dd32 100644--- a/playwright/package.json+++ b/playwright/package.json@@ -6,7 +6,8 @@},"dependencies": {"@playwright/test": "catalog:",- "@posthog/frontend": "workspace:*"+ "@posthog/frontend": "workspace:*",+ "snappyjs": "^0.7.0"},"peerDependencies": {}}diff --git a/playwright/snappyjs.d.ts b/playwright/snappyjs.d.tsnew file mode 100644index 000000000000..33b56b94835c--- /dev/null+++ b/playwright/snappyjs.d.ts@@ -0,0 +1,6 @@+declare module 'snappyjs' {+ export function compress(input: Uint8Array | ArrayBuffer | Buffer): Uint8Array+ export function uncompress(compressed: Uint8Array | ArrayBuffer | Buffer): Uint8Array+ const snappyjs: { compress: typeof compress; uncompress: typeof uncompress }+ export default snappyjs+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex f2739a24e7a9..8cdda074729e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -457,7 +457,7 @@ importers:version: 5.3.0jest-image-snapshot:specifier: ^6.4.0- version: 6.4.0([email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])))+ version: 6.4.0([email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])))mockdate:specifier: ^3.0.5version: 3.0.5@@ -1866,7 +1866,7 @@ importers:version: 3.6.0jest-image-snapshot:specifier: ^6.4.0- version: 6.4.0([email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])))+ version: 6.4.0([email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])))storybook:specifier: 'catalog:'version: 10.4.6(@testing-library/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])@@ -2169,6 +2169,9 @@ importers:'@posthog/frontend':specifier: workspace:*version: link:../frontend+ snappyjs:+ specifier: ^0.7.0+ version: 0.7.0products/access_control: {}@@ -2613,7 +2616,7 @@ importers:version: 8.57.0jest:specifier: '*'- version: 30.0.5([email protected]([email protected]))+ version: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))kea:specifier: 'catalog:'version: 4.0.0-pre.5([email protected])@@ -3376,7 +3379,7 @@ importers:version: 2.1.1jest:specifier: '*'- version: 30.0.5([email protected]([email protected]))+ version: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))kea:specifier: 'catalog:'version: 4.0.0-pre.5([email protected])@@ -4239,7 +4242,7 @@ importers:version: 1.2.1jest:specifier: '*'- version: 30.0.5([email protected]([email protected]))+ version: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))kea:specifier: 'catalog:'version: 4.0.0-pre.5([email protected])@@ -26696,7 +26699,7 @@ snapshots:- supports-color- ts-node+ '@jest/[email protected]([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))':dependencies:'@jest/console': 30.0.5'@jest/pattern': 30.0.1@@ -26711,7 +26714,7 @@ snapshots:exit-x: 0.2.2graceful-fs: 4.2.11jest-changed-files: 30.0.5+ jest-config: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))jest-haste-map: 30.0.5jest-message-util: 30.0.5jest-regex-util: 30.0.1@@ -26732,7 +26735,7 @@ snapshots:- supports-color- ts-node- '@jest/[email protected]([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))':+ '@jest/[email protected]([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))':dependencies:'@jest/console': 30.0.5'@jest/pattern': 30.0.1@@ -26747,7 +26750,7 @@ snapshots:exit-x: 0.2.2graceful-fs: 4.2.11jest-changed-files: 30.0.5- jest-config: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ jest-config: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))jest-haste-map: 30.0.5jest-message-util: 30.0.5jest-regex-util: 30.0.1@@ -37944,15 +37947,15 @@ snapshots:- supports-color- ts-node- [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):+ [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:- '@jest/core': 30.0.5([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ '@jest/core': 30.0.5([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))'@jest/test-result': 30.0.5'@jest/types': 30.0.5chalk: 4.1.2exit-x: 0.2.2import-local: 3.2.0- jest-config: 30.0.5(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ jest-config: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))jest-util: 30.0.5jest-validate: 30.0.5yargs: 17.7.2@@ -37963,15 +37966,15 @@ snapshots:- supports-color- ts-node+ [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:- '@jest/core': 30.0.5([email protected]([email protected]))+ '@jest/core': 30.0.5([email protected](@swc/[email protected])(@types/[email protected])([email protected]))'@jest/test-result': 30.0.5'@jest/types': 30.0.5chalk: 4.1.2exit-x: 0.2.2import-local: 3.2.0- jest-config: 30.0.5([email protected]([email protected]))+ jest-config: 30.0.5(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))jest-util: 30.0.5jest-validate: 30.0.5yargs: 17.7.2@@ -38109,7 +38112,7 @@ snapshots:- babel-plugin-macros- supports-color+ [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:'@babel/core': 7.29.0'@jest/get-type': 30.0.1@@ -38138,11 +38141,12 @@ snapshots:optionalDependencies:'@types/node': 22.18.8esbuild-register: 3.6.0([email protected])transitivePeerDependencies:- babel-plugin-macros- supports-color- [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):+ [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:'@babel/core': 7.29.0'@jest/get-type': 30.0.1@@ -38171,7 +38175,7 @@ snapshots:optionalDependencies:'@types/node': 22.18.8esbuild-register: 3.6.0([email protected])transitivePeerDependencies:- babel-plugin-macros- supports-color@@ -38209,7 +38213,7 @@ snapshots:- babel-plugin-macros- supports-color- [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):+ [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:'@babel/core': 7.29.0'@jest/get-type': 30.0.1@@ -38237,12 +38241,13 @@ snapshots:strip-json-comments: 3.1.1optionalDependencies:'@types/node': 25.8.0+ esbuild-register: 3.6.0([email protected])transitivePeerDependencies:- babel-plugin-macros- supports-color+ [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:'@babel/core': 7.29.0'@jest/get-type': 30.0.1@@ -38269,7 +38274,8 @@ snapshots:slash: 3.0.0strip-json-comments: 3.1.1optionalDependencies:- esbuild-register: 3.6.0([email protected])+ '@types/node': 25.8.0transitivePeerDependencies:- babel-plugin-macros- supports-color@@ -39164,12 +39170,12 @@ snapshots:- supports-color- ts-node- [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):+ [email protected](@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:- '@jest/core': 30.0.5([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ '@jest/core': 30.0.5([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))'@jest/types': 30.0.5import-local: 3.2.0- jest-cli: 30.0.5(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))+ jest-cli: 30.0.5(@types/[email protected])([email protected]([email protected]))([email protected](@swc/[email protected])(@types/[email protected])([email protected]))transitivePeerDependencies:- '@types/node'- babel-plugin-macros@@ -39177,12 +39183,12 @@ snapshots:- supports-color- ts-node+ [email protected](@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected])):dependencies:- '@jest/core': 30.0.5([email protected]([email protected]))+ '@jest/core': 30.0.5([email protected](@swc/[email protected])(@types/[email protected])([email protected]))'@jest/types': 30.0.5import-local: 3.2.0- jest-cli: 30.0.5([email protected]([email protected]))+ jest-cli: 30.0.5(@types/[email protected])([email protected](@swc/[email protected])(@types/[email protected])([email protected]))transitivePeerDependencies:- '@types/node'- babel-plugin-macrosdiff --git a/products/replay/frontend/e2e/player.spec.ts b/products/replay/frontend/e2e/player.spec.tsnew file mode 100644index 000000000000..58eee0d729f0--- /dev/null+++ b/products/replay/frontend/e2e/player.spec.ts@@ -0,0 +1,282 @@+import { PlaywrightWorkspaceSetupResult, expect, test } from '@playwright-utils/workspace-test-base'+import { Locator, Page } from '@playwright/test'+import snappy from 'snappyjs'++import { recordingMetaJson } from 'scenes/session-recordings/__mocks__/recording_meta'+import {+ lateFullSnapshotAsJSONLines,+ snapshotsAsJSONLines,+} from 'scenes/session-recordings/__mocks__/recording_snapshots'++import { SessionRecordingType } from '~/types'++// The base mock recording is ~12s across two browser windows, and serving each window as its own blob_v2 source exercises multi-source loading, promotion, and cross-source seeks.+const SESSION_ID = recordingMetaJson.id+const [windowOneJSONL, windowTwoJSONL] = snapshotsAsJSONLines().trim().split('\n')+const BASE_TS = 1682952380877 // first event of windowOneJSONL, matches recordingMetaJson.start_time++interface MockRecording {+ meta: SessionRecordingType+ blobs: string[] // JSONL body per blob key ('0', '1', ...)+ delayMsByKey?: Record<string, number>+}++function isoAt(offsetMs: number): string {+ return new Date(BASE_TS + offsetMs).toISOString()+}++function metaVariant(id: string, durationMs: number): SessionRecordingType {+ return {+ ...recordingMetaJson,+ id,+ recording_duration: Math.floor(durationMs / 1000),+ start_time: isoAt(0),+ end_time: isoAt(durationMs),+ }+}++function shiftJSONLine(line: string, offsetMs: number): string {+ const parsed = JSON.parse(line)+ return JSON.stringify({+ window_id: parsed.window_id,+ data: parsed.data.map((e: { timestamp: number }) => ({ ...e, timestamp: e.timestamp + offsetMs })),+ })+}++function stripFullSnapshots(line: string): string {+ const parsed = JSON.parse(line)+ return JSON.stringify({+ window_id: parsed.window_id,+ data: parsed.data.filter((e: { type: number }) => e.type !== 2),+ })+}++function lastEventTimestamp(line: string): number {+ const parsed = JSON.parse(line)+ return parsed.data[parsed.data.length - 1].timestamp+}++const RECORDINGS: Record<string, MockRecording> = {+ // Two windows served as two blob sources.+ [SESSION_ID]: {+ meta: recordingMetaJson,+ blobs: [windowOneJSONL, windowTwoJSONL],+ },+ // Same two sources, but the second blob arrives late — forces buffering then recovery.+ [`${SESSION_ID}-slow`]: {+ meta: metaVariant(`${SESSION_ID}-slow`, lastEventTimestamp(windowTwoJSONL) - BASE_TS),+ blobs: [windowOneJSONL, windowTwoJSONL],+ delayMsByKey: { '1': 4000 },+ },+ // ~6s of activity, a 2-minute idle gap, then the same activity again.+ [`${SESSION_ID}-gap`]: {+ meta: metaVariant(`${SESSION_ID}-gap`, lastEventTimestamp(windowOneJSONL) - BASE_TS + 126000),+ blobs: [`${windowOneJSONL}\n${shiftJSONLine(windowOneJSONL, 126000)}`],+ },+ // The only full snapshot arrives 5s into the recording — seeks before it must clamp forward.+ [`${SESSION_ID}-late`]: {+ meta: metaVariant(`${SESSION_ID}-late`, 6000),+ blobs: [lateFullSnapshotAsJSONLines(BASE_TS, 5000).trim()],+ },+ // No full snapshot at all — the recording can never render.+ [`${SESSION_ID}-nofs`]: {+ meta: metaVariant(`${SESSION_ID}-nofs`, lastEventTimestamp(windowOneJSONL) - BASE_TS),+ blobs: [stripFullSnapshots(windowOneJSONL)],+ },+}++// Frame each blob's JSONL as a raw-Snappy block behind a 4-byte big-endian length, matching what recording-api serves for blob_v2.+function snappyBlocks(texts: string[]): Buffer {+ const parts: Buffer[] = []+ for (const text of texts) {+ const compressed = Buffer.from(snappy.compress(Buffer.from(text, 'utf-8')))+ const length = Buffer.alloc(4)+ length.writeUInt32BE(compressed.length, 0)+ parts.push(length, compressed)+ }+ return Buffer.concat(parts)+}++async function mockRecordingApi(page: Page): Promise<void> {+ for (const [sessionId, recording] of Object.entries(RECORDINGS)) {+ await page.route(+ new RegExp(`/api/environments/\\d+/session_recordings/${sessionId}/snapshots/?(\\?.*)?$`),+ async (route) => {+ const url = new URL(route.request().url())+ // Content requests carry ?source=blob_v2 (+ a blob key range); listing requests don't.+ if (url.searchParams.get('source') === 'blob_v2') {+ const start = Number(+ url.searchParams.get('start_blob_key') ?? url.searchParams.get('blob_key') ?? 0+ )+ const end = Number(url.searchParams.get('end_blob_key') ?? start)+ const keys = recording.blobs+ .map((_, i) => `${i}`)+ .filter((k) => Number(k) >= start && Number(k) <= end)+ const delay = Math.max(...keys.map((k) => recording.delayMsByKey?.[k] ?? 0), 0)+ if (delay > 0) {+ await new Promise((resolve) => setTimeout(resolve, delay))+ }+ // blob_v2 content is length-prefixed Snappy on the wire, which the player fetches with decompress=false and decompresses client-side.+ return route.fulfill({+ status: 200,+ contentType: 'application/octet-stream',+ body: snappyBlocks(keys.map((k) => recording.blobs[Number(k)])),+ })+ }+ return route.fulfill({+ status: 200,+ json: {+ sources: recording.blobs.map((blob, i) => {+ const parsedFirst = JSON.parse(blob.split('\n')[0])+ return {+ source: 'blob_v2',+ blob_key: `${i}`,+ start_timestamp: new Date(parsedFirst.data[0].timestamp).toISOString(),+ end_timestamp: new Date(lastEventTimestamp(blob.split('\n').at(-1)!)).toISOString(),+ }+ }),+ },+ })+ }+ )+ await page.route(new RegExp(`/api/environments/\\d+/session_recordings/${sessionId}/?(\\?.*)?$`), (route) =>+ route.fulfill({ status: 200, json: recording.meta })+ )+ }+}++function playerFrame(page: Page): Locator {+ return page.locator('.PlayerFrame__content .replayer-wrapper iframe')+}++// One button whose data-attr reflects player state and stays assertable while the auto-hiding controls chrome is hidden (hover via revealControls before clicking it).+function playPauseButton(page: Page): Locator {+ return page.locator('[data-attr=recording-play], [data-attr=recording-pause], [data-attr=recording-rewind]').first()+}++async function revealControls(page: Page): Promise<void> {+ await page.locator('.SessionRecordingPlayerWrapper').hover()+}++// The buffering state class lands on both the player container and the "Buffering…" overlay text, so scope to the first match to avoid a strict-mode violation.+function bufferingIndicator(page: Page): Locator {+ return page.locator('.SessionRecordingPlayer--buffering').first()+}++async function scrubTo(page: Page, fraction: number): Promise<void> {+ await revealControls(page)+ const slider = page.locator('.PlayerSeekbar__slider')+ const box = (await slider.boundingBox())!+ await page.mouse.click(box.x + box.width * fraction, box.y + box.height / 2)+}++test.describe.configure({ mode: 'serial' })++test.describe('Session replay player', () => {+ let workspace: PlaywrightWorkspaceSetupResult | null = null++ test.beforeAll(async ({ playwrightSetup }) => {+ workspace = await playwrightSetup.createWorkspace({ skip_onboarding: true })+ })++ test.beforeEach(async ({ page, playwrightSetup }) => {+ await playwrightSetup.loginAndNavigateToTeam(page, workspace!)+ await mockRecordingApi(page)+ })++ test('plays a multi-source recording, pauses, seeks, scrubs, and reaches the end', async ({ page }) => {+ await test.step('boots and autoplays from the start', async () => {+ await page.goto(`/replay/${SESSION_ID}?t=0`)+ await expect(playerFrame(page)).toBeVisible({ timeout: 30000 })+ await expect(playPauseButton(page)).toHaveAttribute('data-attr', 'recording-pause')+ await expect(page.getByTestId('recording-timestamp')).toHaveText(/00:0[1-9]|00:1[01]/, { timeout: 15000 })+ })++ await test.step('pauses mid-playback', async () => {+ await revealControls(page)+ await page.locator('[data-attr=recording-pause]').click()+ await expect(playPauseButton(page)).toHaveAttribute('data-attr', 'recording-play')+ })++ await test.step('seeking backward while paused stays paused', async () => {+ await revealControls(page)+ await page.getByTestId('seek-skip-backward').click()+ await expect(page.getByTestId('recording-timestamp')).toHaveText(/00:00.*00:11/)+ await expect(playPauseButton(page)).toHaveAttribute('data-attr', 'recording-play')+ await expect(bufferingIndicator(page)).not.toBeVisible()+ })++ await test.step('resumes and plays across both windows to the end', async () => {+ await revealControls(page)+ await page.locator('[data-attr=recording-play]').click()+ await expect(playPauseButton(page)).toHaveAttribute('data-attr', 'recording-pause')+ // Reaching the end proves playback advanced through both blob sources.+ await expect(playPauseButton(page)).toHaveAttribute('data-attr', 'recording-rewind', { timeout: 30000 })+ })++ await test.step('rewind at the end restarts playback from the start', async () => {+ await page.getByTestId('replay-overlay-rewind').click()+ await expect(playPauseButton(page)).toHaveAttribute('data-attr', 'recording-pause')+ await expect(page.getByTestId('recording-timestamp')).toHaveText(/00:0[0-5].*00:11/)+ })++ await test.step('scrubbing into the second window while playing keeps playing', async () => {+ await scrubTo(page, 0.8)+ await expect(page.getByTestId('recording-timestamp')).toHaveText(/00:0[89]|00:1[01]/)+ await expect(playPauseButton(page)).toHaveAttribute('data-attr', 'recording-pause')+ // ...and end detection still works after a scrub.+ await expect(playPauseButton(page)).toHaveAttribute('data-attr', 'recording-rewind', { timeout: 15000 })+ })+ })++ test('deep link with ?t and ?pause renders a paused frame mid-recording', async ({ page }) => {+ await page.goto(`/replay/${SESSION_ID}?pause=true&t=9`)+ await expect(playerFrame(page)).toBeVisible({ timeout: 30000 })+ await expect(page.getByTestId('recording-timestamp')).toHaveText(/00:09.*00:11/)+ await expect(playPauseButton(page)).toHaveAttribute('data-attr', 'recording-play')+ await expect(bufferingIndicator(page)).not.toBeVisible()+ })++ test('deep link past the end clamps to the last frame instead of buffering forever', async ({ page }) => {+ await page.goto(`/replay/${SESSION_ID}?pause=true&t=999`)+ await expect(playerFrame(page)).toBeVisible({ timeout: 30000 })+ await expect(page.getByTestId('recording-timestamp')).toHaveText(/00:11.*00:11/)+ await expect(page.getByTestId('replay-overlay-resume')).toBeAttached()+ await expect(bufferingIndicator(page)).not.toBeVisible()+ })++ test('fast-forwards through long inactivity and resumes normal playback', async ({ page }) => {+ await page.goto(`/replay/${SESSION_ID}-gap?t=0`)+ await expect(playerFrame(page)).toBeVisible({ timeout: 30000 })+ await expect(playPauseButton(page)).toHaveAttribute('data-attr', 'recording-pause')+ // ~6s of activity precede the 2-minute gap; skipping plays the gap at >=50x.+ await expect(page.getByText('Skipping inactivity')).toBeVisible({ timeout: 20000 })+ await expect(page.getByTestId('recording-timestamp')).toHaveText(/02:0[6-9]|02:1[0-9]/, { timeout: 20000 })+ await expect(playPauseButton(page)).toHaveAttribute('data-attr', 'recording-pause')+ })++ test('seeking before a late full snapshot clamps forward to the first renderable frame', async ({ page }) => {+ await page.goto(`/replay/${SESSION_ID}-late?pause=true&t=0`)+ await expect(playerFrame(page)).toBeVisible({ timeout: 30000 })+ await expect(page.getByTestId('recording-timestamp')).toHaveText(/00:05.*00:06/)+ await expect(bufferingIndicator(page)).not.toBeVisible()+ })++ test('a recording with no full snapshot shows a terminal error instead of buffering', async ({ page }) => {+ await page.goto(`/replay/${SESSION_ID}-nofs?pause=true&t=0`)+ await expect(page.getByRole('heading', { name: "This recording can't be played" })).toBeVisible({+ timeout: 30000,+ })+ await expect(bufferingIndicator(page)).not.toBeVisible()+ })++ test('buffers while a source is still loading and recovers when it arrives', async ({ page }) => {+ await page.goto(`/replay/${SESSION_ID}-slow?pause=true&t=9`)+ // The target position lives in the delayed second source, so the player must buffer first...+ await expect(bufferingIndicator(page)).toBeVisible({ timeout: 15000 })+ // ...and render the requested frame once the source lands, without manual intervention.+ await expect(playerFrame(page)).toBeVisible({ timeout: 30000 })+ await expect(page.getByTestId('recording-timestamp')).toHaveText(/00:09.*00:11/)+ await expect(bufferingIndicator(page)).not.toBeVisible()+ })+})