Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(replay): harden the player pipeline against stuck-buffering states (#69821)

Tue Haulund5720dd731b6d
diff --git a/common/replay-shared/src/snapshot-processing/chrome-extension-stripping.test.ts b/common/replay-shared/src/snapshot-processing/chrome-extension-stripping.test.ts
index 5d808a7a2148..689ed5a20ee9 100644
--- a/common/replay-shared/src/snapshot-processing/chrome-extension-stripping.test.ts
+++ b/common/replay-shared/src/snapshot-processing/chrome-extension-stripping.test.ts
@@ -22,6 +22,19 @@ describe('stripChromeExtensionDataFromNode', () => {
expect(matched.size).toBe(0)
})
+ it.each([
+ ['undefined', undefined],
+ ['null', null],
+ ['a string (undecoded full snapshot data.node)', 'not-a-node'],
+ ])('returns false without throwing when node is %s', (_label, node) => {
+ const matched = new Set<string>()
+ let stripped: boolean | undefined
+ expect(() => {
+ stripped = stripChromeExtensionDataFromNode(node as unknown as serializedNodeWithId, needles, matched)
+ }).not.toThrow()
+ expect(stripped).toBe(false)
+ })
+
it('does not throw or match when attributes object lacks relevant keys', () => {
const node: serializedNodeWithId = {
type: NodeType.Element,
diff --git a/common/replay-shared/src/snapshot-processing/chrome-extension-stripping.ts b/common/replay-shared/src/snapshot-processing/chrome-extension-stripping.ts
index 2d2f9ab3329a..0d27da2a579c 100644
--- a/common/replay-shared/src/snapshot-processing/chrome-extension-stripping.ts
+++ b/common/replay-shared/src/snapshot-processing/chrome-extension-stripping.ts
@@ -4,6 +4,7 @@ import { EventType } from 'posthog-js/rrweb-types'
import { serializedNodeWithId } from 'posthog-js/rrweb-types'
import { RecordingSnapshot } from '../types'
+import { isObject } from '../utils'
export const CHROME_EXTENSION_DENY_LIST: Record<string, string> = {
'dji-sru': 'snap and read',
@@ -138,6 +139,12 @@ export function stripChromeExtensionDataFromNode(
needles: string[],
matchedExtensions: Set<string>
): boolean {
+ // Guard against a non-object node (e.g. a full snapshot that failed to decompress): the `'childNodes' in node`
+ // check below throws on undefined, and the safelyCheck* helpers already no-op on non-objects anyway.
+ if (!isObject(node)) {
+ return false
+ }
+
let stripped = false
if (safelyCheckCSSAttribute(node, 'textContent', needles, matchedExtensions)) {
diff --git a/common/replay-shared/src/snapshot-processing/parse-encoded-snapshots.ts b/common/replay-shared/src/snapshot-processing/parse-encoded-snapshots.ts
index 174c11f891f4..d42a1177e0b7 100644
--- a/common/replay-shared/src/snapshot-processing/parse-encoded-snapshots.ts
+++ b/common/replay-shared/src/snapshot-processing/parse-encoded-snapshots.ts
@@ -110,7 +110,9 @@ export const parseEncodedSnapshots = async (
error: error instanceof Error ? error.message : 'Unknown error',
feature: 'session-recording-client-side-decompression',
})
- return []
+ // Rethrow so the source load fails and retries/errors: returning [] would record a corrupt
+ // source as successfully-fetched-but-empty, leaving the player buffering with no error.
+ throw error
}
}
@@ -139,7 +141,8 @@ export const parseEncodedSnapshots = async (
decodeError: decodeError instanceof Error ? decodeError.message : 'Unknown error',
feature: 'session-recording-client-side-decompression',
})
- return []
+ // Rethrow the original decompression error (see length-prefixed path above).
+ throw error
}
}
}
diff --git a/common/replay-shared/src/snapshot-processing/process-all-snapshots.ts b/common/replay-shared/src/snapshot-processing/process-all-snapshots.ts
index bc788adbc089..2cf65836df38 100644
--- a/common/replay-shared/src/snapshot-processing/process-all-snapshots.ts
+++ b/common/replay-shared/src/snapshot-processing/process-all-snapshots.ts
@@ -1,4 +1,4 @@
-import { EventType, eventWithTime, fullSnapshotEvent } from 'posthog-js/rrweb-types'
+import { EventType, eventWithTime, fullSnapshotEvent, IncrementalSource } from 'posthog-js/rrweb-types'
import { transformEventToWeb } from '../mobile'
import { noOpTelemetry, ReplayTelemetry } from '../telemetry'
@@ -32,6 +32,9 @@ export const createWindowIdRegistry = (): RegisterWindowIdCallback => {
export type ProcessingCache = {
snapshots: Record<SourceKey, RecordingSnapshot[]>
+ // Sources processed while viewport data was unavailable (meta patch failed). They are left out of
+ // `snapshots` so a later pass — e.g. once events land — can re-process them with a viewport.
+ viewportGaps?: Set<SourceKey>
}
function extractImgNodeFromMobileIncremental(snapshot: RecordingSnapshot): any | undefined {
@@ -130,8 +133,13 @@ export async function processAllSnapshots(
seenFullByWindow: {},
previousTimestamp: null,
seenHashes: new Set<number>(),
+ sourceHadViewportGap: false,
}
+ // Reset each pass: any source with a gap was left uncached, so it re-processes below and
+ // re-registers its gap if the viewport is still unavailable.
+ processingCache.viewportGaps = new Set<SourceKey>()
+
const YIELD_AFTER_MS = 50
let lastYield = performance.now()
@@ -157,6 +165,7 @@ export async function processAllSnapshots(
}
context.sourceResult = []
+ context.sourceHadViewportGap = false
const sortedSnapshots = sourceSnapshots.sort((a, b) => a.timestamp - b.timestamp)
context.seenHashes = new Set<number>()
const pushPatchedMeta = createPushPatchedMeta(
@@ -185,10 +194,16 @@ export async function processAllSnapshots(
}
}
- processingCache.snapshots[sourceKey] = context.sourceResult
+ if (context.sourceHadViewportGap) {
+ // Don't freeze a meta-less result in the cache — a later pass (once viewport-defining
+ // events load) must be able to re-process this source and patch the missing meta.
+ processingCache.viewportGaps.add(sourceKey)
+ } else {
+ processingCache.snapshots[sourceKey] = context.sourceResult
- if (snapshotsBySource[sourceKey]) {
- snapshotsBySource[sourceKey].snapshots = []
+ if (snapshotsBySource[sourceKey]) {
+ snapshotsBySource[sourceKey].snapshots = []
+ }
}
}
@@ -205,6 +220,8 @@ type ProcessSnapshotContext = {
seenFullByWindow: Record<number, boolean>
previousTimestamp: number | null
seenHashes: Set<number>
+ // Set when a meta patch failed because no viewport was available for the current source
+ sourceHadViewportGap: boolean
}
function createPushPatchedMeta(
@@ -251,6 +268,7 @@ function createPushPatchedMeta(
})
return true
}
+ context.sourceHadViewportGap = true
throttleCapture(`${sessionRecordingId}-no-viewport-found`, () => {
telemetry.captureException(new Error('No event viewport or meta snapshot found for full snapshot'), {
throttleCaptureKey: `${sessionRecordingId}-no-viewport-found`,
@@ -317,13 +335,53 @@ function processSnapshot(
context.sourceResult.push(syntheticFull)
}
+ // Like the FullSnapshot guard below: decompressEvent fails open, so a Mutation or StyleSheetRule
+ // incremental whose compressed fields didn't decompress still carries strings where rrweb expects
+ // arrays and would throw inside the Replayer at play time. Drop it rather than crash playback.
+ if (snapshot.type === EventType.IncrementalSnapshot && isObject(snapshot.data)) {
+ const data = snapshot.data as Record<string, unknown>
+ const compressedFields =
+ data.source === IncrementalSource.Mutation
+ ? ['adds', 'removes', 'texts', 'attributes']
+ : data.source === IncrementalSource.StyleSheetRule
+ ? ['adds', 'removes']
+ : []
+ if (compressedFields.some((field) => typeof data[field] === 'string')) {
+ throttleCapture(`${sessionRecordingId}-undecodable-incremental-snapshot`, () => {
+ telemetry.captureException(new Error('Incremental snapshot could not be decoded'), {
+ sessionRecordingId,
+ sourceKey,
+ source: data.source,
+ feature: 'session-recording-incremental-snapshot-decoding',
+ })
+ })
+ return
+ }
+ }
+
if (snapshot.type === EventType.FullSnapshot) {
+ const fullSnapshot = snapshot as RecordingSnapshot & fullSnapshotEvent & eventWithTime
+
+ // A FullSnapshot whose payload failed to decompress (e.g. truncated at capture/ingestion) still
+ // arrives here with `data` as the raw compressed string — decompressEvent swallows the gunzip error.
+ // Dereferencing `data.node` below would throw, which processAllSnapshots surfaces as an unhandled
+ // rejection that leaves every source stuck unpromoted and the player buffering forever. Drop it
+ // instead: with no usable FullSnapshot the renderability machinery reports the recording unplayable.
+ if (!isObject(fullSnapshot.data) || !isObject(fullSnapshot.data.node)) {
+ throttleCapture(`${sessionRecordingId}-undecodable-full-snapshot`, () => {
+ telemetry.captureException(new Error('Full snapshot could not be decoded'), {
+ sessionRecordingId,
+ sourceKey,
+ feature: 'session-recording-full-snapshot-decoding',
+ })
+ })
+ return
+ }
+
context.seenFullByWindow[snapshot.windowId] = true
pushPatchedMeta(snapshot.timestamp, snapshot.windowId, snapshot)
context.hasSeenMeta = false
- const fullSnapshot = snapshot as RecordingSnapshot & fullSnapshotEvent & eventWithTime
-
if (
stripChromeExtensionDataFromNode(
fullSnapshot.data.node,
diff --git a/common/replay-shared/src/snapshot-store/SnapshotStore.ts b/common/replay-shared/src/snapshot-store/SnapshotStore.ts
index 41ca0c835679..d4213459e8f1 100644
--- a/common/replay-shared/src/snapshot-store/SnapshotStore.ts
+++ b/common/replay-shared/src/snapshot-store/SnapshotStore.ts
@@ -23,6 +23,11 @@ export class SnapshotStore {
const existing = source.blob_key ? existingByKey.get(source.blob_key) : undefined
if (existing) {
existing.index = index
+ // An ongoing recording's tail blob can extend under a stable blob_key — refresh the
+ // metadata or already-loaded data past the stale endMs renders as "not buffered yet".
+ existing.source = source
+ existing.startMs = source.start_timestamp ? new Date(source.start_timestamp).getTime() : 0
+ existing.endMs = source.end_timestamp ? new Date(source.end_timestamp).getTime() : 0
return existing
}
return {
@@ -258,9 +263,10 @@ export class SnapshotStore {
}
// 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 {
+ // `excludeIndexes` keeps raw data for sources that must be re-processable (e.g. meta patched once viewport data arrives).
+ clearSnapshotData(excludeIndexes?: Set<number>): void {
for (const entry of this.entries) {
- if (entry.state === 'loaded') {
+ if (entry.state === 'loaded' && !excludeIndexes?.has(entry.index)) {
entry.processedSnapshots = null
}
}
diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.ts
index 004005f3d4b8..4658b307cd11 100644
--- a/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.ts
+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.ts
@@ -9,6 +9,7 @@ import {
keyForSource,
processAllSnapshots,
SnapshotStore,
+ SourceKey,
SourceLoadingState,
} from '@posthog/replay-shared'
@@ -154,6 +155,10 @@ export const sessionRecordingDataCoordinatorLogic = kea<sessionRecordingDataCoor
setRecordingReportedLoaded: true,
processSnapshotsAsync: true,
setProcessedSnapshots: (snapshots: RecordingSnapshot[]) => ({ snapshots }),
+ // Terminal: snapshot processing kept throwing and all retries are exhausted. The player maps
+ // this to an error state — without it the affected sources stay unpromoted forever and the
+ // player buffers with no error surfaced.
+ snapshotProcessingFailed: true,
}),
reducers(() => ({
reportedLoaded: [
@@ -187,6 +192,11 @@ export const sessionRecordingDataCoordinatorLogic = kea<sessionRecordingDataCoor
loadEventsSuccess: () => {
actions.reportUsageIfFullyLoaded()
+ // Events carry the viewport data used to patch missing meta events. Sources processed
+ // before events loaded were left uncached (viewportGaps) — re-run so they get their meta.
+ if (cache.processingCache?.viewportGaps?.size) {
+ actions.processSnapshotsAsync()
+ }
},
// loadFullEventData shares the sessionEventsData loader, so while it is in flight
@@ -217,13 +227,15 @@ export const sessionRecordingDataCoordinatorLogic = kea<sessionRecordingDataCoor
const sources = values.snapshotSources
const 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[] = []
+ // fetched sources this pass will cover — promoted to loaded on completion, including empty
+ // ones that contribute no snapshots. Tracked by key, not index: a setSources refresh during
+ // the await below re-indexes entries, and promoting stale indexes would flip the wrong source.
+ const coveredKeys: SourceKey[] = []
if (sources) {
for (let i = 0; i < sources.length; i++) {
const entry = values.snapshotStore.getEntry(i)
if (entry?.state === 'fetched') {
- coveredIndexes.push(i)
+ coveredKeys.push(keyForSource(sources[i]))
}
if (entry?.state !== 'unloaded' && entry?.processedSnapshots?.length) {
snapshotsBySource[keyForSource(sources[i])] = {
@@ -250,6 +262,10 @@ export const sessionRecordingDataCoordinatorLogic = kea<sessionRecordingDataCoor
if (cache.processingFailureCount <= 3) {
await breakpoint(cache.processingFailureCount * 1000)
actions.processSnapshotsAsync()
+ } else {
+ // Give up loudly: nothing re-triggers processing from here, so surface a terminal
+ // error instead of leaving the player buffering forever.
+ actions.snapshotProcessingFailed()
}
return
}
@@ -257,14 +273,24 @@ export const sessionRecordingDataCoordinatorLogic = kea<sessionRecordingDataCoor
breakpoint()
+ const keyToIndex = new Map((values.snapshotSources ?? []).map((s, i) => [keyForSource(s), i]))
+ const coveredIndexes = coveredKeys.map((k) => keyToIndex.get(k)).filter((i): i is number => i !== undefined)
+
// 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 the load planner work correctly.
const synced = values.snapshotStore.syncFullSnapshotTimestamps(result)
- // Release raw snapshot arrays from the store — only the metadata (fullSnapshots, state) is still needed.
- values.snapshotStore.clearSnapshotData()
+ // Release raw snapshot arrays from the store — only the metadata (fullSnapshots, state) is
+ // still needed. Sources processed without viewport data keep their raw snapshots so the
+ // loadEventsSuccess re-run below can re-process them with a viewport.
+ const viewportGapIndexes = new Set(
+ [...(cache.processingCache.viewportGaps ?? [])]
+ .map((k) => keyToIndex.get(k))
+ .filter((i): i is number => i !== undefined)
+ )
+ values.snapshotStore.clearSnapshotData(viewportGapIndexes)
if (promoted || synced) {
actions.storeUpdated()
diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.test.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.test.ts
index 9d04b476ea05..901762776736 100644
--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.test.ts
+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.test.ts
@@ -256,6 +256,20 @@ describe('sessionRecordingPlayerLogic', () => {
})
})
+ describe('terminal data failures', () => {
+ // Give-up signals must surface as a player error even when partial data already loaded —
+ // otherwise the affected range buffers forever with no error shown.
+ it.each(['snapshotProcessingFailed', 'snapshotSourceLoadExhausted'] as const)(
+ '%s sets a player error',
+ (action) => {
+ const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {})
+ logic.actions[action]()
+ expect(logic.values.playerError).toBe(action)
+ consoleError.mockRestore()
+ }
+ )
+ })
+
describe('currentPlayerTime clamping', () => {
// Mock recording: start=1682952380877, end=1682952392745, durationMs=11868
const START = 1682952380877
diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts
index 7075c40f0c01..c40e1f4fed17 100644
--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts
+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts
@@ -517,7 +517,14 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(
connect((props: SessionRecordingPlayerLogicProps) => ({
values: [
snapshotDataLogic(props),
- ['snapshotsLoaded', 'snapshotsLoading', 'snapshotSources', 'snapshotStore', 'allSourcesLoaded'],
+ [
+ 'snapshotsLoaded',
+ 'snapshotsLoading',
+ 'snapshotSources',
+ 'snapshotStore',
+ 'allSourcesLoaded',
+ 'storeVersion',
+ ],
sessionRecordingDataCoordinatorLogic(props),
[
'urls',
@@ -546,6 +553,7 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(
'loadSnapshots',
'loadSnapshotsForSourceFailure',
'loadSnapshotSourcesFailure',
+ 'snapshotSourceLoadExhausted',
'loadNextSnapshotSource',
'loadAllSources',
'setTargetTimestamp',
@@ -553,7 +561,7 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(
'setPlayerActive',
],
sessionRecordingDataCoordinatorLogic(props),
- ['loadRecordingData', 'loadRecordingMetaSuccess'],
+ ['loadRecordingData', 'loadRecordingMetaSuccess', 'snapshotProcessingFailed'],
playerSettingsLogic,
['setSpeed', 'setSkipInactivitySetting', 'setPlayerControlsOverlay'],
sessionRecordingEventUsageLogic,
@@ -1108,12 +1116,15 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(
// how playback can recover (e.g. when the initial full snapshot was lost at
// capture time, the recording is only playable from a later FullSnapshot).
seekRenderability: [
- (s) => [s.segmentForTimestamp, s.snapshotStore, s.allSourcesLoaded, s.sessionPlayerData],
+ // storeVersion is what makes store mutations visible here (#53893): `snapshotStore` is a
+ // reference-stable mutable object and cannot drive re-evaluation on its own.
+ (s) => [s.segmentForTimestamp, s.snapshotStore, s.allSourcesLoaded, s.sessionPlayerData, s.storeVersion],
(
segmentForTimestamp: (timestamp?: number) => RecordingSegment | null,
snapshotStore: SnapshotStore,
allSourcesLoaded: boolean,
- sessionPlayerData: SessionPlayerData
+ sessionPlayerData: SessionPlayerData,
+ _storeVersion: number
) => {
// 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 => {
@@ -1524,74 +1535,86 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(
cache.disposables.add(
() => {
- const replayer = new Replayer(values.sessionPlayerData.snapshotsByWindowId[windowId], config)
- const iframeCleanups: (() => void)[] = []
-
- replayer.on('fullsnapshot-rebuilded', () => {
- const iframeContentWindow = replayer.iframe.contentWindow
- const iframeFetch = iframeContentWindow?.fetch
-
- const setupErrorHandlers = (): void => {
- if (
- iframeFetch &&
- !(iframeFetch as any).__isWrappedForErrorReporting &&
- iframeContentWindow
- ) {
- const originalFetch = iframeFetch
- const windowRef = new WeakRef(iframeContentWindow)
-
- iframeContentWindow.fetch = wrapFetchAndReport({
- fetch: iframeFetch,
- onError: (errorDetails: ResourceErrorDetails) => {
- actions.caughtAssetErrorFromIframe(errorDetails)
- },
- })
- ;(iframeContentWindow.fetch as any).__isWrappedForErrorReporting = true
-
- iframeCleanups.push(() => {
- const window = windowRef.deref()
- if (window && window.fetch) {
- window.fetch = originalFetch
- delete (window.fetch as any).__isWrappedForErrorReporting
- }
- })
- }
-
- if (iframeContentWindow) {
- iframeCleanups.push(
- registerErrorListeners({
- iframeWindow: iframeContentWindow,
- onError: (error) => actions.caughtAssetErrorFromIframe(error),
+ // rrweb throws synchronously on malformed events while building the initial DOM;
+ // the config.onError callback only covers its async internal errors. Without this
+ // catch the throw escapes the listener and the player buffers forever.
+ try {
+ const replayer = new Replayer(values.sessionPlayerData.snapshotsByWindowId[windowId], config)
+ const iframeCleanups: (() => void)[] = []
+
+ replayer.on('fullsnapshot-rebuilded', () => {
+ const iframeContentWindow = replayer.iframe.contentWindow
+ const iframeFetch = iframeContentWindow?.fetch
+
+ const setupErrorHandlers = (): void => {
+ if (
+ iframeFetch &&
+ !(iframeFetch as any).__isWrappedForErrorReporting &&
+ iframeContentWindow
+ ) {
+ const originalFetch = iframeFetch
+ const windowRef = new WeakRef(iframeContentWindow)
+
+ iframeContentWindow.fetch = wrapFetchAndReport({
+ fetch: iframeFetch,
+ onError: (errorDetails: ResourceErrorDetails) => {
+ actions.caughtAssetErrorFromIframe(errorDetails)
+ },
+ })
+ ;(iframeContentWindow.fetch as any).__isWrappedForErrorReporting = true
+
+ iframeCleanups.push(() => {
+ const window = windowRef.deref()
+ if (window && window.fetch) {
+ window.fetch = originalFetch
+ delete (window.fetch as any).__isWrappedForErrorReporting
+ }
})
- )
+ }
+
+ if (iframeContentWindow) {
+ iframeCleanups.push(
+ registerErrorListeners({
+ iframeWindow: iframeContentWindow,
+ onError: (error) => actions.caughtAssetErrorFromIframe(error),
+ })
+ )
+ }
}
- }
- setupErrorHandlers()
- })
+ setupErrorHandlers()
+ })
- actions.setPlayer({ replayer, windowId })
+ actions.setPlayer({ replayer, windowId })
- return () => {
- canvasPlugin.destroy()
- hlsPlugin.destroy()
+ return () => {
+ canvasPlugin.destroy()
+ hlsPlugin.destroy()
- if (replayer) {
- for (const cleanup of iframeCleanups) {
- cleanup()
- }
- iframeCleanups.length = 0
+ if (replayer) {
+ for (const cleanup of iframeCleanups) {
+ cleanup()
+ }
+ iframeCleanups.length = 0
- const iframe = replayer.iframe
- replayer.destroy()
+ const iframe = replayer.iframe
+ replayer.destroy()
- if (iframe?.contentDocument?.body) {
- iframe.contentDocument.body.innerHTML = ''
- }
- if (iframe?.contentDocument?.head) {
- iframe.contentDocument.head.innerHTML = ''
+ if (iframe?.contentDocument?.body) {
+ iframe.contentDocument.body.innerHTML = ''
+ }
+ if (iframe?.contentDocument?.head) {
+ iframe.contentDocument.head.innerHTML = ''
+ }
}
}
+ } catch (error) {
+ posthog.captureException(error, {
+ feature: 'session-recording-replayer-init',
+ sessionRecordingId: props.sessionRecordingId,
+ })
+ actions.setPlayerError('replayerInitFailure')
+ return () => {}
}
},
`replayer-${props.mode}`,
@@ -1727,16 +1750,26 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(
// 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()
+ // rrweb throws synchronously on malformed events it replays through — surface an error
+ // state rather than letting the throw escape the listener and wedge the state machine.
+ try {
+ 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()
+ }
+ } catch (error) {
+ posthog.captureException(error, {
+ feature: 'session-recording-replayer-playback',
+ sessionRecordingId: props.sessionRecordingId,
+ })
+ actions.setPlayerError('replayerPlaybackFailure')
}
},
initializePlayerFromStart: () => {
@@ -1806,7 +1839,16 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(
const YIELD_AFTER_MS = 50
let lastYield = performance.now()
for (let i = 0; i < eventsToAdd.length; i++) {
- values.player?.replayer?.addEvent(eventsToAdd[i])
+ try {
+ values.player?.replayer?.addEvent(eventsToAdd[i])
+ } catch (error) {
+ // A single malformed event shouldn't kill the whole sync — skip it, keep the rest.
+ posthog.captureException(error, {
+ feature: 'session-recording-replayer-add-event',
+ sessionRecordingId: props.sessionRecordingId,
+ })
+ continue
+ }
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
@@ -1865,6 +1907,16 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(
actions.setPlayerError('loadSnapshotSourcesFailure')
}
},
+ // Both are terminal give-ups: unlike the per-attempt failures above they fire even when other
+ // data already loaded, because the missing range would otherwise buffer forever with no error.
+ snapshotSourceLoadExhausted: () => {
+ console.error('PostHog Recording Playback Error: A snapshot source repeatedly failed to load')
+ actions.setPlayerError('snapshotSourceLoadExhausted')
+ },
+ snapshotProcessingFailed: () => {
+ console.error('PostHog Recording Playback Error: Snapshot processing repeatedly failed')
+ actions.setPlayerError('snapshotProcessingFailed')
+ },
setPlay: () => {
if (!values.snapshotsLoaded) {
actions.loadSnapshots()
@@ -2214,6 +2266,15 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(
if (values.pauseForced) {
actions.setPause()
}
+ } catch (error) {
+ // A replayer throw here would otherwise kill the animation loop silently — the
+ // playhead freezes while the controls still say "playing". Stop cleanly and surface it.
+ posthog.captureException(error, {
+ feature: 'session-recording-replayer-animation',
+ sessionRecordingId: props.sessionRecordingId,
+ })
+ actions.stopAnimation()
+ actions.setPlayerError('replayerPlaybackFailure')
} finally {
cache._inUpdateAnimation = false
}
diff --git a/frontend/src/scenes/session-recordings/player/snapshot-processing/process-all-snapshots.test.ts b/frontend/src/scenes/session-recordings/player/snapshot-processing/process-all-snapshots.test.ts
index c6a00acf0c0b..4b43e8b79610 100644
--- a/frontend/src/scenes/session-recordings/player/snapshot-processing/process-all-snapshots.test.ts
+++ b/frontend/src/scenes/session-recordings/player/snapshot-processing/process-all-snapshots.test.ts
@@ -1,5 +1,6 @@
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
+import { IncrementalSource } from 'posthog-js/rrweb-types'
import { hasAnyWireframes, keyForSource, processAllSnapshots } from '@posthog/replay-shared'
@@ -322,6 +323,18 @@ describe('process all snapshots', () => {
expect(result).toHaveLength(0)
})
+ it('rejects when a length-prefixed block fails to decompress', async () => {
+ // Resolving to [] here would record a corrupt source as successfully-fetched-but-empty
+ // and the player would buffer forever with no error surfaced.
+ const mockCompressedData = createLengthPrefixedData([new Uint8Array([9, 9, 9])])
+
+ mockWorkerManager.decompress.mockRejectedValue(new Error('Decompression failed'))
+
+ await expect(parseEncodedSnapshots(mockCompressedData, 'test-session')).rejects.toThrow(
+ 'Decompression failed'
+ )
+ })
+
it('filters out empty lines in decompressed data', async () => {
const sessionId = 'test-session'
@@ -962,4 +975,88 @@ describe('process all snapshots', () => {
})
})
})
+
+ describe('undecodable full snapshot', () => {
+ // A full snapshot that failed to decompress reaches processing with `data` still a raw string; it
+ // must be dropped rather than dereferenced (see the guard in process-all-snapshots.ts for context).
+ const sessionId = '1234'
+ const source = { source: 'blob_v2', blob_key: '0' } as SessionRecordingSnapshotSource
+ const key = keyForSource(source)
+ const viewport = (): { width: string; height: string; href: string } => ({
+ width: '100',
+ height: '100',
+ href: 'https://example.com',
+ })
+
+ it.each([
+ ['a raw compressed string', 'H4sIAAAAAAAA_truncated'],
+ ['an object without a node', { foo: 'bar' }],
+ ])('drops a full snapshot whose data is %s without throwing', async (_label, badData) => {
+ const snapshots = [
+ { windowId: 1, timestamp: 1000, type: 4, data: { width: 100, height: 100, href: 'x' } },
+ { windowId: 1, timestamp: 1001, cv: '2024-10', type: 2, data: badData },
+ { windowId: 1, timestamp: 1002, type: 3, data: { source: 2, positions: [] } },
+ ] as unknown as RecordingSnapshot[]
+
+ const result = await processAllSnapshots(
+ [source],
+ { [key]: { snapshots } },
+ { snapshots: {} },
+ viewport,
+ sessionId
+ )
+
+ expect(result.some((e) => e.type === 2)).toBe(false)
+ expect(result.some((e) => e.type === 3)).toBe(true)
+ })
+ })
+
+ describe('undecodable incremental snapshot', () => {
+ // The incremental analogue of the full-snapshot case above: compressed fields that failed to
+ // decompress arrive as strings where rrweb expects arrays and must be dropped, not replayed.
+ const sessionId = '1234'
+ const source = { source: 'blob_v2', blob_key: '0' } as SessionRecordingSnapshotSource
+ const key = keyForSource(source)
+ const viewport = (): { width: string; height: string; href: string } => ({
+ width: '100',
+ height: '100',
+ href: 'https://example.com',
+ })
+
+ it.each([
+ [
+ 'mutation with string texts',
+ { source: IncrementalSource.Mutation, texts: 'H4sI_truncated', attributes: [], removes: [], adds: [] },
+ ],
+ [
+ 'mutation with string adds',
+ { source: IncrementalSource.Mutation, texts: [], attributes: [], removes: [], adds: 'H4sI_truncated' },
+ ],
+ ['stylesheet rule with string adds', { source: IncrementalSource.StyleSheetRule, adds: 'H4sI_truncated' }],
+ ])('drops a %s without throwing', async (_label, badData) => {
+ const snapshots = [
+ { windowId: 1, timestamp: 1000, type: 4, data: { width: 100, height: 100, href: 'x' } },
+ { windowId: 1, timestamp: 1001, cv: '2024-10', type: 3, data: badData },
+ {
+ windowId: 1,
+ timestamp: 1002,
+ type: 3,
+ data: { source: IncrementalSource.Scroll, id: 1, x: 0, y: 5 },
+ },
+ ] as unknown as RecordingSnapshot[]
+
+ const result = await processAllSnapshots(
+ [source],
+ { [key]: { snapshots } },
+ { snapshots: {} },
+ viewport,
+ sessionId
+ )
+
+ expect(result.filter((e) => e.type === 3 && (e.data as any)?.source === badData.source)).toHaveLength(0)
+ expect(
+ result.filter((e) => e.type === 3 && (e.data as any)?.source === IncrementalSource.Scroll)
+ ).toHaveLength(1)
+ })
+ })
})
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.ts
index 929509447837..70612b131c65 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
@@ -103,6 +103,33 @@ describe('SnapshotStore', () => {
expect(store.getEntry(0)?.processedSnapshots).toHaveLength(1)
expect(store.getEntry(0)?.processedSnapshots?.[0].timestamp).toBe(1000)
})
+
+ it('refreshes metadata when a preserved blob_key extends its end_timestamp', () => {
+ // An ongoing recording's tail blob grows under a stable blob_key — a stale endMs would
+ // render already-loaded data as "not buffered yet"
+ const store = new SnapshotStore()
+ store.setSources([makeSource(0, 0, 5)])
+ markLoaded(store, 0, [makeFullSnapshot(1000)])
+
+ store.setSources([makeSource(0, 0, 9)])
+
+ expect(store.getSourceStates()[0].endMs).toBe(Date.UTC(2023, 7, 11, 12, 9, 0))
+ expect(store.getSourceStates()[0].state).toBe('loaded')
+ })
+ })
+
+ describe('clearSnapshotData', () => {
+ it('keeps raw snapshots only for excluded indexes', () => {
+ const store = new SnapshotStore()
+ store.setSources(makeSources(2))
+ markLoaded(store, 0, [makeFullSnapshot(1000)])
+ markLoaded(store, 1, [makeSnapshot(2000)])
+
+ store.clearSnapshotData(new Set([0]))
+
+ expect(store.getEntry(0)?.processedSnapshots).toHaveLength(1)
+ expect(store.getEntry(1)?.processedSnapshots).toBeNull()
+ })
})
describe('markFetched + markProcessed seeding', () => {
diff --git a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.test.ts b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.test.ts
index 0fda14961737..8af959e2e2b2 100644
--- a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.test.ts
+++ b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.test.ts
@@ -1,3 +1,4 @@
+import { expectLogic } from 'kea-test-utils'
import { EventType, IncrementalSource, NodeType, mutationData } from 'posthog-js/rrweb-types'
import { chunkMutationSnapshot, MUTATION_CHUNK_SIZE } from '@posthog/replay-shared'
@@ -72,6 +73,19 @@ describe('snapshotDataLogic', () => {
})
})
+ describe('source load give-up', () => {
+ it('dispatches snapshotSourceLoadExhausted once retries are exhausted', async () => {
+ const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {})
+ await expectLogic(logic, () => {
+ logic.actions.loadSnapshotsForSourceFailure('load failed', new Error('load failed'))
+ logic.actions.loadSnapshotsForSourceFailure('load failed', new Error('load failed'))
+ logic.actions.loadSnapshotsForSourceFailure('load failed', new Error('load failed'))
+ logic.actions.loadSnapshotsForSourceFailure('load failed', new Error('load failed'))
+ }).toDispatchActions(['snapshotSourceLoadExhausted'])
+ consoleError.mockRestore()
+ })
+ })
+
describe('snapshot parsing', () => {
const sessionId = '12345'
const numberOfParsedLinesInData = 8
diff --git a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx
index b77e25c05d98..6cf8d83ce56c 100644
--- a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx
+++ b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx
@@ -50,6 +50,10 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([
actions({
setSnapshots: (snapshots: RecordingSnapshot[]) => ({ snapshots }),
loadSnapshots: true,
+ // Terminal: a source kept failing to load and retries are exhausted. Distinct from the
+ // per-attempt loadSnapshotsForSourceFailure so the player can show an error even when other
+ // sources already loaded (otherwise seeks into the missing range buffer forever).
+ snapshotSourceLoadExhausted: true,
loadSnapshotSources: (breakpointLength?: number) => ({ breakpointLength }),
loadNextSnapshotSource: true,
loadSnapshotsForSource: (sources: Pick<SessionRecordingSnapshotSource, 'source' | 'blob_key'>[]) => ({
@@ -135,7 +139,9 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([
const response = await api.recordings.listSnapshotSources(props.sessionRecordingId, headers)
if (!response || !response.sources) {
- return []
+ // A null/malformed body is a failed load, not a recording with no sources —
+ // returning [] here would silently dead-end with no error and no polling.
+ throw new Error('Malformed response listing snapshot sources')
}
const anyBlobV2 = response.sources.some((s) => s.source === SnapshotSourceType.blob_v2)
@@ -378,6 +384,9 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([
loadSnapshotsForSourceFailure: async (_, breakpoint) => {
cache.loadFailureCount = (cache.loadFailureCount ?? 0) + 1
if (cache.loadFailureCount > 3) {
+ // Give up loudly: nothing else retries this source, so without a terminal action the
+ // player would buffer forever whenever playback reaches the missing range.
+ actions.snapshotSourceLoadExhausted()
return
}
await breakpoint(cache.loadFailureCount * 2000)