: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): find the framed player in exports and retry frame loads (#100583)
Tom Piccirello5e680d759a9c
diff --git a/frontend/src/scenes/session-recordings/player/PlayerFrame.test.tsx b/frontend/src/scenes/session-recordings/player/PlayerFrame.test.tsxindex c73536bf77ba..ff7f89b2c842 100644--- a/frontend/src/scenes/session-recordings/player/PlayerFrame.test.tsx+++ b/frontend/src/scenes/session-recordings/player/PlayerFrame.test.tsx@@ -1,6 +1,6 @@import '@testing-library/jest-dom'-import { fireEvent, render } from '@testing-library/react'+import { act, fireEvent, render } from '@testing-library/react'import { BindLogic, Provider } from 'kea'import posthog from 'posthog-js'@@ -69,17 +69,76 @@ describe('PlayerFrame', () => {})// A same-origin error page, a login redirect, or a browser network-error page all fire load- // with a document that has no mount node. The player must not stay blank with no report.- it('falls back to the app document and reports it when the frame loads without a mount node', () => {- const captureSpy = jest.spyOn(posthog, 'captureException')- const { container, iframe } = renderPlayerFrame()+ // with a document that has no mount node. The frame gets retried before the player falls back+ // to the app document. Each retry records what the frame showed, and only the fallback is an exception.+ it('retries a frame that loads without a mount node, then falls back to the app document', () => {+ jest.useFakeTimers()+ try {+ const captureSpy = jest.spyOn(posthog, 'capture')+ const captureExceptionSpy = jest.spyOn(posthog, 'captureException')+ const { container, iframe } = renderPlayerFrame()- fireEvent.load(iframe)+ fireEvent.load(iframe)+ expect(container.querySelector('iframe')).toBe(iframe)+ act(() => {+ jest.advanceTimersByTime(1000)+ })+ expect(iframe).toHaveAttribute('src', '/replay_player_frame/index.html?retry=1')- expect(container.querySelector('iframe')).toBeNull()- const fallback = container.querySelector('div.PlayerFrame__content')- expect(fallback).not.toBeNull()- expect(sessionRecordingPlayerLogic(logicProps).values.rootFrame).toBe(fallback)- expect(captureSpy).toHaveBeenCalledTimes(1)+ // A browser error page is cross-origin to the app, so the frame's document is unreadable.+ Object.defineProperty(iframe, 'contentDocument', { value: null, configurable: true })+ fireEvent.load(iframe)+ act(() => {+ jest.advanceTimersByTime(2000)+ })+ expect(iframe).toHaveAttribute('src', '/replay_player_frame/index.html?retry=2')++ fireEvent.load(iframe)++ expect(container.querySelector('iframe')).toBeNull()+ const fallback = container.querySelector('div.PlayerFrame__content')+ expect(fallback).not.toBeNull()+ expect(sessionRecordingPlayerLogic(logicProps).values.rootFrame).toBe(fallback)+ expect(+ captureSpy.mock.calls+ .filter(([event]) => event === 'replay player frame load retried')+ .map(([, properties]) => [properties?.attempt, properties?.frameDocumentReadable])+ ).toEqual([+ [1, true],+ [2, false],+ ])+ expect(captureExceptionSpy).toHaveBeenCalledTimes(1)+ expect(captureExceptionSpy.mock.calls[0][1]).toMatchObject({ attempt: 3, frameDocumentReadable: false })+ } finally {+ jest.useRealTimers()+ }+ })++ // A frame cannot load while the browser is offline, and the app-document fallback needs no network,+ // so the player falls back at once instead of waiting for a connection that may not come back.+ it('falls back to the app document without a retry while the browser is offline', () => {+ const onLine = jest.spyOn(navigator, 'onLine', 'get').mockReturnValue(false)+ jest.useFakeTimers()+ try {+ const captureSpy = jest.spyOn(posthog, 'capture')+ const captureExceptionSpy = jest.spyOn(posthog, 'captureException')+ const { container, iframe } = renderPlayerFrame()++ fireEvent.load(iframe)+ act(() => {+ jest.advanceTimersByTime(10000)+ })++ expect(container.querySelector('iframe')).toBeNull()+ const fallback = container.querySelector('div.PlayerFrame__content')+ expect(fallback).not.toBeNull()+ expect(sessionRecordingPlayerLogic(logicProps).values.rootFrame).toBe(fallback)+ expect(captureSpy).not.toHaveBeenCalledWith('replay player frame load retried', expect.anything())+ expect(captureExceptionSpy).toHaveBeenCalledTimes(1)+ expect(captureExceptionSpy.mock.calls[0][1]).toMatchObject({ attempt: 1, browserOnline: false })+ } finally {+ jest.useRealTimers()+ onLine.mockRestore()+ }})})diff --git a/frontend/src/scenes/session-recordings/player/PlayerFrame.tsx b/frontend/src/scenes/session-recordings/player/PlayerFrame.tsxindex b5c4b4c6f7b0..d559a1983d12 100644--- a/frontend/src/scenes/session-recordings/player/PlayerFrame.tsx+++ b/frontend/src/scenes/session-recordings/player/PlayerFrame.tsx@@ -23,8 +23,15 @@ const PLAYER_FRAME_CONTENT_ID = 'player-frame-content'export const PlayerFrame = (): JSX.Element => {const replayDimensionRef = useRef<viewportResizeDimension>()- const { player, sessionRecordingId, maskingWindow, speed, resolution, playerFrameDocumentFailed } =- useValues(sessionRecordingPlayerLogic)+ const {+ player,+ sessionRecordingId,+ maskingWindow,+ speed,+ resolution,+ playerFrameDocumentFailed,+ playerFrameLoadRetries,+ } = useValues(sessionRecordingPlayerLogic)const { setScale, setRootFrame, playerFrameDocumentLoadFailed } = useActions(sessionRecordingPlayerLogic)const { featureFlags } = useValues(featureFlagLogic)@@ -32,6 +39,9 @@ export const PlayerFrame = (): JSX.Element => {// flag-off path. That path still works, so the player renders rather than staying blank.const ownDocument = !!featureFlags[FEATURE_FLAGS.REPLAY_PLAYER_OWN_DOCUMENT] && !playerFrameDocumentFailed+ // A frame loads again only when its src changes, so each retry adds a query string the server ignores.+ const frameSrc = playerFrameLoadRetries ? `${PLAYER_FRAME_SRC}?retry=${playerFrameLoadRetries}` : PLAYER_FRAME_SRC+const iframeRef = useRef<HTMLIFrameElement | null>(null)// rrweb's mount point. Under the flag it lives in the player frame's document, not this one.const frameRef = useRef<HTMLDivElement | null>(null)@@ -98,7 +108,7 @@ export const PlayerFrame = (): JSX.Element => {}// A same-origin error page, a login redirect, and a browser error page all fire load too,// so a load event does not prove the shell document arrived.- playerFrameDocumentLoadFailed()+ playerFrameDocumentLoadFailed(iframeRef.current)return}frameRef.current = content as HTMLDivElement@@ -161,7 +171,7 @@ export const PlayerFrame = (): JSX.Element => {<iframeref={iframeRef}className="PlayerFrame__document"- src={PLAYER_FRAME_SRC}+ src={frameSrc}onLoad={handleFrameLoad}title="Session replay player"// Interaction belongs to the app's controls, not the recorded page.diff --git a/frontend/src/scenes/session-recordings/player/playerFrameLoadDiagnostics.ts b/frontend/src/scenes/session-recordings/player/playerFrameLoadDiagnostics.tsnew file mode 100644index 000000000000..f46c66f73130--- /dev/null+++ b/frontend/src/scenes/session-recordings/player/playerFrameLoadDiagnostics.ts@@ -0,0 +1,40 @@+export interface PlayerFrameLoadDiagnostics {+ frameDocumentReadable: boolean+ frameUrlPath: string | null+ frameDocumentTitle: string | null+ frameContentType: string | null+ frameReadyState: DocumentReadyState | null+ frameResponseStatus: number | null+ browserOnline: boolean+ pageVisibility: DocumentVisibilityState+ msSincePageLoad: number+}++const MAX_TITLE_LENGTH = 100++// Resource Timing records the frame's navigation in the embedding document. A navigation that never finished has+// no entry, and some browsers leave out `responseStatus`. jsdom has no `getEntriesByName`, and the retry runs after+// this, so a missing API must not throw here.+function responseStatus(src: string): number | null {+ const entry = performance.getEntriesByName?.(src).at(-1) as PerformanceResourceTiming | undefined+ return entry?.responseStatus ?? null+}++// Describes what the frame loaded in place of the shell document, so a report can tell a network+// error page, an HTTP error, and a redirect apart.+export function getPlayerFrameLoadDiagnostics(iframe: HTMLIFrameElement | null): PlayerFrameLoadDiagnostics {+ // A browser error page or a redirect to another origin makes the frame cross-origin, which hides its document.+ const frameDocument = iframe?.contentDocument ?? null+ return {+ frameDocumentReadable: frameDocument !== null,+ // The path alone, because a query string can carry a token.+ frameUrlPath: frameDocument?.location.pathname ?? null,+ frameDocumentTitle: frameDocument ? frameDocument.title.slice(0, MAX_TITLE_LENGTH) : null,+ frameContentType: frameDocument?.contentType ?? null,+ frameReadyState: frameDocument?.readyState ?? null,+ frameResponseStatus: iframe ? responseStatus(iframe.src) : null,+ browserOnline: navigator.onLine,+ pageVisibility: document.visibilityState,+ msSincePageLoad: Math.round(performance.now()),+ }+}diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.tsindex a86b68d0f1ab..81734d60a74a 100644--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts@@ -73,6 +73,7 @@ import {type playerCommentOverlayLogicType,} from './commenting/playerFrameCommentOverlayLogic'import { clipWindowSeconds } from './controller/clipRange'+import { getPlayerFrameLoadDiagnostics } from './playerFrameLoadDiagnostics'import { playerSettingsLogic } from './playerSettingsLogic'import { snapshotDataLogic } from './snapshotDataLogic'import {@@ -94,6 +95,10 @@ const IS_TEST_MODE = process.env.NODE_ENV === 'test'export const PLAYBACK_SPEEDS = [0.5, 1, 1.5, 2, 3, 4, 8, 16]export const ONE_FRAME_MS = 100 // We don't really have frames but this feels granular enoughexport const ONE_SECOND_MS = 1000+// A failed frame load is usually transient, so the frame gets a few more chances before the player+// falls back to the app document.+const MAX_PLAYER_FRAME_LOAD_RETRIES = 2+const PLAYER_FRAME_RETRY_DELAY_MS = 1000export type { ResourceErrorDetails, GroupedAssetErrors, DoctorDiagnostics } from './utils/asset-error-grouping'@@ -641,6 +646,9 @@ export interface sessionRecordingPlayerLogicValues {player: Player | nullplayerError: string | nullplayerFrameDocumentFailed: boolean+ playerFrameLoadFailures: number+ playerFrameLoadRetries: number+ playerFrameLoadStopped: booleanplayerSpeed: numberplayingState: SessionPlayerState.PLAY | SessionPlayerState.PAUSEplayingTimeTracking: PlayerTimeTracking@@ -881,8 +889,8 @@ export interface sessionRecordingPlayerLogicActions {playerErrorSeen: (error: any) => {error: any}- playerFrameDocumentLoadFailed: () => {- value: true+ playerFrameDocumentLoadFailed: (iframe: HTMLIFrameElement | null) => {+ iframe: HTMLIFrameElement | null}restartIframePlayback: () => {value: true@@ -890,6 +898,9 @@ export interface sessionRecordingPlayerLogicActions {retryLoadingSnapshots: () => {value: true}+ retryPlayerFrameLoad: () => {+ value: true+ }schedulePlayerTimeTracking: () => {value: true}@@ -1018,6 +1029,9 @@ export interface sessionRecordingPlayerLogicActions {stopAnimation: () => {value: true}+ stopRetryingPlayerFrameLoad: () => {+ value: true+ }syncPlayerSpeed: () => {value: true}@@ -1050,6 +1064,7 @@ export interface sessionRecordingPlayerLogicActions {export interface sessionRecordingPlayerLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {+ playerFrameDocumentFailed: (playerFrameLoadFailures: number, playerFrameLoadStopped: boolean) => booleansessionRecordingId: (sessionRecordingId: string) => stringlogicProps: (arg: any) => SessionRecordingPlayerLogicPropsplayNextRecording: (arg: any) => ((automatic: boolean) => void) | undefined@@ -1304,7 +1319,9 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(incrementClickCount: true,// the error is emitted from code we don't control in rrweb, so we can't guarantee it's really an ErrorplayerErrorSeen: (error: any) => ({ error }),- playerFrameDocumentLoadFailed: true,+ playerFrameDocumentLoadFailed: (iframe: HTMLIFrameElement | null) => ({ iframe }),+ retryPlayerFrameLoad: true,+ stopRetryingPlayerFrameLoad: true,fingerprintReported: (fingerprint: string) => ({ fingerprint }),setDebugSnapshotTypes: (types: EventType[]) => ({ types }),setDebugSnapshotIncrementalSources: (incrementalSources: IncrementalSource[]) => ({ incrementalSources }),@@ -1500,8 +1517,10 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(},],isBuffering: [true, { startBuffer: () => true, endBuffer: () => false }],- // The frame's src never changes, so a second load never arrives on its own, and nothing resets this.- playerFrameDocumentFailed: [false, { playerFrameDocumentLoadFailed: () => true }],+ playerFrameLoadFailures: [0, { playerFrameDocumentLoadFailed: (failures) => failures + 1 }],+ // PlayerFrame adds this to the frame's src, because a frame loads again only when its src changes.+ playerFrameLoadRetries: [0, { retryPlayerFrameLoad: (retries) => retries + 1 }],+ playerFrameLoadStopped: [false, { stopRetryingPlayerFrameLoad: () => true }],playerError: [null as string | null,{@@ -1576,6 +1595,12 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(],})),selectors({+ // Nothing resets this, because the frame's src stops changing once the retries run out.+ playerFrameDocumentFailed: [+ (s) => [s.playerFrameLoadFailures, s.playerFrameLoadStopped],+ (playerFrameLoadFailures: number, playerFrameLoadStopped: boolean): boolean =>+ playerFrameLoadStopped || playerFrameLoadFailures > MAX_PLAYER_FRAME_LOAD_RETRIES,+ ],// Prop references for use by other logicssessionRecordingId: [(_, p) => [p.sessionRecordingId], (sessionRecordingId: string) => sessionRecordingId],logicProps: [() => [(_, props) => props], (props): SessionRecordingPlayerLogicProps => props],@@ -2281,12 +2306,36 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(actions.setPlay()}},- playerFrameDocumentLoadFailed: () => {- // The player still works from the app document, so the only sign of this is the report.- posthog.captureException(new Error('Replay player frame loaded without its mount node'), {- feature: 'session-recording-player-frame',+ playerFrameDocumentLoadFailed: ({ iframe }) => {+ const report = {sessionRecordingId: props.sessionRecordingId,- })+ attempt: values.playerFrameLoadFailures,+ ...getPlayerFrameLoadDiagnostics(iframe),+ }+ // A load retried while offline fails again, and the app-document fallback needs no network, so+ // an offline browser gets that fallback now. A connection can stay away for the rest of the+ // session, and a viewer whose snapshots are loaded already must not wait for it.+ if (values.playerFrameDocumentFailed || !navigator.onLine) {+ actions.stopRetryingPlayerFrameLoad()+ // The app-document fallback hides the failure from the viewer, so the only sign of it is the report.+ posthog.captureException(new Error('Replay player frame loaded without its mount node'), {+ feature: 'session-recording-player-frame',+ ...report,+ })+ return+ }+ posthog.capture('replay player frame load retried', report)+ const delayMs = PLAYER_FRAME_RETRY_DELAY_MS * values.playerFrameLoadFailures+ cache.disposables.add(+ () => {+ const timer = setTimeout(() => actions.retryPlayerFrameLoad(), delayMs)+ return () => clearTimeout(timer)+ },+ 'playerFrameLoadRetry',+ // The default pause clears this timer when the tab hides and starts the full delay again on+ // show, so a frame that failed in a hidden tab would never get its retry.+ { pauseOnPageHidden: false }+ )},playerErrorSeen: ({ error }) => {const fingerprint = encodeURIComponent(error.message + error.filename + error.lineno + error.colno)diff --git a/products/exports/backend/tasks/image_exporter.py b/products/exports/backend/tasks/image_exporter.pyindex a3c2f872ba53..b9024829a4ed 100644--- a/products/exports/backend/tasks/image_exporter.py+++ b/products/exports/backend/tasks/image_exporter.py@@ -72,15 +72,24 @@ MAX_WIDTH_PIXELS = 4000 # Max width for wide content like funnels with many steMAX_HEIGHT_PIXELS = 5000 # Prevents Chrome from consuming excessive memory on very tall pagesCONTENT_PADDING = 80 # Padding for card borders-MEASURE_CONTENT_HEIGHT_JS = """+REPLAY_WRAPPER_SELECTOR = ".replayer-wrapper"++# The replay player mounts rrweb either in the app document or inside its own same-origin frame+# document, and a document query never crosses into a frame, so look in both.+FIND_REPLAY_WRAPPER_JS = f"""(+ document.querySelector('{REPLAY_WRAPPER_SELECTOR}') ||+ document.querySelector('iframe.PlayerFrame__document')?.contentDocument?.querySelector('{REPLAY_WRAPPER_SELECTOR}')+)"""++MEASURE_CONTENT_HEIGHT_JS = f"""const element = document.querySelector('.InsightCard__viz') ||document.querySelector('.ExportedInsight__content') ||- document.querySelector('.replayer-wrapper') ||+ {FIND_REPLAY_WRAPPER_JS} ||document.querySelector('.heatmap-exporter');- if (element) {+ if (element) {{const rect = element.getBoundingClientRect();return Math.max(rect.height, document.body.scrollHeight);- }+ }}return document.body.scrollHeight;"""@@ -92,7 +101,7 @@ MEASURE_CONTENT_WIDTH_JS = f"""}}// Check for replay player- const replayElement = document.querySelector('.replayer-wrapper');+ const replayElement = {FIND_REPLAY_WRAPPER_JS};if (replayElement) {{return replayElement.offsetWidth;}}@@ -243,7 +252,7 @@ def _export_to_png(url_to_render = absolute_uri(f"/exporter?token={access_token}&t={exported_asset.export_context.get('timestamp') or 0}&fullscreen=true")- wait_for_css_selector = exported_asset.export_context.get("css_selector", ".replayer-wrapper")+ wait_for_css_selector = exported_asset.export_context.get("css_selector", REPLAY_WRAPPER_SELECTOR)screenshot_width = exported_asset.export_context.get("width", 1400)screenshot_height = exported_asset.export_context.get("height", 600)@@ -457,7 +466,12 @@ def _screenshot_asset_browserless(try:page.goto(url_to_render, wait_until="domcontentloaded", timeout=page_load_timeout * 1000)- page.wait_for_selector(wait_for_css_selector, state="attached", timeout=page_load_timeout * 1000)+ if wait_for_css_selector == REPLAY_WRAPPER_SELECTOR:+ page.wait_for_function(+ f"() => !!{FIND_REPLAY_WRAPPER_JS}", timeout=page_load_timeout * 1000, polling=100+ )+ else:+ page.wait_for_selector(wait_for_css_selector, state="attached", timeout=page_load_timeout * 1000)except PlaywrightTimeoutError as e:with posthoganalytics.new_context():posthoganalytics.tag("stage", "image_exporter.page_load_timeout")diff --git a/products/exports/backend/tasks/test/test_image_exporter.py b/products/exports/backend/tasks/test/test_image_exporter.pyindex 7170f3aeaa1e..606fa4f04b26 100644--- a/products/exports/backend/tasks/test/test_image_exporter.py+++ b/products/exports/backend/tasks/test/test_image_exporter.py@@ -931,6 +931,35 @@ class TestScreenshotAssetBrowserless(SimpleTestCase):assert isinstance(ctx.exception.__cause__, PlaywrightTimeoutError)assert "Timeout 30000ms exceeded" in str(ctx.exception.__cause__)+ def test_replay_export_finds_the_player_inside_its_frame_document(self) -> None:+ # The player can mount rrweb inside its own frame document. A selector wait or a document query+ # never looks inside a frame, so the export would time out, or measure the page without the player.+ page = MagicMock()+ context = MagicMock()+ context.new_page.return_value = page+ browser = MagicMock()+ browser.new_context.return_value = context+ playwright_obj = MagicMock()+ playwright_obj.chromium.connect_over_cdp.return_value = browser+ sync_playwright_cm = MagicMock()+ sync_playwright_cm.__enter__.return_value = playwright_obj++ with (+ patch(+ "products.exports.backend.tasks.image_exporter.sync_playwright",+ return_value=sync_playwright_cm,+ ),+ patch.object(settings, "BROWSERLESS_CDP_URL", "wss://chrome.browserless.io"),+ ):+ image_exporter._screenshot_asset_browserless("p", "u", 1400, ".replayer-wrapper")++ assert all(call.args[0] != ".replayer-wrapper" for call in page.wait_for_selector.call_args_list)+ page.wait_for_function.assert_called_once()+ assert "iframe.PlayerFrame__document" in page.wait_for_function.call_args.args[0]+ measure_scripts = [call.args[0] for call in page.evaluate.call_args_list]+ assert measure_scripts+ assert all("iframe.PlayerFrame__document" in script for script in measure_scripts)+class TestDimensionHelpers(SimpleTestCase):@parameterized.expand(