Skip to content

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

fix(persons): claim stranded person rows on create instead of duplicating them (#82047)

Eli Reismaneba26a651d92
diff --git a/nodejs/src/common/persons/metrics.ts b/nodejs/src/common/persons/metrics.ts
index bb115e911864..66d6195b627f 100644
--- a/nodejs/src/common/persons/metrics.ts
+++ b/nodejs/src/common/persons/metrics.ts
@@ -196,6 +196,15 @@ 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 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-stranded-claim.test.ts b/nodejs/src/common/persons/repositories/postgres-person-repository-stranded-claim.test.ts
new file mode 100644
index 000000000000..44b675818a65
--- /dev/null
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository-stranded-claim.test.ts
@@ -0,0 +1,380 @@
+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')
+
+// Production does NOT have the unique (team_id, uuid) index the tracked schema declares
+// (posthog_person_new_uuid_idx is non-unique in both prod regions), which is what lets
+// duplicate persons exist there at all. The tests below recreate that reality; with the
+// tracked schema's unique index in place, the duplicate scenarios cannot even be seeded
+// and 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.ts b/nodejs/src/common/persons/repositories/postgres-person-repository.ts
index 3260a8d6e252..d3069ef88d09 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.ts
@@ -5,6 +5,7 @@ import { buildIntegerMatcher } from '~/common/config/config'
import { PERSON_DISTINCT_IDS_OUTPUT } from '~/common/outputs/persons'
import {
oversizedPersonPropertiesTrimmedCounter,
+ personCreateStrandedClaimCounter,
personJsonFieldSizeHistogram,
personPropertiesSizeViolationCounter,
} from '~/common/persons/metrics'
@@ -81,6 +82,17 @@ export interface PostgresPersonRepositoryOptions {
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
}
const DEFAULT_OPTIONS: PostgresPersonRepositoryOptions = {
@@ -88,6 +100,7 @@ const DEFAULT_OPTIONS: PostgresPersonRepositoryOptions = {
personPropertiesDbConstraintLimitBytes: DEFAULT_PERSON_PROPERTIES_DB_CONSTRAINT_LIMIT_BYTES,
personPropertiesTrimTargetBytes: DEFAULT_PERSON_PROPERTIES_TRIM_TARGET_BYTES,
personMergeTombstoneTeamAllowlist: '',
+ personCreateClaimTeamAllowlist: '',
}
export class PostgresPersonRepository
@@ -95,6 +108,7 @@ export class PostgresPersonRepository
{
private options: PostgresPersonRepositoryOptions
private isTombstoneTeam: ValueMatcher<number>
+ private isClaimTeam: ValueMatcher<number>
constructor(
private postgres: PostgresRouter,
@@ -102,6 +116,7 @@ export class PostgresPersonRepository
) {
this.options = { ...DEFAULT_OPTIONS, ...options }
this.isTombstoneTeam = buildIntegerMatcher(this.options.personMergeTombstoneTeamAllowlist, true)
+ this.isClaimTeam = buildIntegerMatcher(this.options.personCreateClaimTeamAllowlist, true)
}
private async handleOversizedPersonProperties(
@@ -533,6 +548,21 @@ export class PostgresPersonRepository
// 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,
@@ -773,6 +803,258 @@ 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),
+ }
+ }
+
+ 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(
diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.ts
index 7948384295a5..5849da157066 100644
--- a/nodejs/src/ingestion/config.ts
+++ b/nodejs/src/ingestion/config.ts
@@ -177,6 +177,12 @@ export type IngestionConsumerConfig = {
// recreated person revives above its own tombstone. Comma-separated team IDs, or '*' for all
// teams; empty means no teams.
PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST: string
+ // 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
@@ -322,6 +328,7 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {
PERSON_MERGE_FOLD_ENABLED: false,
PERSON_MERGE_FOLD_TEAM_ALLOWLIST: '*',
PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST: '',
+ PERSON_CREATE_CLAIM_TEAM_ALLOWLIST: '',
// Group batch writing config
GROUP_BATCH_WRITING_USE_BATCH_UPDATES: true,
diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.ts
index c5e8cdaee4f4..f7bfb9eb5ddc 100644
--- a/nodejs/src/servers/ingestion-api-server.ts
+++ b/nodejs/src/servers/ingestion-api-server.ts
@@ -282,6 +282,7 @@ export class IngestionApiServer implements NodeServer {
const postgresPersonRepository = new PostgresPersonRepository(this.postgres, {
calculatePropertiesSize: this.config.PERSON_UPDATE_CALCULATE_PROPERTIES_SIZE,
personMergeTombstoneTeamAllowlist: this.config.PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST,
+ personCreateClaimTeamAllowlist: this.config.PERSON_CREATE_CLAIM_TEAM_ALLOWLIST,
})
const personRepository = buildPersonRepository(
personhogClient,
diff --git a/nodejs/src/servers/ingestion-general-server.ts b/nodejs/src/servers/ingestion-general-server.ts
index ddfebdf596e2..1c7ac6980302 100644
--- a/nodejs/src/servers/ingestion-general-server.ts
+++ b/nodejs/src/servers/ingestion-general-server.ts
@@ -221,6 +221,7 @@ export class IngestionGeneralServer implements NodeServer {
const postgresPersonRepository = new PostgresPersonRepository(this.postgres, {
calculatePropertiesSize: this.config.PERSON_UPDATE_CALCULATE_PROPERTIES_SIZE,
personMergeTombstoneTeamAllowlist: this.config.PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST,
+ personCreateClaimTeamAllowlist: this.config.PERSON_CREATE_CLAIM_TEAM_ALLOWLIST,
})
const personRepository = buildPersonRepository(
personhogClient,