: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(ingestion): key survey usage records by submission so partials bill once (#100136)
Ben White5d91895cf22f
diff --git a/nodejs/src/ingestion/common/steps/usage-records-steps.test.ts b/nodejs/src/ingestion/common/steps/usage-records-steps.test.tsindex 04afe9234e67..dce355b659a4 100644--- a/nodejs/src/ingestion/common/steps/usage-records-steps.test.ts+++ b/nodejs/src/ingestion/common/steps/usage-records-steps.test.ts@@ -3,7 +3,9 @@ import { DateTime } from 'luxon'import { UsageIngestionClient, UsageRecordInput } from '~/common/usage-ingestion/client'import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { IngestedEventInfo } from '~/ingestion/common/steps/event-processing/emit-event-step'+import { resolveAnalyticsUsageKey } from '~/ingestion/common/usage-records/billable-events'import { isOkResult } from '~/ingestion/framework/results'+import { Properties } from '~/plugin-scaffold'import { Person } from '~/types'import { createRecordEventUsageAfterIngestStep, createRecordEventUsageStep } from './usage-records-steps'@@ -41,11 +43,11 @@ describe('usage-records-steps', () => {async function queueEventUsage(ingested: Promise<IngestedEventInfo | null>[],- event: Partial<{ event: string; eventUuid: string; distinctId: string }> = {},+ event: Partial<{ event: string; eventUuid: string; distinctId: string; properties: Properties }> = {},personProcessing: { processPerson?: boolean; person?: Person } = {},headers: { now?: Date } = {}): Promise<void> {- const prepare = createRecordEventUsageStep(() => 'events')+ const prepare = createRecordEventUsageStep(resolveAnalyticsUsageKey)const prepared = await prepare({preparedEvent: {teamId: 42,@@ -53,6 +55,7 @@ describe('usage-records-steps', () => {eventUuid: 'event-uuid',distinctId: 'user-7',timestamp: '2026-06-15T23:55:00.000Z',+ properties: {},...event,},headers,@@ -110,6 +113,26 @@ describe('usage-records-steps', () => {expect(new Set(ingestedUsage.map((record) => record.recordId)).size).toBe(2)})+ it.each([+ ['share a submission ID', { $survey_id: 'survey-1', $survey_submission_id: 'submission-1' }, 1],+ ['have no submission ID', { $survey_id: 'survey-1' }, 2],+ ])('bills partial and completed survey sent events once when they %s', async (_name, properties, expected) => {+ const acknowledged = (): Promise<IngestedEventInfo> => Promise.resolve({ topic: 'events', partition: 0 })+ const step = (eventUuid: string, completed: boolean): Promise<void> =>+ queueEventUsage([acknowledged()], {+ event: 'survey sent',+ eventUuid,+ properties: { ...properties, $survey_completed: completed },+ })+ await step('partial-uuid', false)+ await step('completed-uuid', true)++ await eventUsageBatch.flush()++ expect(ingestedUsage.every((record) => record.usageKey === 'survey_responses')).toBe(true)+ expect(new Set(ingestedUsage.map((record) => record.recordId)).size).toBe(expected)+ })+it('bills two events apart when only the position of a newline differs', async () => {const acknowledged = (): Promise<IngestedEventInfo> => Promise.resolve({ topic: 'events', partition: 0 })await queueEventUsage([acknowledged()], { event: 'a\nb', distinctId: 'c' })diff --git a/nodejs/src/ingestion/common/steps/usage-records-steps.ts b/nodejs/src/ingestion/common/steps/usage-records-steps.tsindex 242c98e3f600..aa5afb3f205c 100644--- a/nodejs/src/ingestion/common/steps/usage-records-steps.ts+++ b/nodejs/src/ingestion/common/steps/usage-records-steps.ts@@ -3,10 +3,15 @@ import { createHash } from 'node:crypto'import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { resolvePersonMode } from '~/ingestion/common/steps/event-processing/create-event'import { IngestedEventInfo } from '~/ingestion/common/steps/event-processing/emit-event-step'-import { EVENTS_USAGE_KEY, UsageKeyResolver } from '~/ingestion/common/usage-records/billable-events'+import {+ EVENTS_USAGE_KEY,+ SURVEY_RESPONSES_USAGE_KEY,+ UsageKeyResolver,+} from '~/ingestion/common/usage-records/billable-events'import { BeforeBatchStep } from '~/ingestion/framework/batching-pipeline'import { PipelineResult, ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'+import { Properties } from '~/plugin-scaffold'import { EventHeaders, Person } from '~/types'export interface EventUsageBatchContext {@@ -27,32 +32,58 @@ export function createEventUsageBeforeBatchStep<TInput, CInput, CBatch>(}export interface RecordEventUsageInput {- preparedEvent: { teamId: number; event: string; eventUuid: string; distinctId: string; timestamp: string }+ preparedEvent: {+ teamId: number+ event: string+ eventUuid: string+ distinctId: string+ timestamp: string+ properties: Properties+ }headers: Pick<EventHeaders, 'now'>eventUsageBatch: UsageRecordBatchprocessPerson?: booleanperson?: Person}+/**+ * Hashed rather than joined: event names and distinct IDs are client-supplied and together+ * exceed the 512-byte identifier the service accepts, and one oversized record makes the+ * service reject the whole request. The timestamp is UTC-normalized upstream, so its first+ * ten characters are the day `toDate` resolves in the billing table's sorting key.+ */+function hashedRecordId(timestamp: string, identity: string[]): string {+ const day = timestamp.slice(0, 10)+ // JSON rather than a separator, so `a\nb` + `c` and `a` + `b\nc` hash differently.+ return `${day}:${createHash('sha256').update(JSON.stringify(identity)).digest('hex').slice(0, 32)}`+}+/*** Mirrors the events table's dedup identity, `(team_id, toDate(timestamp), event,* distinct_id, uuid)`, minus the team the billing sorting key already carries. The UUID alone* is not that identity: two events sharing one but differing in day, name or distinct_id are* separate rows there, and the nightly report counts them separately, so billing must too.- *- * Hashed rather than joined, because event names and distinct IDs are client-supplied and- * together exceed the 512-byte identifier the service accepts. One oversized record makes the- * service reject the whole request, which would drop every record batched with it.- *- * The timestamp is UTC-normalized upstream, so its first ten characters are the same day- * `toDate` resolves.*/function analyticsRecordId(preparedEvent: RecordEventUsageInput['preparedEvent']): string {- const day = preparedEvent.timestamp.slice(0, 10)- // JSON rather than a separator: an event name and a distinct ID can both contain any- // character, so `a\nb` with `c` and `a` with `b\nc` would hash the same and bill once.- const identity = JSON.stringify([preparedEvent.event, preparedEvent.distinctId, preparedEvent.eventUuid])- return `${day}:${createHash('sha256').update(identity).digest('hex').slice(0, 32)}`+ return hashedRecordId(preparedEvent.timestamp, [+ preparedEvent.event,+ preparedEvent.distinctId,+ preparedEvent.eventUuid,+ ])+}++/**+ * Each answered step of a multi-question survey emits its own `survey sent` event. The nightly+ * report bills one row per `($survey_id, $survey_submission_id)`, so sharing that identity lets+ * the billing table's ReplacingMergeTree collapse the steps the same way.+ */+function surveyResponseRecordId(preparedEvent: RecordEventUsageInput['preparedEvent']): string {+ const surveyId = preparedEvent.properties.$survey_id+ const submissionId = preparedEvent.properties.$survey_submission_id+ if (typeof submissionId !== 'string' || submissionId === '') {+ return analyticsRecordId(preparedEvent)+ }+ return hashedRecordId(preparedEvent.timestamp, [typeof surveyId === 'string' ? surveyId : '', submissionId])}export interface EventUsageRecord {@@ -97,7 +128,10 @@ export function createRecordEventUsageStep<T extends RecordEventUsageInput>(return Promise.resolve(ok({ ...input, eventUsageRecords: undefined }))}const { teamId } = input.preparedEvent- const recordId = analyticsRecordId(input.preparedEvent)+ const recordId =+ usageKey === SURVEY_RESPONSES_USAGE_KEY+ ? surveyResponseRecordId(input.preparedEvent)+ : analyticsRecordId(input.preparedEvent)const captureTimestampMs = input.headers.now?.getTime()const timestampMs = Number.isFinite(captureTimestampMs) ? captureTimestampMs : undefinedconst eventUsageRecords: EventUsageRecord[] = [{ teamId, usageKey, recordId, timestampMs }]