Skip to content

: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.

fix(persons): write the identified flag inside the attach transaction (#117102)

Zach Brownf650f94ef6b0
diff --git a/nodejs/src/ingestion/common/persons/person-merge-postgres.test.ts b/nodejs/src/ingestion/common/persons/person-merge-postgres.test.ts
index b98783994287..0a3355698ddf 100644
--- a/nodejs/src/ingestion/common/persons/person-merge-postgres.test.ts
+++ b/nodejs/src/ingestion/common/persons/person-merge-postgres.test.ts
@@ -10,7 +10,7 @@ import {
PostgresPersonMerge,
personMergeEventProducedCounter,
} from './person-merge-postgres'
-import { createDefaultSyncMergeMode } from './person-merge-types'
+import { MergeOutcomeOversizedError, createDefaultSyncMergeMode } from './person-merge-types'
import { MergePersonsRequest } from './persons-store'
describe('PostgresPersonMerge merge events', () => {
@@ -152,7 +152,9 @@ describe('PostgresPersonMerge merge events', () => {
const tx = {
claimLifecycleMarks: jest.fn(),
isPersonLive: jest.fn().mockResolvedValue(true),
+ readMergeRows: jest.fn().mockResolvedValue([existingPerson]),
addDistinctId: jest.fn().mockResolvedValue([mappingMessage]),
+ updatePersonForMerge: jest.fn().mockResolvedValue([existingPerson, [], false]),
releaseLifecycleMarks: jest.fn(),
}
const store = {
@@ -182,6 +184,127 @@ describe('PostgresPersonMerge merge events', () => {
await expect(result.kafkaAck).resolves.toBeUndefined()
})
+ // The identified flag must commit with the mapping so another pod cannot attach a second user, and the
+ // committed row decides it: the batch's view can already show the flag pending.
+ it.each([
+ { name: 'writes the flag from the committed row and caches it', locked: true, cached: false, row: false },
+ { name: 'writes the flag when only the batch view shows it pending', locked: true, cached: true, row: false },
+ { name: 'leaves the row and cache alone when the row is identified', locked: true, cached: false, row: true },
+ { name: 'defers the flag to the flush for a deferred-outcome team', locked: false, cached: false, row: false },
+ ])('a one-exists merge $name', async ({ locked, cached, row }) => {
+ const order: string[] = []
+ const existingPerson = {
+ id: 'p1',
+ uuid: targetPerson.uuid,
+ team_id: 2,
+ is_identified: cached,
+ } as unknown as InternalPerson
+ const committedRow = { ...existingPerson, is_identified: row, version: 1 } as InternalPerson
+ const writtenRow = { ...committedRow, is_identified: true, version: 2 } as InternalPerson
+ const cachedRow = { ...writtenRow, properties: { pending: true } } as InternalPerson
+ const flagMessage = { output: PERSON_DISTINCT_IDS_OUTPUT, value: Buffer.from('{"flag":true}') }
+ const tx = {
+ claimLifecycleMarks: jest.fn(),
+ isPersonLive: jest.fn().mockResolvedValue(true),
+ readMergeRows: jest.fn().mockImplementation(() => {
+ order.push('readMergeRows')
+ return Promise.resolve([committedRow])
+ }),
+ addDistinctId: jest.fn().mockImplementation(() => {
+ order.push('addDistinctId')
+ return Promise.resolve([])
+ }),
+ updatePersonForMerge: jest.fn().mockImplementation(() => {
+ order.push('updatePersonForMerge')
+ return Promise.resolve([writtenRow, [flagMessage], true])
+ }),
+ releaseLifecycleMarks: jest.fn().mockImplementation(() => {
+ order.push('releaseLifecycleMarks')
+ return Promise.resolve()
+ }),
+ }
+ const store = {
+ fetchForUpdate: jest
+ .fn()
+ .mockImplementation((_teamId: number, distinctId: string) =>
+ Promise.resolve(distinctId === 'd' ? existingPerson : null)
+ ),
+ inTransaction: jest
+ .fn()
+ .mockImplementation(async (_description: string, body: (tx: unknown) => Promise<unknown>) => {
+ const result = await body(tx)
+ order.push('commit')
+ return result
+ }),
+ takeMergedRow: jest.fn().mockImplementation(() => {
+ order.push('takeMergedRow')
+ return cachedRow
+ }),
+ }
+ const merge = buildSingleSourceMerge(store, new UUIDT().toString(), { isLockedOutcomeTeam: () => locked })
+
+ const result = await merge.execute()
+
+ expect(result.results).toEqual([{ sourceDistinctId: 'anon', outcome: 'attached' }])
+ if (locked && !row) {
+ expect(order).toEqual([
+ 'readMergeRows',
+ 'addDistinctId',
+ 'updatePersonForMerge',
+ 'releaseLifecycleMarks',
+ 'commit',
+ 'takeMergedRow',
+ ])
+ expect(tx.updatePersonForMerge).toHaveBeenCalledWith(committedRow, { is_identified: true }, 'd')
+ expect(store.takeMergedRow).toHaveBeenCalledWith(writtenRow, 'd', { is_identified: true }, null, 0)
+ expect(mockOutputs.produce).toHaveBeenCalledWith(
+ PERSON_DISTINCT_IDS_OUTPUT,
+ expect.objectContaining({ value: flagMessage.value })
+ )
+ expect(result.survivor).toBe(cachedRow)
+ } else {
+ expect(tx.readMergeRows).toHaveBeenCalledTimes(locked ? 1 : 0)
+ expect(tx.updatePersonForMerge).not.toHaveBeenCalled()
+ expect(store.takeMergedRow).not.toHaveBeenCalled()
+ expect(result.survivor).toBe(existingPerson)
+ }
+ })
+
+ it('a one-exists merge on a row over the size limit commits the mapping without the flag', async () => {
+ const existingPerson = { id: 'p1', uuid: targetPerson.uuid, team_id: 2 } as unknown as InternalPerson
+ const mappingMessage = { output: PERSON_DISTINCT_IDS_OUTPUT, value: Buffer.from('{}') }
+ const tx = {
+ claimLifecycleMarks: jest.fn(),
+ isPersonLive: jest.fn().mockResolvedValue(true),
+ readMergeRows: jest.fn().mockResolvedValue([existingPerson]),
+ addDistinctId: jest.fn().mockResolvedValue([mappingMessage]),
+ updatePersonForMerge: jest.fn().mockRejectedValue(new MergeOutcomeOversizedError('over the limit')),
+ releaseLifecycleMarks: jest.fn(),
+ }
+ const store = {
+ fetchForUpdate: jest
+ .fn()
+ .mockImplementation((_teamId: number, distinctId: string) =>
+ Promise.resolve(distinctId === 'd' ? existingPerson : null)
+ ),
+ inTransaction: jest
+ .fn()
+ .mockImplementation((_description: string, body: (tx: unknown) => Promise<unknown>) => body(tx)),
+ takeMergedRow: jest.fn(),
+ }
+ const merge = buildSingleSourceMerge(store, new UUIDT().toString())
+
+ const result = await merge.execute()
+
+ expect(store.inTransaction).toHaveBeenCalledTimes(2)
+ expect(tx.updatePersonForMerge).toHaveBeenCalledTimes(1)
+ expect(tx.addDistinctId).toHaveBeenCalledTimes(2)
+ expect(store.takeMergedRow).not.toHaveBeenCalled()
+ expect(mockOutputs.produce).toHaveBeenCalledTimes(1)
+ expect(result.results).toEqual([{ sourceDistinctId: 'anon', outcome: 'attached' }])
+ expect(result.survivor).toBe(existingPerson)
+ })
+
// Same contract as the one-exists case: createPerson returns its messages and the
// branch produces after commit, so the creation transaction never spans Kafka.
it('a neither-exists merge produces the creation messages after the transaction', async () => {
diff --git a/nodejs/src/ingestion/common/persons/person-merge-postgres.ts b/nodejs/src/ingestion/common/persons/person-merge-postgres.ts
index 6f32471d14c7..7d52887f647b 100644
--- a/nodejs/src/ingestion/common/persons/person-merge-postgres.ts
+++ b/nodejs/src/ingestion/common/persons/person-merge-postgres.ts
@@ -144,6 +144,9 @@ export interface PostgresMergePolicy {
noopMappingDebounce?: MergeMappingDebounce
}
+/** A committed attach: the survivor, the flag write when there was one, and the messages to produce. */
+type AttachOutcome = readonly [InternalPerson, MergePersonUpdate | null, PersonMessage[]]
+
/**
* The keys a merge changes. The event's $set keys and keys this pod's pending unset hides go as sets, because the view
* can show a set-once that has not landed and the row can still hold a hidden key. Every other key only fills a gap.
@@ -301,6 +304,68 @@ export class PostgresPersonMerge {
return byId
}
+ /**
+ * Adds the distinct id to the person. With `writeFlag`, the committed row decides whether the identified flag
+ * is written with the mapping: the batch's view of the person can show the flag pending while Postgres still
+ * holds false, and a merge on another pod that reads the row before this batch flushes would attach a second
+ * user to it.
+ */
+ private async attachDistinctId(
+ existingPerson: InternalPerson,
+ distinctIdToAdd: string,
+ distinctIdsToPurge: [string, string],
+ writeFlag: boolean
+ ): Promise<AttachOutcome> {
+ const teamId = this.teamId
+ const lifecycleOpId = lifecycleOpIdFromEvent(teamId, this.request.eventUuid)
+ const deleted = (): Error =>
+ new TargetPersonNotFoundError('Person was deleted before the merge could add a distinct id')
+ this.discardOverrideCounts()
+ return await this.inTransaction('mergeDistinctIds-OneExists', async (tx) => {
+ // The person's lifecycle mark keeps a concurrent tombstone from landing
+ // between this check and the distinct id insert (an orphaned mapping).
+ await tx.claimLifecycleMarks(
+ lifecycleOpId,
+ existingPerson.team_id,
+ [{ personId: existingPerson.id, personUuid: existingPerson.uuid, role: 'target' }],
+ this.targetDistinctId
+ )
+ if (!(await tx.isPersonLive(existingPerson, this.targetDistinctId))) {
+ // Purge the stale cache entries so the caller's retry attempt
+ // re-fetches from Postgres instead of replaying the cached,
+ // now-tombstoned person into the same failure.
+ for (const distinctId of distinctIdsToPurge) {
+ this.store.removeDistinctIdFromCache(teamId, distinctId)
+ }
+ throw deleted()
+ }
+ // See the note on `distinctIdVersion` in mergeSingle.
+ const distinctIdVersion = 1
+ this.recordOverrideCount('oneExists')
+
+ // The row first, before the mapping insert takes a key-share lock on it, as the merge paths order theirs.
+ const row = writeFlag
+ ? (await this.lockMergeRows(tx, existingPerson, [], deleted)).get(existingPerson.id)
+ : undefined
+ const messages = await tx.addDistinctId(existingPerson, distinctIdToAdd, distinctIdVersion)
+ let survivor = existingPerson
+ let outcome: MergePersonUpdate | null = null
+ let survivorMessages: PersonMessage[] = []
+ if (row !== undefined && !row.is_identified) {
+ const identified: MergePersonUpdate = { is_identified: true }
+ let written: boolean
+ ;[survivor, survivorMessages, written] = await tx.updatePersonForMerge(
+ row,
+ identified,
+ this.targetDistinctId
+ )
+ outcome = written ? identified : null
+ }
+ await tx.releaseLifecycleMarks(lifecycleOpId, teamId, this.targetDistinctId)
+ return [survivor, outcome, [...messages, ...survivorMessages]] as const
+ })
+ }
+
/**
* Target wins over sources, earlier sources over later; the event's ops apply on top. Returns the pending
* changes each row's view took, so the entries can be settled against them after the commit.
@@ -479,39 +544,39 @@ export class PostgresPersonMerge {
}
})()
- this.discardOverrideCounts()
- const lifecycleOpId = lifecycleOpIdFromEvent(teamId, this.request.eventUuid)
- const [result, kafkaMessages] = await this.inTransaction('mergeDistinctIds-OneExists', async (tx) => {
- // The person's lifecycle mark keeps a concurrent tombstone from landing
- // between this check and the distinct id insert (an orphaned mapping).
- await tx.claimLifecycleMarks(
- lifecycleOpId,
- existingPerson.team_id,
- [{ personId: existingPerson.id, personUuid: existingPerson.uuid, role: 'target' }],
- this.targetDistinctId
+ let committed: AttachOutcome
+ try {
+ committed = await this.attachDistinctId(
+ existingPerson,
+ distinctIdToAdd,
+ [otherPersonDistinctId, mergeIntoDistinctId],
+ this.lockedOutcomeEnabled()
)
- if (!(await tx.isPersonLive(existingPerson, this.targetDistinctId))) {
- // Purge the stale cache entries so the caller's retry attempt
- // re-fetches from Postgres instead of replaying the cached,
- // now-tombstoned person into the same failure.
- this.store.removeDistinctIdFromCache(teamId, otherPersonDistinctId)
- this.store.removeDistinctIdFromCache(teamId, mergeIntoDistinctId)
- throw new TargetPersonNotFoundError('Person was deleted before the merge could add a distinct id')
+ } catch (error) {
+ // A row already over the properties size limit rejects the flag write. The mapping still commits
+ // and the flag rides the flush, as the merge path drops its oversized outcome.
+ if (!(error instanceof MergeOutcomeOversizedError)) {
+ throw error
}
- // See comment above about `distinctIdVersion`
- const distinctIdVersion = 1
- this.recordOverrideCount('oneExists')
-
- const messages = await tx.addDistinctId(existingPerson, distinctIdToAdd, distinctIdVersion)
- await tx.releaseLifecycleMarks(lifecycleOpId, teamId, this.targetDistinctId)
- return [existingPerson, messages] as const
- })
+ committed = await this.attachDistinctId(
+ existingPerson,
+ distinctIdToAdd,
+ [otherPersonDistinctId, mergeIntoDistinctId],
+ false
+ )
+ }
+ const [survivorRow, survivorUpdate, kafkaMessages] = committed
+ // After the commit, so a rollback leaves nothing of the attach in the cache: the person's entry takes
+ // the row, and its pending property changes stay pending since the write carried none.
+ const survivor = survivorUpdate
+ ? this.store.takeMergedRow(survivorRow, this.targetDistinctId, survivorUpdate, null, this.batchId)
+ : survivorRow
this.flushOverrideCounts()
// Produce only after the transaction commits: a produce awaited inside the
// transaction holds row locks and lifecycle marks across the Kafka roundtrip.
const kafkaAck = this.produceMessages(kafkaMessages)
return {
- survivor: result,
+ survivor,
results: [{ sourceDistinctId: otherPersonDistinctId, outcome: 'attached' }],
kafkaAck,
}
diff --git a/nodejs/tests/ingestion/person-state-batch.serial.test.ts b/nodejs/tests/ingestion/person-state-batch.serial.test.ts
index 5f5d0f646594..20481f929c51 100644
--- a/nodejs/tests/ingestion/person-state-batch.serial.test.ts
+++ b/nodejs/tests/ingestion/person-state-batch.serial.test.ts
@@ -1295,13 +1295,14 @@ describe('PersonState.processEvent()', () => {
await flushPersonStoreToKafka(kafkaProducer, context.personStore, kafkaAcks)
const persons = await fetchPostgresPersonsH()
+ // The attach commits the identified flag with the mapping, ahead of the batch flush.
expect(person).toMatchObject({
id: expect.any(String),
uuid: newUserUuid,
properties: {},
created_at: timestamp,
- version: 0,
- is_identified: false,
+ version: 1,
+ is_identified: true,
})
expect(mergeService.getUpdateIsIdentified()).toBeTruthy()
@@ -1311,9 +1312,9 @@ describe('PersonState.processEvent()', () => {
id: person!.id,
uuid: newUserUuid,
created_at: timestamp,
- is_identified: false,
+ is_identified: true,
properties: {},
- version: 0,
+ version: 1,
})
// verify Postgres distinct_ids
@@ -1753,13 +1754,14 @@ describe('PersonState.processEvent()', () => {
const persons = await fetchPostgresPersonsH()
+ // The attach commits the identified flag with the mapping, ahead of the batch flush.
expect(person).toMatchObject({
id: expect.any(String),
uuid: oldUserUuid,
properties: {},
created_at: timestamp,
- version: 0,
- is_identified: false,
+ version: 1,
+ is_identified: true,
})
expect(mergeService.getUpdateIsIdentified()).toBeTruthy()
expect(personRepository.updatePerson).not.toHaveBeenCalled()
@@ -1770,9 +1772,9 @@ describe('PersonState.processEvent()', () => {
id: person!.id,
uuid: oldUserUuid,
created_at: timestamp,
- is_identified: false,
+ is_identified: true,
properties: {},
- version: 0,
+ version: 1,
})
// verify Postgres distinct_ids