:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ingestion): reland tombstone merges behind the team allowlist (#80062)
José Sequeira4776f8c14ebf
diff --git a/nodejs/src/common/personhog/personhog-person-repository.test.ts b/nodejs/src/common/personhog/personhog-person-repository.test.tsindex 0b7aa8323051..730378356900 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.tsindex 89721db6b04d..123454e6f5bf 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.tsindex cf34805ab81f..f0ed187972f2 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.tsindex a5340ca62779..10c66670ef05 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[]>personPropertiesSize(personId: string, teamId: number): Promise<number>diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository-transaction.ts b/nodejs/src/common/persons/repositories/postgres-person-repository-transaction.tsindex e51537cf0109..fdaf8f8f2b1f 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 PersonRepositoryTranreturn 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.tsindex 3b0c57868b5d..5981b1977064 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'@@ -202,6 +207,19 @@ describe('PostgresPersonRepository', () => {})describe('tombstoned rows', () => {+ // Revival on create/addDistinctId runs only for allowlisted teams; the+ // default repository exercises the legacy (master) path.+ let revivalRepository: PostgresPersonRepository++ beforeEach(() => {+ revivalRepository = new PostgresPersonRepository(postgres, {+ calculatePropertiesSize: 0,+ personPropertiesDbConstraintLimitBytes: 1024 * 1024,+ personPropertiesTrimTargetBytes: 512 * 1024,+ personMergeTombstoneTeamAllowlist: '*',+ })+ })+async function tombstonePerson(person: InternalPerson): Promise<void> {await postgres.query(PostgresUse.PERSONS_WRITE,@@ -220,6 +238,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 +294,422 @@ 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 revivalRepository.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 revivalRepository.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 revivalRepository.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 revivalRepository.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 revivalRepository.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 revivalRepository.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 revivalRepository.addDistinctId(oldOwner, 'recycled-did', 0)+ await tombstoneDistinctId(team.id, 'recycled-did')++ const messages = await revivalRepository.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(revivalRepository.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.tsindex ec94af445b96..3260a8d6e252 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 PostgresPersonRepositoryimplements 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(@@ -518,6 +529,264 @@ export class PostgresPersonRepositoryprimaryDistinctId: { distinctId: string; version?: number },extraDistinctIds: { distinctId: string; version?: number }[] = [],tx?: TransactionClient+ ): Promise<CreatePersonResult> {+ // Teams outside the tombstone rollout run the query shipped on master,+ // untouched: clearing the allowlist is a full rollback to it.+ if (!this.isTombstoneTeam(teamId)) {+ return await this.createPersonLegacy(+ createdAt,+ properties,+ propertiesLastUpdatedAt,+ propertiesLastOperation,+ teamId,+ isUserId,+ isIdentified,+ uuid,+ primaryDistinctId,+ extraDistinctIds,+ tx+ )+ }++ // 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+ }++ // Fresh inserts start at version 0; a tombstone conflict revives at death_version + 1 instead.+ const personVersion = 0++ try {+ // Sanitize and measure JSON field sizes+ const sanitizedProperties = sanitizeJsonbValue(properties)+ const sanitizedPropertiesLastUpdatedAt = sanitizeJsonbValue(propertiesLastUpdatedAt)+ const sanitizedPropertiesLastOperation = sanitizeJsonbValue(propertiesLastOperation)++ // Record JSON field sizes (using string length as approximation)+ if (typeof sanitizedProperties === 'string') {+ personJsonFieldSizeHistogram+ .labels({ operation: 'createPerson', field: 'properties' })+ .observe(sanitizedProperties.length)+ }+ if (typeof sanitizedPropertiesLastUpdatedAt === 'string') {+ personJsonFieldSizeHistogram+ .labels({ operation: 'createPerson', field: 'properties_last_updated_at' })+ .observe(sanitizedPropertiesLastUpdatedAt.length)+ }+ if (typeof sanitizedPropertiesLastOperation === 'string') {+ personJsonFieldSizeHistogram+ .labels({ operation: 'createPerson', field: 'properties_last_operation' })+ .observe(sanitizedPropertiesLastOperation.length)+ }++ // For new persons, set last_seen_at to the hour-rounded createdAt+ const lastSeenAt = createdAt.startOf('hour')++ const personParams = [+ createdAt.toISO(),+ sanitizedProperties,+ sanitizedPropertiesLastUpdatedAt,+ sanitizedPropertiesLastOperation,+ teamId,+ isUserId,+ isIdentified,+ uuid,+ personVersion,+ lastSeenAt.toISO(),+ ]++ // 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. The+ // arbiter requires the unique (team_id, uuid) index, which is why this+ // query only runs for allowlisted teams: enabling a team is gated on+ // that index existing in the environment.+ 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.map(({ distinctId }) => distinctId),+ distinctIds.map(({ version }) => version),+ ],+ 'insertPerson',+ 'warn'+ )++ 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 row of distinctIdRows) {+ kafkaMessages.push({+ output: PERSON_DISTINCT_IDS_OUTPUT,+ value: Buffer.from(+ JSON.stringify({+ person_id: person.uuid,+ team_id: teamId,+ distinct_id: row.distinct_id,+ version: Number(row.version),+ is_deleted: 0,+ })+ ),+ })+ }++ return {+ success: true,+ person,+ messages: kafkaMessages,+ created: true,+ }+ } catch (error) {+ if (this.isPropertiesSizeConstraintViolation(error)) {+ // For createPerson, we just log and reject since there's no existing person to update+ personPropertiesSizeViolationCounter.inc({+ violation_type: 'create_person_size_violation',+ })++ logger.warn('Rejecting person properties create/update, exceeds size limit', {+ team_id: teamId,+ person_id: undefined,+ violation_type: 'create_person_size_violation',+ })++ throw new PersonPropertiesSizeViolationError(+ `Person properties create would exceed size limit`,+ teamId,+ undefined+ )+ }++ // Re-throw other errors+ throw error+ }+ }++ // Master's createPerson, kept byte-for-byte for teams outside the tombstone+ // rollout. Remove together with the allowlist once tombstone mode is the default.+ private async createPersonLegacy(+ createdAt: DateTime,+ properties: Properties,+ propertiesLastUpdatedAt: PropertiesLastUpdatedAt,+ propertiesLastOperation: PropertiesLastOperation,+ teamId: number,+ isUserId: number | null,+ isIdentified: boolean,+ uuid: string,+ primaryDistinctId: { distinctId: string; version?: number },+ extraDistinctIds: { distinctId: string; version?: number }[] = [],+ tx?: TransactionClient): Promise<CreatePersonResult> {const distinctIds = [primaryDistinctId, ...extraDistinctIds]for (const distinctId of distinctIds) {@@ -691,6 +960,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 +975,7 @@ export class PostgresPersonRepositoryrows = 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 +987,85 @@ export class PostgresPersonRepositoryif (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 +1073,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 +1095,7 @@ export class PostgresPersonRepositoryrows = 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,15 +1108,158 @@ export class PostgresPersonRepositoryif (!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,version: number,tx?: TransactionClient+ ): Promise<PersonMessage[]> {+ // Teams outside the tombstone rollout run the query shipped on master,+ // untouched: clearing the allowlist is a full rollback to it.+ if (!this.isTombstoneTeam(person.team_id)) {+ return await this.addDistinctIdLegacy(person, distinctId, version, tx)+ }++ const insertResult = await this.postgres.query(+ tx ?? PostgresUse.PERSONS_WRITE,+ // 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'+ )++ 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: Number(insertedVersion || 0),+ person_id: person.uuid,+ is_deleted: 0,+ })+ ),+ },+ ]+ }++ // Master's addDistinctId, kept byte-for-byte for teams outside the tombstone+ // rollout. Remove together with the allowlist once tombstone mode is the default.+ private async addDistinctIdLegacy(+ person: InternalPerson,+ distinctId: string,+ version: number,+ tx?: TransactionClient): Promise<PersonMessage[]> {const insertResult = await this.postgres.query(tx ?? PostgresUse.PERSONS_WRITE,@@ -810,6 +1302,7 @@ export class PostgresPersonRepositoryFROM posthog_persondistinctidWHERE person_id = $2AND team_id = $3+ AND is_deleted = falseORDER BY idFOR UPDATE SKIP LOCKEDLIMIT $4@@ -824,6 +1317,7 @@ export class PostgresPersonRepositorySET person_id = $1, version = COALESCE(version, 0)::numeric + 1WHERE person_id = $2AND team_id = $3+ AND is_deleted = falseRETURNING *`@@ -939,6 +1433,7 @@ export class PostgresPersonRepositorySET person_id = $1, version = COALESCE(version, 0)::numeric + 1WHERE person_id = ANY($2::bigint[])AND team_id = $3+ AND is_deleted = falseRETURNING *`,[target.id, sourceIds, target.team_id],'updateDistinctIdPersonFold'@@ -1092,14 +1587,14 @@ export class PostgresPersonRepositoryupdate).map((field, index) => `"${sanitizeSqlIdentifier(field)}" = $${index + 1}`- )} WHERE id = $${idParamIndex} AND team_id = $${teamIdParamIndex}+ )} WHERE id = $${idParamIndex} AND team_id = $${teamIdParamIndex} AND is_deleted = falseRETURNING ${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 aboveconst 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 = falseRETURNING ${PERSON_COLUMNS}/* operation='updatePerson',purpose='${tag || 'update'}' */`@@ -1179,7 +1674,7 @@ export class PostgresPersonRepositoryis_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 = falseRETURNING ${PERSON_COLUMNS}`,[@@ -1305,7 +1800,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 = falseRETURNING ${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.tsindex 81c72b342ffe..bbfa416bfb42 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.tsindex 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): Propertiereturn 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, isDeletteam_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.tsindex 7c7e39711349..964a64faeeea 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]),@@ -163,6 +166,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: jestdiff --git a/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts b/nodejs/src/ingestion/common/persons/batch-writing-person-store.tsindex a410250fda99..38d666ed4f76 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-propertyimport { 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'@@ -1377,6 +1381,32 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStorereturn 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.tsindex 5c88407b531b..d0788db8ffbe 100644--- a/nodejs/src/ingestion/common/persons/person-context.ts+++ b/nodejs/src/ingestion/common/persons/person-context.ts@@ -65,7 +65,9 @@ export class PersonContext {isTeamEnabled: () => 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!}diff --git a/nodejs/src/ingestion/common/persons/person-merge-service.ts b/nodejs/src/ingestion/common/persons/person-merge-service.tsindex 345db05cfff8..49c7219e19b6 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, each writing 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: {@@ -249,13 +289,38 @@ 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 distinctIdVersion = 1this.recordOverrideCount('oneExists')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()@@ -521,9 +586,31 @@ export class PersonMergeService {const currentTarget = targetthis.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@@ -577,6 +664,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]]})@@ -716,9 +806,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,{@@ -766,6 +890,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]]})@@ -795,11 +922,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 persondiff --git a/nodejs/src/ingestion/common/persons/person-uuid.ts b/nodejs/src/ingestion/common/persons/person-uuid.tsindex 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.tsindex 659f02b505ab..4f4f442535f7 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(@@ -221,6 +230,23 @@ class BatchBoundPersonsStoreTransaction implements PersonsStoreTransactionForBatreturn 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)}@@ -430,6 +456,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.tsindex 3a64d316f483..6aa0777c58e7 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.tsindex c0140756d88f..1b29f648f0b0 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.tsindex 7797e11d6c68..ae794a1951be 100644--- a/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.ts@@ -8,6 +8,8 @@ export interface EventPipelineRunnerOptions {PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: stringPERSON_MERGE_FOLD_ENABLED: booleanPERSON_MERGE_FOLD_TEAM_ALLOWLIST: string+ /** Teams whose merges run new-world: lifecycle-mark claims plus tombstone deletes: '*' for all, '' to disable, or comma-separated team IDs */+ PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST: stringPERSON_JSONB_SIZE_ESTIMATE_ENABLE: numberPERSON_PROPERTIES_UPDATE_ALL: boolean/** Teams whose $feature_flag_called events default to personless: '*' for all, '' to disable, or comma-separated team IDs */diff --git a/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts b/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.tsindex cbab1888bcaa..6dc61e410254 100644--- a/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts@@ -45,6 +45,8 @@ export function createProcessPersonsStep<TInput extends ProcessPersonsInput>(partitionCount: options.PERSON_MERGE_EVENTS_PARTITION_COUNT,isTeamEnabled: buildIntegerMatcher(options.PERSON_MERGE_EVENTS_TEAM_ALLOWLIST, true),}+ const isMergeTombstoneTeam = buildIntegerMatcher(options.PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST, true)+return async function processPersonsStep(input: TInput): Promise<PipelineResult<TInput & ProcessPersonsOutput, AsyncOutput>> {@@ -69,7 +71,8 @@ export function createProcessPersonsStep<TInput extends ProcessPersonsInput>(options.PERSON_PROPERTIES_UPDATE_ALL,shouldUpdateLastSeenAt,mergeEventsConfig,- 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.tsindex fb54846ad253..1e23967ef822 100644--- a/nodejs/src/ingestion/config.ts+++ b/nodejs/src/ingestion/config.ts@@ -168,6 +168,13 @@ export type IngestionConsumerConfig = {PERSON_MERGE_FOLD_ENABLED: boolean// Teams eligible for merge folding: comma-separated team IDs, or '*' for all teams.PERSON_MERGE_FOLD_TEAM_ALLOWLIST: string+ // 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// Group batch writing configGROUP_BATCH_WRITING_USE_BATCH_UPDATES: boolean@@ -312,6 +319,7 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: '2',PERSON_MERGE_FOLD_ENABLED: false,PERSON_MERGE_FOLD_TEAM_ALLOWLIST: '*',+ PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST: '',// Group batch writing configGROUP_BATCH_WRITING_USE_BATCH_UPDATES: true,diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.tsindex ec90fe08c63a..7d5403c1de9a 100644--- a/nodejs/src/ingestion/ingestion-consumer.ts+++ b/nodejs/src/ingestion/ingestion-consumer.ts@@ -291,6 +291,7 @@ export class IngestionConsumer {PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: this.config.PERSON_MERGE_EVENTS_TEAM_ALLOWLIST,PERSON_MERGE_FOLD_ENABLED: this.config.PERSON_MERGE_FOLD_ENABLED,PERSON_MERGE_FOLD_TEAM_ALLOWLIST: this.config.PERSON_MERGE_FOLD_TEAM_ALLOWLIST,+ PERSON_MERGE_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.tsindex 6d2a0fe4958c..9d83eec26ace 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,@@ -398,6 +399,7 @@ export class IngestionApiServer implements NodeServer {PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: this.config.PERSON_MERGE_EVENTS_TEAM_ALLOWLIST,PERSON_MERGE_FOLD_ENABLED: this.config.PERSON_MERGE_FOLD_ENABLED,PERSON_MERGE_FOLD_TEAM_ALLOWLIST: this.config.PERSON_MERGE_FOLD_TEAM_ALLOWLIST,+ PERSON_MERGE_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.tsindex 2c2882875d9f..ddfebdf596e2 100644--- a/nodejs/src/servers/ingestion-general-server.ts+++ b/nodejs/src/servers/ingestion-general-server.ts@@ -220,6 +220,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.tsindex 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.tsindex 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.tsindex 0a8700a90715..35ce3db1d7c3 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@@ -54,6 +54,7 @@ describe('createProcessPersonsStep', () => {PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: '*',PERSON_MERGE_FOLD_ENABLED: false,PERSON_MERGE_FOLD_TEAM_ALLOWLIST: '*',+ 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.tsindex 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.tsindex d1fab31c3797..0250e26b645a 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,9 @@ 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,+ mergeTombstoneEnabled)return new PersonMergeService(context)}@@ -3822,6 +3825,262 @@ 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,+ })++ // Revival on create runs only for allowlisted teams.+ const tombstoneRepository = new PostgresPersonRepository(hub.postgres, {+ personMergeTombstoneTeamAllowlist: '*',+ })+ const mergeService: PersonMergeService = personMergeService(+ {+ event: '$merge_dangerously',+ distinct_id: secondUserDistinctId,+ properties: { alias: firstUserDistinctId },+ uuid: new UUIDT().toString(),+ },+ hub,+ tombstoneRepository,+ 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, {