: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
feat(replay): surface clock skew between device and server time (#88053)
posthog[bot]87dc7b7b922d
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/kafka/types.ts b/nodejs/src/ingestion/pipelines/sessionreplay/kafka/types.tsindex 0edbf4995763..f29627faf458 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/kafka/types.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/kafka/types.ts@@ -8,6 +8,10 @@ const dateTimeSchema = z.custom<DateTime>((val) => val instanceof DateTime)export const RawEventMessageSchema = z.object({distinct_id: z.string(),data: z.string(),+ // Capture stamps both at the same instant; their difference is the sender's clock offset.+ // Optional: capture omits sent_at when the client sends none.+ sent_at: z.string().optional(),+ now: z.string().optional(),})export type RawEventMessage = z.infer<typeof RawEventMessageSchema>diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.tsindex 0fd23a2befad..2550184a3ac1 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts@@ -4,6 +4,9 @@ import { recordMessagesDroppedByRestrictions } from './otel-metrics'const BUCKETS_KB_WRITTEN = [0, 128, 512, 1024, 5120, 10240, 20480, 51200, 102400, 204800, Infinity]+/** Whether the sender device clock reads ahead of or behind the server-stamped message time. */+export type ClockSkewDirection = 'device_ahead' | 'device_behind'+export class SessionRecordingIngesterMetrics {private static readonly sessionsHandled = new Gauge({name: 'recording_blob_ingestion_v2_session_manager_count',@@ -55,6 +58,18 @@ export class SessionRecordingIngesterMetrics {labelNames: ['content_encoding'],})+ private static readonly messageClockSkew = new Histogram({+ name: 'recording_blob_ingestion_v2_message_clock_skew_seconds',+ help: 'Absolute offset between the sender device clock at upload (sent_at) and the server clock at receipt (now), by direction. Replay skips the skew correction every other event gets, so a large offset means the recording start_time — the default playlist sort — disagrees with the corrected event time.',+ labelNames: ['direction'],+ buckets: [1, 5, 30, 60, 300, 900, 1800, 3600, 7200, 21600, 43200, 86400],+ })++ private static readonly messageClockSkewUnmeasured = new Counter({+ name: 'recording_blob_ingestion_v2_message_clock_skew_unmeasured',+ 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 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',@@ -82,6 +97,14 @@ export class SessionRecordingIngesterMetrics {this.messagesByEncoding.labels(encoding).inc()}+ public static incrementMessageClockSkewUnmeasured(): void {+ this.messageClockSkewUnmeasured.inc()+ }++ public static observeMessageClockSkew(direction: ClockSkewDirection, seconds: number): void {+ this.messageClockSkew.labels(direction).observe(seconds)+ }+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 e1540b128881..23ba15722345 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.test.ts@@ -4,7 +4,13 @@ import { gzip } from 'zlib'import { PipelineResultType } from '~/ingestion/framework/results'-import { ParseMessageStepInput, createParseMessageStep, decompressMessageValue } from './parse-message-step'+import { SessionRecordingIngesterMetrics } from './metrics'+import {+ ParseMessageStepInput,+ createParseMessageStep,+ decompressMessageValue,+ observeClockSkew,+} from './parse-message-step'import { SessionReplayHeaders } from './pipeline-types'const compressWithGzip = promisify(gzip)@@ -25,6 +31,8 @@ describe('createParseMessageStep', () => {snapshotSource?: stringlib?: stringdistinctId?: string+ sentAt?: string+ now?: string}): string {const event = {event: '$snapshot_items',@@ -42,6 +50,12 @@ describe('createParseMessageStep', () => {if (options.distinctId !== undefined) {rawMessage.distinct_id = options.distinctId}+ if (options.sentAt !== undefined) {+ rawMessage.sent_at = options.sentAt+ }+ if (options.now !== undefined) {+ rawMessage.now = options.now+ }return JSON.stringify(rawMessage)}@@ -594,6 +608,67 @@ describe('createParseMessageStep', () => {}})+ describe('clock skew', () => {+ const HOUR_MS = 60 * 60 * 1000+ const serverNow = '2023-01-01T00:00:00.000Z'+ let observeSpy: jest.SpyInstance+ let unmeasuredSpy: jest.SpyInstance++ beforeEach(() => {+ observeSpy = jest.spyOn(SessionRecordingIngesterMetrics, 'observeMessageClockSkew').mockImplementation()+ unmeasuredSpy = jest+ .spyOn(SessionRecordingIngesterMetrics, 'incrementMessageClockSkewUnmeasured')+ .mockImplementation()+ })++ afterEach(() => {+ jest.restoreAllMocks()+ })++ it.each([+ ['reads 1h ahead of the server', '2023-01-01T01:00:00.000Z', 'device_ahead', 3600],+ ['reads 1h behind the server', '2022-12-31T23:00:00.000Z', 'device_behind', 3600],+ ['agrees with the server', serverNow, 'device_ahead', 0],+ ])('records the offset when the device clock %s', (_desc, sentAt, direction, seconds) => {+ observeClockSkew(sentAt, serverNow)++ expect(observeSpy).toHaveBeenCalledWith(direction, seconds)+ expect(unmeasuredSpy).not.toHaveBeenCalled()+ })++ it.each([+ ['capture recorded no sent_at', undefined, serverNow],+ ['sent_at is unparseable', 'not-a-date', serverNow],+ ['capture recorded no now', '2023-01-01T01:00:00.000Z', undefined],+ ])('counts the message as unmeasured when %s', (_desc, sentAt, now) => {+ observeClockSkew(sentAt, now)++ expect(observeSpy).not.toHaveBeenCalled()+ expect(unmeasuredSpy).toHaveBeenCalledTimes(1)+ })++ it('reports no offset for a buffered upload from a correctly clocked device', async () => {+ const step = createParseMessageStep()+ const now = Date.now()+ const uploadedAt = new Date(now).toISOString()+ const payload = createSnapshotPayload({+ sessionId: 'session-1',+ // Buffering, not a wrong clock: the Kafka message time would read this as an hour of skew.+ snapshotItems: [{ type: 2, timestamp: now - HOUR_MS }],+ distinctId: 'user-123',+ sentAt: uploadedAt,+ now: uploadedAt,+ })+ const input = createInput(0, 1, payload, undefined, { timestamp: now })++ const result = await step(input)++ expect(result.type).toBe(PipelineResultType.OK)+ expect(result.warnings).toHaveLength(0)+ expect(observeSpy).toHaveBeenCalledWith('device_ahead', 0)+ })+ })+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 b5971ac254da..2d9a6af9749c 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.ts@@ -120,6 +120,28 @@ function getValidEvents(events: unknown[]): {}}+/**+ * Record the sender's clock offset: the device clock at upload (`sent_at`) against the server clock+ * at receipt (`now`). Capture stamps both at the same instant, so buffering shifts them equally and+ * cancels; the Kafka message time against rrweb event times does not cancel. Capture omits `sent_at`+ * 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)) {+ SessionRecordingIngesterMetrics.incrementMessageClockSkewUnmeasured()+ return+ }+ const skewMs = sentAtMs - nowMs+ const direction = skewMs >= 0 ? 'device_ahead' : 'device_behind'+ SessionRecordingIngesterMetrics.observeMessageClockSkew(direction, Math.abs(skewMs) / 1000)+}+/*** Creates a step that parses raw Kafka messages into ParsedMessageData.* This step is additive - it preserves all input properties and adds parsedMessage.@@ -137,7 +159,6 @@ export function createParseMessageStep<T extends ParseMessageStepInput>(): Proceif (!message.value || !message.timestamp) {return dlq('message_value_or_timestamp_is_empty')}-let messageUnzipped: Buffertry {messageUnzipped = decompressMessageValue(message)@@ -221,6 +242,8 @@ export function createParseMessageStep<T extends ParseMessageStepInput>(): Procereturn dlq('distinct_id_header_body_mismatch')}+ observeClockSkew(messageResult.data.sent_at, messageResult.data.now)+const parsedMessage: ParsedMessageData = {metadata: {partition: message.partition,