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(ingestion): recover a person create that loses the uuid key (#87377)

Eli Reismane718b26ca52e
diff --git a/nodejs/src/common/persons/metrics.ts b/nodejs/src/common/persons/metrics.ts
index 66d6195b627f..f1d87da4f21a 100644
--- a/nodejs/src/common/persons/metrics.ts
+++ b/nodejs/src/common/persons/metrics.ts
@@ -205,6 +205,14 @@ export const personCreateStrandedClaimCounter = new Counter({
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',
+ // uuid: resolved to the row already holding the uuid, after recovery by distinct ID found nothing
+ // none: the holder was gone by the time we looked, so the create failed
+ labelNames: ['resolved_by'],
+})
+
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.ts
index 5981b1977064..43d8bc6eeff9 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
@@ -463,13 +463,50 @@ describe('PostgresPersonRepository', () => {
}
)
- expect(second).toEqual({ success: false, error: 'CreationConflict', distinctIds: ['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
+ // the pipeline retries until the consumer dies with uncommitted offsets.
+ expect(second).toEqual({
+ success: false,
+ error: 'CreationConflict',
+ distinctIds: ['live-uuid-did-2'],
+ conflictingPerson: expect.objectContaining({ id: first.person.id, uuid }),
+ })
await expect(repository.fetchPerson(team.id, 'live-uuid-did')).resolves.toMatchObject({
version: 0,
properties: { a: 1 },
})
})
+ it('returns the uuid holder when the create runs inside a transaction', async () => {
+ // The legacy path recovers from a caught unique violation, which leaves the
+ // transaction aborted. Reading the holder on that transaction raises 25P02 and the
+ // throw escapes the conflict branch entirely, failing the merge saga that reaches
+ // createPerson through inTransaction. `repository` has no allowlist, so it takes
+ // that path rather than the ON CONFLICT one.
+ const team = await getFirstTeam(hub.postgres)
+ const uuid = new UUIDT().toString()
+ const first = await repository.createPerson(TIMESTAMP, { a: 1 }, {}, {}, team.id, null, false, uuid, {
+ distinctId: 'tx-uuid-did',
+ })
+ if (!first.success) {
+ throw new Error('Failed to create person')
+ }
+
+ const second = await repository.inTransaction('conflict-inside-transaction', (tx) =>
+ tx.createPerson(TIMESTAMP, { b: 2 }, {}, {}, team.id, null, false, uuid, {
+ distinctId: 'tx-uuid-did-2',
+ })
+ )
+
+ expect(second).toEqual({
+ success: false,
+ error: 'CreationConflict',
+ distinctIds: ['tx-uuid-did-2'],
+ conflictingPerson: expect.objectContaining({ id: first.person.id, uuid }),
+ })
+ })
+
it('createPerson dedupes repeated distinct ids instead of failing the multi-insert', async () => {
const team = await getFirstTeam(hub.postgres)
const uuid = new UUIDT().toString()
diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository.ts b/nodejs/src/common/persons/repositories/postgres-person-repository.ts
index d3069ef88d09..dac21d47ca3c 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.ts
@@ -70,6 +70,14 @@ 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
}
@@ -317,6 +325,36 @@ export class PostgresPersonRepository
}
}
+ /**
+ * The person that already holds this (team_id, uuid).
+ *
+ * Read straight after a create loses the key, so the caller can resolve to that person
+ * instead of failing. Recovering by distinct ID cannot find this row whenever the holder
+ * does not own the distinct ID we were creating for, which is the case that turns a
+ * conflict into a stuck consumer.
+ *
+ * Pass `tx` only from a path whose transaction is still usable. After a unique violation it
+ * is not: Postgres aborts the transaction and rejects every later statement on it with
+ * 25P02, and nothing here opens a savepoint (`postgres.ts` runs plain BEGIN/COMMIT/ROLLBACK).
+ * A caller recovering from that error must omit `tx` and read on a pool connection, the way
+ * the distinct-ID recovery in person-create-service already does. The holder was committed
+ * by another transaction, which is why we conflicted with it, so a pool connection sees it.
+ */
+ private async fetchPersonByUuid(
+ teamId: number,
+ uuid: string,
+ tx?: TransactionClient
+ ): Promise<InternalPerson | undefined> {
+ const { rows } = await this.postgres.query<RawPerson>(
+ tx ?? PostgresUse.PERSONS_WRITE,
+ `SELECT ${PERSON_COLUMNS} FROM posthog_person
+ WHERE team_id = $1 AND uuid = $2 AND is_deleted = false`,
+ [teamId, uuid],
+ 'fetchPersonByUuid'
+ )
+ return rows.length > 0 ? this.toPerson(rows[0]) : undefined
+ }
+
async fetchPersonsByDistinctIds(
teamPersons: { teamId: TeamId; distinctId: string }[],
useReadReplica: boolean = true,
@@ -719,6 +757,7 @@ export class PostgresPersonRepository
success: false,
error: 'CreationConflict',
distinctIds: distinctIds.map((d) => d.distinctId),
+ conflictingPerson: await this.fetchPersonByUuid(teamId, uuid, tx),
}
}
@@ -748,6 +787,8 @@ export class PostgresPersonRepository
[distinctIdRows.map((row) => row.id), teamId, person.id],
'undoInsertPerson'
)
+ // A distinct-ID collision, not a uuid one: the caller resolves this by
+ // re-fetching on distinct ID, so there is no holder to look up.
return {
success: false,
error: 'CreationConflict',
@@ -1030,6 +1071,12 @@ export class PostgresPersonRepository
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,
}
}
@@ -1214,6 +1261,12 @@ export class PostgresPersonRepository
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,
}
}
diff --git a/nodejs/src/common/utils/db/db.ts b/nodejs/src/common/utils/db/db.ts
index ee0a2a29b98c..83d6d59b1b23 100644
--- a/nodejs/src/common/utils/db/db.ts
+++ b/nodejs/src/common/utils/db/db.ts
@@ -19,7 +19,14 @@ export type CreatePersonResult =
readonly messages: PersonMessage[]
readonly created: false
}
- | { readonly success: false; readonly error: 'CreationConflict'; readonly distinctIds: string[] }
+ | {
+ readonly success: false
+ readonly error: 'CreationConflict'
+ readonly distinctIds: string[]
+ // The person that already holds this (team_id, uuid), when we could read it back.
+ // Absent means the holder disappeared between the failed write and the lookup.
+ readonly conflictingPerson?: InternalPerson
+ }
| { readonly success: false; readonly error: 'PropertiesSizeViolation'; readonly distinctIds: string[] }
export interface PersonPropertiesSize {
diff --git a/nodejs/src/ingestion/common/persons/person-create-service.test.ts b/nodejs/src/ingestion/common/persons/person-create-service.test.ts
index df84e9b00064..d70026e70dd3 100644
--- a/nodejs/src/ingestion/common/persons/person-create-service.test.ts
+++ b/nodejs/src/ingestion/common/persons/person-create-service.test.ts
@@ -3,6 +3,7 @@ import { DateTime } from 'luxon'
import { PersonPropertiesSizeViolationError } from '~/common/persons/repositories/person-repository'
import { UUIDT } from '~/common/utils/utils'
import { emitIngestionWarning } from '~/ingestion/common/ingestion-warnings'
+import { InternalPerson } from '~/types'
import { PersonContext } from './person-context'
import { PersonCreateService } from './person-create-service'
@@ -190,6 +191,87 @@ describe('PersonCreateService', () => {
expect(mockPersonStore.fetchForUpdate).toHaveBeenCalledWith(teamId, 'test-distinct-id')
})
+ it('should resolve to the row holding the uuid when no distinct ID resolves it', async () => {
+ // The holder owns a different distinct ID, so recovery by distinct ID finds nothing.
+ // Before this returned the holder, the create threw an error the pipeline rethrows
+ // until the consumer dies with uncommitted offsets.
+ const makePerson = (id: string): InternalPerson => ({
+ id,
+ uuid: new UUIDT().toString(),
+ team_id: teamId,
+ properties: {},
+ created_at: createdAt,
+ version: 1,
+ is_identified: false,
+ is_user_id: null,
+ properties_last_updated_at: {},
+ properties_last_operation: {},
+ last_seen_at: null,
+ })
+ const holder = makePerson('999')
+ mockPersonStore.createPerson.mockResolvedValue({
+ success: false,
+ error: 'CreationConflict',
+ distinctIds: ['test-distinct-id'],
+ conflictingPerson: holder,
+ })
+ mockPersonStore.fetchForUpdate.mockResolvedValue(null)
+
+ const [person, created] = await personCreateService.createPerson(
+ createdAt,
+ properties,
+ propertiesOnce,
+ teamId,
+ isUserId,
+ isIdentified,
+ creatorEventUuid,
+ primaryDistinctId
+ )
+
+ expect(person).toEqual(holder)
+ expect(created).toBe(false)
+ })
+
+ it('should prefer the distinct ID match over the uuid holder when both exist', async () => {
+ // A concurrent create of the same distinct ID is the common case and must keep
+ // resolving to that person, not to whatever holds the uuid.
+ const makePerson = (id: string): InternalPerson => ({
+ id,
+ uuid: new UUIDT().toString(),
+ team_id: teamId,
+ properties: {},
+ created_at: createdAt,
+ version: 1,
+ is_identified: false,
+ is_user_id: null,
+ properties_last_updated_at: {},
+ properties_last_operation: {},
+ last_seen_at: null,
+ })
+ const holder = makePerson('999')
+ const byDistinctId = makePerson('2')
+ mockPersonStore.createPerson.mockResolvedValue({
+ success: false,
+ error: 'CreationConflict',
+ distinctIds: ['test-distinct-id'],
+ conflictingPerson: holder,
+ })
+ mockPersonStore.fetchForUpdate.mockResolvedValue(byDistinctId)
+
+ const [person] = await personCreateService.createPerson(
+ createdAt,
+ properties,
+ propertiesOnce,
+ teamId,
+ isUserId,
+ isIdentified,
+ creatorEventUuid,
+ primaryDistinctId
+ )
+
+ expect(person).toEqual(byDistinctId)
+ })
+
it('should throw error when creation conflict occurs but person cannot be fetched', async () => {
const conflictResult = {
success: false,
diff --git a/nodejs/src/ingestion/common/persons/person-create-service.ts b/nodejs/src/ingestion/common/persons/person-create-service.ts
index e9b93be2c686..8c96cdc353af 100644
--- a/nodejs/src/ingestion/common/persons/person-create-service.ts
+++ b/nodejs/src/ingestion/common/persons/person-create-service.ts
@@ -1,5 +1,6 @@
import { DateTime } from 'luxon'
+import { personCreateConflictResolvedCounter } from '~/common/persons/metrics'
import { PersonPropertiesSizeViolationError } from '~/common/persons/repositories/person-repository'
import { emitIngestionWarning } from '~/ingestion/common/ingestion-warnings'
import { uuidFromDistinctId } from '~/ingestion/common/persons/person-uuid'
@@ -74,7 +75,19 @@ export class PersonCreateService {
}
}
- // If we still can't find the person, something is wrong
+ // Nothing owns the distinct IDs we tried to create, so the row holding this
+ // uuid owns a different one. Resolve to it: the alternative is an error with no
+ // isRetriable, which the pipeline rethrows until the consumer dies with
+ // uncommitted offsets. The event is attributed to the holder without moving any
+ // mapping, so no two identities are silently merged.
+ if (result.conflictingPerson) {
+ personCreateConflictResolvedCounter.labels({ resolved_by: 'uuid' }).inc()
+ return [result.conflictingPerson, false]
+ }
+
+ // The holder vanished between the failed write and the lookup, so there is
+ // nothing to resolve to.
+ personCreateConflictResolvedCounter.labels({ resolved_by: 'none' }).inc()
throw new Error(
`Person creation failed with constraint violation, but could not fetch existing person for distinct IDs: ${result.distinctIds.join(
', '