Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(ingestion): remove the person merge tombstone team allowlist (#113197)

José Sequeira138dbcadbd47
diff --git a/nodejs/src/common/persons/metrics.ts b/nodejs/src/common/persons/metrics.ts
index a8d713287508..7e58d7ec05e1 100644
--- a/nodejs/src/common/persons/metrics.ts
+++ b/nodejs/src/common/persons/metrics.ts
@@ -239,15 +239,6 @@ export const personProfileBatchIgnoredPropertiesCounter = new Counter({
labelNames: ['property'],
})
-export const personCreateStrandedClaimCounter = new Counter({
- name: 'person_create_stranded_claim_total',
- help: 'Person creations routed through the stranded-row claim statement, by outcome',
- // claimed: adopted an unreachable row holding this (team_id, uuid)
- // inserted: no row held the uuid, fresh insert
- // inserted_duplicate: a reachable person already held the uuid, so the insert created a duplicate key
- labelNames: ['outcome'],
-})
-
export const personCreateConflictResolvedCounter = new Counter({
name: 'person_create_conflict_resolved_total',
help: 'Person creations that lost the (team_id, uuid) key, by how the conflict was resolved',
diff --git a/nodejs/src/common/persons/repositories/person-repository.ts b/nodejs/src/common/persons/repositories/person-repository.ts
index 85a2875d36ec..58ad864d8998 100644
--- a/nodejs/src/common/persons/repositories/person-repository.ts
+++ b/nodejs/src/common/persons/repositories/person-repository.ts
@@ -54,8 +54,7 @@ export class DistinctIdConflictError extends Error {
/**
* 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.
+ * Callers refresh the person and retry, re-moving the new rows.
*/
export class PersonTombstoneBlockedError extends Error {
constructor(
diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository-stranded-claim.serial.test.ts b/nodejs/src/common/persons/repositories/postgres-person-repository-stranded-claim.serial.test.ts
deleted file mode 100644
index c8eb490b92f4..000000000000
--- a/nodejs/src/common/persons/repositories/postgres-person-repository-stranded-claim.serial.test.ts
+++ /dev/null
@@ -1,382 +0,0 @@
-// Serial: drops and recreates a shared PostgreSQL index.
-import { DateTime } from 'luxon'
-
-import { PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT } from '~/common/outputs/persons'
-import { personCreateStrandedClaimCounter } from '~/common/persons/metrics'
-import { closeHub, createHub } from '~/common/utils/db/hub'
-import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'
-import { parseJSON } from '~/common/utils/json-parse'
-import { UUIDT } from '~/common/utils/utils'
-import { resetTestDatabase } from '~/tests/helpers/sql'
-import { Hub, Team } from '~/types'
-
-import { PostgresPersonRepository } from './postgres-person-repository'
-import { TEST_TIMESTAMP, fetchDistinctIdValues, getFirstTeam } from './test-helpers'
-
-jest.mock('~/common/utils/logger')
-
-// The tracked schema's UNIQUE (team_id, uuid) index blocks the duplicate rows these tests
-// seed, so the index is recreated non-unique for the fixture. Production enforces uniqueness,
-// which is why the claim path matters: a stranded person (one no distinct ID resolves to) still
-// holds its uuid, and a returning user derives that same uuid, so the insert hits a constraint
-// violation the claim path has to resolve. Without the fixture every claim test would pass
-// vacuously.
-async function makeUuidIndexNonUnique(postgres: PostgresRouter): Promise<void> {
- const { rows } = await postgres.query(
- PostgresUse.PERSONS_WRITE,
- `SELECT i.indisunique FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid
- WHERE c.relname = 'posthog_person_new_uuid_idx'`,
- [],
- 'checkUuidIndex'
- )
- if (rows.length > 0 && !rows[0].indisunique) {
- return
- }
- await postgres.query(PostgresUse.PERSONS_WRITE, `DROP INDEX IF EXISTS posthog_person_new_uuid_idx`, [], 'dropIdx')
- await postgres.query(
- PostgresUse.PERSONS_WRITE,
- `CREATE INDEX posthog_person_new_uuid_idx ON posthog_person (team_id, uuid)`,
- [],
- 'createIdx'
- )
-}
-
-async function restoreUniqueUuidIndex(postgres: PostgresRouter): Promise<void> {
- // The last test leaves duplicate (team_id, uuid) rows behind; clear them or the
- // unique index cannot build.
- await postgres.query(PostgresUse.PERSONS_WRITE, `DELETE FROM posthog_persondistinctid`, [], 'clearPdi')
- await postgres.query(PostgresUse.PERSONS_WRITE, `DELETE FROM posthog_person`, [], 'clearPersons')
- await postgres.query(PostgresUse.PERSONS_WRITE, `DROP INDEX IF EXISTS posthog_person_new_uuid_idx`, [], 'dropIdx')
- await postgres.query(
- PostgresUse.PERSONS_WRITE,
- `CREATE UNIQUE INDEX posthog_person_new_uuid_idx ON posthog_person (team_id, uuid)`,
- [],
- 'createIdx'
- )
-}
-
-describe('PostgresPersonRepository stranded-row claim', () => {
- let hub: Hub
- let postgres: PostgresRouter
- let repository: PostgresPersonRepository
- let team: Team
-
- beforeEach(async () => {
- hub = await createHub()
- await resetTestDatabase()
- postgres = hub.postgres
- await makeUuidIndexNonUnique(postgres)
- repository = new PostgresPersonRepository(postgres, {
- calculatePropertiesSize: 0,
- personCreateClaimTeamAllowlist: '*',
- })
- team = await getFirstTeam(postgres)
- personCreateStrandedClaimCounter.reset()
- })
-
- afterEach(async () => {
- await closeHub(hub)
- jest.clearAllMocks()
- })
-
- afterAll(async () => {
- // Other suites share this worker's database and expect the tracked schema.
- const cleanupHub = await createHub()
- await restoreUniqueUuidIndex(cleanupHub.postgres)
- await closeHub(cleanupHub)
- })
-
- // A person row with no distinct-ID mapping, the way rows stranded by out-of-band
- // mapping deletion look in production.
- async function seedStrandedPerson(
- teamId: number,
- uuid: string,
- overrides: {
- version?: number
- properties?: Record<string, any>
- isIdentified?: boolean
- isDeleted?: boolean
- } = {}
- ): Promise<number> {
- const { rows } = await postgres.query(
- PostgresUse.PERSONS_WRITE,
- `INSERT INTO posthog_person (
- created_at, properties, properties_last_updated_at, properties_last_operation,
- team_id, is_user_id, is_identified, uuid, version, is_deleted
- ) VALUES ($1, $2, '{}', '{}', $3, NULL, $4, $5, $6, $7) RETURNING id`,
- [
- DateTime.fromISO('2023-06-01T00:00:00.000Z').toISO(),
- JSON.stringify(overrides.properties ?? { stale: 'value' }),
- teamId,
- overrides.isIdentified ?? false,
- uuid,
- overrides.version ?? 3,
- overrides.isDeleted ?? false,
- ],
- 'seedStrandedPerson'
- )
- return Number(rows[0].id)
- }
-
- async function addMapping(teamId: number, personId: number, distinctId: string, isDeleted = false): Promise<void> {
- await postgres.query(
- PostgresUse.PERSONS_WRITE,
- `INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version, is_deleted)
- VALUES ($1, $2, $3, 0, $4)`,
- [distinctId, personId, teamId, isDeleted],
- 'seedMapping'
- )
- }
-
- async function fetchPersonRows(teamId: number, uuid: string): Promise<{ id: number; version: number }[]> {
- const { rows } = await postgres.query(
- PostgresUse.PERSONS_WRITE,
- `SELECT id, version FROM posthog_person WHERE team_id = $1 AND uuid = $2 ORDER BY id`,
- [teamId, uuid],
- 'fetchPersonRows'
- )
- return rows.map((r: any) => ({ id: Number(r.id), version: Number(r.version) }))
- }
-
- async function createPerson(
- uuid: string,
- distinctId: string,
- properties: Record<string, any> = {}
- ): ReturnType<PostgresPersonRepository['createPerson']> {
- return await repository.createPerson(TEST_TIMESTAMP, properties, {}, {}, team.id, null, true, uuid, {
- distinctId,
- })
- }
-
- async function getCounterValue(outcome: string): Promise<number> {
- const metric = await personCreateStrandedClaimCounter.get()
- return metric.values.find((v) => v.labels.outcome === outcome)?.value ?? 0
- }
-
- it('the fixture allows duplicate (team_id, uuid) rows, like production', async () => {
- const uuid = new UUIDT().toString()
- await seedStrandedPerson(team.id, uuid)
- // With the tracked schema's unique index this second insert would throw, and
- // every scenario below would be untestable.
- await expect(seedStrandedPerson(team.id, uuid)).resolves.toEqual(expect.any(Number))
- })
-
- it('claims the stranded row: same row id, reset properties, bumped version, new mapping', async () => {
- const uuid = new UUIDT().toString()
- const strandedId = await seedStrandedPerson(team.id, uuid, { version: 7, properties: { stale: 'yes' } })
-
- const result = await createPerson(uuid, 'returning-user', { fresh: 'yes' })
-
- expect(result.success).toBe(true)
- if (!result.success) {
- return
- }
- expect(result.created).toBe(true)
- expect(Number(result.person.id)).toBe(strandedId)
- expect(result.person.uuid).toBe(uuid)
- expect(result.person.properties).toEqual({ fresh: 'yes' })
- expect(result.person.version).toBe(8)
- expect(result.person.is_identified).toBe(true)
-
- // Exactly one row holds the uuid, and the mapping points at it.
- expect(await fetchPersonRows(team.id, uuid)).toEqual([{ id: strandedId, version: 8 }])
- expect(await fetchDistinctIdValues(postgres, result.person)).toEqual(['returning-user'])
- expect(await getCounterValue('claimed')).toBe(1)
- })
-
- it('emits the person update and the distinct-id mapping to Kafka on a claim', async () => {
- const uuid = new UUIDT().toString()
- await seedStrandedPerson(team.id, uuid)
-
- const result = await createPerson(uuid, 'returning-user')
- expect(result.success).toBe(true)
- if (!result.success) {
- return
- }
-
- const personMessages = result.messages.filter((m) => m.output === PERSONS_OUTPUT)
- const didMessages = result.messages.filter((m) => m.output === PERSON_DISTINCT_IDS_OUTPUT)
- expect(personMessages).toHaveLength(1)
- expect(didMessages).toHaveLength(1)
-
- const didPayload = parseJSON(didMessages[0].value!.toString())
- expect(didPayload).toEqual({
- person_id: uuid,
- team_id: team.id,
- distinct_id: 'returning-user',
- // Version 0 keeps the mapping out of the ClickHouse overrides view: events
- // stamped with this deterministic uuid already point at the right person.
- version: 0,
- is_deleted: 0,
- })
- })
-
- it('claims exactly one row (the oldest) when several stranded rows share the uuid', async () => {
- const uuid = new UUIDT().toString()
- const olderId = await seedStrandedPerson(team.id, uuid, { version: 1 })
- const newerId = await seedStrandedPerson(team.id, uuid, { version: 5 })
-
- const result = await createPerson(uuid, 'returning-user')
- expect(result.success).toBe(true)
- if (!result.success) {
- return
- }
-
- expect(Number(result.person.id)).toBe(olderId)
- const rows = await fetchPersonRows(team.id, uuid)
- // The newer stranded row is untouched; repair tooling owns it.
- expect(rows).toEqual([
- { id: olderId, version: 2 },
- { id: newerId, version: 5 },
- ])
- expect(await getCounterValue('claimed')).toBe(1)
- })
-
- it('never claims a row the product can still reach', async () => {
- const uuid = new UUIDT().toString()
- const reachableId = await seedStrandedPerson(team.id, uuid, { version: 4 })
- await addMapping(team.id, reachableId, 'other-distinct-id')
-
- const result = await createPerson(uuid, 'second-distinct-id')
- expect(result.success).toBe(true)
- if (!result.success) {
- return
- }
-
- // Pre-existing behavior for this (bounded, known) case: a duplicate row is
- // created rather than ingestion failing. The metric is the alarm.
- expect(Number(result.person.id)).not.toBe(reachableId)
- const rows = await fetchPersonRows(team.id, uuid)
- expect(rows).toHaveLength(2)
- expect(rows[0]).toEqual({ id: reachableId, version: 4 })
- expect(await getCounterValue('inserted_duplicate')).toBe(1)
- expect(await getCounterValue('claimed')).toBe(0)
- })
-
- it('treats a row whose only mapping is soft-deleted as claimable', async () => {
- const uuid = new UUIDT().toString()
- const strandedId = await seedStrandedPerson(team.id, uuid)
- await addMapping(team.id, strandedId, 'dead-distinct-id', true)
-
- const result = await createPerson(uuid, 'live-distinct-id')
- expect(result.success).toBe(true)
- if (!result.success) {
- return
- }
-
- expect(Number(result.person.id)).toBe(strandedId)
- expect(await getCounterValue('claimed')).toBe(1)
- })
-
- it('never claims a tombstoned (is_deleted) row: falls through to a fresh insert', async () => {
- const uuid = new UUIDT().toString()
- const tombstonedId = await seedStrandedPerson(team.id, uuid, { version: 6, isDeleted: true })
-
- const result = await createPerson(uuid, 'returning-user')
- expect(result.success).toBe(true)
- if (!result.success) {
- return
- }
-
- // The tombstoned row is not revived; the create behaves as if it were absent.
- expect(Number(result.person.id)).not.toBe(tombstonedId)
- expect(result.person.version).toBe(0)
- expect(await fetchPersonRows(team.id, uuid)).toEqual([
- { id: tombstonedId, version: 6 },
- { id: Number(result.person.id), version: 0 },
- ])
- expect(await getCounterValue('claimed')).toBe(0)
- expect(await getCounterValue('inserted')).toBe(1)
- })
-
- it('claims with extra distinct IDs: every mapping lands on the claimed row', async () => {
- const uuid = new UUIDT().toString()
- const strandedId = await seedStrandedPerson(team.id, uuid)
-
- const result = await repository.createPerson(
- TEST_TIMESTAMP,
- {},
- {},
- {},
- team.id,
- null,
- true,
- uuid,
- { distinctId: 'primary-id' },
- [{ distinctId: 'extra-id', version: 2 }]
- )
- expect(result.success).toBe(true)
- if (!result.success) {
- return
- }
-
- expect(Number(result.person.id)).toBe(strandedId)
- expect((await fetchDistinctIdValues(postgres, result.person)).sort()).toEqual(['extra-id', 'primary-id'])
-
- const didPayloads = result.messages
- .filter((m) => m.output === PERSON_DISTINCT_IDS_OUTPUT)
- .map((m) => parseJSON(m.value!.toString()))
- expect(didPayloads).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ distinct_id: 'primary-id', version: 0, person_id: uuid }),
- expect.objectContaining({ distinct_id: 'extra-id', version: 2, person_id: uuid }),
- ])
- )
- expect(didPayloads).toHaveLength(2)
- expect(await getCounterValue('claimed')).toBe(1)
- })
-
- it('inserts normally when nothing holds the uuid', async () => {
- const uuid = new UUIDT().toString()
- const result = await createPerson(uuid, 'brand-new-user', { a: 1 })
-
- expect(result.success).toBe(true)
- if (!result.success) {
- return
- }
- expect(result.created).toBe(true)
- expect(result.person.uuid).toBe(uuid)
- expect(result.person.version).toBe(0)
- expect(await fetchDistinctIdValues(postgres, result.person)).toEqual(['brand-new-user'])
- expect(await getCounterValue('inserted')).toBe(1)
- expect(await getCounterValue('claimed')).toBe(0)
- })
-
- it('returns CreationConflict when the distinct ID is already mapped', async () => {
- const uuid = new UUIDT().toString()
- const first = await createPerson(uuid, 'contested-distinct-id')
- expect(first.success).toBe(true)
-
- // Same repository-level contract as the legacy path: the caller resolves the
- // conflict by re-fetching the person by distinct ID.
- const second = await createPerson(new UUIDT().toString(), 'contested-distinct-id')
- expect(second.success).toBe(false)
- if (second.success) {
- return
- }
- expect(second.error).toBe('CreationConflict')
- })
-
- it('does not claim for teams outside the allowlist', async () => {
- const legacyRepository = new PostgresPersonRepository(postgres, {
- calculatePropertiesSize: 0,
- // personCreateClaimTeamAllowlist deliberately unset
- })
- const uuid = new UUIDT().toString()
- const strandedId = await seedStrandedPerson(team.id, uuid)
-
- const result = await legacyRepository.createPerson(TEST_TIMESTAMP, {}, {}, {}, team.id, null, true, uuid, {
- distinctId: 'returning-user',
- })
- expect(result.success).toBe(true)
- if (!result.success) {
- return
- }
-
- // Legacy behavior preserved: a duplicate row, the stranded one untouched.
- expect(Number(result.person.id)).not.toBe(strandedId)
- expect(await fetchPersonRows(team.id, uuid)).toHaveLength(2)
- expect(await getCounterValue('claimed')).toBe(0)
- expect(await getCounterValue('inserted')).toBe(0)
- })
-})
diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts b/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
index 5c55996e1d60..c47ef6e91e6a 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
@@ -206,19 +206,6 @@ 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: '*',
- })
- })
-
function recordQueryTags(): () => string[] {
const spy = jest.spyOn(postgres, 'query')
return () => spy.mock.calls.map((call) => String(call[3]))
@@ -628,38 +615,18 @@ describe('PostgresPersonRepository', () => {
it('createPerson revives a tombstoned person and its distinct id at death_version + 1', async () => {
const uuid = new UUIDT().toString()
- const first = await revivalRepository.createPerson(
- TIMESTAMP,
- { a: 1 },
- {},
- {},
- team.id,
- null,
- false,
- uuid,
- {
- distinctId: 'revive-did',
- }
- )
+ const first = await repository.createPerson(TIMESTAMP, { a: 1 }, {}, {}, team.id, null, false, uuid, {
+ distinctId: 'revive-did',
+ })
if (!first.success) {
throw new Error('Failed to create person')
}
await tombstonePerson(first.person)
await tombstoneDistinctId(team.id, 'revive-did')
- const revived = await revivalRepository.createPerson(
- TIMESTAMP,
- { b: 2 },
- {},
- {},
- team.id,
- null,
- true,
- uuid,
- {
- distinctId: 'revive-did',
- }
- )
+ const revived = await repository.createPerson(TIMESTAMP, { b: 2 }, {}, {}, team.id, null, true, uuid, {
+ distinctId: 'revive-did',
+ })
if (!revived.success) {
throw new Error('Expected revival to succeed')
@@ -678,36 +645,16 @@ describe('PostgresPersonRepository', () => {
it('createPerson returns CreationConflict against a live person with the same uuid', async () => {
const uuid = new UUIDT().toString()
- const first = await revivalRepository.createPerson(
- TIMESTAMP,
- { a: 1 },
- {},
- {},
- team.id,
- null,
- false,
- uuid,
- {
- distinctId: 'live-uuid-did',
- }
- )
+ const first = await repository.createPerson(TIMESTAMP, { a: 1 }, {}, {}, team.id, null, false, uuid, {
+ distinctId: 'live-uuid-did',
+ })
if (!first.success) {
throw new Error('Failed to create person')
}
- const second = await revivalRepository.createPerson(
- TIMESTAMP,
- { b: 2 },
- {},
- {},
- team.id,
- null,
- false,
- uuid,
- {
- distinctId: 'live-uuid-did-2',
- }
- )
+ const second = await repository.createPerson(TIMESTAMP, { b: 2 }, {}, {}, team.id, null, false, uuid, {
+ distinctId: 'live-uuid-did-2',
+ })
// The holder owns a different distinct ID, so recovering by distinct ID cannot find
// it. Returning it here is what lets the caller resolve instead of raising an error
@@ -755,7 +702,7 @@ describe('PostgresPersonRepository', () => {
it('createPerson dedupes repeated distinct ids instead of failing the multi-insert', async () => {
const uuid = new UUIDT().toString()
- const result = await revivalRepository.createPerson(
+ const result = await repository.createPerson(
TIMESTAMP,
{},
{},
@@ -781,7 +728,7 @@ describe('PostgresPersonRepository', () => {
const uuid = new UUIDT().toString()
const queryTags = recordQueryTags()
- const result = await revivalRepository.createPerson(
+ const result = await repository.createPerson(
TIMESTAMP,
{ secret: 'value' },
{},
@@ -812,10 +759,10 @@ describe('PostgresPersonRepository', () => {
it('createPerson undone by a live mapping leaves a reattached stray tombstoned', async () => {
const liveOwner = await createTestPerson(team.id, 'mixed-contested-did')
const deadOwner = await createTestPerson(team.id, 'mixed-stray-owner-did')
- await revivalRepository.addDistinctId(deadOwner, 'mixed-stray-did', 1)
+ await repository.addDistinctId(deadOwner, 'mixed-stray-did', 1)
await tombstonePerson(deadOwner)
- const result = await revivalRepository.createPerson(
+ const result = await repository.createPerson(
TIMESTAMP,
{},
{},
@@ -848,19 +795,9 @@ describe('PostgresPersonRepository', () => {
'createPerson',
async (): Promise<[string, PersonMessage[]]> => {
const uuid = new UUIDT().toString()
- const result = await revivalRepository.createPerson(
- TIMESTAMP,
- {},
- {},
- {},
- team.id,
- null,
- false,
- uuid,
- {
- distinctId: 'stray-did',
- }
- )
+ const result = await repository.createPerson(TIMESTAMP, {}, {}, {}, team.id, null, false, uuid, {
+ distinctId: 'stray-did',
+ })
if (!result.success) {
throw new Error('Expected creation to succeed')
}
@@ -871,12 +808,12 @@ describe('PostgresPersonRepository', () => {
'addDistinctId',
async (): Promise<[string, PersonMessage[]]> => {
const newOwner = await createTestPerson(team.id, 'stray-adder-did')
- return [newOwner.uuid, await revivalRepository.addDistinctId(newOwner, 'stray-did', 1)]
+ return [newOwner.uuid, await repository.addDistinctId(newOwner, 'stray-did', 1)]
},
],
])('%s takes over a live mapping left on a tombstoned person', async (_name, write) => {
const deadOwner = await createTestPerson(team.id, 'stray-owner-did')
- await revivalRepository.addDistinctId(deadOwner, 'stray-did', 1)
+ await repository.addDistinctId(deadOwner, 'stray-did', 1)
await tombstonePerson(deadOwner)
const [ownerUuid, messages] = await write()
@@ -891,17 +828,9 @@ describe('PostgresPersonRepository', () => {
const owner = await createTestPerson(team.id, 'self-stray-did')
await tombstonePerson(owner)
- const result = await revivalRepository.createPerson(
- TIMESTAMP,
- {},
- {},
- {},
- team.id,
- null,
- false,
- owner.uuid,
- { distinctId: 'self-stray-did' }
- )
+ const result = await repository.createPerson(TIMESTAMP, {}, {}, {}, team.id, null, false, owner.uuid, {
+ distinctId: 'self-stray-did',
+ })
expect(result).toMatchObject({ success: true, person: { id: owner.id, uuid: owner.uuid } })
await expect(repository.fetchPerson(team.id, 'self-stray-did')).resolves.toMatchObject({ uuid: owner.uuid })
@@ -910,10 +839,10 @@ describe('PostgresPersonRepository', () => {
it('addDistinctId revives a tombstoned mapping, repointing it at the new person', async () => {
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 repository.addDistinctId(oldOwner, 'recycled-did', 0)
await tombstoneDistinctId(team.id, 'recycled-did')
- const messages = await revivalRepository.addDistinctId(newOwner, 'recycled-did', 0)
+ const messages = await repository.addDistinctId(newOwner, 'recycled-did', 0)
await expect(repository.fetchPerson(team.id, 'recycled-did')).resolves.toMatchObject({
uuid: newOwner.uuid,
@@ -940,9 +869,7 @@ describe('PostgresPersonRepository', () => {
}
const queryTags = recordQueryTags()
- await expect(revivalRepository.addDistinctId(person, distinctId, 0)).rejects.toThrow(
- DistinctIdConflictError
- )
+ await expect(repository.addDistinctId(person, distinctId, 0)).rejects.toThrow(DistinctIdConflictError)
expect(queryTags()).not.toContain('lockStrayDistinctIds')
}
)
@@ -1042,23 +969,12 @@ describe('PostgresPersonRepository', () => {
})
})
- describe('tombstone-mode deletes', () => {
- let tombstoneRepository: PostgresPersonRepository
-
- beforeEach(() => {
- tombstoneRepository = new PostgresPersonRepository(postgres, {
- calculatePropertiesSize: 0,
- personPropertiesDbConstraintLimitBytes: 1024 * 1024,
- personPropertiesTrimTargetBytes: 512 * 1024,
- personMergeTombstoneTeamAllowlist: '*',
- })
- })
-
+ describe('deletes', () => {
it('deletePerson tombstones the row at the exact death version with scrubbed properties', async () => {
const person = await createTestPerson(team.id, 'ts-delete-did', { secret: 'x' })
await tombstoneDistinctId(team.id, 'ts-delete-did')
- const messages = await tombstoneRepository.deletePerson(person)
+ const messages = await repository.deletePerson(person)
expect(messages).toHaveLength(1)
const message = parseJSON(messages[0].value!.toString())
@@ -1078,7 +994,7 @@ describe('PostgresPersonRepository', () => {
it('deletePerson refuses while live distinct ids still point at the person', async () => {
const person = await createTestPerson(team.id, 'ts-blocked-did')
- await expect(tombstoneRepository.deletePerson(person)).rejects.toThrow(PersonTombstoneBlockedError)
+ await expect(repository.deletePerson(person)).rejects.toThrow(PersonTombstoneBlockedError)
await expect(repository.fetchPerson(team.id, 'ts-blocked-did')).resolves.toMatchObject({
uuid: person.uuid,
})
@@ -1091,7 +1007,7 @@ describe('PostgresPersonRepository', () => {
await tombstoneDistinctId(team.id, 'ts-batch-fresh-did')
await tombstonePerson(alreadyDead)
- const messages = await tombstoneRepository.deletePersons([alreadyDead, fresh])
+ const messages = await repository.deletePersons([alreadyDead, fresh])
expect(messages).toHaveLength(1)
const message = parseJSON(messages[0].value!.toString())
@@ -1276,62 +1192,6 @@ describe('PostgresPersonRepository', () => {
})
describe('deletePerson()', () => {
- it('should delete person from postgres', async () => {
- const uuid = new UUIDT().toString()
- const result = await repository.createPerson(TIMESTAMP, {}, {}, {}, team.id, null, true, uuid, {
- distinctId: 'delete-test-distinct',
- })
- if (!result.success) {
- throw new Error('Failed to create person')
- }
- const person = result.person
- const kafkaMessages = result.messages
-
- const personOutputs = new IngestionOutputs({
- [PERSONS_OUTPUT]: new SingleIngestionOutput(PERSONS_OUTPUT, KAFKA_PERSON, mockProducer, 'test'),
- [PERSON_DISTINCT_IDS_OUTPUT]: new SingleIngestionOutput(
- PERSON_DISTINCT_IDS_OUTPUT,
- KAFKA_PERSON_DISTINCT_ID,
- mockProducer,
- 'test'
- ),
- })
- await Promise.all(
- kafkaMessages.map((msg) => personOutputs.produce(msg.output, { value: msg.value, key: null }))
- )
-
- // Delete distinct IDs first to avoid FK constraint violation
- await hub.postgres.query(
- PostgresUse.PERSONS_WRITE,
- 'DELETE FROM posthog_persondistinctid WHERE person_id = $1',
- [person.id],
- 'deleteDistinctIds'
- )
-
- const deleteMessages = await repository.deletePerson(person)
-
- // Verify person is deleted from postgres
- const fetchedPerson = await fetchPersonByPersonId(hub, team.id, person.id)
- expect(fetchedPerson).toEqual(undefined)
-
- // Verify kafka messages are generated
- expect(deleteMessages).toHaveLength(1)
- expect(deleteMessages[0].output).toBe(PERSONS_OUTPUT)
- expect(deleteMessages[0].value).not.toBeNull()
-
- const messageValue = parseJSON(deleteMessages[0].value!.toString())
- expect(messageValue).toEqual({
- id: person.uuid,
- created_at: person.created_at.toFormat('yyyy-MM-dd HH:mm:ss'),
- properties: JSON.stringify(person.properties),
- team_id: person.team_id,
- is_identified: Number(person.is_identified),
- is_deleted: 1,
- version: person.version + 100, // version is incremented by 100 for deletions
- last_seen_at: person.last_seen_at?.toFormat('yyyy-MM-dd HH:mm:ss') ?? null,
- })
- })
-
it('should handle deleting person that does not exist', async () => {
const nonExistentPerson = {
id: '999999',
@@ -3584,22 +3444,6 @@ describe('PostgresPersonRepository', () => {
})
describe('deletePersons()', () => {
- it('deletes multiple persons and returns one deletion message each', async () => {
- const person1 = await createTestPerson(team.id, 'fold-delete-1', {})
- const person2 = await createTestPerson(team.id, 'fold-delete-2', {})
- // Distinct ids reference persons via FK; clear them before deletion
- const target = await createTestPerson(team.id, 'fold-delete-target', {})
- await repository.moveDistinctIdsFromPersons([person1, person2], target)
-
- const messages = await repository.deletePersons([person1, person2])
-
- expect(messages).toHaveLength(2)
- const deletedUuids = messages.map((message) => parseJSON(message.value!.toString()).id).sort()
- expect(deletedUuids).toEqual([person1.uuid, person2.uuid].sort())
- expect(await fetchPersonByPersonId(hub, team.id, person1.id)).toBeUndefined()
- expect(await fetchPersonByPersonId(hub, team.id, person2.id)).toBeUndefined()
- })
-
it('returns no messages for already-deleted persons and empty input', async () => {
const person = await createTestPerson(team.id, 'fold-delete-3', {})
const target = await createTestPerson(team.id, 'fold-delete-target-2', {})
@@ -3667,14 +3511,3 @@ describe('PostgresPersonRepository', () => {
})
})
})
-
-async function fetchPersonByPersonId(hub: Hub, teamId: number, personId: string): Promise<any | undefined> {
- const selectResult = await hub.postgres.query(
- PostgresUse.PERSONS_WRITE,
- `SELECT * FROM posthog_person WHERE team_id = $1 AND id = $2`,
- [teamId, personId],
- 'fetchPersonByPersonId'
- )
-
- return selectResult.rows[0]
-}
diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository.ts b/nodejs/src/common/persons/repositories/postgres-person-repository.ts
index c71cbf52b131..d066ffcf70a7 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.ts
@@ -5,7 +5,6 @@ import { buildIntegerMatcher } from '~/common/config/config'
import { PERSON_DISTINCT_IDS_OUTPUT } from '~/common/outputs/persons'
import {
oversizedPersonPropertiesTrimmedCounter,
- personCreateStrandedClaimCounter,
personJsonFieldSizeHistogram,
personPropertiesSizeViolationCounter,
personStrayDistinctIdTombstonedCounter,
@@ -73,14 +72,6 @@ const PERSON_COLUMN_NAMES = [
export const PERSON_COLUMNS = PERSON_COLUMN_NAMES.join(', ')
const PERSON_COLUMNS_PREFIXED = PERSON_COLUMN_NAMES.map((column) => `p.${column}`).join(', ')
-// Postgres reports the violated index per partition (posthog_person_p58_team_id_uuid_idx),
-// so match on the column instead of a fixed name. The distinct-ID constraint is named
-// "unique distinct_id for team new", which this does not match.
-function isUuidConstraintViolation(error: unknown): boolean {
- const constraint = (error as { constraint?: unknown } | null)?.constraint
- return typeof constraint === 'string' && constraint.includes('uuid')
-}
-
function queryTag(base: string, callerTag?: string): string {
return callerTag ? `${base}:${callerTag}` : base
}
@@ -91,19 +82,6 @@ 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
- /**
- * Teams whose person creation claims an existing unreachable row holding the same
- * (team_id, uuid) instead of inserting a duplicate. Person UUIDs are deterministic
- * (uuidv5 of team_id:distinct_id), so on teams where posthog_persondistinctid rows
- * were destroyed outside the write path, a returning user's create would otherwise
- * mint a second row with an identical (team_id, uuid). Scoped to affected teams
- * because the claim probe adds an index lookup to the hottest write path.
- * NOT the tombstone allowlist: that one routes to a query whose ON CONFLICT
- * (team_id, uuid) arbiter requires a unique index production does not have yet.
- */
- personCreateClaimTeamAllowlist: string
/** Teams whose batch writes merge per key with the row; other teams write the pod's whole view over it ('*' for all). */
personBatchWritePerKeyTeamAllowlist: string
}
@@ -112,8 +90,6 @@ const DEFAULT_OPTIONS: PostgresPersonRepositoryOptions = {
calculatePropertiesSize: 0,
personPropertiesDbConstraintLimitBytes: DEFAULT_PERSON_PROPERTIES_DB_CONSTRAINT_LIMIT_BYTES,
personPropertiesTrimTargetBytes: DEFAULT_PERSON_PROPERTIES_TRIM_TARGET_BYTES,
- personMergeTombstoneTeamAllowlist: '',
- personCreateClaimTeamAllowlist: '',
personBatchWritePerKeyTeamAllowlist: '*',
}
@@ -121,8 +97,6 @@ export class PostgresPersonRepository
implements PersonRepository, RawPostgresPersonRepository, PersonRepositoryTransaction
{
private options: PostgresPersonRepositoryOptions
- private isTombstoneTeam: ValueMatcher<number>
- private isClaimTeam: ValueMatcher<number>
private isPerKeyWriteTeam: ValueMatcher<number>
constructor(
@@ -130,8 +104,6 @@ export class PostgresPersonRepository
options?: Partial<PostgresPersonRepositoryOptions>
) {
this.options = { ...DEFAULT_OPTIONS, ...options }
- this.isTombstoneTeam = buildIntegerMatcher(this.options.personMergeTombstoneTeamAllowlist, true)
- this.isClaimTeam = buildIntegerMatcher(this.options.personCreateClaimTeamAllowlist, true)
this.isPerKeyWriteTeam = buildIntegerMatcher(this.options.personBatchWritePerKeyTeamAllowlist, true)
}
@@ -702,39 +674,6 @@ export class PostgresPersonRepository
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)) {
- if (this.isClaimTeam(teamId)) {
- return await this.createPersonWithStrandedClaim(
- createdAt,
- properties,
- propertiesLastUpdatedAt,
- propertiesLastOperation,
- teamId,
- isUserId,
- isIdentified,
- uuid,
- primaryDistinctId,
- extraDistinctIds,
- tx
- )
- }
- 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.
@@ -811,9 +750,7 @@ export class PostgresPersonRepository
// 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.
+ // arbiter requires the unique (team_id, uuid) index.
const query = `
WITH inserted_person AS (
INSERT INTO posthog_person (
@@ -975,502 +912,19 @@ export class PostgresPersonRepository
}
}
- /**
- * createPersonLegacy plus one behavior change: when a live posthog_person row already
- * holds this (team_id, uuid) and no live distinct-ID mapping points at it, that row is
- * unreachable by the product (persons resolve only via distinct_id -> posthog_persondistinctid
- * -> person_id), so it is claimed - reset from this event and given the new mapping -
- * instead of a second row being inserted with an identical (team_id, uuid).
- *
- * The uuid is deterministic (uuidv5 of `${teamId}:${primaryDistinctId}`), so a claimed row
- * was originally created for this same distinct ID; the claim reunites a person with its
- * own row. The mapping keeps version 0, exactly like a fresh insert: the ClickHouse
- * overrides view only consumes versions > 0, and events already stamped with this uuid
- * point at the right person either way.
- *
- * Concurrency safety does not depend on any posthog_person index: a concurrent creator
- * for the same uuid necessarily carries the same primary distinct ID, so its mapping
- * insert collides on the unique (team_id, distinct_id) index and rolls this whole
- * single statement back, surfacing as CreationConflict just like the legacy path.
- */
- private async createPersonWithStrandedClaim(
- 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) {
- distinctId.version ||= 0
- }
-
- // Fresh inserts start at version 0; a claim continues the claimed row's counter so
- // its ClickHouse row (same uuid) is overwritten rather than outranked.
- const personVersion = 0
-
- try {
- const sanitizedProperties = sanitizeJsonbValue(properties)
- const sanitizedPropertiesLastUpdatedAt = sanitizeJsonbValue(propertiesLastUpdatedAt)
- const sanitizedPropertiesLastOperation = sanitizeJsonbValue(propertiesLastOperation)
-
- 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')
-
- // holders is one probe on the (team_id, uuid) index; the reachability check is one
- // probe per holder on the (team_id, person_id) index. Duplicate groups can hold
- // several unreachable rows, so claimable takes exactly one (the oldest, min id);
- // repair tooling resolves the rest. The claim resets properties from this event rather
- // than reviving the stranded row's - deliberate, matching the tombstone revival
- // path, so data a deletion may have targeted is not resurrected.
- // The mapping insert has no ON CONFLICT: a collision must abort the whole
- // statement, same as the legacy path.
- const query = `
- WITH holders AS (
- SELECT p.id,
- EXISTS (
- SELECT 1 FROM posthog_persondistinctid d
- WHERE d.team_id = $5 AND d.person_id = p.id AND d.is_deleted = false
- ) AS reachable
- FROM posthog_person p
- WHERE p.team_id = $5 AND p.uuid = $8 AND p.is_deleted = false
- ),
- claimable AS (
- -- The oldest unreachable holder is selected with a scalar min(), not
- -- ORDER BY id LIMIT 1: the pkey is (team_id, id), so an ordered LIMIT
- -- lets the planner satisfy the sort by walking the team's id range and
- -- filtering, which on a large team scans millions of rows when the match
- -- is rare or absent. Equality on a scalar subquery leaves only a pkey
- -- point probe in the plan space.
- -- is_deleted is re-verified here (not only in holders) because under READ
- -- COMMITTED, FOR UPDATE follows a concurrent update to the row's new version
- -- and rechecks only this WHERE; without it, a row tombstoned between snapshot
- -- and lock would be claimed without clearing its is_deleted flag. A row
- -- tombstoned mid-race empties this CTE, falling through to a fresh insert.
- SELECT p.id FROM posthog_person p
- WHERE p.team_id = $5
- AND p.id = (SELECT min(h.id) FROM holders h WHERE NOT h.reachable)
- AND p.is_deleted = false
- FOR UPDATE
- ),
- claimed AS (
- UPDATE posthog_person p SET
- created_at = $1,
- properties = $2,
- properties_last_updated_at = $3,
- properties_last_operation = $4,
- is_user_id = $6,
- is_identified = $7,
- version = COALESCE(p.version, 0) + 1,
- last_seen_at = $10
- FROM claimable c
- WHERE p.team_id = $5 AND p.id = c.id
- RETURNING ${PERSON_COLUMNS_PREFIXED}
- ),
- inserted 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
- )
- SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10
- WHERE NOT EXISTS (SELECT 1 FROM claimable)
- RETURNING ${PERSON_COLUMNS}
- ),
- person AS (
- SELECT *, true AS was_claimed FROM claimed
- UNION ALL
- SELECT *, false AS was_claimed FROM inserted
- ),
- 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, p.id, $5, d.version
- FROM person p
- CROSS JOIN unnest($11::text[], $12::bigint[]) AS d(distinct_id, version)
- RETURNING id, distinct_id, version
- )
- SELECT
- p.*,
- (SELECT count(*)::int FROM holders h WHERE h.reachable) AS reachable_holder_count,
- (
- 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 person p;`
-
- const { rows } = await this.postgres.query<
- RawPerson & {
- was_claimed: boolean
- reachable_holder_count: number
- distinct_id_rows: { id: string; distinct_id: string; version: number }[]
- }
- >(
- tx ?? PostgresUse.PERSONS_WRITE,
- query,
- [
- createdAt.toISO(),
- sanitizedProperties,
- sanitizedPropertiesLastUpdatedAt,
- sanitizedPropertiesLastOperation,
- teamId,
- isUserId,
- isIdentified,
- uuid,
- personVersion,
- lastSeenAt.toISO(),
- distinctIds.map(({ distinctId }) => distinctId),
- distinctIds.map(({ version }) => version),
- ],
- 'insertPersonWithStrandedClaim',
- 'warn'
- )
-
- const {
- was_claimed: wasClaimed,
- reachable_holder_count: reachableHolderCount,
- distinct_id_rows: distinctIdRows,
- ...personRow
- } = rows[0]
- const person = this.toPerson(personRow)
-
- if (wasClaimed) {
- personCreateStrandedClaimCounter.inc({ outcome: 'claimed' })
- } else if (reachableHolderCount > 0) {
- // A reachable person already holds this uuid via a different distinct ID, so
- // this insert created a duplicate (team_id, uuid) - the pre-existing behavior.
- // Loud on purpose: these rows block the unique index build.
- personCreateStrandedClaimCounter.inc({ outcome: 'inserted_duplicate' })
- logger.warn('Created person duplicates a reachable (team_id, uuid)', {
- team_id: teamId,
- person_uuid: uuid,
- reachable_holder_count: reachableHolderCount,
- })
- } else {
- personCreateStrandedClaimCounter.inc({ outcome: 'inserted' })
- }
-
- 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) {
- // Same conflict contract as the legacy path: a unique violation means a
- // concurrent creator won the mapping, and the caller re-fetches by distinct ID.
- if (error instanceof Error && error.message.includes('unique constraint')) {
- return {
- success: false,
- error: 'CreationConflict',
- distinctIds: distinctIds.map((d) => d.distinctId),
- // No tx: the violation just aborted it, so a read on it would raise 25P02
- // instead of returning the holder, and the throw would escape this catch
- // and fail the merge this recovery exists to keep alive.
- conflictingPerson: isUuidConstraintViolation(error)
- ? await this.fetchPersonByUuid(teamId, uuid)
- : undefined,
- }
- }
-
- if (this.isPropertiesSizeConstraintViolation(error)) {
- 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
- )
- }
-
- 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) {
- distinctId.version ||= 0
- }
-
- // The Person is being created, and so we can hardcode version 0!
- const personVersion = 0
-
- try {
- const columns = [
- 'created_at',
- 'properties',
- 'properties_last_updated_at',
- 'properties_last_operation',
- 'team_id',
- 'is_user_id',
- 'is_identified',
- 'uuid',
- 'version',
- 'last_seen_at',
- ]
- const valuePlaceholders = columns.map((_, i) => `$${i + 1}`).join(', ')
-
- // Sanitize and measure JSON field sizes
- const sanitizedProperties = sanitizeJsonbValue(properties)
- const sanitizedPropertiesLastUpdatedAt = sanitizeJsonbValue(propertiesLastUpdatedAt)
- 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(),
- ]
-
- // Find the actual index of team_id in the personParams array (1-indexed for SQL)
- const teamIdParamIndex = personParams.indexOf(teamId) + 1
- const distinctIdVersionStartIndex = columns.length + 1
- const distinctIdStartIndex = distinctIdVersionStartIndex + distinctIds.length
-
- const distinctIdsCTE =
- distinctIds.length > 0
- ? `, distinct_ids AS (
- INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version)
- VALUES ${distinctIds
- .map(
- // NOTE: Keep this in sync with the posthog_persondistinctid INSERT in
- // `addDistinctId`
- (_, index) => `(
- $${distinctIdStartIndex + index},
- (SELECT id FROM inserted_person),
- $${teamIdParamIndex},
- $${distinctIdVersionStartIndex + index}
- )`
- )
- .join(', ')}
- )`
- : ''
-
- const query =
- `WITH inserted_person AS (
- INSERT INTO posthog_person (${columns.join(', ')})
- VALUES (${valuePlaceholders})
- RETURNING ${PERSON_COLUMNS}
- )` +
- distinctIdsCTE +
- ` SELECT * FROM inserted_person;`
-
- const { rows } = await this.postgres.query<RawPerson>(
- tx ?? PostgresUse.PERSONS_WRITE,
- query,
- [
- ...personParams,
- ...distinctIds
- .slice()
- .reverse()
- .map(({ version }) => version),
- ...distinctIds
- .slice()
- .reverse()
- .map(({ distinctId }) => distinctId),
- ],
- 'insertPerson',
- 'warn'
- )
- const person = this.toPerson(rows[0])
-
- const kafkaMessages: PersonMessage[] = [generateKafkaPersonUpdateMessage(person)]
-
- for (const distinctId of distinctIds) {
- kafkaMessages.push({
- output: PERSON_DISTINCT_IDS_OUTPUT,
- value: Buffer.from(
- JSON.stringify({
- person_id: person.uuid,
- team_id: teamId,
- distinct_id: distinctId.distinctId,
- version: distinctId.version,
- is_deleted: 0,
- })
- ),
- })
- }
-
- return {
- success: true,
- person,
- messages: kafkaMessages,
- created: true,
- }
- } catch (error) {
- // Handle constraint violation - another process created the person concurrently
- if (error instanceof Error && error.message.includes('unique constraint')) {
- // This is not of type CreatePersonResult?
- return {
- success: false,
- error: 'CreationConflict',
- distinctIds: distinctIds.map((d) => d.distinctId),
- // No tx: the violation just aborted it, so a read on it would raise 25P02
- // instead of returning the holder, and the throw would escape this catch
- // and fail the merge this recovery exists to keep alive.
- conflictingPerson: isUuidConstraintViolation(error)
- ? await this.fetchPersonByUuid(teamId, uuid)
- : undefined,
- }
- }
-
- 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
- }
- }
-
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 }>(
- tx ?? PostgresUse.PERSONS_WRITE,
- 'DELETE FROM posthog_person WHERE team_id = $1 AND id = $2 RETURNING version',
- [person.team_id, person.id],
- 'deletePerson'
- )
- rows = result.rows
- } catch (error) {
- if (error.code === '40P01') {
- logger.warn('🔒', 'Deadlock detected — rolling back for the caller to retry.', {
- team_id: person.team_id,
- person_id: person.id,
- })
- }
- throw error
- }
-
- let kafkaMessages: PersonMessage[] = []
-
- if (rows.length > 0) {
- const [row] = rows
- 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
+ return await this.tombstonePersons([person], tx)
}
/**
- * Tombstone-mode delete: the row stays in place as the key's version floor, with the
+ * Tombstone 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.
+ * the merge's refresh-and-retry handling.
*/
private async tombstonePersons(persons: InternalPerson[], tx?: TransactionClient): Promise<PersonMessage[]> {
const teamId = persons[0].team_id
@@ -1536,50 +990,7 @@ export class PostgresPersonRepository
if (persons.length === 0) {
return []
}
-
- // 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
- // folds deleting overlapping persons lock in a consistent order either
- // way; sorting here just keeps the parameter and logs deterministic.
- const personIds = [...personById.keys()].sort((a, b) => (BigInt(a) < BigInt(b) ? -1 : 1))
-
- let rows: { id: string; version: string }[] = []
- try {
- const result = await this.postgres.query<{ id: string; version: string }>(
- tx ?? PostgresUse.PERSONS_WRITE,
- 'DELETE FROM posthog_person WHERE team_id = $1 AND id = ANY($2::bigint[]) RETURNING id, version',
- [teamId, personIds],
- 'deletePersons'
- )
- rows = result.rows
- } 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
- }
-
- return rows.flatMap((row) => {
- const person = personById.get(String(row.id))
- if (!person) {
- return []
- }
- 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),
- ]
- })
+ return await this.tombstonePersons(persons, tx)
}
async claimLifecycleMarks(
@@ -1684,12 +1095,6 @@ export class PostgresPersonRepository
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`.
@@ -1743,39 +1148,6 @@ export class PostgresPersonRepository
]
}
- // 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,
- // NOTE: Keep this in sync with the posthog_persondistinctid INSERT in `createPerson`
- 'INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version) VALUES ($1, $2, $3, $4) RETURNING *',
- [distinctId, person.id, person.team_id, version],
- 'addDistinctId',
- 'warn'
- )
-
- const { id, ...personDistinctIdCreated } = insertResult.rows[0] as PersonDistinctId
- return [
- {
- output: PERSON_DISTINCT_IDS_OUTPUT,
- value: Buffer.from(
- JSON.stringify({
- ...personDistinctIdCreated,
- version,
- person_id: person.uuid,
- is_deleted: 0,
- })
- ),
- },
- ]
- }
-
async moveDistinctIds(
source: InternalPerson,
target: InternalPerson,
diff --git a/nodejs/src/common/utils/db/utils.ts b/nodejs/src/common/utils/db/utils.ts
index b1f0be269196..e3f07e9bbac8 100644
--- a/nodejs/src/common/utils/db/utils.ts
+++ b/nodejs/src/common/utils/db/utils.ts
@@ -131,9 +131,9 @@ export function personInitialAndUTMProperties(properties: Properties): Propertie
return properties
}
-// 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.
+// Deletion call sites own the version they emit (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,
diff --git a/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts b/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
index 64ffd517183e..609aa357f742 100644
--- a/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
+++ b/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
@@ -123,8 +123,6 @@ export interface BatchWritingPersonsStoreOptions {
* always wants a positive interval).
*/
metricEmissionIntervalMs: number
- /** Teams on the new-world merge behavior (lifecycle-mark claims plus tombstone deletes); '*' for all. */
- mergeTombstoneTeamAllowlist: string
/** Teams whose merges lock the person rows and write the survivor in the transaction; others queue it for the flush. */
mergeLockedOutcomeTeamAllowlist: string
/** Gate, partition count, and team allowlist ('*' for all) for the cross-partition merge-event producer. */
@@ -145,7 +143,6 @@ const DEFAULT_OPTIONS: BatchWritingPersonsStoreOptions = {
optimisticUpdateRetryInterval: 50,
updateAllProperties: false,
metricEmissionIntervalMs: 30_000,
- mergeTombstoneTeamAllowlist: '',
mergeLockedOutcomeTeamAllowlist: '*',
mergeEventsEnabled: false,
mergeEventsPartitionCount: 64,
@@ -197,7 +194,6 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
this.options = { ...DEFAULT_OPTIONS, ...options }
this.mergePolicy = {
updateAllProperties: this.options.updateAllProperties,
- isTombstoneTeam: buildIntegerMatcher(this.options.mergeTombstoneTeamAllowlist, true),
isLockedOutcomeTeam: buildIntegerMatcher(this.options.mergeLockedOutcomeTeamAllowlist, true),
mergeEvents: {
enabled: this.options.mergeEventsEnabled,
diff --git a/nodejs/src/ingestion/common/persons/person-merge-postgres.test.ts b/nodejs/src/ingestion/common/persons/person-merge-postgres.test.ts
index 7323570fe579..9a987001784a 100644
--- a/nodejs/src/ingestion/common/persons/person-merge-postgres.test.ts
+++ b/nodejs/src/ingestion/common/persons/person-merge-postgres.test.ts
@@ -44,7 +44,6 @@ describe('PostgresPersonMerge merge events', () => {
mockOutputs as any,
{
updateAllProperties: false,
- isTombstoneTeam: () => false,
isLockedOutcomeTeam: () => true,
mergeEvents,
},
@@ -150,7 +149,12 @@ describe('PostgresPersonMerge merge events', () => {
output: PERSON_DISTINCT_IDS_OUTPUT,
value: Buffer.from('{}'),
}
- const tx = { addDistinctId: jest.fn().mockResolvedValue([mappingMessage]) }
+ const tx = {
+ claimLifecycleMarks: jest.fn(),
+ isPersonLive: jest.fn().mockResolvedValue(true),
+ addDistinctId: jest.fn().mockResolvedValue([mappingMessage]),
+ releaseLifecycleMarks: jest.fn(),
+ }
const store = {
fetchForUpdate: jest
.fn()
@@ -288,7 +292,6 @@ describe('PostgresPersonMerge merge events', () => {
mockOutputs as never,
{
updateAllProperties: false,
- isTombstoneTeam: () => false,
isLockedOutcomeTeam: () => true,
mergeEvents: { enabled: false, partitionCount: 64, isTeamEnabled: () => false },
...policyOverrides,
@@ -337,7 +340,6 @@ describe('PostgresPersonMerge merge events', () => {
mockOutputs as never,
{
updateAllProperties: false,
- isTombstoneTeam: () => false,
isLockedOutcomeTeam: () => true,
mergeEvents: { enabled: false, partitionCount: 64, isTeamEnabled: () => false },
},
diff --git a/nodejs/src/ingestion/common/persons/person-merge-postgres.ts b/nodejs/src/ingestion/common/persons/person-merge-postgres.ts
index 7b8c2263224d..11fa02429fdc 100644
--- a/nodejs/src/ingestion/common/persons/person-merge-postgres.ts
+++ b/nodejs/src/ingestion/common/persons/person-merge-postgres.ts
@@ -129,8 +129,6 @@ export interface MergeEventsConfig {
export interface PostgresMergePolicy {
/** When true, all property changes trigger person updates; mirrors the store option of the same name. */
updateAllProperties: boolean
- /** Teams on the new-world merge behavior: lifecycle-mark claims plus tombstone deletes. */
- isTombstoneTeam: ValueMatcher<number>
/** Teams whose merge locks the person rows and writes the survivor in its transaction; others queue it for the flush. */
isLockedOutcomeTeam: ValueMatcher<number>
mergeEvents: MergeEventsConfig
@@ -215,10 +213,6 @@ export class PostgresPersonMerge {
return DateTime.fromMillis(this.request.createdAtMs, { zone: 'utc' })
}
- private tombstoneEnabled(): boolean {
- return this.policy.isTombstoneTeam(this.teamId)
- }
-
private lockedOutcomeEnabled(): boolean {
return this.policy.isLockedOutcomeTeam(this.teamId)
}
@@ -479,35 +473,28 @@ export class PostgresPersonMerge {
this.discardOverrideCounts()
const lifecycleOpId = lifecycleOpIdFromEvent(teamId, this.request.eventUuid)
const [result, kafkaMessages] = await this.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.tombstoneEnabled()) {
- await tx.claimLifecycleMarks(
- lifecycleOpId,
- existingPerson.team_id,
- [{ personId: existingPerson.id, personUuid: existingPerson.uuid, role: 'target' }],
- this.targetDistinctId
- )
- if (!(await tx.isPersonLive(existingPerson, this.targetDistinctId))) {
- // Purge the stale cache entries so the caller's retry attempt
- // re-fetches from Postgres instead of replaying the cached,
- // now-tombstoned person into the same failure.
- this.store.removeDistinctIdFromCache(teamId, otherPersonDistinctId)
- this.store.removeDistinctIdFromCache(teamId, mergeIntoDistinctId)
- throw new TargetPersonNotFoundError(
- 'Person was deleted before the merge could add a distinct id'
- )
- }
+ // The person's lifecycle mark keeps a concurrent tombstone from landing
+ // between this check and the distinct id insert (an orphaned mapping).
+ await tx.claimLifecycleMarks(
+ lifecycleOpId,
+ existingPerson.team_id,
+ [{ personId: existingPerson.id, personUuid: existingPerson.uuid, role: 'target' }],
+ this.targetDistinctId
+ )
+ if (!(await tx.isPersonLive(existingPerson, this.targetDistinctId))) {
+ // Purge the stale cache entries so the caller's retry attempt
+ // re-fetches from Postgres instead of replaying the cached,
+ // now-tombstoned person into the same failure.
+ this.store.removeDistinctIdFromCache(teamId, otherPersonDistinctId)
+ this.store.removeDistinctIdFromCache(teamId, mergeIntoDistinctId)
+ throw new TargetPersonNotFoundError('Person was deleted before the merge could add a distinct id')
}
// See comment above about `distinctIdVersion`
const distinctIdVersion = 1
this.recordOverrideCount('oneExists')
const messages = await tx.addDistinctId(existingPerson, distinctIdToAdd, distinctIdVersion)
- if (this.tombstoneEnabled()) {
- await tx.releaseLifecycleMarks(lifecycleOpId, teamId, this.targetDistinctId)
- }
+ await tx.releaseLifecycleMarks(lifecycleOpId, teamId, this.targetDistinctId)
return [existingPerson, messages] as const
})
this.flushOverrideCounts()
@@ -761,26 +748,24 @@ export class PostgresPersonMerge {
const [survivorRow, survivorUpdate, kafkaMessages] = await this.inTransaction(
'mergePeopleFold',
async (tx): Promise<[InternalPerson, MergePersonUpdate | null, PersonMessage[]]> => {
- // New-world folds claim every person, keeping concurrent lifecycle operations
+ // Folds claim every person, keeping concurrent lifecycle operations
// (other merges, the delete saga) off the targets and sources until commit.
- if (this.tombstoneEnabled()) {
- 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.targetDistinctId
- )
- if (!(await tx.isPersonLive(currentTarget, this.targetDistinctId))) {
- throw new MergeFoldConflictError('Fold target was deleted concurrently')
- }
+ 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.targetDistinctId
+ )
+ if (!(await tx.isPersonLive(currentTarget, this.targetDistinctId))) {
+ throw new MergeFoldConflictError('Fold target was deleted concurrently')
}
if (!this.lockedOutcomeEnabled()) {
return await this.deferredOutcomeFold(
@@ -839,9 +824,7 @@ export class PostgresPersonMerge {
deleteMessages = await tx.deletePersons(mergeSources, this.targetDistinctId)
}
- if (this.tombstoneEnabled()) {
- await tx.releaseLifecycleMarks(lifecycleOpId, teamId, this.targetDistinctId)
- }
+ await tx.releaseLifecycleMarks(lifecycleOpId, teamId, this.targetDistinctId)
return [survivor, outcome, [...moveMessages, ...survivorMessages, ...deleteMessages]]
}
)
@@ -1009,38 +992,36 @@ export class PostgresPersonMerge {
const [survivorRow, survivorUpdate, kafkaMessages] = await this.inTransaction(
'mergePeople',
async (tx): Promise<[InternalPerson, MergePersonUpdate | null, PersonMessage[]]> => {
- // New-world merges claim both persons in the lifecycle mark table: at
+ // 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.tombstoneEnabled()) {
- 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.targetDistinctId
- )
- if (!(await tx.isPersonLive(currentTargetPerson, this.targetDistinctId))) {
- throw new TargetPersonNotFoundError('Target person was deleted concurrently')
- }
- if (!(await tx.isPersonLive(currentSourcePerson, this.targetDistinctId))) {
- throw new SourcePersonNotFoundError('Source person was deleted concurrently')
- }
+ 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.targetDistinctId
+ )
+ if (!(await tx.isPersonLive(currentTargetPerson, this.targetDistinctId))) {
+ throw new TargetPersonNotFoundError('Target person was deleted concurrently')
+ }
+ if (!(await tx.isPersonLive(currentSourcePerson, this.targetDistinctId))) {
+ throw new SourcePersonNotFoundError('Source person was deleted concurrently')
}
if (!this.lockedOutcomeEnabled()) {
return await this.deferredOutcomeTransaction(
@@ -1094,9 +1075,7 @@ export class PostgresPersonMerge {
? this.store.rejectMergeOutcome(currentTargetPerson, outcome, this.targetDistinctId)
: await tx.updatePersonForMerge(currentTargetPerson, outcome, this.targetDistinctId)
const deletePersonMessages = await tx.deletePerson(currentSourcePerson, this.targetDistinctId)
- if (this.tombstoneEnabled()) {
- await tx.releaseLifecycleMarks(lifecycleOpId, this.teamId, this.targetDistinctId)
- }
+ await tx.releaseLifecycleMarks(lifecycleOpId, this.teamId, this.targetDistinctId)
return [
survivor,
written ? outcome : null,
@@ -1147,8 +1126,8 @@ export class PostgresPersonMerge {
} 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:
+ // as PersonTombstoneBlockedError by the tombstone's live-mapping guard, or as a
+ // foreign key violation. The retry mechanism will:
// 1. Refresh the source person data to see all distinct IDs (including newly added ones)
// 2. Move ALL distinct IDs to the target person
// 3. Successfully delete the now-empty source person
@@ -1349,9 +1328,7 @@ export class PostgresPersonMerge {
)
await tx.updateCohortsAndFeatureFlagsForMerge(source.team_id, source.id, target.id, this.targetDistinctId)
const deletePersonMessages = await tx.deletePerson(source, this.targetDistinctId)
- if (this.tombstoneEnabled()) {
- await tx.releaseLifecycleMarks(lifecycleOpId, this.teamId, this.targetDistinctId)
- }
+ await tx.releaseLifecycleMarks(lifecycleOpId, this.teamId, this.targetDistinctId)
return [survivor, null, [...allDistinctIdMessages, ...deletePersonMessages]]
}
@@ -1380,9 +1357,7 @@ export class PostgresPersonMerge {
)
deleteMessages = await tx.deletePersons(mergeSources, this.targetDistinctId)
}
- if (this.tombstoneEnabled()) {
- await tx.releaseLifecycleMarks(lifecycleOpId, this.teamId, this.targetDistinctId)
- }
+ await tx.releaseLifecycleMarks(lifecycleOpId, this.teamId, this.targetDistinctId)
return [survivor, null, [...moveMessages, ...deleteMessages]]
}
diff --git a/nodejs/src/ingestion/common/persons/person-merge-types.ts b/nodejs/src/ingestion/common/persons/person-merge-types.ts
index 61722ee2b24a..05a30ae88133 100644
--- a/nodejs/src/ingestion/common/persons/person-merge-types.ts
+++ b/nodejs/src/ingestion/common/persons/person-merge-types.ts
@@ -98,7 +98,7 @@ export class TargetPersonNotFoundError extends PersonMergePersonNotFoundError {
/**
* Error when source person cannot be deleted due to concurrent distinct ID additions.
* This occurs when a concurrent merge operation adds a distinct ID to the person being
- * deleted, causing a foreign key constraint violation. The retry will refresh the person
+ * deleted, which blocks the tombstone delete. The retry will refresh the person
* data and move all distinct IDs (including the newly added ones) before attempting deletion.
*/
export class SourcePersonHasDistinctIdsError extends PersonMergePersonNotFoundError {
diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.ts
index 3d0dc158562d..d55e36a16d6f 100644
--- a/nodejs/src/ingestion/config.ts
+++ b/nodejs/src/ingestion/config.ts
@@ -192,12 +192,6 @@ 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
- // Teams whose merges and deletes tombstone the person row instead of hard-deleting it, and
- // whose creates revive a tombstoned key. Every environment rolled this out to all teams, so
- // '*' is the default. Comma-separated team IDs, or '*' for all teams; empty means no teams.
- // Teams off this list attach distinct ids without lifecycle marks. Personhog's tombstone RPC
- // cannot coordinate with those attaches, so a delete can leave a live mapping on a deleted person.
- PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST: string
// Teams whose merges lock the person rows and write the survivor in the transaction; other teams queue it for
// the next flush. Enable after PERSON_BATCH_WRITING_PER_KEY_TEAM_ALLOWLIST. Team IDs, or '*'; empty means none.
PERSON_MERGE_LOCKED_OUTCOME_TEAM_ALLOWLIST: string
@@ -207,12 +201,6 @@ export type IngestionConsumerConfig = {
PERSON_MERGE_NOOP_MAPPING_EMISSION_ENABLED: boolean
PERSON_MERGE_NOOP_MAPPING_EMISSION_CACHE_SIZE: number
PERSON_MERGE_NOOP_MAPPING_EMISSION_TTL_MS: number
- // Teams whose person creation claims an existing unreachable posthog_person row holding
- // the same deterministic (team_id, uuid) instead of inserting a duplicate row. Scope to
- // teams whose distinct-ID mappings were destroyed outside the write path (stranded rows);
- // for everyone else the probe is wasted load on the hottest write statement.
- // Comma-separated team IDs, or '*' for all teams; empty means no teams.
- PERSON_CREATE_CLAIM_TEAM_ALLOWLIST: string
// Group batch writing config
GROUP_BATCH_WRITING_USE_BATCH_UPDATES: boolean
@@ -385,12 +373,10 @@ 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: '*',
PERSON_MERGE_LOCKED_OUTCOME_TEAM_ALLOWLIST: '',
PERSON_MERGE_NOOP_MAPPING_EMISSION_ENABLED: false,
PERSON_MERGE_NOOP_MAPPING_EMISSION_CACHE_SIZE: 500_000,
PERSON_MERGE_NOOP_MAPPING_EMISSION_TTL_MS: 60 * 60 * 1000,
- PERSON_CREATE_CLAIM_TEAM_ALLOWLIST: '',
// Group batch writing config
GROUP_BATCH_WRITING_USE_BATCH_UPDATES: true,
diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.ts
index fb3f95e82eea..ced87d61464d 100644
--- a/nodejs/src/ingestion/ingestion-consumer.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.ts
@@ -238,7 +238,6 @@ export class IngestionConsumer {
maxOptimisticUpdateRetries: this.config.PERSON_BATCH_WRITING_MAX_OPTIMISTIC_UPDATE_RETRIES,
optimisticUpdateRetryInterval: this.config.PERSON_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS,
updateAllProperties: this.config.PERSON_PROPERTIES_UPDATE_ALL,
- mergeTombstoneTeamAllowlist: this.config.PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST,
mergeLockedOutcomeTeamAllowlist: this.config.PERSON_MERGE_LOCKED_OUTCOME_TEAM_ALLOWLIST,
mergeEventsEnabled: effectivePersonMergeEventsEnabled(this.config),
mergeEventsPartitionCount: this.config.PERSON_MERGE_EVENTS_PARTITION_COUNT,
diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.ts
index 0033011fd0b7..3190fe42e0aa 100644
--- a/nodejs/src/servers/ingestion-api-server.ts
+++ b/nodejs/src/servers/ingestion-api-server.ts
@@ -231,8 +231,6 @@ 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,
- personCreateClaimTeamAllowlist: this.config.PERSON_CREATE_CLAIM_TEAM_ALLOWLIST,
personBatchWritePerKeyTeamAllowlist: this.config.PERSON_BATCH_WRITING_PER_KEY_TEAM_ALLOWLIST,
})
const personRepository = buildPersonRepository(
@@ -349,7 +347,6 @@ export class IngestionApiServer implements NodeServer {
maxOptimisticUpdateRetries: this.config.PERSON_BATCH_WRITING_MAX_OPTIMISTIC_UPDATE_RETRIES,
optimisticUpdateRetryInterval: this.config.PERSON_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS,
updateAllProperties: this.config.PERSON_PROPERTIES_UPDATE_ALL,
- mergeTombstoneTeamAllowlist: this.config.PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST,
mergeLockedOutcomeTeamAllowlist: this.config.PERSON_MERGE_LOCKED_OUTCOME_TEAM_ALLOWLIST,
mergeEventsEnabled: effectivePersonMergeEventsEnabled(this.config),
mergeEventsPartitionCount: this.config.PERSON_MERGE_EVENTS_PARTITION_COUNT,
diff --git a/nodejs/src/servers/ingestion-general-server.ts b/nodejs/src/servers/ingestion-general-server.ts
index bca3d7a69657..e80bb178dffe 100644
--- a/nodejs/src/servers/ingestion-general-server.ts
+++ b/nodejs/src/servers/ingestion-general-server.ts
@@ -222,8 +222,6 @@ 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,
- personCreateClaimTeamAllowlist: this.config.PERSON_CREATE_CLAIM_TEAM_ALLOWLIST,
personBatchWritePerKeyTeamAllowlist: this.config.PERSON_BATCH_WRITING_PER_KEY_TEAM_ALLOWLIST,
})
const personRepository = buildPersonRepository(
diff --git a/nodejs/tests/helpers/ingestion-e2e.ts b/nodejs/tests/helpers/ingestion-e2e.ts
index 5977a36fc591..3f8ac56f7f6c 100644
--- a/nodejs/tests/helpers/ingestion-e2e.ts
+++ b/nodejs/tests/helpers/ingestion-e2e.ts
@@ -452,7 +452,6 @@ 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,
personBatchWritePerKeyTeamAllowlist: serverConfig.PERSON_BATCH_WRITING_PER_KEY_TEAM_ALLOWLIST,
})
const personRepository = buildPersonRepository(
diff --git a/nodejs/tests/ingestion/ingestion-e2e.test.ts b/nodejs/tests/ingestion/ingestion-e2e.test.ts
index 0fd1ae8d4f94..32e2764c3fe4 100644
--- a/nodejs/tests/ingestion/ingestion-e2e.test.ts
+++ b/nodejs/tests/ingestion/ingestion-e2e.test.ts
@@ -37,13 +37,10 @@ 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,
@@ -54,7 +51,6 @@ 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.serial.test.ts b/nodejs/tests/ingestion/person-state-batch.serial.test.ts
index bee06da96043..5f5d0f646594 100644
--- a/nodejs/tests/ingestion/person-state-batch.serial.test.ts
+++ b/nodejs/tests/ingestion/person-state-batch.serial.test.ts
@@ -313,8 +313,7 @@ describe('PersonState.processEvent()', () => {
team = mainTeam,
mergeMode = createDefaultSyncMergeMode(),
mergeEventsConfig?: { enabled: boolean; partitionCount: number; teamAllowlist?: string },
- customPersonsStore?: BatchWritingPersonsStore,
- mergeTombstoneEnabled = false
+ customPersonsStore?: BatchWritingPersonsStore
) {
const fullEvent = {
team_id: teamId,
@@ -331,7 +330,6 @@ describe('PersonState.processEvent()', () => {
(customHub ? new PostgresPersonRepository(customHub.postgres) : personRepository),
createPersonOutputs(kafkaProducer),
{
- mergeTombstoneTeamAllowlist: mergeTombstoneEnabled ? '*' : '',
mergeEventsEnabled: mergeEventsConfig?.enabled ?? false,
mergeEventsPartitionCount: mergeEventsConfig?.partitionCount ?? 64,
// Allow-all default so the enabled/produce tests are unaffected by the
@@ -1849,7 +1847,7 @@ describe('PersonState.processEvent()', () => {
expect.objectContaining({
id: expect.any(String),
is_deleted: 1,
- version: 100,
+ version: 1,
}),
])
)
@@ -1932,7 +1930,7 @@ describe('PersonState.processEvent()', () => {
expect.objectContaining({
id: expect.any(String),
is_deleted: 1,
- version: 100,
+ version: 1,
}),
])
)
@@ -2132,7 +2130,7 @@ describe('PersonState.processEvent()', () => {
expect.objectContaining({
id: expect.any(String),
is_deleted: 1,
- version: 100,
+ version: 1,
}),
])
)
@@ -3011,7 +3009,7 @@ describe('PersonState.processEvent()', () => {
expect.objectContaining({
id: expect.any(String),
is_deleted: 1,
- version: 100,
+ version: 1,
}),
])
)
@@ -3522,7 +3520,7 @@ describe('PersonState.processEvent()', () => {
expect.objectContaining({
id: secondUserUuid,
is_deleted: 1,
- version: 100,
+ version: 1,
}),
])
)
@@ -4438,7 +4436,7 @@ describe('PersonState.processEvent()', () => {
)
})
- it('tombstone-mode merge with a concurrently tombstoned source converges to a no-op instead of half-applying', async () => {
+ it('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,
})
@@ -4461,9 +4459,7 @@ describe('PersonState.processEvent()', () => {
// and merge the stale source properties into the target. The stale fetch is
// seeded into the store's cache: a fresh fetch filters tombstoned persons, and
// the race this pins is precisely a fetch that predates the tombstone.
- const staleCacheStore = new BatchWritingPersonsStore(personRepository, createPersonOutputs(kafkaProducer), {
- mergeTombstoneTeamAllowlist: '*',
- })
+ const staleCacheStore = new BatchWritingPersonsStore(personRepository, createPersonOutputs(kafkaProducer))
staleCacheStore.setCachedPersonForUpdate(
teamId,
secondUserDistinctId,
@@ -4489,8 +4485,7 @@ describe('PersonState.processEvent()', () => {
mainTeam,
createDefaultSyncMergeMode(),
undefined,
- staleCacheStore,
- true
+ staleCacheStore
)
const result = await mergeService.merge(secondUserDistinctId, firstUserDistinctId, teamId, timestamp)
@@ -4514,15 +4509,11 @@ describe('PersonState.processEvent()', () => {
expect(targetDistinctIds).toEqual([firstUserDistinctId])
})
- it('tombstone-mode merge retries past a cached tombstoned person instead of failing', async () => {
+ it('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',
@@ -4531,14 +4522,11 @@ describe('PersonState.processEvent()', () => {
uuid: new UUIDT().toString(),
},
hub,
- tombstoneRepository,
+ personRepository,
true,
timestamp,
mainTeam,
- createDefaultSyncMergeMode(),
- undefined,
- undefined,
- true
+ createDefaultSyncMergeMode()
)
// Warm the batch cache with the live person, then tombstone it and its
@@ -4569,7 +4557,7 @@ describe('PersonState.processEvent()', () => {
expect(result.person).toBeDefined()
})
- it('tombstone-mode merge held off by a live lifecycle claim drops with a warning', async () => {
+ it('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,
})
@@ -4601,10 +4589,7 @@ describe('PersonState.processEvent()', () => {
true,
timestamp,
mainTeam,
- createDefaultSyncMergeMode(),
- undefined,
- undefined,
- true
+ createDefaultSyncMergeMode()
)
const result = await mergeService.handleIdentifyOrAlias()
@@ -4625,7 +4610,7 @@ describe('PersonState.processEvent()', () => {
}
})
- it('tombstone-mode merge stamps the exact death version on the source row and its death message', async () => {
+ it('merge stamps the exact death version on the source row and its death message', async () => {
await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {
distinctId: firstUserDistinctId,
})
@@ -4634,10 +4619,6 @@ describe('PersonState.processEvent()', () => {
})
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',
@@ -4646,14 +4627,11 @@ describe('PersonState.processEvent()', () => {
uuid: new UUIDT().toString(),
},
hub,
- tombstoneRepository,
+ personRepository,
true,
timestamp,
mainTeam,
- createDefaultSyncMergeMode(),
- undefined,
- undefined,
- true
+ createDefaultSyncMergeMode()
)
const result = await mergeService.merge(secondUserDistinctId, firstUserDistinctId, teamId, timestamp)
diff --git a/nodejs/tests/ingestion/postgres-parity.test.ts b/nodejs/tests/ingestion/postgres-parity.test.ts
index 22ad210de0c9..157ab05762f1 100644
--- a/nodejs/tests/ingestion/postgres-parity.test.ts
+++ b/nodejs/tests/ingestion/postgres-parity.test.ts
@@ -21,7 +21,7 @@ import { PluginServerMode, PluginsServerConfig, PropertyUpdateOperation, Timesta
import { Clickhouse } from '../helpers/clickhouse'
import { waitForExpect } from '../helpers/expectations'
import { ensureKafkaTopics } from '../helpers/kafka'
-import { createUserTeamAndOrganization, uniqueTestId } from '../helpers/sql'
+import { createUserTeamAndOrganization, fetchPostgresPersons, uniqueTestId } from '../helpers/sql'
jest.mock('~/common/utils/logger')
@@ -569,7 +569,7 @@ describe('postgres parity', () => {
(await clickhouse.fetchPersons(teamId)).length === 1 ? ['deleted!'] : []
)
const clickHousePersons = await clickhouse.fetchPersons(teamId)
- const postgresPersons = await fetchPersons(postgres, teamId)
+ const postgresPersons = await fetchPostgresPersons(postgres, teamId)
expect(clickHousePersons.length).toEqual(1)
expect(postgresPersons.length).toEqual(1)