: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): reach exposures captured outside the playable window (#95050)
Marcel Poelker5d716b8bc164
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex bcbd4281dda0..952e03f88684 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5813,13 +5813,17 @@ snapshots:replay-overview-tab-experiments--current-experiment-not-exposed--light:hash: v1.k794b7964.3df16a2a43537af9a1c3cf4feb182529a7633cc5d4fc01011b80ee0a129281e8.YLJI9RsTHmIC0QasDoX6Djt-U_PGNo4FfTRSVKOwPLsreplay-overview-tab-experiments--default--dark:- hash: v1.k794b7964.79330e398cb2b6402ab847a6ab8e2ee61e71bd531473a6db0624b0d31538ad67.VS3PPJVIbJk5jHfGaUd7LjpdfWGQApwqjdvAKZhlInA+ hash: v1.k794b7964.cdc4c87099a9fd4cfe4b6d43d18d599d281e5f062dd0b8882b3bc16ea4662793.waPFcJx0-GOyEQz5VYGoq5B6UxXd41xpjSBJ8LjM5Roreplay-overview-tab-experiments--default--light:- hash: v1.k794b7964.40d99fa3c1d49cb1f4b21f3b9f727ad298ddf24767716bca7101ed3bf05192b4.F8N5B6OxXWv_eLUhNzKlkuuU5PqwKvSYqKb3nVLCkcs+ hash: v1.k794b7964.ec69e95bfa93d70631455ca76e445a283951eee3ee63e44be754a15a09b2dc8d.ftOf6U1hGjd-TT6gIpWypmX6zNjLOBduD17KtLtaP5Qreplay-overview-tab-experiments--empty--dark:hash: v1.k794b7964.13e51a486b40a1455fde0075af333e3dff21f25491d06cc59ab10c24200eb1d2.Fn0OHVeRm39HLB3-xcZUZavR375CxuNraJZdmfxTS-Ureplay-overview-tab-experiments--empty--light:hash: v1.k794b7964.34d2a031b8e3cea8e905aacec4f7d70ae9f625f56bb1649d8e95f73b1eba71a8._AeRzz6TNgrSmnERRCH2YbGUFjFBA4HPfW4wFM4uySU+ replay-overview-tab-experiments--exposure-outside-window--dark:+ hash: v1.k794b7964.f261f85d6665ac370b191f6c4ed20498a71abf49eb1b3d94cf840f38e650ce8e.Ub39RpdNuFjHa1mFLoCH-5YfP1GscA47Gp2yCVHzgq8+ replay-overview-tab-experiments--exposure-outside-window--light:+ hash: v1.k794b7964.c308cb1719304a37f4b681d01f2269a80e2a4454f5beb1a4763f8a92a6b72722.HmOtduvkvo-ibuMV8MkHjbGVZbLlqZKIG3h1q2Sz-V8replay-overview-tab-experiments--loading--dark:hash: v1.k794b7964.55ed027ece39592bf5eee139b78d0147e93849476016cd690928a1416cce057a.FCepXFnoPBB-F5-GGDsNJtwO_uHeAKixmqN28WPHZkQreplay-overview-tab-experiments--loading--light:diff --git a/frontend/src/scenes/session-recordings/__mocks__/experiment_session_context.ts b/frontend/src/scenes/session-recordings/__mocks__/experiment_session_context.tsindex c8b43f2b15b6..d7de4e4f3b72 100644--- a/frontend/src/scenes/session-recordings/__mocks__/experiment_session_context.ts+++ b/frontend/src/scenes/session-recordings/__mocks__/experiment_session_context.ts@@ -131,7 +131,8 @@ export const experimentSessionContextResponse: ExperimentSessionContextResponseAflag_key: 'search-bar-placement',variant: 'control',variants_seen: ['control'],- // Exposure captured just before the recording's playable range — seen, but nothing to jump to.+ // Exposure captured before the recording's first frame. Renders a negative offset that+ // jumps to the first frame.first_exposure_timestamp: '2023-05-01T14:45:00.000000Z',}),makeExperimentSessionContextItem({diff --git a/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.stories.tsx b/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.stories.tsxindex cd693a547289..8c50f705a577 100644--- a/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.stories.tsx+++ b/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.stories.tsx@@ -11,6 +11,7 @@ import {ENROLLED_CURRENT_EXPERIMENT_ID,experimentSessionContextEnrolledCurrentResponse,experimentSessionContextResponse,+ makeExperimentSessionContextItem,} from '../../__mocks__/experiment_session_context'import { recordingMetaJson } from '../../__mocks__/recording_meta'import { sessionRecordingDataCoordinatorLogic } from '../sessionRecordingDataCoordinatorLogic'@@ -94,6 +95,49 @@ CurrentExperimentNotExposed.decorators = [}),]+// The recording window resolves to 14:46:20–14:46:32 from the meta mock. One exposure fired before+// the first frame, one inside, one after the last frame, so the story snapshots the signed offsets+// (-, none, +) that the out-of-window rows now render.+export function ExposureOutsideWindow(): JSX.Element {+ return <MockedPlayerSidebarExperimentsSection sessionRecordingId="experiment-context-out-of-window" />+}+ExposureOutsideWindow.parameters = {+ testOptions: {+ waitForLoadersToDisappear: true,+ waitForSelector: '[data-attr=replay-experiment-context-jump-to-first-exposure]',+ },+}+ExposureOutsideWindow.decorators = [+ mswDecorator({+ get: {+ '/api/environments/:team_id/session_recordings/:id': recordingMetaJson,+ '/api/projects/:team_id/experiments/session_context/': {+ session_id: 'experiment-context-out-of-window',+ results: [+ makeExperimentSessionContextItem({+ experiment_id: 301,+ experiment_name: 'Exposed before first frame',+ flag_key: 'exposed-before-first-frame',+ first_exposure_timestamp: '2023-05-01T14:45:57.000000Z',+ }),+ makeExperimentSessionContextItem({+ experiment_id: 302,+ experiment_name: 'Exposed in window',+ flag_key: 'exposed-in-window',+ first_exposure_timestamp: '2023-05-01T14:46:26.000000Z',+ }),+ makeExperimentSessionContextItem({+ experiment_id: 303,+ experiment_name: 'Exposed after last frame',+ flag_key: 'exposed-after-last-frame',+ first_exposure_timestamp: '2023-05-01T14:47:00.000000Z',+ }),+ ],+ },+ },+ }),+]+// While the context request is in flight the box shows a skeleton placeholder — but only when the// viewer arrived from an experiment's recordings tab, so the route is put on /experiments/<id>// first. The mocked request never resolves, holding the section in its loading state.diff --git a/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.test.tsx b/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.test.tsxindex 839ab2521b09..c92cf4a97ca4 100644--- a/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.test.tsx+++ b/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.test.tsx@@ -1,46 +1,168 @@import '@testing-library/jest-dom'-import { render, screen } from '@testing-library/react'+import { fireEvent, render, screen, waitFor } from '@testing-library/react'import { BindLogic, Provider } from 'kea'import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'import { urls } from 'scenes/urls'+import type { ExperimentSessionContextResponseApi } from 'products/experiments/frontend/generated/api.schemas'+import {ENROLLED_CURRENT_EXPERIMENT_ID,experimentSessionContextEnrolledCurrentResponse,+ makeExperimentSessionContextItem,} from '../../__mocks__/experiment_session_context'import { setupSessionRecordingTest } from '../__mocks__/test-setup'import { sessionRecordingPlayerLogic } from '../sessionRecordingPlayerLogic'-import { PlayerSidebarExperimentsSection } from './PlayerSidebarExperimentsSection'+import { computeExposureSeek, PlayerSidebarExperimentsSection } from './PlayerSidebarExperimentsSection'describe('PlayerSidebarExperimentsSection', () => {- const logicProps = {- sessionRecordingId: experimentSessionContextEnrolledCurrentResponse.session_id,- playerKey: 'experiments-section-test',- }-- beforeEach(() => {- setupSessionRecordingTest({- getMocks: {- '/api/projects/:team_id/experiments/session_context/': experimentSessionContextEnrolledCurrentResponse,- },+ describe('computeExposureSeek', () => {+ const START = 1_000_000+ const END = 1_100_000++ // The recorder boots after or stops before the exposure event, so the exposure lands outside+ // the captured frames. Each case pins the sign of the offset and the frame the jump lands on.+ it.each([+ ['before the first frame', 997_000, END, -3_000, 'before', START],+ ['inside the window', 1_040_000, END, 40_000, 'inside', 1_040_000],+ ['after the last frame', 1_112_000, END, 12_000, 'after', END],+ ['exactly on the last frame stays in window', END, END, 100_000, 'inside', END],+ ['with an unknown end stays in window', 1_200_000, null, 200_000, 'inside', 1_200_000],+ ])('places an exposure %s', (_label, exposedAtMs, endMs, offsetMs, placement, seekTargetMs) => {+ expect(computeExposureSeek(exposedAtMs, START, endMs as number | null)).toEqual({+ offsetMs,+ placement,+ seekTargetMs,+ })})})- // Pinning lifts the arrived-from experiment out of the enrolled group, and so out of that group's- // label. Without a marker of its own the row claims an exposure this session has no event for.- it('says the pinned experiment was not exposed when the session has no exposure event for it', async () => {- router.actions.push(urls.experiment(ENROLLED_CURRENT_EXPERIMENT_ID))+ describe('rendering', () => {+ beforeEach(() => {+ setupSessionRecordingTest({+ getMocks: {+ '/api/projects/:team_id/experiments/session_context/':+ experimentSessionContextEnrolledCurrentResponse,+ },+ })+ })++ // Pinning lifts the arrived-from experiment out of the enrolled group, and so out of that+ // group's label. Without a marker of its own the row claims an exposure this session has no+ // event for.+ it('says the pinned experiment was not exposed when the session has no exposure event for it', async () => {+ router.actions.push(urls.experiment(ENROLLED_CURRENT_EXPERIMENT_ID))++ render(+ <Provider>+ <BindLogic+ logic={sessionRecordingPlayerLogic}+ props={{+ sessionRecordingId: experimentSessionContextEnrolledCurrentResponse.session_id,+ playerKey: 'experiments-section-test',+ }}+ >+ <PlayerSidebarExperimentsSection />+ </BindLogic>+ </Provider>+ )++ expect(await screen.findByText('Not exposed in this session')).toBeInTheDocument()+ })- render(- <Provider>- <BindLogic logic={sessionRecordingPlayerLogic} props={logicProps}>- <PlayerSidebarExperimentsSection />- </BindLogic>- </Provider>- )+ // The playable window runs from 14:46:20.877 for the recording's 11s duration, which ends+ // ahead of the metadata's end_time (see the recording_meta and recording_snapshots mocks).+ // An exposure outside it used to render a grey, unclickable 00:00; it must now be a signed+ // offset that jumps to the closest captured frame.+ it('renders an out-of-window exposure as a signed, seekable offset', async () => {+ const sessionRecordingId = 'experiment-context-out-of-window'+ const response: ExperimentSessionContextResponseApi = {+ session_id: sessionRecordingId,+ results: [+ makeExperimentSessionContextItem({+ experiment_id: 301,+ experiment_name: 'Before start',+ first_exposure_timestamp: '2023-05-01T14:45:57.000000Z',+ }),+ makeExperimentSessionContextItem({+ experiment_id: 302,+ experiment_name: 'Inside window',+ first_exposure_timestamp: '2023-05-01T14:46:26.000000Z',+ }),+ makeExperimentSessionContextItem({+ experiment_id: 303,+ experiment_name: 'After end',+ first_exposure_timestamp: '2023-05-01T14:47:10.000000Z',+ }),+ makeExperimentSessionContextItem({+ experiment_id: 304,+ experiment_name: 'Fraction of a second before start',+ first_exposure_timestamp: '2023-05-01T14:46:20.577000Z',+ }),+ ],+ }+ setupSessionRecordingTest({+ getMocks: { '/api/projects/:team_id/experiments/session_context/': response },+ })+ // Only /experiments/<id> pins a row; a neutral path keeps them all inline.+ router.actions.push('/replay')- expect(await screen.findByText('Not exposed in this session')).toBeInTheDocument()+ const logicProps = { sessionRecordingId, playerKey: 'oow-test' }+ render(+ <Provider>+ <BindLogic logic={sessionRecordingPlayerLogic} props={logicProps}>+ <PlayerSidebarExperimentsSection />+ </BindLogic>+ </Provider>+ )++ // The exposure column appears only once the window resolves, so wait for the jump link.+ const exposureLink = async (experimentName: string): Promise<HTMLElement> => {+ const row = (await screen.findByText(experimentName)).parentElement as HTMLElement+ return waitFor(() => {+ const link = row.querySelector<HTMLElement>(+ '[data-attr="replay-experiment-context-jump-to-first-exposure"]'+ )+ expect(link).not.toBeNull()+ return link as HTMLElement+ })+ }++ const before = await exposureLink('Before start')+ // An interactive control, not the grey span the out-of-window case used to render. Link+ // with an onClick and no `to` renders a button.+ expect(before.tagName).toBe('BUTTON')+ expect(before.textContent).toBe('-00:24')+ expect((await exposureLink('Inside window')).textContent).toBe('00:05')+ const after = await exposureLink('After end')+ expect(after.textContent).toBe('+00:39')+ // A gap under a second rounds up rather than flooring to 00:00, which would read as the+ // "no exposure here" the signed offset exists to correct.+ expect((await exposureLink('Fraction of a second before start')).textContent).toBe('-00:01')++ // Wiring the jump to the wrong field would pass the helper cases and the label+ // assertions alike, so the click has to land on the closest captured frame itself.+ const logic = sessionRecordingPlayerLogic(logicProps)+ const { start, durationMs } = logic.values.sessionPlayerData+ // The playable window ends a duration after the start, which can precede the metadata's+ // end_time, so the last frame is derived the way the section bounds the window.+ const firstFrameMs = start?.valueOf() as number+ const lastFrameMs = firstFrameMs + durationMs++ fireEvent.click(before)+ await expectLogic(logic).toDispatchActions([+ (action) =>+ action.type === logic.actionTypes.seekToTimestamp && action.payload.timestamp === firstFrameMs,+ ])++ fireEvent.click(after)+ await expectLogic(logic).toDispatchActions([+ (action) =>+ action.type === logic.actionTypes.seekToTimestamp && action.payload.timestamp === lastFrameMs,+ ])+ })})})diff --git a/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.tsx b/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.tsxindex a4af50206e53..ec0ddc093297 100644--- a/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.tsx+++ b/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.tsx@@ -11,7 +11,7 @@ import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'import { Link } from 'lib/lemon-ui/Link'import { Tooltip } from 'lib/lemon-ui/Tooltip'-import { colonDelimitedDuration } from 'lib/utils/durations'+import { colonDelimitedDuration, humanFriendlyDuration } from 'lib/utils/durations'import { addProductIntentForCrossSell } from 'lib/utils/product-intents'import { urls } from 'scenes/urls'@@ -215,40 +215,72 @@ function OpenExperimentButton({ item }: { item: ExperimentSessionContextItemApi)}-const OUT_OF_WINDOW_TOOLTIP =- "The exposure was captured just outside this recording's playable range, so there's no moment to jump to."-// The person's counted first exposure may lie in an earlier session (the experiment analysis counts// exposure per person across the whole run window), so an in-session metric event can precede this one.const EXPOSURE_CAVEAT ='They may have been enrolled in an earlier session, so metric events can fire before this moment.'-function ExposureTime({- timeInRecording,- onSeek,- outOfWindow,-}: {- timeInRecording: number- onSeek?: () => void- outOfWindow?: boolean-}): JSX.Element {- const label = colonDelimitedDuration(Math.max(0, timeInRecording) / 1000, null)- if (onSeek) {- return (- <Tooltip title={`Jump to the first exposure in this session. ${EXPOSURE_CAVEAT}`}>- <Link- className="text-xs tabular-nums shrink-0 min-w-10 text-right"- onClick={onSeek}- data-attr="replay-experiment-context-jump-to-first-exposure"- >- {label}- </Link>- </Tooltip>- )+type ExposurePlacement = 'before' | 'inside' | 'after'++interface ExposureSeek {+ // Signed offset against the nearest captured frame: negative before the first frame, positive+ // after the last one, and the offset from the start for an in-window exposure.+ offsetMs: number+ placement: ExposurePlacement+ // The frame we can show: the exposure moment when it is in window, else the closest captured+ // frame (the first for a before-start exposure, the last for an after-end one).+ seekTargetMs: number+}++// The recorder can boot after the exposure event fired, or stop before it, so the exposure can fall+// outside the captured frames. Place it against the window and pick the closest frame to jump to.+export function computeExposureSeek(+ exposedAtMs: number,+ recordingStartMs: number,+ recordingEndMs: number | null+): ExposureSeek {+ if (exposedAtMs < recordingStartMs) {+ return { offsetMs: exposedAtMs - recordingStartMs, placement: 'before', seekTargetMs: recordingStartMs }+ }+ if (recordingEndMs != null && exposedAtMs > recordingEndMs) {+ return { offsetMs: exposedAtMs - recordingEndMs, placement: 'after', seekTargetMs: recordingEndMs }}+ return { offsetMs: exposedAtMs - recordingStartMs, placement: 'inside', seekTargetMs: exposedAtMs }+}++interface ExposureTimeProps {+ offsetMs: number+ placement: ExposurePlacement+ onSeek: () => void+}++// The label carries the signed offset so an out-of-window exposure reads as real, not as 00:00. A+// before-start or after-end jump lands on the closest captured frame rather than the exposure+// moment, so the tooltip names the gap and says what the jump does.+function ExposureTime({ offsetMs, placement, onSeek }: ExposureTimeProps): JSX.Element {+ // An in-window offset is a playback position, so it floors to match the player clock. An+ // out-of-window gap rounds up instead: flooring one under a second would print 00:00, the same+ // "no exposure here" reading this column exists to correct.+ const seconds = placement === 'inside' ? Math.floor(offsetMs / 1000) : Math.ceil(Math.abs(offsetMs) / 1000)+ const magnitude = colonDelimitedDuration(seconds, null)+ const label = placement === 'before' ? `-${magnitude}` : placement === 'after' ? `+${magnitude}` : magnitude+ // The same rounded value as the label, so the spelled-out gap and the compact offset agree.+ const gap = humanFriendlyDuration(seconds)+ const tooltip =+ placement === 'before'+ ? `The exposure fired ${gap} before the replay begins. Jumps to the first frame.`+ : placement === 'after'+ ? `The exposure fired ${gap} after the replay ends. Jumps to the last frame.`+ : `Jump to the first exposure in this session. ${EXPOSURE_CAVEAT}`return (- <Tooltip title={outOfWindow ? OUT_OF_WINDOW_TOOLTIP : `First exposure in this session. ${EXPOSURE_CAVEAT}`}>- <span className="text-secondary text-xs tabular-nums shrink-0 min-w-10 text-right">{label}</span>+ <Tooltip title={tooltip}>+ <Link+ className="text-xs tabular-nums shrink-0 min-w-10 text-right"+ onClick={onSeek}+ data-attr="replay-experiment-context-jump-to-first-exposure"+ >+ {label}+ </Link></Tooltip>)}@@ -276,15 +308,13 @@ function NotExposedInSessionLabel({ children, className }: { children: string; cfunction ExperimentContextRow({item,- onSeek,- outOfWindow,- timeInRecording,+ exposure,leading,}: {item: ExperimentSessionContextItemApi- onSeek?: () => void- outOfWindow?: boolean- timeInRecording?: number | null+ // The exposure timestamp column: its signed offset and the jump to the closest captured frame.+ // Absent for a row with no exposure (enrolled-only), or before the recording window resolves.+ exposure?: ExposureTimeProps | null// Leading slot rendered before the timestamp — the metric-events expand toggle, or a same-width// spacer so the timestamp and name columns line up across rows.leading?: JSX.Element | null@@ -295,9 +325,7 @@ function ExperimentContextRow({return (<div className="flex flex-row items-center gap-x-2 min-w-0">{leading}- {timeInRecording != null ? (- <ExposureTime timeInRecording={timeInRecording} onSeek={onSeek} outOfWindow={outOfWindow} />- ) : null}+ {exposure ? <ExposureTime {...exposure} /> : null}<div className="flex-1 min-w-0 truncate">{item.experiment_name}</div><VariantTag item={item} /><OpenExperimentButton item={item} />@@ -394,24 +422,26 @@ export function PlayerSidebarExperimentsSection(): JSX.Element | null {// experiment reuses the exact same treatment as the list rows below it.const renderSeenRow = (item: ExperimentSessionContextItemApi): JSX.Element => {const exposedAtMs = item.first_exposure_timestamp ? dayjs(item.first_exposure_timestamp).valueOf() : null- const canSeek = isWithinRecording(exposedAtMs)- // Distinguish "seen but outside the window" (worth a tooltip) from "bounds not known yet"- // (transient, no tooltip) so we never explain a non-jump we can't actually vouch for.- const outOfWindow =- exposedAtMs != null &&- recordingStartMs != null &&- recordingEndMs != null &&- (exposedAtMs < recordingStartMs || exposedAtMs > recordingEndMs)+ // The exposure needs the resolved recording start to place it and to jump. Without it there+ // is no offset to show and nowhere to seek, so the row renders without a timestamp column.+ const seek =+ exposedAtMs != null && recordingStartMs != null+ ? computeExposureSeek(exposedAtMs, recordingStartMs, recordingEndMs)+ : nullconst hasMetrics = item.metrics_in_session.length > 0const isExpanded = expandedExperimentIds.includes(item.experiment_id)return (<div key={item.experiment_id} className="flex flex-col gap-y-0.5 min-w-0"><ExperimentContextRowitem={item}- onSeek={canSeek && exposedAtMs != null ? () => seekToTimestamp(exposedAtMs) : undefined}- outOfWindow={outOfWindow}- timeInRecording={- exposedAtMs != null && recordingStartMs != null ? exposedAtMs - recordingStartMs : null+ exposure={+ seek+ ? {+ offsetMs: seek.offsetMs,+ placement: seek.placement,+ onSeek: () => seekToTimestamp(seek.seekTargetMs),+ }+ : null}leading={// -me-1.5 pulls the timestamp back toward the toggle so the icon and time read