: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(ingestion): add team-gated always-v1 merge versioning (#75879)
José Sequeiraa132ef82d7e8
diff --git a/nodejs/src/ingestion/common/persons/person-context.ts b/nodejs/src/ingestion/common/persons/person-context.tsindex 5c88407b531b..2c6df8b39150 100644--- a/nodejs/src/ingestion/common/persons/person-context.ts+++ b/nodejs/src/ingestion/common/persons/person-context.ts@@ -64,6 +64,11 @@ export class PersonContext {partitionCount: 64,isTeamEnabled: () => false,},+ /**+ * Always-v1 rollout of the personless-table removal: when true, merge-added distinct id+ * mappings get version 1 unconditionally instead of consulting posthog_personlessdistinctid.+ */+ public readonly mergeAlwaysV1: boolean = false,/** Fold plan shared by this event's consecutive $identify run; see person-merge-fold.ts. */public readonly mergeFoldPlan?: MergeFoldPlan) {diff --git a/nodejs/src/ingestion/common/persons/person-merge-service.ts b/nodejs/src/ingestion/common/persons/person-merge-service.tsindex 223d865851c5..7ab2834294d0 100644--- a/nodejs/src/ingestion/common/persons/person-merge-service.ts+++ b/nodejs/src/ingestion/common/persons/person-merge-service.ts@@ -247,6 +247,11 @@ export class PersonMergeService {// the Distinct ID has been merged. This is important so that an event being processed// concurrently for that Distinct ID doesn't emit an event and _miss_ that a different// Person UUID needs to be used now. (See the `processPerson` code in `update` for more.)+ //+ // When `mergeAlwaysV1` is on for the team, check 1 is skipped: every merge-added mapping+ // gets version 1 regardless of personless history. Version 1 is safe in both cases — the+ // override either re-points real personless events or is a harmless transient row the+ // squash job deletes. The upsert (check 2) still runs for the `is_merged` race hint.if ((otherPerson && !mergeIntoPerson) || (!otherPerson && mergeIntoPerson)) {// Only one of the two Distinct IDs points at an existing Person@@ -266,7 +271,7 @@ export class PersonMergeService {this.context.team.id,distinctIdToAdd)- const distinctIdVersion = insertedDistinctId ? 0 : 1+ const distinctIdVersion = this.context.mergeAlwaysV1 || !insertedDistinctId ? 1 : 0this.recordOverrideCount('oneExists', distinctIdVersion > 0)const kafkaMessages = await tx.addDistinctId(existingPerson, distinctIdToAdd, distinctIdVersion)@@ -312,7 +317,11 @@ export class PersonMergeService {// need to actually write an override. (But mostly we're being verbose for// documentation purposes)let distinctId2Version = 0- if (insertedDistinctId1 && insertedDistinctId2) {+ if (this.context.mergeAlwaysV1) {+ // The upsert results are not consulted: the second Distinct ID always gets an+ // override, and no swap is needed since the first one derives the Person UUID.+ distinctId2Version = 1+ } else if (insertedDistinctId1 && insertedDistinctId2) {// We were the first to insert both (neither was used for Personless), so we// can use either as the primary Person UUID and create no overrides.} else if (insertedDistinctId1 && !insertedDistinctId2) {@@ -606,7 +615,7 @@ export class PersonMergeService {for (const pair of missingPairs) {// See mergeDistinctIds for the personless distinctIdVersion logic.const inserted = await tx.addPersonlessDistinctIdForMerge(teamId, pair.anonDistinctId)- const distinctIdVersion = inserted ? 0 : 1+ const distinctIdVersion = this.context.mergeAlwaysV1 || !inserted ? 1 : 0this.recordOverrideCount('fold', distinctIdVersion > 0)addMessages.push(...(await tx.addDistinctId(person, pair.anonDistinctId, distinctIdVersion)))}diff --git a/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.ts b/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.tsindex fcfb86350a57..e11b7bdc2c42 100644--- a/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.ts@@ -8,6 +8,8 @@ export interface EventPipelineRunnerOptions {PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: stringPERSON_MERGE_FOLD_ENABLED: booleanPERSON_MERGE_FOLD_TEAM_ALLOWLIST: string+ /** Teams whose merge-added distinct id mappings always get version 1: '*' for all, '' to disable, or comma-separated team IDs */+ PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: stringPERSON_JSONB_SIZE_ESTIMATE_ENABLE: numberPERSON_PROPERTIES_UPDATE_ALL: boolean/** Teams whose $feature_flag_called events default to personless: '*' for all, '' to disable, or comma-separated team IDs */diff --git a/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts b/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.tsindex 188d2209a6b4..992aebe59818 100644--- a/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts@@ -45,6 +45,7 @@ export function createProcessPersonsStep<TInput extends ProcessPersonsInput>(partitionCount: options.PERSON_MERGE_EVENTS_PARTITION_COUNT,isTeamEnabled: buildIntegerMatcher(options.PERSON_MERGE_EVENTS_TEAM_ALLOWLIST, true),}+ const isMergeAlwaysV1Team = buildIntegerMatcher(options.PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST, true)return async function processPersonsStep(input: TInput@@ -70,6 +71,7 @@ export function createProcessPersonsStep<TInput extends ProcessPersonsInput>(options.PERSON_PROPERTIES_UPDATE_ALL,shouldUpdateLastSeenAt,mergeEventsConfig,+ isMergeAlwaysV1Team(team.id),input.mergeFold.type === 'planned' ? input.mergeFold.plan : undefined)diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.tsindex c9046f1c896b..c5a857d10a47 100644--- a/nodejs/src/ingestion/config.ts+++ b/nodejs/src/ingestion/config.ts@@ -168,6 +168,11 @@ export type IngestionConsumerConfig = {PERSON_MERGE_FOLD_ENABLED: boolean// Teams eligible for merge folding: comma-separated team IDs, or '*' for all teams.PERSON_MERGE_FOLD_TEAM_ALLOWLIST: string+ // Always-v1 rollout of the personless-table removal RFC: for these teams, merge-added distinct+ // id mappings get version 1 unconditionally (always writing a ClickHouse override) instead of+ // consulting posthog_personlessdistinctid for the version-0 optimization. Comma-separated team+ // IDs, or '*' for all teams; empty means no teams.+ PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: string// Group batch writing configGROUP_BATCH_WRITING_USE_BATCH_UPDATES: boolean@@ -310,6 +315,7 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: '2',PERSON_MERGE_FOLD_ENABLED: false,PERSON_MERGE_FOLD_TEAM_ALLOWLIST: '*',+ PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: '',// Group batch writing configGROUP_BATCH_WRITING_USE_BATCH_UPDATES: true,diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.tsindex 5c87f2ed270a..4e37231087e0 100644--- a/nodejs/src/ingestion/ingestion-consumer.ts+++ b/nodejs/src/ingestion/ingestion-consumer.ts@@ -291,6 +291,7 @@ export class IngestionConsumer {PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: this.config.PERSON_MERGE_EVENTS_TEAM_ALLOWLIST,PERSON_MERGE_FOLD_ENABLED: this.config.PERSON_MERGE_FOLD_ENABLED,PERSON_MERGE_FOLD_TEAM_ALLOWLIST: this.config.PERSON_MERGE_FOLD_TEAM_ALLOWLIST,+ PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: this.config.PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST,PERSON_JSONB_SIZE_ESTIMATE_ENABLE: this.config.PERSON_JSONB_SIZE_ESTIMATE_ENABLE,PERSON_PROPERTIES_UPDATE_ALL: this.config.PERSON_PROPERTIES_UPDATE_ALL,FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: this.config.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex 18d17dfe8602..e7a5dcc1b9fe 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -397,6 +397,7 @@ export class IngestionApiServer implements NodeServer {PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: this.config.PERSON_MERGE_EVENTS_TEAM_ALLOWLIST,PERSON_MERGE_FOLD_ENABLED: this.config.PERSON_MERGE_FOLD_ENABLED,PERSON_MERGE_FOLD_TEAM_ALLOWLIST: this.config.PERSON_MERGE_FOLD_TEAM_ALLOWLIST,+ PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: this.config.PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST,PERSON_JSONB_SIZE_ESTIMATE_ENABLE: this.config.PERSON_JSONB_SIZE_ESTIMATE_ENABLE,PERSON_PROPERTIES_UPDATE_ALL: this.config.PERSON_PROPERTIES_UPDATE_ALL,FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: this.config.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,diff --git a/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts b/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.tsindex 88d3913a3b9e..495741a6e196 100644--- a/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts+++ b/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts@@ -14,7 +14,8 @@ import { PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT, PERSON_MERGE_EVENTS_OUTPUTimport { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'import { PostgresPersonRepository } from '~/common/persons/repositories/postgres-person-repository'-import { fetchDistinctIdValues } from '~/common/persons/repositories/test-helpers'+import { fetchDistinctIdValues, fetchDistinctIds } from '~/common/persons/repositories/test-helpers'+import { PostgresUse } from '~/common/utils/db/postgres'import { normalizeEvent, normalizeProcessPerson } from '~/common/utils/event'import { UUIDT } from '~/common/utils/utils'import { BatchWritingPersonsStore } from '~/ingestion/common/persons/batch-writing-person-store'@@ -53,6 +54,7 @@ describe('createProcessPersonsStep', () => {PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: '*',PERSON_MERGE_FOLD_ENABLED: false,PERSON_MERGE_FOLD_TEAM_ALLOWLIST: '*',+ PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: '',PERSON_JSONB_SIZE_ESTIMATE_ENABLE: 0,PERSON_PROPERTIES_UPDATE_ALL: false,FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: '*',@@ -415,6 +417,59 @@ describe('createProcessPersonsStep', () => {}})+ describe('always-v1 team allowlist', () => {+ function identify(anonDistinctId: string, targetDistinctId: string): PluginEvent {+ return {+ ...pluginEvent,+ event: '$identify',+ distinct_id: targetDistinctId,+ uuid: new UUIDT().toString(),+ properties: { $anon_distinct_id: anonDistinctId },+ }+ }++ async function runIdentify(event: PluginEvent, allowlist: string): Promise<void> {+ const step = createProcessPersonsStep(+ { ...options, PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: allowlist },+ personOutputs+ )+ const result = await step(+ createInput({ normalizedEvent: event, timestamp: DateTime.fromISO(event.timestamp!) })+ )+ expect(isOkResult(result)).toBe(true)+ }++ async function versionOf(distinctId: string): Promise<number> {+ const result = await infra.postgres.query<{ version: string | null }>(+ PostgresUse.PERSONS_WRITE,+ 'SELECT version FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2',+ [teamId, distinctId],+ 'fetchDistinctIdVersion'+ )+ expect(result.rows).toHaveLength(1)+ return Number(result.rows[0].version ?? 0)+ }++ it('writes version 1 for merge-added distinct ids only for allowlisted teams', async () => {+ await createPersonWithDistinctIds('user-1')++ // Neither anon id has personless history, so without the gate both would get version 0.+ await runIdentify(identify('anon-gated', 'user-1'), `${teamId}`)+ await runIdentify(identify('anon-ungated', 'user-1'), `${teamId + 1}`)++ expect(await versionOf('anon-gated')).toBe(1)+ expect(await versionOf('anon-ungated')).toBe(0)+ })++ it('gives the non-primary distinct id version 1 when neither points at a person', async () => {+ await runIdentify(identify('anon-new', 'user-new'), '*')++ // The event distinct id derives the person uuid, so it stays at version 0.+ expect(await versionOf('user-new')).toBe(0)+ expect(await versionOf('anon-new')).toBe(1)+ })+ })+describe('merge folding', () => {const foldOptions: EventPipelineRunnerOptions = {...options,@@ -588,6 +643,21 @@ describe('createProcessPersonsStep', () => {expect(distinctIds.sort()).toEqual(['anon-1', 'anon-2', 'user-1'])})+ it('folded personless adds get version 1 for always-v1 teams', async () => {+ await createPersonWithProps('anon-1', { a: 1 })+ // anon-2 has no person row and no personless history, so without the gate it would get version 0+ const plan = planFor('user-1', 'anon-1', 'anon-2')++ await runIdentifies([identifyEvent('anon-1', 'user-1')], plan, {+ ...foldOptions,+ PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: '*',+ })++ expect(plan.status).toBe('executed')+ const rows = await fetchDistinctIds(infra.postgres, plan.mergedPerson!)+ expect(Number(rows.find((row) => row.distinct_id === 'anon-2')!.version ?? 0)).toBe(1)+ })+it('folds under LIMIT merge mode when sources are within the move limit', async () => {await createPersonWithProps('anon-1', { a: 1 })await createPersonWithProps('anon-2', { b: 2 })diff --git a/nodejs/tests/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.integration.test.ts b/nodejs/tests/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.integration.test.tsindex 691aa018e373..05e80b0df1b7 100644--- a/nodejs/tests/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.integration.test.ts+++ b/nodejs/tests/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.integration.test.ts@@ -99,6 +99,7 @@ function buildPipeline(configOverrides: Partial<AiEventSubpipelineConfig> = {})PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: '*',PERSON_MERGE_FOLD_ENABLED: false,PERSON_MERGE_FOLD_TEAM_ALLOWLIST: '*',+ PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: '',PERSON_JSONB_SIZE_ESTIMATE_ENABLE: 0,PERSON_PROPERTIES_UPDATE_ALL: false,FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: '*',