: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): keep an identify from attaching a new id to an identified person (#114816)
Zach Brownd533088b6c16
diff --git a/nodejs/src/ingestion/common/persons/batch-writing-person-store.merge.test.ts b/nodejs/src/ingestion/common/persons/batch-writing-person-store.merge.test.tsindex 0e4ac36f834b..262cbb4b8b01 100644--- a/nodejs/src/ingestion/common/persons/batch-writing-person-store.merge.test.ts+++ b/nodejs/src/ingestion/common/persons/batch-writing-person-store.merge.test.ts@@ -10,6 +10,7 @@ import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outpuimport { InternalPerson } from '~/types'import { BatchWritingPersonsStore } from './batch-writing-person-store'+import { mergeIdentifiedSourceNewTargetCounter } from './person-merge-postgres'import { createDefaultSyncMergeMode } from './person-merge-types'import { EventOps } from './person-update'import { MergePersonsRequest } from './persons-store'@@ -330,6 +331,57 @@ describe('BatchWritingPersonsStore merging through PostgresPersonMerge', () => {expect(fake.rows.get('T')!.properties).toEqual({ [filtered]: 'v' })})+ it.each([+ ['an identified source', 'skipped_already_identified', 's', true],+ ['an unidentified source', 'attached', 's', false],+ ['an identified target', 'attached', 't', true],+ ])('an identify where only %s has a person settles as %s', async (_case, outcome, existingId, identified) => {+ fake.tx.createPerson.mockImplementation(+ (+ _createdAt: DateTime,+ properties: Record<string, unknown>,+ _lastUpdatedAt: unknown,+ _lastOperation: unknown,+ _teamId: number,+ _isUserId: number | null,+ isIdentified: boolean,+ uuid: string,+ primaryDistinctId: { distinctId: string },+ extraDistinctIds: { distinctId: string }[] = []+ ) => {+ fake.addPerson(+ uuid,+ [primaryDistinctId.distinctId, ...extraDistinctIds.map((id) => id.distinctId)],+ properties+ )+ fake.rows.get(uuid)!.is_identified = isIdentified+ return Promise.resolve({+ success: true,+ person: { ...fake.rows.get(uuid)! },+ created: true,+ messages: [],+ })+ }+ )+ fake.addPerson('E', [existingId], {})+ fake.rows.get('E')!.is_identified = identified+ const countedBefore = (await mergeIdentifiedSourceNewTargetCounter.get()).values[0]?.value ?? 0++ const result = await store.mergePersons({ ...mergeRequest('t', 's'), allowIdentifiedSources: false }, 0)++ expect(result.results[0].outcome).toBe(outcome)+ const countedAfter = (await mergeIdentifiedSourceNewTargetCounter.get()).values[0]?.value ?? 0+ expect(countedAfter - countedBefore).toBe(outcome === 'skipped_already_identified' ? 1 : 0)+ if (outcome === 'skipped_already_identified') {+ expect(result.survivor!.uuid).not.toBe('E')+ expect(fake.distinctToUuid.get('1:t')).toBe(result.survivor!.uuid)+ expect(fake.rows.get(result.survivor!.uuid)!.is_identified).toBe(true)+ expect(fake.distinctToUuid.get('1:s')).toBe('E')+ } else {+ expect(result.survivor!.uuid).toBe('E')+ }+ })+it('an explicit $set on a moved id during the merge reaches the survivor although it holds the key', async () => {fake.addPerson('T', ['t'], { k: 'B' })fake.addPerson('S', ['s'], {})diff --git a/nodejs/src/ingestion/common/persons/person-merge-postgres.test.ts b/nodejs/src/ingestion/common/persons/person-merge-postgres.test.tsindex 9a987001784a..b98783994287 100644--- a/nodejs/src/ingestion/common/persons/person-merge-postgres.test.ts+++ b/nodejs/src/ingestion/common/persons/person-merge-postgres.test.ts@@ -265,6 +265,35 @@ describe('PostgresPersonMerge merge events', () => {expect(mockOutputs.produce).toHaveBeenCalledTimes(1)})+ it('a replayed refusal of an identified source re-emits the target mapping its first attempt committed', async () => {+ mockOutputs = { produce: jest.fn().mockResolvedValue(undefined) }+ const target = { id: 'p-target', uuid: targetPerson.uuid, team_id: 2 } as unknown as InternalPerson+ const source = { id: 'p-source', uuid: sourcePerson.uuid, team_id: 2, is_identified: true } as InternalPerson+ const mapping = {+ distinctId: 'd',+ message: { output: PERSON_DISTINCT_IDS_OUTPUT, value: Buffer.from('{"version":0}') },+ }+ const store = {+ fetchForUpdate: jest+ .fn()+ .mockImplementation((_teamId: number, distinctId: string) =>+ Promise.resolve(distinctId === 'd' ? target : source)+ ),+ fetchPersonDistinctIdMappings: jest.fn().mockResolvedValue([mapping]),+ }++ const replay = await buildSingleSourceMerge(store, new UUIDT().toString(), {+ noopMappingDebounce: new MergeMappingDebounce(100, 60_000),+ }).execute()+ await replay.kafkaAck++ expect(replay.results[0].outcome).toBe('skipped_already_identified')+ expect(mockOutputs.produce).toHaveBeenCalledWith(+ PERSON_DISTINCT_IDS_OUTPUT,+ expect.objectContaining({ teamId: 2, value: mapping.message.value })+ )+ })+function buildSingleSourceMerge(store: object,eventUuid: string,diff --git a/nodejs/src/ingestion/common/persons/person-merge-postgres.ts b/nodejs/src/ingestion/common/persons/person-merge-postgres.tsindex 11fa02429fdc..6f32471d14c7 100644--- a/nodejs/src/ingestion/common/persons/person-merge-postgres.ts+++ b/nodejs/src/ingestion/common/persons/person-merge-postgres.ts@@ -82,6 +82,11 @@ export const personMergeEventProducedCounter = new Counter({help: 'Number of person_merge_events messages acked by the broker (gate-on merges only).',})+export const mergeIdentifiedSourceNewTargetCounter = new Counter({+ name: 'person_merge_identified_source_new_target_total',+ help: 'Identifies refused because the source is identified while the target had no person, so the merge created one for the target.',+})+export const mergeNoopMappingEmissionCounter = new Counter({name: 'person_merge_noop_mapping_emission_total',help: 'Distinct ids considered for mapping re-emission on already-satisfied merges.',@@ -459,7 +464,11 @@ export class PostgresPersonMerge {// id whose uuid a newly created person is born on — its events already point at the right// person, so it keeps version 0 and stays out of the overrides join.- if ((otherPerson && !mergeIntoPerson) || (!otherPerson && mergeIntoPerson)) {+ if (otherPerson && !mergeIntoPerson && otherPerson.is_identified && !this.request.allowIdentifiedSources) {+ // Attaching the new target to an identified source would identify one person as two+ // users, so the source keeps its person and the target gets its own, as when both exist.+ return await this.createTargetBesideIdentifiedSource(otherPerson, otherPersonDistinctId)+ } else if ((otherPerson && !mergeIntoPerson) || (!otherPerson && mergeIntoPerson)) {// Only one of the two Distinct IDs points at an existing Personconst [existingPerson, distinctIdToAdd] = (() => {@@ -580,6 +589,44 @@ export class PostgresPersonMerge {}}+ private async createTargetBesideIdentifiedSource(+ source: InternalPerson,+ sourceDistinctId: string+ ): Promise<MergePersonsResult> {+ const teamId = this.teamId+ const [person, kafkaMessages] = await this.inTransaction('mergeDistinctIds-IdentifiedSource', async (tx) => {+ // The target derives the new person's uuid, so its mapping keeps version 0.+ const [created, , messages, idOwned] = await this.createService.createPerson(+ this.timestamp,+ this.request.eventOps.set,+ this.request.eventOps.setOnce,+ teamId,+ null,+ true,+ this.request.eventUuid,+ { distinctId: this.targetDistinctId, version: 0 },+ [],+ tx+ )+ // Another writer now owns the target; the retry re-reads both ids and classifies against it.+ // A uuid held by a person that owns neither id resolves to that holder without mapping the+ // target, as in the neither-exists branch.+ if (idOwned) {+ throw new PersonMergeRaceConditionError(+ `person for ${this.targetDistinctId} was created concurrently during a merge`+ )+ }+ return [created, messages] as const+ })+ mergeIdentifiedSourceNewTargetCounter.inc()+ const kafkaAck = this.produceMessages(kafkaMessages)+ return {+ survivor: person,+ results: [{ sourceDistinctId, outcome: 'skipped_already_identified', sourcePersonUuid: source.uuid }],+ kafkaAck,+ }+ }+/*** Folded-merge execution for a multi-source request: every source* merges into the target inside one transaction. Any failure rolls@@ -885,6 +932,9 @@ export class PostgresPersonMerge {// will not merge a user who's already identified into anyone else.const mergeAllowed = this.request.allowIdentifiedSources || !otherPerson.is_identifiedif (!mergeAllowed) {+ // A replay of a committed createTargetBesideIdentifiedSource lands here, so re-emit+ // the target's mapping in case the crash came before its produce.+ const { kafkaAck } = await this.reemitSatisfiedMappings([mergeIntoDistinctId])return {survivor: mergeInto,results: [@@ -894,6 +944,7 @@ export class PostgresPersonMerge {sourcePersonUuid: otherPerson.uuid,},],+ kafkaAck,}}