:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(persons): reattach a stray distinct id left on a tombstoned person (#111457)
Eli Reisman31966dbd81c1
diff --git a/nodejs/src/common/persons/metrics.ts b/nodejs/src/common/persons/metrics.tsindex 188e5bb95a68..40d831d836f0 100644--- a/nodejs/src/common/persons/metrics.ts+++ b/nodejs/src/common/persons/metrics.ts@@ -250,6 +250,12 @@ export const personCreateConflictResolvedCounter = new Counter({labelNames: ['resolved_by'],})+export const personStrayDistinctIdTombstonedCounter = new Counter({+ name: 'person_stray_distinct_id_tombstoned_total',+ help: 'Live distinct id mappings on a tombstoned person that a write tombstoned so it could reuse the distinct id',+ labelNames: ['operation'],+})+export const personJsonFieldSizeHistogram = new Histogram({name: 'person_json_field_size_bytes',help: 'Approximate size in bytes of serialized JSON fields (using string length as proxy for performance)',diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts b/nodejs/src/common/persons/repositories/postgres-person-repository.test.tsindex f36844915ea5..96c8dbea8be0 100644--- a/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts@@ -6,6 +6,7 @@ import { KAFKA_PERSON, KAFKA_PERSON_DISTINCT_ID } from '~/common/config/kafka-toimport { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT } from '~/common/outputs/persons'import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'+import { PersonMessage } from '~/common/persons/person-message'import { closeHub, createHub } from '~/common/utils/db/hub'import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'import { parseJSON } from '~/common/utils/json-parse'@@ -217,6 +218,11 @@ describe('PostgresPersonRepository', () => {})})+ function recordQueryTags(): () => string[] {+ const spy = jest.spyOn(postgres, 'query')+ return () => spy.mock.calls.map((call) => String(call[3]))+ }+async function tombstonePerson(person: InternalPerson): Promise<void> {await postgres.query(PostgresUse.PERSONS_WRITE,@@ -772,6 +778,7 @@ describe('PostgresPersonRepository', () => {it('createPerson undoes its insert when a distinct id is owned by a live mapping', async () => {await createTestPerson(team.id, 'contested-did')const uuid = new UUIDT().toString()+ const queryTags = recordQueryTags()const result = await revivalRepository.createPerson(TIMESTAMP,@@ -787,6 +794,7 @@ describe('PostgresPersonRepository', () => {)expect(result).toMatchObject({ success: false, error: 'CreationConflict' })+ expect(queryTags()).not.toContain('lockStrayDistinctIds')// 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.@@ -800,6 +808,104 @@ describe('PostgresPersonRepository', () => {await expect(repository.fetchPerson(team.id, 'undo-primary-did')).resolves.toBeUndefined()})+ 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 tombstonePerson(deadOwner)++ const result = await revivalRepository.createPerson(+ TIMESTAMP,+ {},+ {},+ {},+ team.id,+ null,+ false,+ new UUIDT().toString(),+ { distinctId: 'mixed-stray-did' },+ [{ distinctId: 'mixed-contested-did' }]+ )++ expect(result).toMatchObject({ success: false, error: 'CreationConflict' })+ // The tombstone is not published. Its version stays above the mapping's ClickHouse row,+ // and the ClickHouse deletion sweep removes that row with the deleted owner.+ const strayRows = await postgres.query(+ PostgresUse.PERSONS_WRITE,+ 'SELECT is_deleted, version FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2',+ [team.id, 'mixed-stray-did'],+ 'fetchMixedStray'+ )+ expect(strayRows.rows).toEqual([{ is_deleted: true, version: '4' }])+ await expect(repository.fetchPerson(team.id, 'mixed-contested-did')).resolves.toMatchObject({+ uuid: liveOwner.uuid,+ })+ })++ it.each([+ [+ 'createPerson',+ async (): Promise<[string, PersonMessage[]]> => {+ const uuid = new UUIDT().toString()+ const result = await revivalRepository.createPerson(+ TIMESTAMP,+ {},+ {},+ {},+ team.id,+ null,+ false,+ uuid,+ {+ distinctId: 'stray-did',+ }+ )+ if (!result.success) {+ throw new Error('Expected creation to succeed')+ }+ return [uuid, result.messages.slice(1)]+ },+ ],+ [+ 'addDistinctId',+ async (): Promise<[string, PersonMessage[]]> => {+ const newOwner = await createTestPerson(team.id, 'stray-adder-did')+ return [newOwner.uuid, await revivalRepository.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 tombstonePerson(deadOwner)++ const [ownerUuid, messages] = await write()++ await expect(repository.fetchPerson(team.id, 'stray-did')).resolves.toMatchObject({ uuid: ownerUuid })+ expect(messages.map((message) => parseJSON(message.value!.toString()))).toEqual([+ expect.objectContaining({ distinct_id: 'stray-did', person_id: ownerUuid, version: 3, is_deleted: 0 }),+ ])+ })++ it('createPerson that revives the owner of a stray keeps the stray attached', async () => {+ 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' }+ )++ 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 })+ })+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')@@ -821,14 +927,24 @@ describe('PostgresPersonRepository', () => {})})- it('addDistinctId throws DistinctIdConflictError for a live mapping', async () => {- const person = await createTestPerson(team.id, 'conflict-adder-did')- await createTestPerson(team.id, 'already-owned-did')+ it.each([+ ['another live person', 'other-owned-did', false],+ ['the same person', 'conflict-adder-did', true],+ ])(+ 'addDistinctId throws DistinctIdConflictError for a live mapping owned by %s',+ async (_owner, distinctId, ownedBySamePerson) => {+ const person = await createTestPerson(team.id, 'conflict-adder-did')+ if (!ownedBySamePerson) {+ await createTestPerson(team.id, distinctId)+ }+ const queryTags = recordQueryTags()- await expect(revivalRepository.addDistinctId(person, 'already-owned-did', 0)).rejects.toThrow(- DistinctIdConflictError- )- })+ await expect(revivalRepository.addDistinctId(person, distinctId, 0)).rejects.toThrow(+ DistinctIdConflictError+ )+ expect(queryTags()).not.toContain('lockStrayDistinctIds')+ }+ )it('isPersonLive is true for a live person and false for a tombstoned one', async () => {const person = await createTestPerson(team.id, 'live-check-did')diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository.ts b/nodejs/src/common/persons/repositories/postgres-person-repository.tsindex 51ec443cb8e1..be284aa45f53 100644--- a/nodejs/src/common/persons/repositories/postgres-person-repository.ts+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.ts@@ -8,6 +8,7 @@ import {personCreateStrandedClaimCounter,personJsonFieldSizeHistogram,personPropertiesSizeViolationCounter,+ personStrayDistinctIdTombstonedCounter,} from '~/common/persons/metrics'import { canTrimProperty } from '~/common/persons/person-property-utils'import { PersonUpdate, toInternalPerson } from '~/common/persons/person-update-batch'@@ -580,6 +581,113 @@ export class PostgresPersonRepositoryreturn result}+ /** A delete that races an attach can leave a live mapping on a tombstoned person, which no read resolves. */+ private async reattachStrayDistinctIds(+ person: InternalPerson,+ distinctIds: { distinctId: string; version?: number }[],+ operation: 'createPerson' | 'addDistinctId',+ tx?: TransactionClient+ ): Promise<{ id: string; team_id: number; person_id: string; distinct_id: string; version: number }[]> {+ if (distinctIds.length === 0) {+ return []+ }+ const names = distinctIds.map(({ distinctId }) => distinctId)+ // Almost every conflict is a live person's mapping, so return those without the lock below.+ const {+ rows: [{ healthy }],+ } = await this.postgres.query<{ healthy: number }>(+ tx ?? PostgresUse.PERSONS_WRITE,+ `SELECT count(*)::int AS healthy FROM posthog_persondistinctid d+ WHERE d.team_id = $1 AND d.distinct_id = ANY($2::text[]) AND d.is_deleted = false+ AND ($3::bigint IS NULL OR d.person_id <> $3)+ AND EXISTS (+ SELECT 1 FROM posthog_person p+ WHERE p.team_id = d.team_id AND p.id = d.person_id AND p.is_deleted = false+ )`,+ [person.team_id, names, operation === 'createPerson' ? person.id : null],+ 'countHealthyDistinctIdConflicts'+ )+ if (healthy === names.length) {+ return []+ }+ if (!tx) {+ return await this.inRawTransaction('reattachStrayDistinctIds', (newTx) =>+ this.reattachStrayDistinctIds(person, distinctIds, operation, newTx)+ )+ }++ // Lock first: after a lock wait, an UPDATE's person subquery still reads the pre-wait snapshot.+ await this.postgres.query(+ tx,+ `SELECT id FROM posthog_persondistinctid+ WHERE team_id = $1 AND distinct_id = ANY($2::text[]) AND is_deleted = false+ ORDER BY id+ FOR UPDATE`,+ [person.team_id, names],+ 'lockStrayDistinctIds'+ )+ const { rowCount: tombstoned } = await this.postgres.query(+ tx,+ `UPDATE posthog_persondistinctid d+ SET is_deleted = true, version = COALESCE(d.version, 0) + 1+ WHERE d.team_id = $1 AND d.distinct_id = ANY($2::text[]) AND d.is_deleted = false+ AND NOT EXISTS (+ SELECT 1 FROM posthog_person p+ WHERE p.team_id = d.team_id AND p.id = d.person_id AND p.is_deleted = false+ )`,+ [person.team_id, names],+ 'tombstoneStrayDistinctIds'+ )+ if (tombstoned) {+ personStrayDistinctIdTombstonedCounter.labels({ operation }).inc(tombstoned)+ }++ // Retry all of them: a concurrent delete can tombstone a mapping during the lock wait.+ const { rows } = await this.postgres.query<{+ id: string+ team_id: number+ person_id: string+ distinct_id: string+ version: string+ }>(+ tx,+ // NOTE: Keep this in sync with the posthog_persondistinctid INSERT in createPerson and addDistinctId.+ `INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version)+ SELECT d.distinct_id, $1, $2, d.version+ FROM unnest($3::text[], $4::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::text AS id, team_id, person_id, distinct_id, version`,+ [person.id, person.team_id, names, distinctIds.map(({ version }) => version ?? 0)],+ 'reattachStrayDistinctIds'+ )+ const reattached = new Set(rows.map((row) => row.distinct_id))+ const unattached = names.filter((name) => !reattached.has(name))+ // A create with the tombstoned owner's uuid revives that owner, so its mapping stays live and correct.+ // addDistinctId reports a mapping that its own person already holds as a conflict.+ if (operation === 'createPerson' && unattached.length > 0) {+ const { rows: owned } = await this.postgres.query<{+ id: string+ team_id: number+ person_id: string+ distinct_id: string+ version: string+ }>(+ tx,+ `SELECT id::text AS id, team_id, person_id, distinct_id, version+ FROM posthog_persondistinctid+ WHERE team_id = $1 AND person_id = $2 AND distinct_id = ANY($3::text[]) AND is_deleted = false`,+ [person.team_id, person.id, unattached],+ 'fetchOwnedStrayDistinctIds'+ )+ rows.push(...owned)+ }+ return rows.map((row) => ({ ...row, version: Number(row.version) }))+ }+async createPerson(createdAt: DateTime,properties: Properties,@@ -774,6 +882,18 @@ export class PostgresPersonRepositoryconst { distinct_id_rows: distinctIdRows, ...personRow } = rows[0]const person = this.toPerson(personRow)+ if (distinctIdRows.length < distinctIds.length) {+ const attached = new Set(distinctIdRows.map((row) => row.distinct_id))+ distinctIdRows.push(+ ...(await this.reattachStrayDistinctIds(+ person,+ distinctIds.filter(({ distinctId }) => !attached.has(distinctId)),+ 'createPerson',+ tx+ ))+ )+ }+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@@ -1588,7 +1708,12 @@ export class PostgresPersonRepository'warn')- if (insertResult.rows.length === 0) {+ const insertedRows =+ insertResult.rows.length > 0+ ? insertResult.rows+ : await this.reattachStrayDistinctIds(person, [{ distinctId, version }], 'addDistinctId', tx)++ if (insertedRows.length === 0) {throw new DistinctIdConflictError('Distinct id is already owned by a live mapping',person.team_id,@@ -1601,7 +1726,7 @@ export class PostgresPersonRepositoryis_deleted,version: insertedVersion,...personDistinctIdCreated- } = insertResult.rows[0] as PersonDistinctId & { is_deleted: boolean }+ } = insertedRows[0] as PersonDistinctId & { is_deleted: boolean }return [{output: PERSON_DISTINCT_IDS_OUTPUT,