From f1587d0db31bad3797e3a64622c3dd63378b3106 Mon Sep 17 00:00:00 2001 From: Joseph Jin Date: Tue, 1 Dec 2026 15:42:30 -0700 Subject: [PATCH] fix(session-replay-browser): don't record or upload under an expired Analytics session After a long break, the Analytics SDK restores the old session id and only starts a new session when its next event fires. Session Replay recorded under that expired session in the gap. Its min duration clock had started long ago, so the gate passed at once and a near-empty replay was uploaded (0s replays). The plugin now passes the Analytics session timeout and a live lastEventTime getter to Session Replay (analyticsSessionExpiry). With it: - On init, SR does not start recording under an expired session. It starts when setSessionId brings the new session. - If the session expires while recording (same tab, no reload), the min duration clock restarts once, so the leftover is dropped when Analytics starts a new session. Recording continues, so content is kept if no Analytics event comes. Standalone SDK users and plugin users with customSessionId are unchanged. SRC-501 Co-Authored-By: Claude Opus 5.5 --- .../src/session-replay.ts | 8 + .../test/session-replay.test.ts | 22 +++ .../src/config/local-config.ts | 3 + .../src/config/types.ts | 14 ++ .../src/session-replay.ts | 52 ++++- .../test/session-replay.test.ts | 177 ++++++++++++++++++ 6 files changed, 273 insertions(+), 3 deletions(-) diff --git a/packages/plugin-session-replay-browser/src/session-replay.ts b/packages/plugin-session-replay-browser/src/session-replay.ts index 85e78afaa..b1aa0dd1a 100644 --- a/packages/plugin-session-replay-browser/src/session-replay.ts +++ b/packages/plugin-session-replay-browser/src/session-replay.ts @@ -131,6 +131,14 @@ export class SessionReplayPlugin implements EnrichmentPlugin this.config?.lastEventTime, + }, }; await this.sessionReplay.init(config.apiKey, this.srInitOptions).promise; diff --git a/packages/plugin-session-replay-browser/test/session-replay.test.ts b/packages/plugin-session-replay-browser/test/session-replay.test.ts index bf525ccb5..079add056 100644 --- a/packages/plugin-session-replay-browser/test/session-replay.test.ts +++ b/packages/plugin-session-replay-browser/test/session-replay.test.ts @@ -133,6 +133,28 @@ describe('SessionReplayPlugin', () => { expect(init).toHaveBeenCalledWith('static_key', expect.objectContaining({ deviceId: customDeviceId })); }); + test('passes the Analytics session timeout and live last event time to Session Replay', async () => { + const plugin = new SessionReplayPlugin(); + const config = { ...mockConfig, lastEventTime: 1000 } as BrowserConfig; + await plugin.setup(config, mockAmplitude); + const expiry = init.mock.calls[0][1].analyticsSessionExpiry; + expect(expiry?.sessionTimeout).toBe(30 * 60 * 1000); + expect(expiry?.getLastEventTime()).toBe(1000); + + // Reads the current value, not the one at setup. + config.lastEventTime = 2000; + expect(expiry?.getLastEventTime()).toBe(2000); + + await plugin.teardown(); + expect(expiry?.getLastEventTime()).toBeUndefined(); + }); + + test('does not pass session expiry when using custom session id', async () => { + const plugin = new SessionReplayPlugin({ customSessionId: () => 'custom' }); + await plugin.setup(mockConfig, mockAmplitude); + expect(init).toHaveBeenCalledWith('static_key', expect.objectContaining({ analyticsSessionExpiry: undefined })); + }); + test('forwards the local semantic createCapture callback without invoking it', async () => { const factory = jest.fn(() => { throw new Error('only the replay host invokes the factory'); diff --git a/packages/session-replay-browser/src/config/local-config.ts b/packages/session-replay-browser/src/config/local-config.ts index e8abac02f..313fcc285 100644 --- a/packages/session-replay-browser/src/config/local-config.ts +++ b/packages/session-replay-browser/src/config/local-config.ts @@ -22,6 +22,7 @@ import { SessionReplayVersion, SessionReplaySendEventsHandler, SessionReplayFetchConfigHandler, + AnalyticsSessionExpiry, } from './types'; import { SafeLoggerProvider } from '../logger'; import { validateUGCFilterRules } from '../helpers'; @@ -65,6 +66,7 @@ export class SessionReplayLocalConfig extends Config implements ISessionReplayLo maxSingleEventSizeBytes?: number; handleSendEvents?: SessionReplaySendEventsHandler; handleFetchConfig?: SessionReplayFetchConfigHandler; + analyticsSessionExpiry?: AnalyticsSessionExpiry; constructor(apiKey: string, options: SessionReplayOptions) { const defaultConfig = getDefaultConfig(); @@ -174,6 +176,7 @@ export class SessionReplayLocalConfig extends Config implements ISessionReplayLo this.handleFetchConfig = options.handleFetchConfig ?? (httpClient ? ({ url, ...requestOptions }) => httpClient.send(url, requestOptions) : undefined); + this.analyticsSessionExpiry = options.analyticsSessionExpiry; } } diff --git a/packages/session-replay-browser/src/config/types.ts b/packages/session-replay-browser/src/config/types.ts index fe08c5a18..a37f55e4c 100644 --- a/packages/session-replay-browser/src/config/types.ts +++ b/packages/session-replay-browser/src/config/types.ts @@ -419,6 +419,20 @@ export interface SessionReplayLocalConfig extends IConfig { * but for the config GET. The URL passed to the callback already respects `configServerUrl`. */ handleFetchConfig?: SessionReplayFetchConfigHandler; + /** + * @internal Set by `@amplitude/plugin-session-replay-browser`. Lets the SDK tell when the + * Analytics session it records under has expired, using the same rule as the Analytics SDK + * (`now - lastEventTime > sessionTimeout`). Standalone callers manage their own session ids + * and should leave this unset; without it, session expiry is never checked. + */ + analyticsSessionExpiry?: AnalyticsSessionExpiry; +} + +export interface AnalyticsSessionExpiry { + /** The Analytics SDK's session timeout in milliseconds. */ + sessionTimeout: number; + /** Returns the Analytics SDK's last event time, or undefined when it has none. */ + getLastEventTime: () => number | undefined; } export interface FlushIntervalConfig { diff --git a/packages/session-replay-browser/src/session-replay.ts b/packages/session-replay-browser/src/session-replay.ts index 9aa76494e..09abb8315 100644 --- a/packages/session-replay-browser/src/session-replay.ts +++ b/packages/session-replay-browser/src/session-replay.ts @@ -53,6 +53,7 @@ import { getReplayStartTime, pruneStaleReplayStartTimes, removeReplayStartTime, + setReplayStartTime, } from './replay-start-time-store'; import { evaluateTargetingAndStore } from './targeting/targeting-manager'; import { @@ -256,8 +257,8 @@ export class SessionReplay implements AmplitudeSessionReplay { * performance.now(), etc.) are one-line edits. */ private isBelowMinSessionDuration(): boolean { - const minSessionDurationMs = this.config?.minSessionDurationMs; - if (minSessionDurationMs === undefined) { + const config = this.config; + if (!config || config.minSessionDurationMs === undefined) { return false; } // No start time means this session hasn't started recording yet, so it has no replay @@ -265,7 +266,42 @@ export class SessionReplay implements AmplitudeSessionReplay { if (this.sessionStartTime === undefined) { return true; } - return Date.now() - this.sessionStartTime < minSessionDurationMs; + const startTime = this.restartMinDurationClockIfSessionExpired(config, this.sessionStartTime); + return Date.now() - startTime < config.minSessionDurationMs; + } + + /** + * Time at which the current Analytics session expired, or undefined if it hasn't expired + * or expiry can't be checked (standalone SDK, or no Analytics event yet in this session). + */ + private getAnalyticsSessionExpiredAt(config: SessionReplayJoinedConfig): number | undefined { + const expiry = config.analyticsSessionExpiry; + if (!expiry) return undefined; + const lastEventTime = expiry.getLastEventTime(); + if (lastEventTime === undefined) return undefined; + const expiredAt = lastEventTime + expiry.sessionTimeout; + return Date.now() > expiredAt ? expiredAt : undefined; + } + + /** + * The Analytics SDK only starts a new session when its next event fires, so after a long + * break SR can keep recording under the expired session for a while. That session's clock + * started long ago and would pass the gate at once, uploading a near-empty replay. Restart + * the clock once per expiry, so what's recorded after it has to reach the threshold again. + * Recording continues: if no Analytics event comes, the session passes again and the + * content is kept. Returns the start time to measure from. + */ + private restartMinDurationClockIfSessionExpired(config: SessionReplayJoinedConfig, startTime: number): number { + const expiredAt = this.getAnalyticsSessionExpiredAt(config); + if (expiredAt === undefined || startTime > expiredAt) return startTime; + const now = Date.now(); + this.sessionStartTime = now; + const sessionId = this.identifiers?.sessionId; + if (sessionId !== undefined) { + setReplayStartTime(config.apiKey, sessionId, now, this.loggerProvider); + } + this.loggerProvider.log(`Session ${String(sessionId)} expired, restarting the minimum duration clock.`); + return now; } /** @@ -950,6 +986,16 @@ export class SessionReplay implements AmplitudeSessionReplay { } this.eventsManager && shouldSendStoredEvents && void this.eventsManager.sendStoredEvents({ deviceId }); + // On page load the Analytics SDK restores the previous session id even when it has + // expired, and only starts a new one when its first event fires. Don't record under the + // expired id; recording starts when setSessionId() brings the new session. + if (this.config && this.getAnalyticsSessionExpiredAt(this.config) !== undefined) { + this.loggerProvider.log( + `Session ${this.identifiers.sessionId} has expired, waiting for a new session before recording.`, + ); + return Promise.resolve(); + } + return this.recordEvents(); } diff --git a/packages/session-replay-browser/test/session-replay.test.ts b/packages/session-replay-browser/test/session-replay.test.ts index 08dd1873c..7c5829397 100644 --- a/packages/session-replay-browser/test/session-replay.test.ts +++ b/packages/session-replay-browser/test/session-replay.test.ts @@ -3685,6 +3685,183 @@ describe('SessionReplay', () => { ); }); }); + describe('analytics session expiry', () => { + const SESSION_TIMEOUT = 30 * 60 * 1000; + const startTimeKey = `AMP_SR_START_${apiKey.substring(0, 10)}_123`; + let lastEventTime: number | undefined; + + const initWithExpiry = async () => { + await sessionReplay.init(apiKey, { + ...mockOptions, + analyticsSessionExpiry: { sessionTimeout: SESSION_TIMEOUT, getLastEventTime: () => lastEventTime }, + }).promise; + if (!sessionReplay.eventsManager || !sessionReplay.config) { + throw new Error('Did not call init'); + } + return { eventsManager: sessionReplay.eventsManager, config: sessionReplay.config }; + }; + + beforeEach(() => { + globalThis.localStorage.clear(); + lastEventTime = undefined; + }); + + describe('initialize', () => { + test('does not record when the session has expired', async () => { + await initWithExpiry(); + lastEventTime = Date.now() - SESSION_TIMEOUT - 1; + const recordEventsSpy = jest.spyOn(sessionReplay, 'recordEvents'); + await sessionReplay.initialize(); + expect(recordEventsSpy).not.toHaveBeenCalled(); + expect(mockLoggerProvider.log).toHaveBeenCalledWith( + 'Session 123 has expired, waiting for a new session before recording.', + ); + }); + + test('records when the last event is within the session timeout', async () => { + await initWithExpiry(); + lastEventTime = Date.now() - SESSION_TIMEOUT + 1000; + const recordEventsSpy = jest.spyOn(sessionReplay, 'recordEvents'); + await sessionReplay.initialize(); + expect(recordEventsSpy).toHaveBeenCalled(); + }); + + test('records when there is no last event time', async () => { + await initWithExpiry(); + lastEventTime = undefined; + const recordEventsSpy = jest.spyOn(sessionReplay, 'recordEvents'); + await sessionReplay.initialize(); + expect(recordEventsSpy).toHaveBeenCalled(); + }); + + test('records when config is missing', async () => { + await initWithExpiry(); + lastEventTime = Date.now() - SESSION_TIMEOUT - 1; + sessionReplay.config = undefined; + const recordEventsSpy = jest.spyOn(sessionReplay, 'recordEvents'); + await sessionReplay.initialize(); + expect(recordEventsSpy).toHaveBeenCalled(); + }); + + test('starts recording once setSessionId brings a new session', async () => { + await initWithExpiry(); + lastEventTime = Date.now() - SESSION_TIMEOUT - 1; + const recordEventsSpy = jest.spyOn(sessionReplay, 'recordEvents'); + await sessionReplay.initialize(); + expect(recordEventsSpy).not.toHaveBeenCalled(); + + // The Analytics SDK clears lastEventTime when it starts the new session. + lastEventTime = undefined; + await sessionReplay.setSessionId(456).promise; + expect(recordEventsSpy).toHaveBeenCalled(); + }); + }); + + describe('min duration clock', () => { + test('restarts the clock when the session has expired, so the batch is held', async () => { + const { eventsManager, config } = await initWithExpiry(); + const sendMock = jest.fn(); + eventsManager.sendCurrentSequenceEvents = sendMock; + config.minSessionDurationMs = 3000; + // Started hours ago: without the expiry check this would pass the gate at once. + sessionReplay.sessionStartTime = Date.now() - 5 * 60 * 60 * 1000; + lastEventTime = Date.now() - 4 * 60 * 60 * 1000; + + const before = Date.now(); + sessionReplay.sendEvents(); + + expect(sendMock).not.toHaveBeenCalled(); + expect(sessionReplay.sessionStartTime).toBeGreaterThanOrEqual(before); + expect(Number(globalThis.localStorage.getItem(startTimeKey))).toBe(sessionReplay.sessionStartTime); + expect(mockLoggerProvider.log).toHaveBeenCalledWith( + 'Session 123 expired, restarting the minimum duration clock.', + ); + }); + + test('restarts the clock in memory only when there is no current session id', async () => { + const { eventsManager, config } = await initWithExpiry(); + const sendMock = jest.fn(); + eventsManager.sendCurrentSequenceEvents = sendMock; + config.minSessionDurationMs = 3000; + sessionReplay.sessionStartTime = Date.now() - 5 * 60 * 60 * 1000; + lastEventTime = Date.now() - 4 * 60 * 60 * 1000; + sessionReplay.identifiers = undefined; + sessionReplay.getDeviceId = jest.fn().mockReturnValue('1a2b3c'); + const storedBefore = globalThis.localStorage.getItem(startTimeKey); + + const before = Date.now(); + sessionReplay.sendEvents(123); + + expect(sendMock).not.toHaveBeenCalled(); + expect(sessionReplay.sessionStartTime).toBeGreaterThanOrEqual(before); + expect(globalThis.localStorage.getItem(startTimeKey)).toBe(storedBefore); + }); + + test('restarts only once per expiry, then passes after the threshold', async () => { + const { eventsManager, config } = await initWithExpiry(); + const sendMock = jest.fn(); + eventsManager.sendCurrentSequenceEvents = sendMock; + config.minSessionDurationMs = 3000; + lastEventTime = Date.now() - 4 * 60 * 60 * 1000; + // Already restarted after the expiry point (e.g. user came back and only scrolls). + const restartedAt = Date.now() - 5000; + sessionReplay.sessionStartTime = restartedAt; + + sessionReplay.sendEvents(); + + expect(sessionReplay.sessionStartTime).toBe(restartedAt); + expect(sendMock).toHaveBeenCalledWith({ sessionId: 123, deviceId: '1a2b3c' }); + }); + + test('does not restart the clock while the session is active', async () => { + const { eventsManager, config } = await initWithExpiry(); + const sendMock = jest.fn(); + eventsManager.sendCurrentSequenceEvents = sendMock; + config.minSessionDurationMs = 3000; + const startedAt = Date.now() - 60 * 60 * 1000; + sessionReplay.sessionStartTime = startedAt; + lastEventTime = Date.now() - 60 * 1000; + + sessionReplay.sendEvents(); + + expect(sessionReplay.sessionStartTime).toBe(startedAt); + expect(sendMock).toHaveBeenCalled(); + }); + + test('does not restart the clock without analyticsSessionExpiry (standalone SDK)', async () => { + await sessionReplay.init(apiKey, mockOptions).promise; + if (!sessionReplay.eventsManager || !sessionReplay.config) { + throw new Error('Did not call init'); + } + const sendMock = jest.fn(); + sessionReplay.eventsManager.sendCurrentSequenceEvents = sendMock; + sessionReplay.config.minSessionDurationMs = 3000; + const startedAt = Date.now() - 5 * 60 * 60 * 1000; + sessionReplay.sessionStartTime = startedAt; + + sessionReplay.sendEvents(); + + expect(sessionReplay.sessionStartTime).toBe(startedAt); + expect(sendMock).toHaveBeenCalled(); + }); + + test('drops the leftover of an expired session when Analytics starts a new one', async () => { + const { eventsManager, config } = await initWithExpiry(); + const sendMock = jest.fn(); + eventsManager.sendCurrentSequenceEvents = sendMock; + config.minSessionDurationMs = 3000; + sessionReplay.sessionStartTime = Date.now() - 5 * 60 * 60 * 1000; + // The Analytics SDK notifies plugins of the new session before it clears lastEventTime. + lastEventTime = Date.now() - 4 * 60 * 60 * 1000; + + await sessionReplay.setSessionId(456).promise; + + expect(sendMock).not.toHaveBeenCalledWith(expect.objectContaining({ sessionId: 123 })); + // Verdict false → late batches for session 123 get 'drop' from getSendDecision. + expect((sessionReplay as any).pastSessionGateVerdicts.get('123')).toBe(false); + }); + }); + }); describe('stopRecordingEvents', () => { test('it should catch errors as warnings', async () => { await sessionReplay.init(apiKey, mockOptions).promise;