: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): correct recording timestamps for device clock skew (#93203)
Hayne Ryue69d2012003c
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.tsindex 2550184a3ac1..0cccfd241edd 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts@@ -70,6 +70,12 @@ export class SessionRecordingIngesterMetrics {help: 'Replay messages whose clock offset could not be measured because capture recorded no usable sent_at/now pair. Counted separately so an absent measurement is not read as zero skew',})+ private static readonly clockSkewCorrection = new Histogram({+ name: 'recording_blob_ingestion_v2_clock_skew_correction_seconds',+ help: 'Absolute clock skew correction actually applied to rrweb timestamps, per message. Quantized, so it differs from the raw offset in message_clock_skew_seconds',+ buckets: [300, 900, 3600, 21600, 43200, 604800, Infinity],+ })+private static readonly unbilledNewSession = new Counter({name: 'recording_blob_ingestion_v2_unbilled_new_session',help: 'New sessions whose first message failed before the usage step, so a later message for the same session bills nothing while the report still counts the recording',@@ -105,6 +111,10 @@ export class SessionRecordingIngesterMetrics {this.messageClockSkew.labels(direction).observe(seconds)}+ public static observeClockSkewCorrection(skewMs: number): void {+ this.clockSkewCorrection.observe(Math.abs(skewMs) / 1000)+ }+public static resetSessionsRevoked(): void {this.sessionsRevoked.set(0)}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.test.tsindex 23ba15722345..aec77b8e039a 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.test.ts@@ -669,6 +669,100 @@ describe('createParseMessageStep', () => {})})+ describe('clock skew correction', () => {+ const SEVEN_HOURS_MS = 7 * 60 * 60 * 1000++ function skewedInput(options: {+ baseMs: number+ deviceOffsetMs?: number+ latencyMs?: number+ sentAt?: string | null+ now?: string | null+ }): ParseMessageStepInput {+ const { baseMs, deviceOffsetMs = 0, latencyMs = 0 } = options+ const now = options.now === undefined ? new Date(baseMs + latencyMs).toISOString() : options.now+ const sentAt =+ options.sentAt === undefined ? new Date(baseMs + deviceOffsetMs).toISOString() : options.sentAt+ const payload = createSnapshotPayload({+ sessionId: 'session-1',+ snapshotItems: [+ { type: 2, timestamp: baseMs + deviceOffsetMs },+ { type: 3, timestamp: baseMs + deviceOffsetMs + 1000 },+ ],+ distinctId: 'user-123',+ ...(now !== null && { now }),+ ...(sentAt !== null && { sentAt }),+ })+ return createInput(0, 1, payload)+ }++ async function startMsOf(input: ParseMessageStepInput): Promise<number> {+ const result = await createParseMessageStep()(input)+ expect(result.type).toBe(PipelineResultType.OK)+ if (result.type !== PipelineResultType.OK) {+ throw new Error('expected an ok result')+ }+ return result.value.parsedMessage.eventsRange.start.toMillis()+ }++ it.each([+ ['ahead', SEVEN_HOURS_MS],+ ['behind', -SEVEN_HOURS_MS],+ ])('shifts rrweb timestamps to server time when the device clock is %s', async (_name, deviceOffsetMs) => {+ const baseMs = Date.now()+ const step = createParseMessageStep()++ const result = await step(skewedInput({ baseMs, deviceOffsetMs }))++ expect(result.type).toBe(PipelineResultType.OK)+ if (result.type === PipelineResultType.OK) {+ const { parsedMessage } = result.value+ expect(parsedMessage.eventsRange.start.toMillis()).toBe(baseMs)+ expect(parsedMessage.eventsRange.end.toMillis()).toBe(baseMs + 1000)+ expect(parsedMessage.eventsByWindowId['window-1'].map((e) => e.timestamp)).toEqual([+ baseMs,+ baseMs + 1000,+ ])+ }+ })++ it('corrects two messages of one session identically despite different latencies', async () => {+ const baseMs = Date.now()++ const fast = await startMsOf(skewedInput({ baseMs, deviceOffsetMs: SEVEN_HOURS_MS, latencyMs: 50 }))+ const slow = await startMsOf(skewedInput({ baseMs, deviceOffsetMs: SEVEN_HOURS_MS, latencyMs: 2500 }))++ expect(fast).toBe(slow)+ })++ it('leaves a well-behaved clock untouched, so latency cannot reorder its events', async () => {+ const baseMs = Date.now()++ const startMs = await startMsOf(skewedInput({ baseMs, deviceOffsetMs: 400, latencyMs: 900 }))++ expect(startMs).toBe(baseMs + 400)+ })++ const validIso = '2023-01-01T00:00:00.000Z'+ it.each([+ ['sent_at is missing', { sentAt: null }],+ ['now is missing', { now: null }],+ ['sent_at is unparseable', { sentAt: 'not-a-date' }],+ ['now is unparseable', { now: 'not-a-date' }],+ ])(+ 'leaves timestamps unchanged when %s',+ async (_name, overrides: { now?: string | null; sentAt?: string | null }) => {+ const baseMs = Date.now()++ const startMs = await startMsOf(+ skewedInput({ baseMs, deviceOffsetMs: SEVEN_HOURS_MS, now: validIso, ...overrides })+ )++ expect(startMs).toBe(baseMs + SEVEN_HOURS_MS)+ }+ )+ })+describe('decompressMessageValue lz4 hardening', () => {const lz4 = require('lz4')diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.tsindex 2d9a6af9749c..31030dc3d708 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.ts@@ -20,6 +20,7 @@ import { SessionReplayHeaders } from './pipeline-types'const lz4: { decodeBlock(input: Buffer, output: Buffer): number } = require('lz4')const MESSAGE_TIMESTAMP_DIFF_THRESHOLD_DAYS = 7+const CLOCK_SKEW_QUANTUM_MS = 5 * 60 * 1000const GZIP_HEADER = Uint8Array.from([0x1f, 0x8b, 0x08, 0x00])// Compression-bomb cap (mirrors the Rust addon): ~6x the 10 MB largest payload in a production// sample; exceeding it DLQs instead of risking an unclassifiable OOM.@@ -79,7 +80,34 @@ export function decompressMessageValue(message: Message): Buffer {return messageUnzipped}-function getValidEvents(events: unknown[]): {+// null when capture recorded no usable pair, which must not read as zero skew.+function rawClockSkewMs(sentAt: string | undefined, now: string | undefined): number | null {+ if (!sentAt || !now) {+ return null+ }+ const sentAtMs = DateTime.fromISO(sentAt).toMillis()+ const nowMs = DateTime.fromISO(now).toMillis()+ if (!Number.isFinite(sentAtMs) || !Number.isFinite(nowMs)) {+ return null+ }+ return sentAtMs - nowMs+}++// The raw skew includes per-request network latency. Rounding to a coarse quantum gives every+// message of a session the same correction, so latency cannot reorder events the player sorts by+// timestamp, and a well-behaved clock rounds to zero.+function quantizedClockSkewMs(sentAt: string | undefined, now: string | undefined): number {+ const rawSkew = rawClockSkewMs(sentAt, now)+ if (rawSkew === null) {+ return 0+ }+ return Math.round(rawSkew / CLOCK_SKEW_QUANTUM_MS) * CLOCK_SKEW_QUANTUM_MS+}++function getValidEvents(+ events: unknown[],+ clockSkewMs: number+): {validEvents: SnapshotEvent[]startDateTime: DateTimeendDateTime: DateTime@@ -90,6 +118,8 @@ function getValidEvents(events: unknown[]): {if (!parseResult.success || parseResult.data.timestamp <= 0) {return null}+ // Corrected on the event object because the recorder serializes it into the blob.+ parseResult.data.timestamp -= clockSkewMsreturn {event: parseResult.data,dateTime: DateTime.fromMillis(parseResult.data.timestamp),@@ -127,17 +157,11 @@ function getValidEvents(events: unknown[]): {* when the client sends none, so those messages count as unmeasured rather than as zero.*/export function observeClockSkew(sentAt: string | undefined, now: string | undefined): void {- if (!sentAt || !now) {- SessionRecordingIngesterMetrics.incrementMessageClockSkewUnmeasured()- return- }- const sentAtMs = DateTime.fromISO(sentAt).toMillis()- const nowMs = DateTime.fromISO(now).toMillis()- if (!Number.isFinite(sentAtMs) || !Number.isFinite(nowMs)) {+ const skewMs = rawClockSkewMs(sentAt, now)+ if (skewMs === null) {SessionRecordingIngesterMetrics.incrementMessageClockSkewUnmeasured()return}- const skewMs = sentAtMs - nowMsconst direction = skewMs >= 0 ? 'device_ahead' : 'device_behind'SessionRecordingIngesterMetrics.observeMessageClockSkew(direction, Math.abs(skewMs) / 1000)}@@ -197,7 +221,11 @@ export function createParseMessageStep<T extends ParseMessageStepInput>(): Proceconst sessionId = normalizeSessionId($session_id)- const result = getValidEvents($snapshot_items)+ const clockSkewMs = quantizedClockSkewMs(messageResult.data.sent_at, messageResult.data.now)+ if (clockSkewMs !== 0) {+ SessionRecordingIngesterMetrics.observeClockSkewCorrection(clockSkewMs)+ }+ const result = getValidEvents($snapshot_items, clockSkewMs)if (!result) {return drop('message_contained_no_valid_rrweb_events',diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.tsindex 780d44c0ac46..a9503632559f 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts@@ -239,6 +239,40 @@ describe('session-replay-pipeline', () => {}}+ function createSkewedMessage(partition: number, offset: number, sessionId: string, skewMs: number): Message {+ const event = {+ event: '$snapshot_items',+ properties: {+ $session_id: sessionId,+ $window_id: 'window-1',+ $snapshot_items: [{ type: 2, timestamp: now.toMillis() + skewMs, data: {} }],+ },+ }+ const payload = JSON.stringify({+ distinct_id: 'user-123',+ data: JSON.stringify(event),+ now: now.toUTC().toISO(),+ sent_at: now.plus({ milliseconds: skewMs }).toUTC().toISO(),+ })++ return {+ partition,+ offset,+ topic: 'test-topic',+ value: Buffer.from(payload),+ key: Buffer.from('test-key'),+ timestamp: Date.now(),+ headers: [+ { token: Buffer.from('test-token') },+ { session_id: Buffer.from(sessionId) },+ {+ distinct_id: Buffer.from('user-123'),+ },+ ],+ size: payload.length,+ }+ }+function createMessageWithOldTimestamps(partition: number,offset: number,@@ -277,6 +311,34 @@ describe('session-replay-pipeline', () => {const recordedSessionIds = (): string[] =>(mockBatchRecorder.record as jest.Mock).mock.calls.map((call) => call[0].message.session_id)+ it('corrects recording timestamps for a skewed device clock', async () => {+ const skewMs = 7 * 60 * 60 * 1000+ const pipeline = createSessionReplayPipeline({+ outputs,+ eventIngestionRestrictionManager: mockRestrictionManager,+ overflowMode: 'redirect',+ promiseScheduler,+ teamService: mockTeamService,+ retentionService,+ sessionTracker,+ sessionFilter,+ keyStore,+ sessionKeyResolutionMaxConcurrency: 20,+ topHog,+ isDebugLoggingEnabled,+ })++ await runSessionReplayPipeline(+ pipeline,+ [createSkewedMessage(0, 1, 'session-1', skewMs)],+ mockBatchRecorder,+ promiseScheduler+ )++ const recorded = (mockBatchRecorder.record as jest.Mock).mock.calls[0][0].message+ expect(recorded.eventsRange.start.toMillis()).toBe(now.toMillis())+ })+it('passes through messages when no restrictions apply', async () => {const pipeline = createSessionReplayPipeline({outputs,