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.

feat(ingestion): tombstone merges and lifecycle marks behind a flag (#78944)

José Sequeira4352ba21db0e
diff --git a/nodejs/src/common/personhog/personhog-person-repository.test.ts b/nodejs/src/common/personhog/personhog-person-repository.test.ts
index 7e03c88a1ba7..d63224b6472d 100644
--- a/nodejs/src/common/personhog/personhog-person-repository.test.ts
+++ b/nodejs/src/common/personhog/personhog-person-repository.test.ts
@@ -77,6 +77,9 @@ function createMockPostgres(): jest.Mocked<PersonRepository> {
fetchPersonsForUpdateByDistinctIds: jest.fn(),
fetchDistinctIdsForPersons: jest.fn(),
deletePersons: jest.fn(),
+ claimLifecycleMarks: jest.fn(),
+ releaseLifecycleMarks: jest.fn(),
+ isPersonLive: jest.fn(),
updateCohortsAndFeatureFlagsForMergeBatch: jest.fn(),
createPerson: jest.fn(),
updatePerson: jest.fn(),
diff --git a/nodejs/src/common/personhog/personhog-person-repository.ts b/nodejs/src/common/personhog/personhog-person-repository.ts
index 9e034becc4cd..b572972d5f8c 100644
--- a/nodejs/src/common/personhog/personhog-person-repository.ts
+++ b/nodejs/src/common/personhog/personhog-person-repository.ts
@@ -2,7 +2,11 @@ import { DateTime } from 'luxon'
import { PersonMessage } from '~/common/persons/person-message'
import { PersonUpdate } from '~/common/persons/person-update-batch'
-import { InternalPersonWithDistinctId, PersonRepository } from '~/common/persons/repositories/person-repository'
+import {
+ InternalPersonWithDistinctId,
+ LifecycleMarkPerson,
+ PersonRepository,
+} from '~/common/persons/repositories/person-repository'
import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'
import { CreatePersonResult } from '~/common/utils/db/db'
import { logger } from '~/common/utils/logger'
@@ -216,6 +220,18 @@ export class PersonHogPersonRepository implements PersonRepository {
return this.postgres.deletePersons(persons)
}
+ claimLifecycleMarks(opId: string, teamId: number, persons: LifecycleMarkPerson[]): Promise<void> {
+ return this.postgres.claimLifecycleMarks(opId, teamId, persons)
+ }
+
+ releaseLifecycleMarks(opId: string, teamId: number): Promise<void> {
+ return this.postgres.releaseLifecycleMarks(opId, teamId)
+ }
+
+ isPersonLive(person: InternalPerson): Promise<boolean> {
+ return this.postgres.isPersonLive(person)
+ }
+
addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]> {
return this.postgres.addDistinctId(person, distinctId, version)
}
diff --git a/nodejs/src/common/persons/repositories/person-repository-transaction.ts b/nodejs/src/common/persons/repositories/person-repository-transaction.ts
index b47d1bdde7f9..a8f300f9f7e9 100644
--- a/nodejs/src/common/persons/repositories/person-repository-transaction.ts
+++ b/nodejs/src/common/persons/repositories/person-repository-transaction.ts
@@ -1,6 +1,7 @@
import { DateTime } from 'luxon'
import { PersonMessage } from '~/common/persons/person-message'
+import { LifecycleMarkPerson } from '~/common/persons/repositories/person-repository'
import { CreatePersonResult, MoveDistinctIdsResult } from '~/common/utils/db/db'
import { Properties } from '~/plugin-scaffold'
import { InternalPerson, PersonUpdateFields, PropertiesLastOperation, PropertiesLastUpdatedAt, Team } from '~/types'
@@ -30,6 +31,15 @@ export interface PersonRepositoryTransaction {
/** Batched deletePerson for folded merges; all persons must belong to one team. */
deletePersons(persons: InternalPerson[]): Promise<PersonMessage[]>
+ /** See PersonRepository.claimLifecycleMarks; the marks are held until this transaction commits. */
+ claimLifecycleMarks(opId: string, teamId: number, persons: LifecycleMarkPerson[]): Promise<void>
+
+ /** See PersonRepository.releaseLifecycleMarks. */
+ releaseLifecycleMarks(opId: string, teamId: number): Promise<void>
+
+ /** See PersonRepository.isPersonLive; only meaningful while holding the person's mark. */
+ isPersonLive(person: InternalPerson): Promise<boolean>
+
addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]>
moveDistinctIds(source: InternalPerson, target: InternalPerson, limit?: number): Promise<MoveDistinctIdsResult>
diff --git a/nodejs/src/common/persons/repositories/person-repository.ts b/nodejs/src/common/persons/repositories/person-repository.ts
index f27022c6602b..c5b5a418aca6 100644
--- a/nodejs/src/common/persons/repositories/person-repository.ts
+++ b/nodejs/src/common/persons/repositories/person-repository.ts
@@ -34,6 +34,57 @@ export class PersonPropertiesSizeViolationError extends Error {
readonly isRetriable = false
}
+export class DistinctIdConflictError extends Error {
+ constructor(
+ message: string,
+ public teamId: number,
+ public distinctId?: string
+ ) {
+ super(message)
+ this.name = 'DistinctIdConflictError'
+ }
+}
+
+/**
+ * A tombstone delete found live distinct id rows still pointing at the person
+ * (a concurrent merge added or moved them in after ours moved the known set).
+ * The tombstone-mode equivalent of the FK violation a hard delete would raise;
+ * callers refresh the person and retry, re-moving the new rows.
+ */
+export class PersonTombstoneBlockedError extends Error {
+ constructor(
+ message: string,
+ public teamId: number
+ ) {
+ super(message)
+ this.name = 'PersonTombstoneBlockedError'
+ }
+}
+
+/**
+ * A lifecycle-mark claim lost to a live claim by another operation (a delete
+ * saga mid-flight, or a concurrent merge on the same event). At most one live
+ * operation may hold a person; callers back off and retry, by which time the
+ * winner has usually finished.
+ */
+export class PersonClaimedByLifecycleOpError extends Error {
+ constructor(
+ message: string,
+ public teamId: number
+ ) {
+ super(message)
+ this.name = 'PersonClaimedByLifecycleOpError'
+ }
+}
+
+/** A person a merge claims in the lifecycle mark table for the duration of its transaction. */
+export interface LifecycleMarkPerson {
+ personId: string
+ personUuid: string
+ role: 'target' | 'source'
+ ordinal?: number
+}
+
/**
* Read-only person lookups backed by personhog gRPC. Used by services that
* only need to fetch person data (CDP, error tracking, future pipelines).
@@ -146,6 +197,25 @@ export interface PersonRepository {
/** Batched deletePerson for folded merges; all persons must belong to one team. */
deletePersons(persons: InternalPerson[]): Promise<PersonMessage[]>
+ /**
+ * Claims the given persons in the lifecycle mark table for a merge: at most one live
+ * operation (merge or delete saga) may hold a person, enforced by the mark index.
+ * Claim before reading state the transaction relies on, and hold until commit via
+ * releaseLifecycleMarks. Throws PersonClaimedByLifecycleOpError when another
+ * operation holds one of the persons.
+ */
+ claimLifecycleMarks(opId: string, teamId: number, persons: LifecycleMarkPerson[]): Promise<void>
+
+ /** Releases a merge's lifecycle marks; must run in the same transaction as the claim. */
+ releaseLifecycleMarks(opId: string, teamId: number): Promise<void>
+
+ /**
+ * Whether the person row exists and is not tombstoned. Only meaningful while the
+ * caller holds the person's lifecycle mark: the mark excludes concurrent tombstones,
+ * so the answer stays true until the transaction commits.
+ */
+ isPersonLive(person: InternalPerson): Promise<boolean>
+
addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]>
addPersonlessDistinctId(teamId: Team['id'], distinctId: string): Promise<boolean>
diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository-transaction.ts b/nodejs/src/common/persons/repositories/postgres-person-repository-transaction.ts
index 7741fceb5dc5..5401e705022f 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository-transaction.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository-transaction.ts
@@ -6,6 +6,7 @@ import { TransactionClient } from '~/common/utils/db/postgres'
import { Properties } from '~/plugin-scaffold'
import { InternalPerson, PersonUpdateFields, PropertiesLastOperation, PropertiesLastUpdatedAt, Team } from '~/types'
+import { LifecycleMarkPerson } from './person-repository'
import { PersonRepositoryTransaction } from './person-repository-transaction'
import { RawPostgresPersonRepository } from './raw-postgres-person-repository'
@@ -58,6 +59,18 @@ export class PostgresPersonRepositoryTransaction implements PersonRepositoryTran
return await this.repository.deletePersons(persons, this.transaction)
}
+ async claimLifecycleMarks(opId: string, teamId: number, persons: LifecycleMarkPerson[]): Promise<void> {
+ return await this.repository.claimLifecycleMarks(opId, teamId, persons, this.transaction)
+ }
+
+ async releaseLifecycleMarks(opId: string, teamId: number): Promise<void> {
+ return await this.repository.releaseLifecycleMarks(opId, teamId, this.transaction)
+ }
+
+ async isPersonLive(person: InternalPerson): Promise<boolean> {
+ return await this.repository.isPersonLive(person, this.transaction)
+ }
+
async addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]> {
return await this.repository.addDistinctId(person, distinctId, version, this.transaction)
}
diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts b/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
index 0a64855a683c..ee0726671c05 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
@@ -13,7 +13,12 @@ import { NoRowsUpdatedError, UUIDT } from '~/common/utils/utils'
import { createTeam, insertRow, resetTestDatabase } from '~/tests/helpers/sql'
import { Hub, InternalPerson, PropertyUpdateOperation, Team } from '~/types'
-import { PersonPropertiesSizeViolationError } from './person-repository'
+import {
+ DistinctIdConflictError,
+ PersonClaimedByLifecycleOpError,
+ PersonPropertiesSizeViolationError,
+ PersonTombstoneBlockedError,
+} from './person-repository'
import { PostgresPersonRepository } from './postgres-person-repository'
import { createPersonUpdateFields, fetchDistinctIdValues, fetchDistinctIds } from './test-helpers'
@@ -220,6 +225,29 @@ describe('PostgresPersonRepository', () => {
)
}
+ function buildPersonUpdate(person: InternalPerson, distinctId: string, version: number) {
+ return {
+ id: person.id,
+ team_id: person.team_id,
+ uuid: person.uuid,
+ distinct_id: distinctId,
+ properties: { name: 'Jane' },
+ properties_last_updated_at: {},
+ properties_last_operation: {},
+ created_at: person.created_at,
+ version,
+ is_identified: person.is_identified,
+ is_user_id: person.is_user_id,
+ last_seen_at: person.last_seen_at,
+ needs_write: true,
+ properties_to_set: { name: 'Jane' },
+ properties_to_unset: [],
+ original_is_identified: false,
+ original_created_at: DateTime.fromISO('2020-01-01T00:00:00.000Z'),
+ original_last_seen_at: null,
+ }
+ }
+
it('excludes tombstoned persons from person reads', async () => {
const team = await getFirstTeam(hub.postgres)
const person = await createTestPerson(team.id, 'tombstoned-person-did')
@@ -253,6 +281,382 @@ describe('PostgresPersonRepository', () => {
new Map([[person.id, 1]])
)
})
+
+ it('updatePerson does not touch a tombstoned person', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const person = await createTestPerson(team.id, 'guard-update-did')
+ await tombstonePerson(person)
+
+ await expect(
+ repository.updatePerson(
+ person,
+ createPersonUpdateFields(person, { properties: { a: 1 } }),
+ 'guard-test'
+ )
+ ).rejects.toThrow(NoRowsUpdatedError)
+ })
+
+ it('updatePersonAssertVersion does not touch a tombstoned person even at the matching version', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const person = await createTestPerson(team.id, 'guard-assert-did')
+ await tombstonePerson(person)
+
+ // The tombstone bumped the row to person.version + 1; assert against that exact
+ // version so only the is_deleted guard can reject the write.
+ const [version, messages] = await repository.updatePersonAssertVersion(
+ buildPersonUpdate(person, 'guard-assert-did', person.version + 1)
+ )
+
+ expect(version).toBeUndefined()
+ expect(messages).toEqual([])
+ })
+
+ it('updatePersonsBatch skips tombstoned persons and leaves the death version intact', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const livePerson = await createTestPerson(team.id, 'guard-batch-live-did')
+ const deadPerson = await createTestPerson(team.id, 'guard-batch-dead-did')
+ await tombstonePerson(deadPerson)
+ const deathVersion = deadPerson.version + 1
+
+ const results = await repository.updatePersonsBatch([
+ buildPersonUpdate(livePerson, 'guard-batch-live-did', livePerson.version),
+ buildPersonUpdate(deadPerson, 'guard-batch-dead-did', deathVersion),
+ ])
+
+ expect(results.get(livePerson.uuid)).toMatchObject({ success: true })
+ expect(results.get(deadPerson.uuid)?.success).toBe(false)
+ expect(results.get(deadPerson.uuid)?.error).toBeInstanceOf(NoRowsUpdatedError)
+
+ const rows = await postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ 'SELECT version FROM posthog_person WHERE team_id = $1 AND id = $2',
+ [team.id, deadPerson.id],
+ 'fetchDeadPersonVersion'
+ )
+ expect(Number(rows.rows[0].version)).toBe(deathVersion)
+ })
+
+ it.each([
+ [
+ 'moveDistinctIds',
+ (source: InternalPerson, target: InternalPerson) => repository.moveDistinctIds(source, target),
+ ],
+ [
+ 'moveDistinctIds with limit',
+ (source: InternalPerson, target: InternalPerson) => repository.moveDistinctIds(source, target, 10),
+ ],
+ [
+ 'moveDistinctIdsFromPersons',
+ (source: InternalPerson, target: InternalPerson) =>
+ repository.moveDistinctIdsFromPersons([source], target),
+ ],
+ ])('%s moves only live distinct id mappings', async (_name, move) => {
+ const team = await getFirstTeam(hub.postgres)
+ const source = await createTestPerson(team.id, 'guard-move-live-did')
+ const target = await createTestPerson(team.id, 'guard-move-target-did')
+ await repository.addDistinctId(source, 'guard-move-dead-did', 0)
+ await tombstoneDistinctId(team.id, 'guard-move-dead-did')
+
+ const result = await move(source, target)
+
+ expect(result).toMatchObject({ success: true, distinctIdsMoved: ['guard-move-live-did'] })
+ const sourceRows = await fetchDistinctIds(postgres, source)
+ expect(sourceRows).toHaveLength(1)
+ expect(sourceRows[0].distinct_id).toBe('guard-move-dead-did')
+ })
+
+ it('createPerson revives a tombstoned person and its distinct id at death_version + 1', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const uuid = new UUIDT().toString()
+ const first = await repository.createPerson(TIMESTAMP, { a: 1 }, {}, {}, team.id, null, false, uuid, {
+ distinctId: 'revive-did',
+ })
+ if (!first.success) {
+ throw new Error('Failed to create person')
+ }
+ await tombstonePerson(first.person)
+ await tombstoneDistinctId(team.id, 'revive-did')
+
+ const revived = await repository.createPerson(TIMESTAMP, { b: 2 }, {}, {}, team.id, null, true, uuid, {
+ distinctId: 'revive-did',
+ })
+
+ if (!revived.success) {
+ throw new Error('Expected revival to succeed')
+ }
+ expect(revived.created).toBe(true)
+ expect(revived.person.version).toBe(2)
+ expect(revived.person.properties).toEqual({ b: 2 })
+ await expect(repository.fetchPerson(team.id, 'revive-did')).resolves.toMatchObject({ uuid, version: 2 })
+
+ const personMessage = parseJSON(revived.messages[0].value!.toString())
+ expect(personMessage.version).toBe(2)
+ expect(personMessage.is_deleted).toBe(0)
+ const distinctIdMessage = parseJSON(revived.messages[1].value!.toString())
+ expect(distinctIdMessage.version).toBe(2)
+ })
+
+ it('createPerson returns CreationConflict against a live person with the same uuid', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const uuid = new UUIDT().toString()
+ const first = await repository.createPerson(TIMESTAMP, { a: 1 }, {}, {}, team.id, null, false, uuid, {
+ distinctId: 'live-uuid-did',
+ })
+ if (!first.success) {
+ throw new Error('Failed to create person')
+ }
+
+ const second = await repository.createPerson(TIMESTAMP, { b: 2 }, {}, {}, team.id, null, false, uuid, {
+ distinctId: 'live-uuid-did-2',
+ })
+
+ expect(second).toEqual({ success: false, error: 'CreationConflict', distinctIds: ['live-uuid-did-2'] })
+ await expect(repository.fetchPerson(team.id, 'live-uuid-did')).resolves.toMatchObject({
+ version: 0,
+ properties: { a: 1 },
+ })
+ })
+
+ it('createPerson dedupes repeated distinct ids instead of failing the multi-insert', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const uuid = new UUIDT().toString()
+
+ const result = await repository.createPerson(
+ TIMESTAMP,
+ {},
+ {},
+ {},
+ team.id,
+ null,
+ false,
+ uuid,
+ { distinctId: 'dup-did' },
+ [{ distinctId: 'dup-did' }]
+ )
+
+ if (!result.success) {
+ throw new Error('Expected creation to succeed')
+ }
+ // One person message and one mapping message: the duplicate collapsed.
+ expect(result.messages).toHaveLength(2)
+ await expect(repository.fetchPerson(team.id, 'dup-did')).resolves.toMatchObject({ uuid })
+ })
+
+ it('createPerson undoes its insert when a distinct id is owned by a live mapping', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ await createTestPerson(team.id, 'contested-did')
+ const uuid = new UUIDT().toString()
+
+ const result = await repository.createPerson(
+ TIMESTAMP,
+ { secret: 'value' },
+ {},
+ {},
+ team.id,
+ null,
+ false,
+ uuid,
+ { distinctId: 'undo-primary-did' },
+ [{ distinctId: 'contested-did' }]
+ )
+
+ expect(result).toMatchObject({ success: false, error: 'CreationConflict' })
+ // The person row and the primary mapping it did attach are tombstoned, not
+ // left live: a live person unreachable by its contested distinct id would
+ // block the key forever. Like every tombstone, the properties are scrubbed.
+ const personRows = await postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ 'SELECT is_deleted, properties FROM posthog_person WHERE team_id = $1 AND uuid = $2',
+ [team.id, uuid],
+ 'fetchUndonePerson'
+ )
+ expect(personRows.rows).toEqual([{ is_deleted: true, properties: {} }])
+ await expect(repository.fetchPerson(team.id, 'undo-primary-did')).resolves.toBeUndefined()
+ })
+
+ it('addDistinctId revives a tombstoned mapping, repointing it at the new person', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const newOwner = await createTestPerson(team.id, 'adder-did')
+ const oldOwner = await createTestPerson(team.id, 'old-owner-did')
+ await repository.addDistinctId(oldOwner, 'recycled-did', 0)
+ await tombstoneDistinctId(team.id, 'recycled-did')
+
+ const messages = await repository.addDistinctId(newOwner, 'recycled-did', 0)
+
+ await expect(repository.fetchPerson(team.id, 'recycled-did')).resolves.toMatchObject({
+ uuid: newOwner.uuid,
+ })
+ const message = parseJSON(messages[0].value!.toString())
+ expect(message).toEqual({
+ person_id: newOwner.uuid,
+ team_id: team.id,
+ distinct_id: 'recycled-did',
+ version: 2,
+ is_deleted: 0,
+ })
+ })
+
+ it('addDistinctId throws DistinctIdConflictError for a live mapping', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const person = await createTestPerson(team.id, 'conflict-adder-did')
+ await createTestPerson(team.id, 'already-owned-did')
+
+ await expect(repository.addDistinctId(person, 'already-owned-did', 0)).rejects.toThrow(
+ DistinctIdConflictError
+ )
+ })
+
+ it('isPersonLive is true for a live person and false for a tombstoned one', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const person = await createTestPerson(team.id, 'live-check-did')
+
+ await expect(repository.isPersonLive(person)).resolves.toBe(true)
+ await tombstonePerson(person)
+ await expect(repository.isPersonLive(person)).resolves.toBe(false)
+ })
+
+ describe('lifecycle marks', () => {
+ async function countLifecycleRows(opId: string): Promise<{ ops: number; persons: number }> {
+ const ops = await postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ 'SELECT count(*) AS count FROM lifecycle_op WHERE op_id = $1',
+ [opId],
+ 'countLifecycleOps'
+ )
+ const persons = await postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ 'SELECT count(*) AS count FROM lifecycle_op_person WHERE op_id = $1',
+ [opId],
+ 'countLifecycleOpPersons'
+ )
+ return { ops: Number(ops.rows[0].count), persons: Number(persons.rows[0].count) }
+ }
+
+ it('claim and release leave no rows behind', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const person = await createTestPerson(team.id, 'mark-roundtrip-did')
+ const opId = new UUIDT().toString()
+
+ await repository.claimLifecycleMarks(opId, team.id, [
+ { personId: person.id, personUuid: person.uuid, role: 'target' },
+ ])
+ await expect(countLifecycleRows(opId)).resolves.toEqual({ ops: 1, persons: 1 })
+
+ await repository.releaseLifecycleMarks(opId, team.id)
+ await expect(countLifecycleRows(opId)).resolves.toEqual({ ops: 0, persons: 0 })
+ })
+
+ it('claiming a person held by a live operation throws PersonClaimedByLifecycleOpError', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const person = await createTestPerson(team.id, 'mark-conflict-did')
+ const sagaOpId = new UUIDT().toString()
+ // A delete saga's live claim: committed in its own transaction and held
+ // across ours, exactly what the mark index arbitrates against.
+ await repository.claimLifecycleMarks(sagaOpId, team.id, [
+ { personId: person.id, personUuid: person.uuid, role: 'source' },
+ ])
+
+ const mergeOpId = new UUIDT().toString()
+ await expect(
+ repository.claimLifecycleMarks(mergeOpId, team.id, [
+ { personId: person.id, personUuid: person.uuid, role: 'target' },
+ ])
+ ).rejects.toThrow(PersonClaimedByLifecycleOpError)
+
+ await repository.releaseLifecycleMarks(sagaOpId, team.id)
+ })
+
+ it('release scoped to another team leaves the marks in place', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const person = await createTestPerson(team.id, 'mark-scoped-did')
+ const opId = new UUIDT().toString()
+ await repository.claimLifecycleMarks(opId, team.id, [
+ { personId: person.id, personUuid: person.uuid, role: 'target' },
+ ])
+
+ await repository.releaseLifecycleMarks(opId, team.id + 1)
+ await expect(countLifecycleRows(opId)).resolves.toEqual({ ops: 1, persons: 1 })
+
+ await repository.releaseLifecycleMarks(opId, team.id)
+ await expect(countLifecycleRows(opId)).resolves.toEqual({ ops: 0, persons: 0 })
+ })
+
+ it('a released mark no longer blocks a new claim', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const person = await createTestPerson(team.id, 'mark-released-did')
+ const firstOpId = new UUIDT().toString()
+ await repository.claimLifecycleMarks(firstOpId, team.id, [
+ { personId: person.id, personUuid: person.uuid, role: 'target' },
+ ])
+ await repository.releaseLifecycleMarks(firstOpId, team.id)
+
+ const secondOpId = new UUIDT().toString()
+ await repository.claimLifecycleMarks(secondOpId, team.id, [
+ { personId: person.id, personUuid: person.uuid, role: 'target' },
+ ])
+ await repository.releaseLifecycleMarks(secondOpId, team.id)
+ })
+ })
+
+ describe('tombstone-mode deletes', () => {
+ let tombstoneRepository: PostgresPersonRepository
+
+ beforeEach(() => {
+ tombstoneRepository = new PostgresPersonRepository(postgres, {
+ calculatePropertiesSize: 0,
+ personPropertiesDbConstraintLimitBytes: 1024 * 1024,
+ personPropertiesTrimTargetBytes: 512 * 1024,
+ personMergeTombstoneTeamAllowlist: '*',
+ })
+ })
+
+ it('deletePerson tombstones the row at the exact death version with scrubbed properties', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const person = await createTestPerson(team.id, 'ts-delete-did', { secret: 'x' })
+ await tombstoneDistinctId(team.id, 'ts-delete-did')
+
+ const messages = await tombstoneRepository.deletePerson(person)
+
+ expect(messages).toHaveLength(1)
+ const message = parseJSON(messages[0].value!.toString())
+ expect(message).toMatchObject({ id: person.uuid, is_deleted: 1, version: 1, properties: '{}' })
+
+ const { rows } = await postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ 'SELECT is_deleted, version, properties FROM posthog_person WHERE team_id = $1 AND id = $2',
+ [team.id, person.id],
+ 'fetchTombstonedPerson'
+ )
+ expect(rows[0].is_deleted).toBe(true)
+ expect(Number(rows[0].version)).toBe(1)
+ expect(rows[0].properties).toEqual({})
+ })
+
+ it('deletePerson refuses while live distinct ids still point at the person', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const person = await createTestPerson(team.id, 'ts-blocked-did')
+
+ await expect(tombstoneRepository.deletePerson(person)).rejects.toThrow(PersonTombstoneBlockedError)
+ await expect(repository.fetchPerson(team.id, 'ts-blocked-did')).resolves.toMatchObject({
+ uuid: person.uuid,
+ })
+ })
+
+ it('deletePersons tombstones fresh persons and skips already-tombstoned ones', async () => {
+ const team = await getFirstTeam(hub.postgres)
+ const alreadyDead = await createTestPerson(team.id, 'ts-batch-dead-did')
+ const fresh = await createTestPerson(team.id, 'ts-batch-fresh-did')
+ await tombstoneDistinctId(team.id, 'ts-batch-dead-did')
+ await tombstoneDistinctId(team.id, 'ts-batch-fresh-did')
+ await tombstonePerson(alreadyDead)
+
+ const messages = await tombstoneRepository.deletePersons([alreadyDead, fresh])
+
+ expect(messages).toHaveLength(1)
+ const message = parseJSON(messages[0].value!.toString())
+ expect(message).toMatchObject({ id: fresh.uuid, is_deleted: 1, version: 1 })
+ })
+ })
})
describe('createPerson()', () => {
diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository.ts b/nodejs/src/common/persons/repositories/postgres-person-repository.ts
index 6f0f2669a14b..006c6e18b9a6 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.ts
@@ -1,6 +1,7 @@
import { DateTime } from 'luxon'
import { QueryResult } from 'pg'
+import { buildIntegerMatcher } from '~/common/config/config'
import { PERSON_DISTINCT_IDS_OUTPUT } from '~/common/outputs/persons'
import {
oversizedPersonPropertiesTrimmedCounter,
@@ -29,13 +30,18 @@ import {
RawPerson,
Team,
TeamId,
+ ValueMatcher,
} from '~/types'
import {
+ DistinctIdConflictError,
InternalPersonWithDistinctId,
+ LifecycleMarkPerson,
+ PersonClaimedByLifecycleOpError,
PersonMessage,
PersonPropertiesSizeViolationError,
PersonRepository,
+ PersonTombstoneBlockedError,
} from './person-repository'
import { PersonRepositoryTransaction } from './person-repository-transaction'
import { PostgresPersonRepositoryTransaction } from './postgres-person-repository-transaction'
@@ -73,24 +79,29 @@ export interface PostgresPersonRepositoryOptions {
personPropertiesDbConstraintLimitBytes: number
/** Target JSON size (stringified) to trim down to when remediating oversized properties */
personPropertiesTrimTargetBytes: number
+ /** Teams whose merge deletes tombstone the person row instead of hard-deleting it ('*' for all) */
+ personMergeTombstoneTeamAllowlist: string
}
const DEFAULT_OPTIONS: PostgresPersonRepositoryOptions = {
calculatePropertiesSize: 0,
personPropertiesDbConstraintLimitBytes: DEFAULT_PERSON_PROPERTIES_DB_CONSTRAINT_LIMIT_BYTES,
personPropertiesTrimTargetBytes: DEFAULT_PERSON_PROPERTIES_TRIM_TARGET_BYTES,
+ personMergeTombstoneTeamAllowlist: '',
}
export class PostgresPersonRepository
implements PersonRepository, RawPostgresPersonRepository, PersonRepositoryTransaction
{
private options: PostgresPersonRepositoryOptions
+ private isTombstoneTeam: ValueMatcher<number>
constructor(
private postgres: PostgresRouter,
options?: Partial<PostgresPersonRepositoryOptions>
) {
this.options = { ...DEFAULT_OPTIONS, ...options }
+ this.isTombstoneTeam = buildIntegerMatcher(this.options.personMergeTombstoneTeamAllowlist, true)
}
private async handleOversizedPersonProperties(
@@ -519,29 +530,40 @@ export class PostgresPersonRepository
extraDistinctIds: { distinctId: string; version?: number }[] = [],
tx?: TransactionClient
): Promise<CreatePersonResult> {
- const distinctIds = [primaryDistinctId, ...extraDistinctIds]
+ // A conflicted create is undone by a compensating statement, which is only
+ // atomic with the create inside a transaction. Without one, the created person
+ // would be briefly visible to concurrent requests before the undo tombstones it.
+ if (!tx) {
+ return await this.inRawTransaction('createPerson', (newTx) =>
+ this.createPerson(
+ createdAt,
+ properties,
+ propertiesLastUpdatedAt,
+ propertiesLastOperation,
+ teamId,
+ isUserId,
+ isIdentified,
+ uuid,
+ primaryDistinctId,
+ extraDistinctIds,
+ newTx
+ )
+ )
+ }
+
+ // Dedupe by distinct id: ON CONFLICT DO UPDATE raises 21000 when one command
+ // carries the same key twice, even when the WHERE qual would exclude the row.
+ const distinctIds = [primaryDistinctId, ...extraDistinctIds].filter(
+ (entry, index, all) => all.findIndex((other) => other.distinctId === entry.distinctId) === index
+ )
for (const distinctId of distinctIds) {
distinctId.version ||= 0
}
- // The Person is being created, and so we can hardcode version 0!
+ // Fresh inserts start at version 0; a tombstone conflict revives at death_version + 1 instead.
const personVersion = 0
try {
- const columns = [
- 'created_at',
- 'properties',
- 'properties_last_updated_at',
- 'properties_last_operation',
- 'team_id',
- 'is_user_id',
- 'is_identified',
- 'uuid',
- 'version',
- 'last_seen_at',
- ]
- const valuePlaceholders = columns.map((_, i) => `$${i + 1}`).join(', ')
-
// Sanitize and measure JSON field sizes
const sanitizedProperties = sanitizeJsonbValue(properties)
const sanitizedPropertiesLastUpdatedAt = sanitizeJsonbValue(propertiesLastUpdatedAt)
@@ -580,69 +602,119 @@ export class PostgresPersonRepository
lastSeenAt.toISO(),
]
- // Find the actual index of team_id in the personParams array (1-indexed for SQL)
- const teamIdParamIndex = personParams.indexOf(teamId) + 1
- const distinctIdVersionStartIndex = columns.length + 1
- const distinctIdStartIndex = distinctIdVersionStartIndex + distinctIds.length
-
- const distinctIdsCTE =
- distinctIds.length > 0
- ? `, distinct_ids AS (
- INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version)
- VALUES ${distinctIds
- .map(
- // NOTE: Keep this in sync with the posthog_persondistinctid INSERT in
- // `addDistinctId`
- (_, index) => `(
- $${distinctIdStartIndex + index},
- (SELECT id FROM inserted_person),
- $${teamIdParamIndex},
- $${distinctIdVersionStartIndex + index}
- )`
- )
- .join(', ')}
- )`
- : ''
-
- const query =
- `WITH inserted_person AS (
- INSERT INTO posthog_person (${columns.join(', ')})
- VALUES (${valuePlaceholders})
- RETURNING ${PERSON_COLUMNS}
- )` +
- distinctIdsCTE +
- ` SELECT * FROM inserted_person;`
-
- const { rows } = await this.postgres.query<RawPerson>(
+ // A conflict with a tombstoned row is a revival: continue the version
+ // counter above the death version so the reborn key outranks its own
+ // ClickHouse tombstone from its first write. Conflicts with live rows
+ // fail the WHERE qual and surface as CreationConflict below.
+ const query = `
+ WITH inserted_person AS (
+ INSERT INTO posthog_person (
+ created_at, properties, properties_last_updated_at, properties_last_operation,
+ team_id, is_user_id, is_identified, uuid, version, last_seen_at
+ )
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
+ ON CONFLICT (team_id, uuid) DO UPDATE SET
+ is_deleted = false,
+ version = COALESCE(posthog_person.version, 0) + 1,
+ properties = EXCLUDED.properties,
+ properties_last_updated_at = EXCLUDED.properties_last_updated_at,
+ properties_last_operation = EXCLUDED.properties_last_operation,
+ created_at = EXCLUDED.created_at,
+ is_user_id = EXCLUDED.is_user_id,
+ is_identified = EXCLUDED.is_identified,
+ last_seen_at = EXCLUDED.last_seen_at
+ WHERE posthog_person.is_deleted = true
+ RETURNING ${PERSON_COLUMNS}
+ ),
+ inserted_distinct_ids AS (
+ -- NOTE: Keep this in sync with the posthog_persondistinctid INSERT in addDistinctId
+ INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version)
+ SELECT d.distinct_id, ip.id, $5, d.version
+ FROM inserted_person ip
+ CROSS JOIN unnest($11::text[], $12::bigint[]) AS d(distinct_id, version)
+ ON CONFLICT (team_id, distinct_id) DO UPDATE SET
+ person_id = EXCLUDED.person_id,
+ version = COALESCE(posthog_persondistinctid.version, 0) + 1,
+ is_deleted = false
+ WHERE posthog_persondistinctid.is_deleted = true
+ RETURNING id, distinct_id, version
+ )
+ SELECT
+ ip.*,
+ (
+ SELECT COALESCE(jsonb_agg(jsonb_build_object('id', d.id::text, 'distinct_id', d.distinct_id, 'version', d.version)), '[]'::jsonb)
+ FROM inserted_distinct_ids d
+ ) AS distinct_id_rows
+ FROM inserted_person ip;`
+
+ const { rows } = await this.postgres.query<
+ RawPerson & { distinct_id_rows: { id: string; distinct_id: string; version: number }[] }
+ >(
tx ?? PostgresUse.PERSONS_WRITE,
query,
[
...personParams,
- ...distinctIds
- .slice()
- .reverse()
- .map(({ version }) => version),
- ...distinctIds
- .slice()
- .reverse()
- .map(({ distinctId }) => distinctId),
+ distinctIds.map(({ distinctId }) => distinctId),
+ distinctIds.map(({ version }) => version),
],
'insertPerson',
'warn'
)
- const person = this.toPerson(rows[0])
+
+ if (rows.length === 0) {
+ // A live row already owns this (team_id, uuid): a concurrent create or
+ // an existing person. Same outcome as a unique violation.
+ return {
+ success: false,
+ error: 'CreationConflict',
+ distinctIds: distinctIds.map((d) => d.distinctId),
+ }
+ }
+
+ const { distinct_id_rows: distinctIdRows, ...personRow } = rows[0]
+ const person = this.toPerson(personRow)
+
+ if (distinctIdRows.length < distinctIds.length) {
+ // A live mapping owns one of the distinct ids, so the create must not
+ // stand: a person row without that mapping would be unreachable by it
+ // and would block the key's future revival. Tombstoning what this
+ // statement wrote (a monotonic version bump, correct for revived rows
+ // too) restores the pre-insert state.
+ await this.postgres.query(
+ tx ?? PostgresUse.PERSONS_WRITE,
+ `WITH undone_distinct_ids AS (
+ UPDATE posthog_persondistinctid
+ SET is_deleted = true, version = COALESCE(version, 0) + 1
+ WHERE team_id = $2 AND id = ANY($1::bigint[]) AND is_deleted = false
+ )
+ UPDATE posthog_person
+ SET is_deleted = true,
+ version = COALESCE(version, 0) + 1,
+ properties = '{}'::jsonb,
+ properties_last_updated_at = '{}'::jsonb,
+ properties_last_operation = '{}'::jsonb
+ WHERE team_id = $2 AND id = $3 AND is_deleted = false`,
+ [distinctIdRows.map((row) => row.id), teamId, person.id],
+ 'undoInsertPerson'
+ )
+ return {
+ success: false,
+ error: 'CreationConflict',
+ distinctIds: distinctIds.map((d) => d.distinctId),
+ }
+ }
const kafkaMessages: PersonMessage[] = [generateKafkaPersonUpdateMessage(person)]
- for (const distinctId of distinctIds) {
+ for (const row of distinctIdRows) {
kafkaMessages.push({
output: PERSON_DISTINCT_IDS_OUTPUT,
value: Buffer.from(
JSON.stringify({
person_id: person.uuid,
team_id: teamId,
- distinct_id: distinctId.distinctId,
- version: distinctId.version,
+ distinct_id: row.distinct_id,
+ version: Number(row.version),
is_deleted: 0,
})
),
@@ -656,16 +728,6 @@ export class PostgresPersonRepository
created: true,
}
} catch (error) {
- // Handle constraint violation - another process created the person concurrently
- if (error instanceof Error && error.message.includes('unique constraint')) {
- // This is not of type CreatePersonResult?
- return {
- success: false,
- error: 'CreationConflict',
- distinctIds: distinctIds.map((d) => d.distinctId),
- }
- }
-
if (this.isPropertiesSizeConstraintViolation(error)) {
// For createPerson, we just log and reject since there's no existing person to update
personPropertiesSizeViolationCounter.inc({
@@ -691,6 +753,10 @@ export class PostgresPersonRepository
}
async deletePerson(person: InternalPerson, tx?: TransactionClient): Promise<PersonMessage[]> {
+ if (this.isTombstoneTeam(person.team_id)) {
+ return await this.tombstonePersons([person], tx)
+ }
+
let rows: { version: string }[] = []
try {
const result = await this.postgres.query<{ version: string }>(
@@ -702,8 +768,7 @@ export class PostgresPersonRepository
rows = result.rows
} catch (error) {
if (error.code === '40P01') {
- // Deadlock detected — assume someone else is deleting and skip.
- logger.warn('🔒', 'Deadlock detected — assume someone else is deleting and skip.', {
+ logger.warn('🔒', 'Deadlock detected — rolling back for the caller to retry.', {
team_id: person.team_id,
person_id: person.id,
})
@@ -715,11 +780,85 @@ export class PostgresPersonRepository
if (rows.length > 0) {
const [row] = rows
- kafkaMessages = [generateKafkaPersonUpdateMessage({ ...person, version: Number(row.version || 0) }, true)]
+ kafkaMessages = [
+ // The +100 outranks any version bump that landed between our stale read and the
+ // delete; keep in sync with delete_person in posthog/models/person/util.py.
+ generateKafkaPersonUpdateMessage(person, true, Number(row.version || 0) + 100),
+ ]
}
return kafkaMessages
}
+ /**
+ * Tombstone-mode delete: the row stays in place as the key's version floor, with the
+ * death version stamped atomically and the properties scrubbed.
+ *
+ * Runs under the merge's lifecycle marks, which exclude every concurrent identity
+ * mutation of these persons. The live-mapping guard on the stamp is therefore an
+ * invariant assertion rather than the primary defense: rows it finds mean an
+ * identity-mutation path skipped the mark claim. PersonTombstoneBlockedError feeds
+ * the same refresh-and-retry handling as the hard delete's FK violation.
+ */
+ private async tombstonePersons(persons: InternalPerson[], tx?: TransactionClient): Promise<PersonMessage[]> {
+ const teamId = persons[0].team_id
+ const personById = new Map(persons.map((person) => [person.id, person]))
+ const personIds = [...personById.keys()].sort((a, b) => (BigInt(a) < BigInt(b) ? -1 : 1))
+
+ try {
+ const live = await this.postgres.query<{ id: string }>(
+ tx ?? PostgresUse.PERSONS_WRITE,
+ `SELECT id FROM posthog_person
+ WHERE team_id = $1 AND id = ANY($2::bigint[]) AND is_deleted = false
+ ORDER BY id`,
+ [teamId, personIds],
+ 'tombstonePersonsPrecheck'
+ )
+ if (live.rows.length === 0) {
+ // Already tombstoned or gone — same outcome as an empty DELETE.
+ return []
+ }
+ const liveIds = live.rows.map((row) => row.id)
+
+ const { rows } = await this.postgres.query<{ id: string; version: string }>(
+ tx ?? PostgresUse.PERSONS_WRITE,
+ `UPDATE posthog_person p
+ SET is_deleted = true,
+ version = COALESCE(version, 0) + 1,
+ properties = '{}'::jsonb,
+ properties_last_updated_at = '{}'::jsonb,
+ properties_last_operation = '{}'::jsonb
+ WHERE team_id = $1 AND id = ANY($2::bigint[]) AND is_deleted = false
+ AND NOT EXISTS (
+ SELECT 1 FROM posthog_persondistinctid d
+ WHERE d.team_id = $1 AND d.person_id = p.id AND d.is_deleted = false
+ )
+ RETURNING id, version`,
+ [teamId, liveIds],
+ 'tombstonePersons'
+ )
+
+ if (rows.length < liveIds.length) {
+ throw new PersonTombstoneBlockedError('Live distinct ids still point at the person', teamId)
+ }
+
+ return rows.flatMap((row) => {
+ const person = personById.get(String(row.id))
+ if (!person) {
+ return []
+ }
+ return [generateKafkaPersonUpdateMessage({ ...person, properties: {} }, true, Number(row.version || 0))]
+ })
+ } catch (error) {
+ if (error.code === '40P01') {
+ logger.warn('🔒', 'Deadlock detected — rolling back for the caller to retry.', {
+ team_id: teamId,
+ person_ids: personIds,
+ })
+ }
+ throw error
+ }
+ }
+
async deletePersons(persons: InternalPerson[], tx?: TransactionClient): Promise<PersonMessage[]> {
if (persons.length === 0) {
return []
@@ -727,6 +866,10 @@ export class PostgresPersonRepository
// All persons in a folded merge belong to one team.
const teamId = persons[0].team_id
+ if (this.isTombstoneTeam(teamId)) {
+ return await this.tombstonePersons(persons, tx)
+ }
+
const personById = new Map(persons.map((person) => [person.id, person]))
// Postgres acquires the row locks in index scan order (btree scans sort
// the id keys ascending), not in array-parameter order, so concurrent
@@ -745,8 +888,7 @@ export class PostgresPersonRepository
rows = result.rows
} catch (error) {
if (error.code === '40P01') {
- // Deadlock detected — assume someone else is deleting and skip.
- logger.warn('🔒', 'Deadlock detected — assume someone else is deleting and skip.', {
+ logger.warn('🔒', 'Deadlock detected — rolling back for the caller to retry.', {
team_id: teamId,
person_ids: personIds,
})
@@ -759,10 +901,91 @@ export class PostgresPersonRepository
if (!person) {
return []
}
- return [generateKafkaPersonUpdateMessage({ ...person, version: Number(row.version || 0) }, true)]
+ return [
+ // The +100 outranks any version bump that landed between our stale read and the
+ // delete; keep in sync with delete_person in posthog/models/person/util.py.
+ generateKafkaPersonUpdateMessage(person, true, Number(row.version || 0) + 100),
+ ]
})
}
+ async claimLifecycleMarks(
+ opId: string,
+ teamId: number,
+ persons: LifecycleMarkPerson[],
+ tx?: TransactionClient
+ ): Promise<void> {
+ // Sorted claims keep the mark-index insert order deterministic across concurrent
+ // merges touching overlapping persons, so they block instead of deadlocking.
+ const sorted = [...persons].sort((a, b) => (BigInt(a.personId) < BigInt(b.personId) ? -1 : 1))
+ try {
+ await this.postgres.query(
+ tx ?? PostgresUse.PERSONS_WRITE,
+ `INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request, completed_at)
+ VALUES ($1, 'merge', $2, 'completed', $3::jsonb, now())`,
+ [opId, teamId, JSON.stringify({ source: 'ingestion-merge' })],
+ 'claimLifecycleOp'
+ )
+ await this.postgres.query(
+ tx ?? PostgresUse.PERSONS_WRITE,
+ `INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, ordinal, status)
+ SELECT $1, $2, u.person_id, u.person_uuid, u.role, u.ordinal, 'marked'
+ FROM unnest($3::bigint[], $4::uuid[], $5::text[], $6::int[]) AS u(person_id, person_uuid, role, ordinal)`,
+ [
+ opId,
+ teamId,
+ sorted.map((p) => p.personId),
+ sorted.map((p) => p.personUuid),
+ sorted.map((p) => p.role),
+ sorted.map((p) => p.ordinal ?? null),
+ ],
+ 'claimLifecycleMarks'
+ )
+ } catch (error) {
+ // The mark index turns "someone else holds this person" into a unique
+ // violation; a duplicate op_id means a concurrent delivery of the same event.
+ if (
+ error.code === '23505' &&
+ ['lifecycle_op_person_mark', 'lifecycle_op_pkey'].includes(error.constraint)
+ ) {
+ throw new PersonClaimedByLifecycleOpError(
+ 'Person is claimed by a concurrent lifecycle operation',
+ teamId
+ )
+ }
+ throw error
+ }
+ }
+
+ async releaseLifecycleMarks(opId: string, teamId: number, tx?: TransactionClient): Promise<void> {
+ // lifecycle_op_person rows go with the header via ON DELETE CASCADE. Running in
+ // the claiming transaction means committed state never contains this merge's
+ // marks: a concurrent claimant blocked on the index proceeds the moment we
+ // commit, and the delete saga's sweeper never sees an ingestion op to resume.
+ // The team and op-type guards keep a caller bug or op-id collision from ever
+ // deleting another team's op or a delete saga's.
+ await this.postgres.query(
+ tx ?? PostgresUse.PERSONS_WRITE,
+ `DELETE FROM lifecycle_op WHERE op_id = $1 AND team_id = $2 AND op_type = 'merge'`,
+ [opId, teamId],
+ 'releaseLifecycleMarks'
+ )
+ }
+
+ async isPersonLive(person: InternalPerson, tx?: TransactionClient): Promise<boolean> {
+ // Run this as its own statement after claimLifecycleMarks: a claim that waited
+ // on the mark index resumes with its original snapshot, so only a fresh
+ // statement reliably sees a tombstone committed during the wait. Under the mark
+ // the answer is then stable until commit.
+ const { rows } = await this.postgres.query(
+ tx ?? PostgresUse.PERSONS_WRITE,
+ 'SELECT 1 FROM posthog_person WHERE team_id = $1 AND id = $2 AND is_deleted = false',
+ [person.team_id, person.id],
+ 'isPersonLive'
+ )
+ return rows.length > 0
+ }
+
async addDistinctId(
person: InternalPerson,
distinctId: string,
@@ -771,21 +994,44 @@ export class PostgresPersonRepository
): Promise<PersonMessage[]> {
const insertResult = await this.postgres.query(
tx ?? PostgresUse.PERSONS_WRITE,
- // NOTE: Keep this in sync with the posthog_persondistinctid INSERT in `createPerson`
- 'INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version) VALUES ($1, $2, $3, $4) RETURNING *',
+ // NOTE: Keep this in sync with the posthog_persondistinctid INSERT in `createPerson`.
+ // A conflict with a tombstoned mapping is a revival: repoint it and continue the
+ // version counter above the death version. A live mapping is left untouched and
+ // reported as a conflict, matching the pre-tombstone unique violation.
+ `INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT (team_id, distinct_id) DO UPDATE SET
+ person_id = EXCLUDED.person_id,
+ version = COALESCE(posthog_persondistinctid.version, 0) + 1,
+ is_deleted = false
+ WHERE posthog_persondistinctid.is_deleted = true
+ RETURNING *`,
[distinctId, person.id, person.team_id, version],
'addDistinctId',
'warn'
)
- const { id, ...personDistinctIdCreated } = insertResult.rows[0] as PersonDistinctId
+ if (insertResult.rows.length === 0) {
+ throw new DistinctIdConflictError(
+ 'Distinct id is already owned by a live mapping',
+ person.team_id,
+ distinctId
+ )
+ }
+
+ const {
+ id,
+ is_deleted,
+ version: insertedVersion,
+ ...personDistinctIdCreated
+ } = insertResult.rows[0] as PersonDistinctId & { is_deleted: boolean }
return [
{
output: PERSON_DISTINCT_IDS_OUTPUT,
value: Buffer.from(
JSON.stringify({
...personDistinctIdCreated,
- version,
+ version: Number(insertedVersion || 0),
person_id: person.uuid,
is_deleted: 0,
})
@@ -810,6 +1056,7 @@ export class PostgresPersonRepository
FROM posthog_persondistinctid
WHERE person_id = $2
AND team_id = $3
+ AND is_deleted = false
ORDER BY id
FOR UPDATE SKIP LOCKED
LIMIT $4
@@ -824,6 +1071,7 @@ export class PostgresPersonRepository
SET person_id = $1, version = COALESCE(version, 0)::numeric + 1
WHERE person_id = $2
AND team_id = $3
+ AND is_deleted = false
RETURNING *
`
@@ -939,6 +1187,7 @@ export class PostgresPersonRepository
SET person_id = $1, version = COALESCE(version, 0)::numeric + 1
WHERE person_id = ANY($2::bigint[])
AND team_id = $3
+ AND is_deleted = false
RETURNING *`,
[target.id, sourceIds, target.team_id],
'updateDistinctIdPersonFold'
@@ -1177,14 +1426,14 @@ export class PostgresPersonRepository
update
).map(
(field, index) => `"${sanitizeSqlIdentifier(field)}" = $${index + 1}`
- )} WHERE id = $${idParamIndex} AND team_id = $${teamIdParamIndex}
+ )} WHERE id = $${idParamIndex} AND team_id = $${teamIdParamIndex} AND is_deleted = false
RETURNING ${PERSON_COLUMNS}, COALESCE(pg_column_size(properties)::bigint, 0::bigint) as properties_size_bytes
/* operation='updatePersonWithPropertiesSize',purpose='${tag || 'update'}' */`
// Potentially overriding values badly if there was an update to the person after computing updateValues above
const queryString = `UPDATE posthog_person SET version = ${versionString}, ${Object.keys(update).map(
(field, index) => `"${sanitizeSqlIdentifier(field)}" = $${index + 1}`
- )} WHERE id = $${idParamIndex} AND team_id = $${teamIdParamIndex}
+ )} WHERE id = $${idParamIndex} AND team_id = $${teamIdParamIndex} AND is_deleted = false
RETURNING ${PERSON_COLUMNS}
/* operation='updatePerson',purpose='${tag || 'update'}' */`
@@ -1264,7 +1513,7 @@ export class PostgresPersonRepository
is_identified = $4,
last_seen_at = $5,
version = COALESCE(version, 0)::numeric + 1
- WHERE team_id = $6 AND uuid = $7 AND version = $8
+ WHERE team_id = $6 AND uuid = $7 AND version = $8 AND is_deleted = false
RETURNING ${PERSON_COLUMNS}
`,
[
@@ -1390,7 +1639,7 @@ export class PostgresPersonRepository
$7::text[],
$8::text[]
) AS batch(batch_uuid, batch_team_id, new_properties, new_properties_last_updated_at, new_properties_last_operation, new_is_identified, new_created_at, new_last_seen_at)
- WHERE p.uuid = batch.batch_uuid AND p.team_id = batch.batch_team_id
+ WHERE p.uuid = batch.batch_uuid AND p.team_id = batch.batch_team_id AND p.is_deleted = false
RETURNING ${PERSON_COLUMNS_PREFIXED}
`,
[
diff --git a/nodejs/src/common/persons/repositories/raw-postgres-person-repository.ts b/nodejs/src/common/persons/repositories/raw-postgres-person-repository.ts
index 180e98996d6e..3be9e2c7a342 100644
--- a/nodejs/src/common/persons/repositories/raw-postgres-person-repository.ts
+++ b/nodejs/src/common/persons/repositories/raw-postgres-person-repository.ts
@@ -14,7 +14,7 @@ import {
TeamId,
} from '~/types'
-import { InternalPersonWithDistinctId } from './person-repository'
+import { InternalPersonWithDistinctId, LifecycleMarkPerson } from './person-repository'
export interface RawPostgresPersonRepository {
fetchPerson(
@@ -60,6 +60,20 @@ export interface RawPostgresPersonRepository {
/** Batched deletePerson for folded merges; all persons must belong to one team. */
deletePersons(persons: InternalPerson[], tx?: TransactionClient): Promise<PersonMessage[]>
+ /** See PersonRepository.claimLifecycleMarks. */
+ claimLifecycleMarks(
+ opId: string,
+ teamId: number,
+ persons: LifecycleMarkPerson[],
+ tx?: TransactionClient
+ ): Promise<void>
+
+ /** See PersonRepository.releaseLifecycleMarks. */
+ releaseLifecycleMarks(opId: string, teamId: number, tx?: TransactionClient): Promise<void>
+
+ /** See PersonRepository.isPersonLive. */
+ isPersonLive(person: InternalPerson, tx?: TransactionClient): Promise<boolean>
+
addDistinctId(
person: InternalPerson,
distinctId: string,
diff --git a/nodejs/src/common/utils/db/utils.ts b/nodejs/src/common/utils/db/utils.ts
index eccec2b8895f..119b1f0f41dd 100644
--- a/nodejs/src/common/utils/db/utils.ts
+++ b/nodejs/src/common/utils/db/utils.ts
@@ -135,7 +135,20 @@ export function personInitialAndUTMProperties(properties: Properties): Propertie
return properties
}
-export function generateKafkaPersonUpdateMessage(person: InternalPerson, isDeleted = false): PersonMessage {
+// Deletion call sites own the version they emit (the +100 fudge for hard deletes,
+// the exact stamped death version for tombstones), so a deletion must state it
+// explicitly — a stale person.version can never become a no-headroom death row.
+export function generateKafkaPersonUpdateMessage(person: InternalPerson, isDeleted?: false): PersonMessage
+export function generateKafkaPersonUpdateMessage(
+ person: InternalPerson,
+ isDeleted: true,
+ deletedVersion: number
+): PersonMessage
+export function generateKafkaPersonUpdateMessage(
+ person: InternalPerson,
+ isDeleted = false,
+ deletedVersion?: number
+): PersonMessage {
return {
output: PERSONS_OUTPUT,
value: Buffer.from(
@@ -146,7 +159,7 @@ export function generateKafkaPersonUpdateMessage(person: InternalPerson, isDelet
team_id: person.team_id,
is_identified: Number(person.is_identified),
is_deleted: Number(isDeleted),
- version: person.version + (isDeleted ? 100 : 0), // keep in sync with delete_person in posthog/models/person/util.py
+ version: isDeleted ? deletedVersion : person.version,
last_seen_at: person.last_seen_at
? castTimestampOrNow(person.last_seen_at, TimestampFormat.ClickHouseSecondPrecision)
: null,
diff --git a/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts b/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts
index 9c9ecd4f762f..20d57cb33483 100644
--- a/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts
+++ b/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts
@@ -128,6 +128,9 @@ describe('BatchWritingPersonStore', () => {
fetchPersonsForUpdateByDistinctIds: jest.fn().mockResolvedValue([]),
fetchDistinctIdsForPersons: jest.fn().mockResolvedValue({}),
deletePersons: jest.fn().mockResolvedValue([]),
+ claimLifecycleMarks: jest.fn().mockResolvedValue(undefined),
+ releaseLifecycleMarks: jest.fn().mockResolvedValue(undefined),
+ isPersonLive: jest.fn().mockResolvedValue(true),
updateCohortsAndFeatureFlagsForMergeBatch: jest.fn().mockResolvedValue(undefined),
createPerson: jest.fn().mockResolvedValue([person, []]),
updatePerson: jest.fn().mockResolvedValue([person, [], false]),
@@ -166,6 +169,9 @@ describe('BatchWritingPersonStore', () => {
updatePerson: jest.fn().mockResolvedValue([person, [], false]),
deletePerson: jest.fn().mockResolvedValue([]),
deletePersons: jest.fn().mockResolvedValue([]),
+ claimLifecycleMarks: jest.fn().mockResolvedValue(undefined),
+ releaseLifecycleMarks: jest.fn().mockResolvedValue(undefined),
+ isPersonLive: jest.fn().mockResolvedValue(true),
addDistinctId: jest.fn().mockResolvedValue([]),
moveDistinctIds: jest.fn().mockResolvedValue({ success: true, messages: [], distinctIdsMoved: [] }),
moveDistinctIdsFromPersons: jest
diff --git a/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts b/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
index c556496b54d3..e71d974ee0a4 100644
--- a/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
+++ b/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
@@ -23,6 +23,7 @@ import { isFilteredPersonUpdateProperty } from '~/common/persons/person-property
import { PersonUpdate, fromInternalPerson, toInternalPerson } from '~/common/persons/person-update-batch'
import {
InternalPersonWithDistinctId,
+ LifecycleMarkPerson,
PersonMessage,
PersonPropertiesSizeViolationError,
PersonRepository,
@@ -54,6 +55,9 @@ type MethodName =
| 'updatePersonForMerge'
| 'deletePerson'
| 'deletePersons'
+ | 'claimLifecycleMarks'
+ | 'releaseLifecycleMarks'
+ | 'isPersonLive'
| 'addDistinctId'
| 'moveDistinctIds'
| 'moveDistinctIdsFromPersons'
@@ -1399,6 +1403,32 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
return response
}
+ async claimLifecycleMarks(
+ opId: string,
+ teamId: number,
+ persons: LifecycleMarkPerson[],
+ distinctId: string,
+ tx?: PersonRepositoryTransaction
+ ): Promise<void> {
+ this.incrementDatabaseOperation('claimLifecycleMarks', distinctId)
+ return await (tx || this.personRepository).claimLifecycleMarks(opId, teamId, persons)
+ }
+
+ async releaseLifecycleMarks(
+ opId: string,
+ teamId: number,
+ distinctId: string,
+ tx?: PersonRepositoryTransaction
+ ): Promise<void> {
+ this.incrementDatabaseOperation('releaseLifecycleMarks', distinctId)
+ return await (tx || this.personRepository).releaseLifecycleMarks(opId, teamId)
+ }
+
+ async isPersonLive(person: InternalPerson, distinctId: string, tx?: PersonRepositoryTransaction): Promise<boolean> {
+ this.incrementDatabaseOperation('isPersonLive', distinctId)
+ return await (tx || this.personRepository).isPersonLive(person)
+ }
+
async fetchPersonsForUpdateByDistinctIds(
teamId: Team['id'],
distinctIds: string[],
diff --git a/nodejs/src/ingestion/common/persons/person-context.ts b/nodejs/src/ingestion/common/persons/person-context.ts
index 2106a84e64e0..32f765b9de17 100644
--- a/nodejs/src/ingestion/common/persons/person-context.ts
+++ b/nodejs/src/ingestion/common/persons/person-context.ts
@@ -84,7 +84,9 @@ export class PersonContext {
writesDisabled: false,
},
/** Fold plan shared by this event's consecutive $identify run; see person-merge-fold.ts. */
- public readonly mergeFoldPlan?: MergeFoldPlan
+ public readonly mergeFoldPlan?: MergeFoldPlan,
+ /** New-world merge behavior for this team: lifecycle-mark claims plus tombstone deletes. */
+ public readonly mergeTombstoneEnabled: boolean = false
) {
this.eventProperties = event.properties!
this.personlessRollout = {
diff --git a/nodejs/src/ingestion/common/persons/person-merge-service.ts b/nodejs/src/ingestion/common/persons/person-merge-service.ts
index 8084e4101e10..75464a8a5f09 100644
--- a/nodejs/src/ingestion/common/persons/person-merge-service.ts
+++ b/nodejs/src/ingestion/common/persons/person-merge-service.ts
@@ -4,6 +4,10 @@ import { Counter, Histogram } from 'prom-client'
import { personMergeFailureCounter } from '~/common/persons/metrics'
import { PersonMessage } from '~/common/persons/person-message'
import { isDistinctIdIllegal } from '~/common/persons/person-utils'
+import {
+ PersonClaimedByLifecycleOpError,
+ PersonTombstoneBlockedError,
+} from '~/common/persons/repositories/person-repository'
import { timeoutGuard } from '~/common/utils/db/utils'
import { logger } from '~/common/utils/logger'
import { captureException } from '~/common/utils/posthog'
@@ -26,6 +30,7 @@ import {
mergeSuccess,
} from './person-merge-types'
import { applyEventPropertyUpdates, computeEventPropertyUpdates } from './person-update'
+import { lifecycleOpIdFromEvent } from './person-uuid'
import { PersonsStoreTransactionForBatch } from './persons-store-for-batch'
export const mergeFinalFailuresCounter = new Counter({
@@ -62,6 +67,12 @@ export const mergeFoldSizeHistogram = new Histogram({
buckets: [2, 5, 10, 25, 50, 100, 250, 500],
})
+export const mergeClaimDroppedCounter = new Counter({
+ name: 'person_merge_claim_dropped_total',
+ help: 'Merges dropped because another lifecycle operation held a person through every retry.',
+ labelNames: ['call'],
+})
+
export const mergeDistinctIdOverrideCounter = new Counter({
name: 'person_merge_distinct_id_override_total',
help: 'Distinct id mapping rows written during merges, split by whether their version writes a ClickHouse override row.',
@@ -79,7 +90,11 @@ function foldFallbackReason(error: unknown): 'limit' | 'conflict' | 'deadlock' |
if (error instanceof MergeFoldLimitError) {
return 'limit'
}
- if (error instanceof MergeFoldConflictError) {
+ if (
+ error instanceof MergeFoldConflictError ||
+ error instanceof PersonTombstoneBlockedError ||
+ error instanceof PersonClaimedByLifecycleOpError
+ ) {
return 'conflict'
}
if ((error as { code?: string })?.code === '40P01') {
@@ -141,6 +156,31 @@ export class PersonMergeService {
)
}
} catch (e) {
+ if (e instanceof PersonClaimedByLifecycleOpError) {
+ // Expected contention, not a failure: another lifecycle operation held one of
+ // the persons through every retry. Drop the merge with a warning; the event's
+ // property updates still apply to whatever the distinct ids resolve to next.
+ // The counter is the rollout's drop-rate signal; the warning is debounced by
+ // the standard limiter so a long-held claim cannot flood the warnings topic.
+ mergeClaimDroppedCounter.labels({ call: this.context.event.event }).inc()
+ await emitIngestionWarning(this.context.outputs, this.context.team.id, {
+ type: 'merge_race_condition',
+ details: {
+ distinctId: this.context.distinctId,
+ eventUuid: this.context.event.uuid,
+ sourcePersonDistinctId: String(
+ this.context.eventProperties['$anon_distinct_id'] ?? this.context.eventProperties['alias']
+ ),
+ targetPersonDistinctId: this.context.distinctId,
+ },
+ pipelineStep: 'person-merge',
+ })
+ logger.warn('🤔', 'merge dropped: person claimed by a concurrent lifecycle operation', {
+ team_id: this.context.team.id,
+ distinctId: this.context.distinctId,
+ })
+ return mergeSuccess(undefined, Promise.resolve(), true)
+ }
captureException(e, {
tags: { team_id: this.context.team.id, pipeline_step: 'processPersonsStep' },
extra: {
@@ -265,7 +305,29 @@ export class PersonMergeService {
})()
this.discardOverrideCounts()
+ const lifecycleOpId = lifecycleOpIdFromEvent(this.context.team.id, this.context.event.uuid)
const result = await this.context.personStore.inTransaction('mergeDistinctIds-OneExists', async (tx) => {
+ // New-world merges claim the person's lifecycle mark, which keeps a concurrent
+ // tombstone from landing between this check and the distinct id insert (an
+ // orphaned mapping); old-world merges rely on the delete's FK violation instead.
+ if (this.context.mergeTombstoneEnabled) {
+ await tx.claimLifecycleMarks(
+ lifecycleOpId,
+ existingPerson.team_id,
+ [{ personId: existingPerson.id, personUuid: existingPerson.uuid, role: 'target' }],
+ this.context.distinctId
+ )
+ if (!(await tx.isPersonLive(existingPerson, this.context.distinctId))) {
+ // Purge the stale cache entries so the promiseRetry attempt
+ // re-fetches from Postgres instead of replaying the cached,
+ // now-tombstoned person into the same failure.
+ this.context.personStore.removeDistinctIdFromCache(teamId, otherPersonDistinctId)
+ this.context.personStore.removeDistinctIdFromCache(teamId, mergeIntoDistinctId)
+ throw new TargetPersonNotFoundError(
+ 'Person was deleted before the merge could add a distinct id'
+ )
+ }
+ }
// See comment above about `distinctIdVersion`
const insertedDistinctId = this.context.personlessRollout.writesDisabled
? false
@@ -275,6 +337,9 @@ export class PersonMergeService {
const kafkaMessages = await tx.addDistinctId(existingPerson, distinctIdToAdd, distinctIdVersion)
await this.context.produceMessages(kafkaMessages)
+ if (this.context.mergeTombstoneEnabled) {
+ await tx.releaseLifecycleMarks(lifecycleOpId, this.context.team.id, this.context.distinctId)
+ }
return mergeSuccess(existingPerson, Promise.resolve(), true)
})
this.flushOverrideCounts()
@@ -576,9 +641,31 @@ export class PersonMergeService {
const currentTarget = target
this.discardOverrideCounts()
+ const lifecycleOpId = lifecycleOpIdFromEvent(this.context.team.id, this.context.event.uuid)
const [mergedPerson, kafkaMessages] = await this.context.personStore.inTransaction(
'mergePeopleFold',
async (tx) => {
+ // New-world folds claim every person, keeping concurrent lifecycle operations
+ // (other merges, the delete saga) off the targets and sources until commit.
+ if (this.context.mergeTombstoneEnabled) {
+ await tx.claimLifecycleMarks(
+ lifecycleOpId,
+ currentTarget.team_id,
+ [
+ { personId: currentTarget.id, personUuid: currentTarget.uuid, role: 'target' },
+ ...mergeSources.map((source, index) => ({
+ personId: source.id,
+ personUuid: source.uuid,
+ role: 'source' as const,
+ ordinal: index,
+ })),
+ ],
+ this.context.distinctId
+ )
+ if (!(await tx.isPersonLive(currentTarget, this.context.distinctId))) {
+ throw new MergeFoldConflictError('Fold target was deleted concurrently')
+ }
+ }
const expectedMoveCount = await this.assertFoldSourcesWithinMoveBounds(tx, mergeSources)
let person = currentTarget
@@ -635,6 +722,9 @@ export class PersonMergeService {
deleteMessages = await tx.deletePersons(mergeSources, this.context.distinctId)
}
+ if (this.context.mergeTombstoneEnabled) {
+ await tx.releaseLifecycleMarks(lifecycleOpId, this.context.team.id, this.context.distinctId)
+ }
return [person, [...updateMessages, ...moveResult.messages, ...addMessages, ...deleteMessages]]
}
)
@@ -774,9 +864,43 @@ export class PersonMergeService {
.inc()
this.discardOverrideCounts()
+ const lifecycleOpId = lifecycleOpIdFromEvent(this.context.team.id, this.context.event.uuid)
const [mergedPerson, kafkaMessages] = await this.context.personStore.inTransaction(
'mergePeople',
async (tx) => {
+ // New-world merges claim both persons in the lifecycle mark table: at
+ // most one live operation (merge or delete saga) may hold a person, so
+ // neither can be tombstoned under this transaction. The marks say
+ // nothing about tombstones committed before the claim, so assert both
+ // persons are still live while holding them. Liveness checks are
+ // separate statements because a claim that waited on the mark index
+ // resumes with a stale snapshot.
+ if (this.context.mergeTombstoneEnabled) {
+ await tx.claimLifecycleMarks(
+ lifecycleOpId,
+ currentTargetPerson.team_id,
+ [
+ {
+ personId: currentTargetPerson.id,
+ personUuid: currentTargetPerson.uuid,
+ role: 'target',
+ },
+ {
+ personId: currentSourcePerson.id,
+ personUuid: currentSourcePerson.uuid,
+ role: 'source',
+ ordinal: 0,
+ },
+ ],
+ this.context.distinctId
+ )
+ if (!(await tx.isPersonLive(currentTargetPerson, this.context.distinctId))) {
+ throw new TargetPersonNotFoundError('Target person was deleted concurrently')
+ }
+ if (!(await tx.isPersonLive(currentSourcePerson, this.context.distinctId))) {
+ throw new SourcePersonNotFoundError('Source person was deleted concurrently')
+ }
+ }
const [person, updatePersonMessages] = await tx.updatePersonForMerge(
currentTargetPerson,
{
@@ -824,6 +948,9 @@ export class PersonMergeService {
)
const deletePersonMessages = await tx.deletePerson(currentSourcePerson, this.context.distinctId)
+ if (this.context.mergeTombstoneEnabled) {
+ await tx.releaseLifecycleMarks(lifecycleOpId, this.context.team.id, this.context.distinctId)
+ }
return [person, [...updatePersonMessages, ...allDistinctIdMessages, ...deletePersonMessages]]
}
)
@@ -853,11 +980,11 @@ export class PersonMergeService {
return mergeError(error)
} else if (error instanceof PersonMergeLimitExceededError) {
return mergeError(error)
- } else if (error.code === '23503') {
- // Foreign key constraint violation when attempting to delete the source person.
- // This occurs when a concurrent merge operation adds a distinct ID to the source person
- // after we've already moved the distinct IDs we knew about, but before the DELETE executes.
- // The retry mechanism will:
+ } else if (error.code === '23503' || error instanceof PersonTombstoneBlockedError) {
+ // A concurrent merge added a distinct ID to the source person after we've already
+ // moved the distinct IDs we knew about, but before the delete executed — surfaced
+ // as a foreign key violation by the hard delete, or as PersonTombstoneBlockedError
+ // by the tombstone's live-mapping guard. The retry mechanism will:
// 1. Refresh the source person data to see all distinct IDs (including newly added ones)
// 2. Move ALL distinct IDs to the target person
// 3. Successfully delete the now-empty source person
diff --git a/nodejs/src/ingestion/common/persons/person-uuid.ts b/nodejs/src/ingestion/common/persons/person-uuid.ts
index 78ff92eaca8e..e3d227966963 100644
--- a/nodejs/src/ingestion/common/persons/person-uuid.ts
+++ b/nodejs/src/ingestion/common/persons/person-uuid.ts
@@ -4,7 +4,17 @@ import { parse as parseUuid, v5 as uuidv5 } from 'uuid'
// that must be used to deterministrically generate UUIDv5s for Person rows.
const PERSON_UUIDV5_NAMESPACE = parseUuid('932979b4-65c3-4424-8467-0b66ec27bc22')
+// Another randomly generated UUIDv4, namespacing lifecycle op ids.
+const LIFECYCLE_OP_UUIDV5_NAMESPACE = parseUuid('943363e7-16d0-44e1-8c51-ba2c35f6e6a0')
+
export function uuidFromDistinctId(teamId: number, distinctId: string): string {
// Deterministcally create a UUIDv5 based on the (team_id, distinct_id) pair.
return uuidv5(`${teamId}:${distinctId}`, PERSON_UUIDV5_NAMESPACE)
}
+
+// Lifecycle op ids are deterministic per (team_id, event uuid): concurrent deliveries of
+// the same event collide on the op PK, while a client-pinned event uuid cannot address
+// another team's ops.
+export function lifecycleOpIdFromEvent(teamId: number, eventUuid: string): string {
+ return uuidv5(`${teamId}:${eventUuid}`, LIFECYCLE_OP_UUIDV5_NAMESPACE)
+}
diff --git a/nodejs/src/ingestion/common/persons/persons-store-for-batch.ts b/nodejs/src/ingestion/common/persons/persons-store-for-batch.ts
index a423de3ae7d8..d75df613d459 100644
--- a/nodejs/src/ingestion/common/persons/persons-store-for-batch.ts
+++ b/nodejs/src/ingestion/common/persons/persons-store-for-batch.ts
@@ -1,7 +1,7 @@
import { DateTime } from 'luxon'
import { PersonMessage } from '~/common/persons/person-message'
-import { InternalPersonWithDistinctId } from '~/common/persons/repositories/person-repository'
+import { InternalPersonWithDistinctId, LifecycleMarkPerson } from '~/common/persons/repositories/person-repository'
import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'
import { CreatePersonResult, MoveDistinctIdsResult } from '~/common/utils/db/db'
import { Properties } from '~/plugin-scaffold'
@@ -41,6 +41,15 @@ export interface PersonsStoreTransactionForBatch {
deletePerson(person: InternalPerson, distinctId: string): Promise<PersonMessage[]>
+ /** Claims the persons in the lifecycle mark table until commit; conflicts throw. */
+ claimLifecycleMarks(opId: string, teamId: number, persons: LifecycleMarkPerson[], distinctId: string): Promise<void>
+
+ /** Releases a merge's lifecycle marks; same transaction as the claim. */
+ releaseLifecycleMarks(opId: string, teamId: number, distinctId: string): Promise<void>
+
+ /** Whether the person is live; only meaningful while holding its lifecycle mark. */
+ isPersonLive(person: InternalPerson, distinctId: string): Promise<boolean>
+
addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]>
moveDistinctIds(
@@ -233,6 +242,23 @@ class BatchBoundPersonsStoreTransaction implements PersonsStoreTransactionForBat
return this.tx.deletePerson(person, distinctId)
}
+ claimLifecycleMarks(
+ opId: string,
+ teamId: number,
+ persons: LifecycleMarkPerson[],
+ distinctId: string
+ ): Promise<void> {
+ return this.tx.claimLifecycleMarks(opId, teamId, persons, distinctId)
+ }
+
+ releaseLifecycleMarks(opId: string, teamId: number, distinctId: string): Promise<void> {
+ return this.tx.releaseLifecycleMarks(opId, teamId, distinctId)
+ }
+
+ isPersonLive(person: InternalPerson, distinctId: string): Promise<boolean> {
+ return this.tx.isPersonLive(person, distinctId)
+ }
+
addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]> {
return this.tx.addDistinctId(person, distinctId, version, this.batchId)
}
@@ -450,6 +476,29 @@ export class BatchBoundPersonsStore implements PersonsStoreForBatch {
return this.store.deletePerson(person, distinctId, tx)
}
+ claimLifecycleMarks(
+ opId: string,
+ teamId: number,
+ persons: LifecycleMarkPerson[],
+ distinctId: string,
+ tx?: PersonRepositoryTransaction
+ ): Promise<void> {
+ return this.store.claimLifecycleMarks(opId, teamId, persons, distinctId, tx)
+ }
+
+ releaseLifecycleMarks(
+ opId: string,
+ teamId: number,
+ distinctId: string,
+ tx?: PersonRepositoryTransaction
+ ): Promise<void> {
+ return this.store.releaseLifecycleMarks(opId, teamId, distinctId, tx)
+ }
+
+ isPersonLive(person: InternalPerson, distinctId: string, tx?: PersonRepositoryTransaction): Promise<boolean> {
+ return this.store.isPersonLive(person, distinctId, tx)
+ }
+
updateCohortsAndFeatureFlagsForMerge(
teamID: Team['id'],
sourcePersonID: InternalPerson['id'],
diff --git a/nodejs/src/ingestion/common/persons/persons-store-transaction.ts b/nodejs/src/ingestion/common/persons/persons-store-transaction.ts
index 189f3a135b3d..412c39bf8788 100644
--- a/nodejs/src/ingestion/common/persons/persons-store-transaction.ts
+++ b/nodejs/src/ingestion/common/persons/persons-store-transaction.ts
@@ -1,6 +1,7 @@
import { DateTime } from 'luxon'
import { PersonMessage } from '~/common/persons/person-message'
+import { LifecycleMarkPerson } from '~/common/persons/repositories/person-repository'
import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'
import { CreatePersonResult, MoveDistinctIdsResult } from '~/common/utils/db/db'
import { Properties } from '~/plugin-scaffold'
@@ -81,6 +82,23 @@ export class PersonsStoreTransaction {
return await this.store.deletePerson(person, distinctId, this.tx)
}
+ async claimLifecycleMarks(
+ opId: string,
+ teamId: number,
+ persons: LifecycleMarkPerson[],
+ distinctId: string
+ ): Promise<void> {
+ return await this.store.claimLifecycleMarks(opId, teamId, persons, distinctId, this.tx)
+ }
+
+ async releaseLifecycleMarks(opId: string, teamId: number, distinctId: string): Promise<void> {
+ return await this.store.releaseLifecycleMarks(opId, teamId, distinctId, this.tx)
+ }
+
+ async isPersonLive(person: InternalPerson, distinctId: string): Promise<boolean> {
+ return await this.store.isPersonLive(person, distinctId, this.tx)
+ }
+
async addDistinctId(
person: InternalPerson,
distinctId: string,
diff --git a/nodejs/src/ingestion/common/persons/persons-store.ts b/nodejs/src/ingestion/common/persons/persons-store.ts
index 7ecefdddeefe..6afceba0a0d9 100644
--- a/nodejs/src/ingestion/common/persons/persons-store.ts
+++ b/nodejs/src/ingestion/common/persons/persons-store.ts
@@ -1,7 +1,7 @@
import { DateTime } from 'luxon'
import { PersonMessage } from '~/common/persons/person-message'
-import { InternalPersonWithDistinctId } from '~/common/persons/repositories/person-repository'
+import { InternalPersonWithDistinctId, LifecycleMarkPerson } from '~/common/persons/repositories/person-repository'
import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'
import { CreatePersonResult, MoveDistinctIdsResult } from '~/common/utils/db/db'
import { BatchWritingStore } from '~/ingestion/common/stores/batch-writing-store'
@@ -95,6 +95,29 @@ export interface PersonsStore extends BatchWritingStore<FlushResult> {
*/
deletePerson(person: InternalPerson, distinctId: string, tx?: PersonRepositoryTransaction): Promise<PersonMessage[]>
+ /**
+ * Claims the persons in the lifecycle mark table for a merge; at most one live
+ * operation may hold a person. Held until the transaction commits.
+ */
+ claimLifecycleMarks(
+ opId: string,
+ teamId: number,
+ persons: LifecycleMarkPerson[],
+ distinctId: string,
+ tx?: PersonRepositoryTransaction
+ ): Promise<void>
+
+ /** Releases a merge's lifecycle marks; same transaction as the claim. */
+ releaseLifecycleMarks(
+ opId: string,
+ teamId: number,
+ distinctId: string,
+ tx?: PersonRepositoryTransaction
+ ): Promise<void>
+
+ /** Whether the person is live; only meaningful while holding its lifecycle mark. */
+ isPersonLive(person: InternalPerson, distinctId: string, tx?: PersonRepositoryTransaction): Promise<boolean>
+
/**
* Adds a distinct ID to a person
*/
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.ts
index 1fb63353a9c9..7354ec63c3c2 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
@@ -12,6 +12,8 @@ export interface EventPipelineRunnerOptions {
PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: string
/** Teams with personless-table writes and is_merged reads disabled (implies always-v1): '*' for all, '' to disable, or comma-separated team IDs */
PERSONLESS_WRITES_DISABLED_TEAMS: string
+ /** Teams whose merges run new-world: lifecycle-mark claims plus tombstone deletes: '*' for all, '' to disable, or comma-separated team IDs */
+ PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST: string
PERSON_JSONB_SIZE_ESTIMATE_ENABLE: number
PERSON_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.ts
index fbcced96ea6d..02946e2407a1 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
@@ -47,6 +47,7 @@ export function createProcessPersonsStep<TInput extends ProcessPersonsInput>(
}
const isMergeAlwaysV1Team = buildIntegerMatcher(options.PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST, true)
const isPersonlessWritesDisabledTeam = buildIntegerMatcher(options.PERSONLESS_WRITES_DISABLED_TEAMS, true)
+ const isMergeTombstoneTeam = buildIntegerMatcher(options.PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST, true)
return async function processPersonsStep(
input: TInput
@@ -76,7 +77,8 @@ export function createProcessPersonsStep<TInput extends ProcessPersonsInput>(
mergeAlwaysV1: isMergeAlwaysV1Team(team.id),
writesDisabled: isPersonlessWritesDisabledTeam(team.id),
},
- input.mergeFold.type === 'planned' ? input.mergeFold.plan : undefined
+ input.mergeFold.type === 'planned' ? input.mergeFold.plan : undefined,
+ isMergeTombstoneTeam(team.id)
)
const processor = new PersonEventProcessor(
diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.ts
index 46ff382e84a7..a020c1710fb0 100644
--- a/nodejs/src/ingestion/config.ts
+++ b/nodejs/src/ingestion/config.ts
@@ -173,6 +173,13 @@ export type IngestionConsumerConfig = {
// 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
+ // Tombstone rollout of the person-deletion-gaps RFC: for these teams, a merge tombstones the
+ // source person row (is_deleted = true, version stamped in the same transaction, properties
+ // scrubbed) instead of hard-deleting it, and the ClickHouse death row carries that exact
+ // version instead of the version + 100 fudge. The row keeps the key's version counter so a
+ // recreated person revives above its own tombstone. Comma-separated team IDs, or '*' for all
+ // teams; empty means no teams.
+ PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST: string
// Steps 3+4 of the personless-table removal RFC: for these teams, stop writing
// posthog_personlessdistinctid (chunk inserts, single-row fallback, merge upserts) and stop
// reading the is_merged race hint. Implies always-v1 merge versioning for the team, so the
@@ -323,6 +330,7 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {
PERSON_MERGE_FOLD_ENABLED: false,
PERSON_MERGE_FOLD_TEAM_ALLOWLIST: '*',
PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: '',
+ PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST: '',
PERSONLESS_WRITES_DISABLED_TEAMS: '',
// Group batch writing config
diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.ts
index 1fab5e16297e..699a49ec86b1 100644
--- a/nodejs/src/ingestion/ingestion-consumer.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.ts
@@ -293,6 +293,7 @@ export class IngestionConsumer {
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,
PERSONLESS_WRITES_DISABLED_TEAMS: this.config.PERSONLESS_WRITES_DISABLED_TEAMS,
+ PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST: this.config.PERSON_MERGE_TOMBSTONE_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.ts
index a38fd232409b..b7b7ef316d0e 100644
--- a/nodejs/src/servers/ingestion-api-server.ts
+++ b/nodejs/src/servers/ingestion-api-server.ts
@@ -247,6 +247,7 @@ export class IngestionApiServer implements NodeServer {
const postgresPersonRepository = new PostgresPersonRepository(this.postgres, {
calculatePropertiesSize: this.config.PERSON_UPDATE_CALCULATE_PROPERTIES_SIZE,
+ personMergeTombstoneTeamAllowlist: this.config.PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST,
})
const personRepository = buildPersonRepository(
personhogClient,
@@ -400,6 +401,7 @@ export class IngestionApiServer implements NodeServer {
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,
PERSONLESS_WRITES_DISABLED_TEAMS: this.config.PERSONLESS_WRITES_DISABLED_TEAMS,
+ PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST: this.config.PERSON_MERGE_TOMBSTONE_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-general-server.ts b/nodejs/src/servers/ingestion-general-server.ts
index 8bce90d912bd..f40573122ea4 100644
--- a/nodejs/src/servers/ingestion-general-server.ts
+++ b/nodejs/src/servers/ingestion-general-server.ts
@@ -219,6 +219,7 @@ export class IngestionGeneralServer implements NodeServer {
const postgresPersonRepository = new PostgresPersonRepository(this.postgres, {
calculatePropertiesSize: this.config.PERSON_UPDATE_CALCULATE_PROPERTIES_SIZE,
+ personMergeTombstoneTeamAllowlist: this.config.PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST,
})
const personRepository = buildPersonRepository(
personhogClient,
diff --git a/nodejs/tests/helpers/ingestion-e2e.ts b/nodejs/tests/helpers/ingestion-e2e.ts
index ee3b02340979..2d0159ae2793 100644
--- a/nodejs/tests/helpers/ingestion-e2e.ts
+++ b/nodejs/tests/helpers/ingestion-e2e.ts
@@ -425,6 +425,7 @@ export async function createIngestionTestInfra(
const postgresGroupRepository = new PostgresGroupRepository(postgres)
const postgresPersonRepository = new PostgresPersonRepository(postgres, {
calculatePropertiesSize: serverConfig.PERSON_UPDATE_CALCULATE_PROPERTIES_SIZE,
+ personMergeTombstoneTeamAllowlist: serverConfig.PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST,
})
const personRepository = buildPersonRepository(
personhogClient,
diff --git a/nodejs/tests/helpers/sql.ts b/nodejs/tests/helpers/sql.ts
index c7f18c8f4fb0..6da9f804b54e 100644
--- a/nodejs/tests/helpers/sql.ts
+++ b/nodejs/tests/helpers/sql.ts
@@ -476,7 +476,9 @@ export const createOrganizationMembership = async (pg: PostgresRouter, organizat
}
export async function fetchPostgresPersons(postgres: PostgresRouter, teamId: number) {
- const query = `SELECT ${PERSON_COLUMNS} FROM posthog_person WHERE team_id = ${teamId} ORDER BY id`
+ // Live persons only, matching production reads: in tombstone mode a merged-away
+ // source keeps its row with is_deleted = true.
+ const query = `SELECT ${PERSON_COLUMNS} FROM posthog_person WHERE team_id = ${teamId} AND is_deleted = false ORDER BY id`
return (await postgres.query(PostgresUse.PERSONS_READ, query, undefined, 'persons')).rows.map(
// NOTE: we map to update some values here to maintain
// compatibility with `hub.fetchPersons`.
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.ts
index f0b80ca7152d..4bdbd25af699 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
@@ -56,6 +56,7 @@ describe('createProcessPersonsStep', () => {
PERSON_MERGE_FOLD_TEAM_ALLOWLIST: '*',
PERSON_MERGE_ALWAYS_V1_TEAM_ALLOWLIST: '',
PERSONLESS_WRITES_DISABLED_TEAMS: '',
+ PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST: '',
PERSON_JSONB_SIZE_ESTIMATE_ENABLE: 0,
PERSON_PROPERTIES_UPDATE_ALL: false,
FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: '*',
diff --git a/nodejs/tests/ingestion/ingestion-e2e.test.ts b/nodejs/tests/ingestion/ingestion-e2e.test.ts
index 2d5341389e7e..1965aaec24e4 100644
--- a/nodejs/tests/ingestion/ingestion-e2e.test.ts
+++ b/nodejs/tests/ingestion/ingestion-e2e.test.ts
@@ -38,10 +38,13 @@ jest.mock('~/common/utils/logger')
// and one with them all on, keeping CI cost flat while both modes stay fully
// covered. Batched group updates default to on, so the off arm pins them off
// to keep the individual CAS flush path (still the fallback) e2e-covered.
+// Merge-source tombstoning rides the on arm, so both the hard-delete and the
+// tombstone delete run the full suite.
describe.each([
{
PERSONS_PREFETCH_ENABLED: true,
PERSON_MERGE_FOLD_ENABLED: false,
+ PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST: '',
GROUPS_PREFETCH_ENABLED: false,
GROUP_BATCH_WRITING_USE_BATCH_CREATES: false,
GROUP_BATCH_WRITING_USE_BATCH_UPDATES: false,
@@ -49,6 +52,7 @@ describe.each([
{
PERSONS_PREFETCH_ENABLED: true,
PERSON_MERGE_FOLD_ENABLED: true,
+ PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST: '*',
GROUPS_PREFETCH_ENABLED: true,
GROUP_BATCH_WRITING_USE_BATCH_CREATES: true,
GROUP_BATCH_WRITING_USE_BATCH_UPDATES: true,
diff --git a/nodejs/tests/ingestion/person-state-batch.test.ts b/nodejs/tests/ingestion/person-state-batch.test.ts
index db2ba238b4ea..2ee260ed8442 100644
--- a/nodejs/tests/ingestion/person-state-batch.test.ts
+++ b/nodejs/tests/ingestion/person-state-batch.test.ts
@@ -296,7 +296,8 @@ describe('PersonState.processEvent()', () => {
team = mainTeam,
mergeMode = createDefaultSyncMergeMode(),
mergeEventsConfig?: { enabled: boolean; partitionCount: number; isTeamEnabled?: (teamId: number) => boolean },
- customPersonsStore?: BatchWritingPersonsStore
+ customPersonsStore?: BatchWritingPersonsStore,
+ mergeTombstoneEnabled = false
) {
const fullEvent = {
team_id: teamId,
@@ -326,7 +327,10 @@ describe('PersonState.processEvent()', () => {
false,
// isTeamEnabled defaults to allow-all so the enabled/produce tests are unaffected by the
// team gate; pass it explicitly to exercise the allowlist.
- { isTeamEnabled: () => true, ...(mergeEventsConfig ?? { enabled: false, partitionCount: 64 }) }
+ { isTeamEnabled: () => true, ...(mergeEventsConfig ?? { enabled: false, partitionCount: 64 }) },
+ undefined,
+ undefined,
+ mergeTombstoneEnabled
)
return new PersonMergeService(context)
}
@@ -3894,6 +3898,258 @@ describe('PersonState.processEvent()', () => {
)
})
+ it('tombstone-mode merge with a concurrently tombstoned source converges to a no-op instead of half-applying', async () => {
+ const target = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, true, firstUserUuid, {
+ distinctId: firstUserDistinctId,
+ })
+ const source = await createPerson(
+ hub,
+ timestamp,
+ { plan: 'pro' },
+ {},
+ {},
+ teamId,
+ null,
+ true,
+ secondUserUuid,
+ { distinctId: secondUserDistinctId }
+ )
+
+ // A concurrent operation tombstones the source after our stale fetch, while an
+ // identity write that raced the tombstone left a live mapping pointing at it.
+ // Without the post-claim source liveness check the merge would move that mapping
+ // and merge the stale source properties into the target.
+ await hub.postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ 'UPDATE posthog_person SET is_deleted = true, version = version + 1 WHERE team_id = $1 AND id = $2',
+ [teamId, source.id],
+ 'testTombstoneSource'
+ )
+
+ const mergeService: PersonMergeService = personMergeService(
+ {
+ event: '$merge_dangerously',
+ distinct_id: firstUserDistinctId,
+ uuid: new UUIDT().toString(),
+ },
+ hub,
+ personRepository,
+ true,
+ timestamp,
+ mainTeam,
+ createDefaultSyncMergeMode(),
+ undefined,
+ undefined,
+ true
+ )
+
+ const result = await mergeService.mergePeople({
+ mergeInto: target,
+ mergeIntoDistinctId: firstUserDistinctId,
+ otherPerson: source,
+ otherPersonDistinctId: secondUserDistinctId,
+ })
+
+ // The retry refreshes by the source distinct id, which no longer resolves to a
+ // live person, so the merge converges to a no-op on the untouched target.
+ expect(result.success).toBe(true)
+ if (!result.success) {
+ throw new Error('Merge should have succeeded')
+ }
+ expect(result.person).toMatchObject({ id: target.id, uuid: firstUserUuid })
+
+ const persons = await fetchPostgresPersonsH()
+ expect(persons.length).toEqual(1)
+ expect(persons[0]).toMatchObject({
+ id: target.id,
+ properties: {},
+ version: 0,
+ })
+ const targetDistinctIds = await fetchPostgresDistinctIdsForPerson(hub.postgres, target.id)
+ expect(targetDistinctIds).toEqual([firstUserDistinctId])
+ })
+
+ it('tombstone-mode merge retries past a cached tombstoned person instead of failing', async () => {
+ const person = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {
+ distinctId: firstUserDistinctId,
+ })
+
+ const mergeService: PersonMergeService = personMergeService(
+ {
+ event: '$merge_dangerously',
+ distinct_id: secondUserDistinctId,
+ properties: { alias: firstUserDistinctId },
+ uuid: new UUIDT().toString(),
+ },
+ hub,
+ personRepository,
+ true,
+ timestamp,
+ mainTeam,
+ createDefaultSyncMergeMode(),
+ undefined,
+ undefined,
+ true
+ )
+
+ // Warm the batch cache with the live person, then tombstone it and its
+ // mapping out-of-band: the cache is now stale about liveness, and only a
+ // purge-on-throw lets the retry see the fresh state.
+ await mergeService.getContext().personStore.fetchForUpdate(teamId, firstUserDistinctId)
+ await hub.postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ 'UPDATE posthog_person SET is_deleted = true, version = version + 1 WHERE team_id = $1 AND id = $2',
+ [teamId, person.id],
+ 'testTombstonePerson'
+ )
+ await hub.postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ 'UPDATE posthog_persondistinctid SET is_deleted = true, version = COALESCE(version, 0) + 1 WHERE team_id = $1 AND distinct_id = $2',
+ [teamId, firstUserDistinctId],
+ 'testTombstoneDistinctId'
+ )
+
+ const result = await mergeService.merge(firstUserDistinctId, secondUserDistinctId, teamId, timestamp)
+
+ // The purged retry re-fetches, finds neither distinct id live, and
+ // recreates the person instead of exhausting retries on the cached row.
+ expect(result.success).toBe(true)
+ if (!result.success) {
+ throw new Error('Merge should have succeeded')
+ }
+ expect(result.person).toBeDefined()
+ })
+
+ it('tombstone-mode merge held off by a live lifecycle claim drops with a warning', async () => {
+ const target = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {
+ distinctId: firstUserDistinctId,
+ })
+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {
+ distinctId: secondUserDistinctId,
+ })
+
+ // The file-level observer's spy dies with the first test's restoreAllMocks;
+ // observe this test's produces through a fresh spy.
+ const producerObserver = new KafkaProducerObserver(kafkaProducer)
+
+ // A concurrent lifecycle operation (e.g. a delete saga) holds the target
+ // through every merge retry.
+ const holderOpId = new UUIDT().toString()
+ await personRepository.claimLifecycleMarks(holderOpId, teamId, [
+ { personId: target.id, personUuid: target.uuid, role: 'source' },
+ ])
+
+ try {
+ const mergeService: PersonMergeService = personMergeService(
+ {
+ event: '$merge_dangerously',
+ distinct_id: firstUserDistinctId,
+ properties: { alias: secondUserDistinctId },
+ uuid: new UUIDT().toString(),
+ },
+ hub,
+ personRepository,
+ true,
+ timestamp,
+ mainTeam,
+ createDefaultSyncMergeMode(),
+ undefined,
+ undefined,
+ true
+ )
+
+ const result = await mergeService.handleIdentifyOrAlias()
+
+ // The merge is dropped, not failed: success with no person, plus the warning.
+ expect(result.success).toBe(true)
+ if (!result.success) {
+ throw new Error('Expected a dropped merge to resolve successfully')
+ }
+ expect(result.person).toBeUndefined()
+
+ const warnings = producerObserver
+ .getProducedKafkaMessagesForTopic(KAFKA_INGESTION_WARNINGS)
+ .filter((w) => (w.value as any)?.type === 'merge_race_condition')
+ expect(warnings).toHaveLength(1)
+ } finally {
+ await personRepository.releaseLifecycleMarks(holderOpId, teamId)
+ }
+ })
+
+ it('tombstone-mode merge stamps the exact death version on the source row and its death message', async () => {
+ const target = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {
+ distinctId: firstUserDistinctId,
+ })
+ const source = await createPerson(
+ hub,
+ timestamp,
+ { plan: 'pro' },
+ {},
+ {},
+ teamId,
+ null,
+ false,
+ secondUserUuid,
+ { distinctId: secondUserDistinctId }
+ )
+
+ const producerObserver = new KafkaProducerObserver(kafkaProducer)
+ // The delete mode is a repository option, separate from the context flag.
+ const tombstoneRepository = new PostgresPersonRepository(hub.postgres, {
+ personMergeTombstoneTeamAllowlist: '*',
+ })
+ const mergeService: PersonMergeService = personMergeService(
+ {
+ event: '$merge_dangerously',
+ distinct_id: firstUserDistinctId,
+ properties: { alias: secondUserDistinctId },
+ uuid: new UUIDT().toString(),
+ },
+ hub,
+ tombstoneRepository,
+ true,
+ timestamp,
+ mainTeam,
+ createDefaultSyncMergeMode(),
+ undefined,
+ undefined,
+ true
+ )
+
+ const result = await mergeService.mergePeople({
+ mergeInto: target,
+ mergeIntoDistinctId: firstUserDistinctId,
+ otherPerson: source,
+ otherPersonDistinctId: secondUserDistinctId,
+ })
+ expect(result.success).toBe(true)
+ if (!result.success) {
+ throw new Error('Merge should have succeeded')
+ }
+ await flushPersonStoreToKafka(kafkaProducer, mergeService.getContext().personStore, result.kafkaAck)
+
+ // The source row survives as a tombstone at exactly death version
+ // (source.version + 1) with scrubbed properties — not a hard delete.
+ const sourceRows = await hub.postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ 'SELECT is_deleted, version, properties FROM posthog_person WHERE team_id = $1 AND uuid = $2',
+ [teamId, secondUserUuid],
+ 'fetchTombstonedSource'
+ )
+ expect(sourceRows.rows).toEqual([{ is_deleted: true, version: '1', properties: {} }])
+
+ // Filtered reads hide the tombstone: only the target remains visible.
+ const persons = await fetchPostgresPersonsH()
+ expect(persons.map((p) => p.uuid)).toEqual([firstUserUuid])
+
+ // The death message carries the exact death version, not the +100 fudge.
+ const deathMessages = producerObserver
+ .getProducedKafkaMessagesForTopic(KAFKA_PERSON)
+ .filter((m) => (m.value as any)?.id === secondUserUuid && (m.value as any)?.is_deleted === 1)
+ expect(deathMessages).toHaveLength(1)
+ expect(deathMessages[0].value).toMatchObject({ is_deleted: 1, version: 1, properties: '{}' })
+ })
+
describe('SYNC mode with batch processing', () => {
it('merges all distinct IDs when batch size is larger than total distinct IDs', async () => {
const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {