: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(usage-ingestion): preserve trusted capture timestamps (#94038)
Ben White948e20157b18
diff --git a/nodejs/src/common/usage-ingestion/usage-record-batch.ts b/nodejs/src/common/usage-ingestion/usage-record-batch.tsindex 01acdf1e7627..dc5d9a8b1889 100644--- a/nodejs/src/common/usage-ingestion/usage-record-batch.ts+++ b/nodejs/src/common/usage-ingestion/usage-record-batch.ts@@ -13,6 +13,7 @@ interface PendingRecord {recordId: stringquantity: numberunit?: string+ timestampMs?: number}/**@@ -43,13 +44,13 @@ export class UsageRecordBatch {return this.client !== null && this.config.isTeamEnabled(teamId)}- add(teamId: number, usageKey: string, recordId: string, quantity = 1, unit?: string): void {+ add(teamId: number, usageKey: string, recordId: string, quantity = 1, unit?: string, timestampMs?: number): void {if (quantity <= 0 || !this.accepts(teamId)) {return}const key = `${teamId}:${usageKey}:${recordId}`if (!this.records.has(key)) {- this.records.set(key, { teamId, usageKey, recordId, quantity, unit })+ this.records.set(key, { teamId, usageKey, recordId, quantity, unit, timestampMs })}}@@ -62,7 +63,8 @@ export class UsageRecordBatch {acknowledgements: Promise<unknown | null>[],teamId: number,usageKey: string,- recordId: string+ recordId: string,+ timestampMs?: number): void {// A record that would be dropped must not put the flush behind its Kafka writes.if (!this.accepts(teamId)) {@@ -72,7 +74,7 @@ export class UsageRecordBatch {Promise.all(acknowledgements).then((results) => {if (results.every((result) => result !== null)) {- this.add(teamId, usageKey, recordId)+ this.add(teamId, usageKey, recordId, 1, undefined, timestampMs)}})// Kafka errors are handled by the producer side effect. They must@@ -94,17 +96,15 @@ export class UsageRecordBatch {if (!this.client || this.records.size === 0) {return}- // Flush time, never anything off the event. toDate of this lands in the storage- // sorting key, so a customer-supplied value would let a customer decide whether- // their own records deduplicate.- const timestampMs = Date.now()+ // Aggregate producers have no per-record capture time, so retain their flush-time clock.+ const flushedAtMs = Date.now()const records: UsageRecordInput[] = [...this.records.values()].map((record) => ({recordId: record.recordId,teamId: record.teamId,usageKey: record.usageKey,unit: record.unit ?? this.config.unit,quantity: record.quantity,- timestampMs,+ timestampMs: record.timestampMs ?? flushedAtMs,}))this.records.clear()await this.client.ingest(records)diff --git a/nodejs/src/ingestion/common/steps/usage-records-steps.test.ts b/nodejs/src/ingestion/common/steps/usage-records-steps.test.tsindex 10e843c5d2f6..04afe9234e67 100644--- a/nodejs/src/ingestion/common/steps/usage-records-steps.test.ts+++ b/nodejs/src/ingestion/common/steps/usage-records-steps.test.ts@@ -42,7 +42,8 @@ describe('usage-records-steps', () => {async function queueEventUsage(ingested: Promise<IngestedEventInfo | null>[],event: Partial<{ event: string; eventUuid: string; distinctId: string }> = {},- personProcessing: { processPerson?: boolean; person?: Person } = {}+ personProcessing: { processPerson?: boolean; person?: Person } = {},+ headers: { now?: Date } = {}): Promise<void> {const prepare = createRecordEventUsageStep(() => 'events')const prepared = await prepare({@@ -54,6 +55,7 @@ describe('usage-records-steps', () => {timestamp: '2026-06-15T23:55:00.000Z',...event,},+ headers,eventUsageBatch,...personProcessing,})@@ -144,6 +146,22 @@ describe('usage-records-steps', () => {])})+ it('uses trusted capture time when an event flushes six hours later', async () => {+ const capturedAtMs = FLUSH_TIMESTAMP_MS+ jest.setSystemTime(capturedAtMs)+ await queueEventUsage(+ [Promise.resolve({ topic: 'events', partition: 0 })],+ {},+ {},+ { now: new Date(capturedAtMs) }+ )++ jest.advanceTimersByTime(6 * 60 * 60 * 1000)+ await eventUsageBatch.flush()++ expect(ingestedUsage[0]).toEqual(expect.objectContaining({ timestampMs: capturedAtMs }))+ })+// The meters have to match `person_mode` in the nightly report's two billable-event queries,// which count `full` and `force_upgrade` as enhanced and `propertyless` as not. A force upgrade// only happens when the client asked for propertyless, so it is the case that breaks if thediff --git a/nodejs/src/ingestion/common/steps/usage-records-steps.ts b/nodejs/src/ingestion/common/steps/usage-records-steps.tsindex 99ba4da57ffa..242c98e3f600 100644--- a/nodejs/src/ingestion/common/steps/usage-records-steps.ts+++ b/nodejs/src/ingestion/common/steps/usage-records-steps.ts@@ -7,7 +7,7 @@ import { EVENTS_USAGE_KEY, UsageKeyResolver } from '~/ingestion/common/usage-recimport { BeforeBatchStep } from '~/ingestion/framework/batching-pipeline'import { PipelineResult, ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'-import { Person } from '~/types'+import { EventHeaders, Person } from '~/types'export interface EventUsageBatchContext {eventUsageBatch: UsageRecordBatch@@ -28,6 +28,7 @@ export function createEventUsageBeforeBatchStep<TInput, CInput, CBatch>(export interface RecordEventUsageInput {preparedEvent: { teamId: number; event: string; eventUuid: string; distinctId: string; timestamp: string }+ headers: Pick<EventHeaders, 'now'>eventUsageBatch: UsageRecordBatchprocessPerson?: booleanperson?: Person@@ -58,6 +59,7 @@ export interface EventUsageRecord {teamId: numberusageKey: stringrecordId: string+ timestampMs?: number}export interface EventUsageRecordContext {@@ -96,7 +98,9 @@ export function createRecordEventUsageStep<T extends RecordEventUsageInput>(}const { teamId } = input.preparedEventconst recordId = analyticsRecordId(input.preparedEvent)- const eventUsageRecords: EventUsageRecord[] = [{ teamId, usageKey, recordId }]+ const captureTimestampMs = input.headers.now?.getTime()+ const timestampMs = Number.isFinite(captureTimestampMs) ? captureTimestampMs : undefined+ const eventUsageRecords: EventUsageRecord[] = [{ teamId, usageKey, recordId, timestampMs }]// Mirrors the report's enhanced-persons query: the plain billable count plus a `person_mode`// filter, so an event billed under its own key is outside both. Reading the mode stored on// the event rather than `processPerson` keeps force upgrades counted.@@ -104,7 +108,7 @@ export function createRecordEventUsageStep<T extends RecordEventUsageInput>(usageKey === EVENTS_USAGE_KEY &&resolvePersonMode(input.person, input.processPerson ?? false) !== 'propertyless') {- eventUsageRecords.push({ teamId, usageKey: 'enhanced_person_events', recordId })+ eventUsageRecords.push({ teamId, usageKey: 'enhanced_person_events', recordId, timestampMs })}return Promise.resolve(ok({ ...input, eventUsageRecords }))}@@ -127,7 +131,8 @@ export function createRecordEventUsageAfterIngestStep<T extends RecordEventUsageinput.ingested,record.teamId,record.usageKey,- record.recordId+ record.recordId,+ record.timestampMs)}}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/pipeline-types.ts b/nodejs/src/ingestion/pipelines/sessionreplay/pipeline-types.tsindex 0c38b5ed67f4..c9a6457eb79d 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/pipeline-types.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/pipeline-types.ts@@ -23,6 +23,7 @@ export interface SessionReplayHeaders {token: stringsession_id: stringdistinct_id: string+ now?: Date}/** Tags an element with whether its session is being seen for the first time in this batch. */diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-usage-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-usage-step.test.tsindex fb2bc9b86547..6a118ad19550 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-usage-step.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-usage-step.test.ts@@ -91,6 +91,17 @@ describe('createRecordSessionUsageStep', () => {expect(await record('web', 'posthog-js', false)).toEqual([])})+ it('uses trusted capture time from replay headers', async () => {+ const capturedAtMs = 1_700_000_000_000+ const value = buildValue('web', 'posthog-js', true)+ value.headers.now = new Date(capturedAtMs)++ await createRecordSessionUsageStep(usageBatch)(value)+ await usageBatch.flush()++ expect(ingested[0]).toEqual(expect.objectContaining({ timestampMs: capturedAtMs }))+ })+describe('trackUnbilledNewSessions', () => {async function unbilledCount(): Promise<number> {const metric = register.getSingleMetric('recording_blob_ingestion_v2_unbilled_new_session')!diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-usage-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-usage-step.tsindex ab32b27e740e..3b6e763170da 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-usage-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-usage-step.ts@@ -37,7 +37,15 @@ export function createRecordSessionUsageStep<T extends SessionUsageInput>(return function recordSessionUsage(value): Promise<PipelineResult<Recordable<T>>> {if (value.isNewSession) {const meter = billableMeter(value.parsedMessage.snapshot_source)- usageBatch?.add(value.team.teamId, meter, value.headers.session_id)+ const captureTimestampMs = value.headers.now?.getTime()+ usageBatch?.add(+ value.team.teamId,+ meter,+ value.headers.session_id,+ 1,+ undefined,+ Number.isFinite(captureTimestampMs) ? captureTimestampMs : undefined+ )}return Promise.resolve(ok(value))}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/validate-headers-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/validate-headers-step.test.tsindex 8e7ea0959157..a1b596700d21 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/validate-headers-step.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/validate-headers-step.test.ts@@ -7,11 +7,12 @@ import { createValidateSessionReplayHeadersStep } from './validate-headers-step'describe('createValidateSessionReplayHeadersStep', () => {const step = createValidateSessionReplayHeadersStep()- it('narrows headers to the guaranteed fields and drops the rest, preserving other input', async () => {+ it('narrows headers while preserving trusted capture time and other input', async () => {const step = createValidateSessionReplayHeadersStep<{ marker: string; headers: EventHeaders }>()+ const now = new Date('2026-09-03T10:00:00.000Z')const input = {marker: 'preserved',- headers: createTestEventHeaders({ token: 'tok', session_id: 'sess-1', distinct_id: 'user-1' }),+ headers: createTestEventHeaders({ token: 'tok', session_id: 'sess-1', distinct_id: 'user-1', now }),}const result = await step(input)@@ -19,8 +20,7 @@ describe('createValidateSessionReplayHeadersStep', () => {expect(isOkResult(result)).toBe(true)if (isOkResult(result)) {expect(result.value.marker).toBe('preserved')- // Only the guaranteed replay headers survive — the wide EventHeaders fields are dropped.- expect(result.value.headers).toEqual({ token: 'tok', session_id: 'sess-1', distinct_id: 'user-1' })+ expect(result.value.headers).toEqual({ token: 'tok', session_id: 'sess-1', distinct_id: 'user-1', now })}})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/validate-headers-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/validate-headers-step.tsindex 8772d3852cdc..582f41587f20 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/validate-headers-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/validate-headers-step.ts@@ -21,7 +21,7 @@ export function createValidateSessionReplayHeadersStep<T extends ValidateSessionReplayHeadersStepInput,>(): ProcessingStep<T, Omit<T, 'headers'> & { headers: SessionReplayHeaders }> {return async function validateReplayHeadersStep(input) {- const { token, session_id, distinct_id } = input.headers+ const { token, session_id, distinct_id, now } = input.headersif (!token) {return dlq('no_token_in_header')@@ -34,7 +34,7 @@ export function createValidateSessionReplayHeadersStep<}return Promise.resolve(- ok({ ...input, headers: { token, session_id: normalizeSessionId(session_id), distinct_id } })+ ok({ ...input, headers: { token, session_id: normalizeSessionId(session_id), distinct_id, now } }))}}diff --git a/posthog/models/usage_ingestion/billing_usage_records.py b/posthog/models/usage_ingestion/billing_usage_records.pyindex a1dc8310b5bd..bbca95c345f4 100644--- a/posthog/models/usage_ingestion/billing_usage_records.py+++ b/posthog/models/usage_ingestion/billing_usage_records.py@@ -27,9 +27,9 @@ def billing_usage_records_data_table_engine() -> ReplacingMergeTree:)-# Every producer stamps `timestamp` from its own clock when it flushes, never from anything a-# customer sends, which is what lets toDate(timestamp) sit in the sorting key. Sourcing it from-# event data would hand a customer control over whether their records deduplicate.+# Event-derived producers use trusted server capture time when available; aggregate producers use+# their emission clock. Never use customer-supplied timestamps, which would let a customer control+# whether their records deduplicate.BASE_BILLING_USAGE_RECORDS_COLUMNS = """schema_version UInt8,record_id String,diff --git a/proto/usage_ingestion/v1/service.proto b/proto/usage_ingestion/v1/service.protoindex 0fda20cecbf9..44dc43bf54f5 100644--- a/proto/usage_ingestion/v1/service.proto+++ b/proto/usage_ingestion/v1/service.proto@@ -21,7 +21,8 @@ message BillingUsageRecord {// so producers cannot supply one.int64 team_id = 1;- // Stamp this from the producer's own clock when it emits, never from a customer payload.+ // Stamp this from trusted server capture time when available; otherwise use the producer's+ // emission clock. Never use a customer payload.// It is part of the identity, so a value a customer controls would let them decide// whether their own records deduplicate.int64 timestamp_ms = 2;diff --git a/rust/batch-import-worker/src/parse/content/amplitude.rs b/rust/batch-import-worker/src/parse/content/amplitude.rsindex 9c6fe69c508c..94ceb5f5608f 100644--- a/rust/batch-import-worker/src/parse/content/amplitude.rs+++ b/rust/batch-import-worker/src/parse/content/amplitude.rs@@ -320,7 +320,7 @@ fn create_group_identify_event(session_id: None,ip: "".to_string(),data: serde_json::to_string(&raw_event)?,- now: timestamp.format("%Y-%m-%d %H:%M:%S%.3f").to_string(),+ now: Utc::now().to_rfc3339(),sent_at: None,token: context.token.clone(),event: "$groupidentify".to_string(),@@ -1907,9 +1907,8 @@ mod tests {assert_eq!(group_identify_data["event"], "$groupidentify");assert_eq!(group_identify_data["timestamp"], specific_timestamp);- // Verify the timestamp is not a "now" timestamp- let now = chrono::Utc::now();- assert_ne!(group_identify_data["timestamp"], now.to_rfc3339());+ // The event timestamp is customer-supplied; `now` is the trusted server capture time.+ assert_ne!(group_identify_event.inner.now, "2023-10-15 14:30:00.000");// Check original event also has the same timestamplet original_event = &result[1];diff --git a/rust/usage-ingestion/src/counters.rs b/rust/usage-ingestion/src/counters.rsindex dbd08621beae..bc7ac44fb496 100644--- a/rust/usage-ingestion/src/counters.rs+++ b/rust/usage-ingestion/src/counters.rs@@ -113,8 +113,6 @@ pub struct CounterAccumulator {impl CounterAccumulator {pub fn add_record(&self, record: &KafkaBillingUsageRecord) -> Result<(), CounterAddError> {- // TODO: Pass trusted capture time from event-derived producers into `usage_timestamp`.- // Batch-flush time rebuckets lagged records into wrong quota windows; customer event timestamps must not be used.self.add(record.team_id,record.organization_id,