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): guarantee merge mapping delivery without produce awaits (#96917)

José Sequeira0a58e92bafac
diff --git a/nodejs/src/common/personhog/personhog-person-repository.test.ts b/nodejs/src/common/personhog/personhog-person-repository.test.ts
index 730378356900..87f3bcae865d 100644
--- a/nodejs/src/common/personhog/personhog-person-repository.test.ts
+++ b/nodejs/src/common/personhog/personhog-person-repository.test.ts
@@ -76,6 +76,7 @@ function createMockPostgres(): jest.Mocked<PersonRepository> {
fetchPersonsByPersonIds: jest.fn(),
fetchPersonsForUpdateByDistinctIds: jest.fn(),
fetchDistinctIdsForPersons: jest.fn(),
+ fetchPersonDistinctIdMappings: jest.fn(),
deletePersons: jest.fn(),
claimLifecycleMarks: jest.fn(),
releaseLifecycleMarks: jest.fn(),
diff --git a/nodejs/src/common/personhog/personhog-person-repository.ts b/nodejs/src/common/personhog/personhog-person-repository.ts
index 123454e6f5bf..ec109b38df2a 100644
--- a/nodejs/src/common/personhog/personhog-person-repository.ts
+++ b/nodejs/src/common/personhog/personhog-person-repository.ts
@@ -5,6 +5,7 @@ import { PersonUpdate } from '~/common/persons/person-update-batch'
import {
InternalPersonWithDistinctId,
LifecycleMarkPerson,
+ PersonDistinctIdMapping,
PersonRepository,
} from '~/common/persons/repositories/person-repository'
import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'
@@ -166,6 +167,10 @@ export class PersonHogPersonRepository implements PersonRepository {
}
}
+ fetchPersonDistinctIdMappings(_teamId: TeamId, _distinctIds: string[]): Promise<PersonDistinctIdMapping[]> {
+ return Promise.reject(new Error('fetchPersonDistinctIdMappings is not implemented for personhog'))
+ }
+
// All write operations delegate directly to Postgres
createPerson(
diff --git a/nodejs/src/common/persons/repositories/person-repository.ts b/nodejs/src/common/persons/repositories/person-repository.ts
index 10c66670ef05..84db4dd48be6 100644
--- a/nodejs/src/common/persons/repositories/person-repository.ts
+++ b/nodejs/src/common/persons/repositories/person-repository.ts
@@ -21,6 +21,12 @@ export type InternalPersonWithDistinctId = InternalPerson & {
distinct_id: string
}
+/** A distinct id's committed mapping row, shaped for re-emission to ClickHouse. */
+export type PersonDistinctIdMapping = {
+ distinctId: string
+ message: PersonMessage
+}
+
export class PersonPropertiesSizeViolationError extends Error {
constructor(
message: string,
@@ -159,6 +165,12 @@ export interface PersonRepository {
options?: { limitPerPerson?: number; useReadReplica?: boolean }
): Promise<Record<string, string[]>>
+ /**
+ * Reads the authoritative side: a stale pairing re-emitted with its version would
+ * overwrite a newer mapping. Ids without a live mapping are absent from the result.
+ */
+ fetchPersonDistinctIdMappings(teamId: TeamId, distinctIds: string[]): Promise<PersonDistinctIdMapping[]>
+
createPerson(
createdAt: DateTime,
properties: Properties,
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 c5ecc066001b..a16d85dd2763 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts
@@ -979,6 +979,51 @@ describe('PostgresPersonRepository', () => {
})
})
+ describe('fetchPersonDistinctIdMappings()', () => {
+ // Re-emission healing depends on this read carrying the committed pairing:
+ // a stale uuid or version 0 would overwrite or fail to repair ClickHouse.
+ it('returns the committed uuid and version per mapping, skipping deleted and missing ids', async () => {
+ const sourcePerson = await createTestPerson(team.id, 'anon')
+ const targetPerson = await createTestPerson(team.id, 'main')
+ const moveResult = await repository.moveDistinctIds(sourcePerson, targetPerson, undefined)
+ expect(moveResult.success).toBe(true)
+ await repository.addDistinctId(targetPerson, 'deleted-id', 1)
+ await postgres.query(
+ PostgresUse.PERSONS_WRITE,
+ 'UPDATE posthog_persondistinctid SET is_deleted = true WHERE team_id = $1 AND distinct_id = $2',
+ [team.id, 'deleted-id'],
+ 'markDeletedForTest'
+ )
+
+ const mappings = await repository.fetchPersonDistinctIdMappings(team.id, [
+ 'anon',
+ 'main',
+ 'deleted-id',
+ 'never-seen',
+ ])
+
+ const byDistinctId = Object.fromEntries(
+ mappings.map((mapping) => [mapping.distinctId, parseJSON(mapping.message.value!.toString())])
+ )
+ expect(Object.keys(byDistinctId).sort()).toEqual(['anon', 'main'])
+ expect(byDistinctId['anon']).toEqual({
+ team_id: team.id,
+ distinct_id: 'anon',
+ person_id: targetPerson.uuid,
+ version: 1,
+ is_deleted: 0,
+ })
+ expect(byDistinctId['main']).toEqual({
+ team_id: team.id,
+ distinct_id: 'main',
+ person_id: targetPerson.uuid,
+ version: 0,
+ is_deleted: 0,
+ })
+ expect(mappings.every((mapping) => mapping.message.output === PERSON_DISTINCT_IDS_OUTPUT)).toBe(true)
+ })
+ })
+
describe('moveDistinctIds()', () => {
it('should move distinct IDs from source to target person', async () => {
const sourcePerson = await createTestPerson(team.id, 'source-distinct-id', { name: 'Source Person' })
diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository.ts b/nodejs/src/common/persons/repositories/postgres-person-repository.ts
index dac21d47ca3c..6ca26408148f 100644
--- a/nodejs/src/common/persons/repositories/postgres-person-repository.ts
+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.ts
@@ -39,6 +39,7 @@ import {
InternalPersonWithDistinctId,
LifecycleMarkPerson,
PersonClaimedByLifecycleOpError,
+ PersonDistinctIdMapping,
PersonMessage,
PersonPropertiesSizeViolationError,
PersonRepository,
@@ -1851,6 +1852,41 @@ export class PostgresPersonRepository
return rows.map((row) => row.distinct_id)
}
+ async fetchPersonDistinctIdMappings(teamId: number, distinctIds: string[]): Promise<PersonDistinctIdMapping[]> {
+ if (distinctIds.length === 0) {
+ return []
+ }
+
+ const { rows } = await this.postgres.query<{ distinct_id: string; version: string | null; uuid: string }>(
+ PostgresUse.PERSONS_WRITE,
+ `SELECT pd.distinct_id, pd.version, p.uuid
+ FROM posthog_persondistinctid pd
+ JOIN posthog_person p ON p.id = pd.person_id AND p.team_id = pd.team_id
+ WHERE pd.team_id = $1 AND pd.distinct_id = ANY($2) AND pd.is_deleted = false`,
+ [teamId, distinctIds],
+ 'fetchPersonDistinctIdMappings'
+ )
+
+ return rows.map((row) => {
+ const version = Number(row.version || 0)
+ return {
+ distinctId: row.distinct_id,
+ message: {
+ output: PERSON_DISTINCT_IDS_OUTPUT,
+ value: Buffer.from(
+ JSON.stringify({
+ team_id: teamId,
+ distinct_id: row.distinct_id,
+ person_id: row.uuid,
+ version,
+ is_deleted: 0,
+ })
+ ),
+ },
+ }
+ })
+ }
+
async personPropertiesSize(personId: string, teamId: number): Promise<number> {
const queryString = `
SELECT COALESCE(pg_column_size(properties)::bigint, 0::bigint) AS total_props_bytes
diff --git a/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts b/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts
index 671a7f737c7d..5469b5d3a4f6 100644
--- a/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts
+++ b/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts
@@ -126,6 +126,7 @@ describe('BatchWritingPersonStore', () => {
const mockRepo = {
fetchPerson: jest.fn().mockResolvedValue(person),
fetchPersonDistinctIds: jest.fn().mockResolvedValue([]),
+ fetchPersonDistinctIdMappings: jest.fn().mockResolvedValue([]),
fetchPersonsByDistinctIds: jest.fn().mockResolvedValue([]),
fetchPersonsByPersonIds: jest.fn().mockResolvedValue([]),
fetchPersonsForUpdateByDistinctIds: jest.fn().mockResolvedValue([]),
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 5ed824c2f9ed..26b1327db34c 100644
--- a/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
+++ b/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
@@ -25,6 +25,7 @@ import { PersonUpdate, fromInternalPerson, toInternalPerson } from '~/common/per
import {
InternalPersonWithDistinctId,
LifecycleMarkPerson,
+ PersonDistinctIdMapping,
PersonMessage,
PersonPropertiesSizeViolationError,
PersonRepository,
@@ -41,6 +42,7 @@ import { PersonBatchWritingDbWriteMode } from '~/ingestion/config'
import { Properties } from '~/plugin-scaffold'
import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt, Team } from '~/types'
+import { MergeMappingDebounce } from './merge-mapping-debounce'
import { PersonOutputs } from './person-context'
import { PostgresMergePolicy, PostgresPersonMerge } from './person-merge-postgres'
import {
@@ -118,6 +120,10 @@ export interface BatchWritingPersonsStoreOptions {
mergeEventsEnabled: boolean
mergeEventsPartitionCount: number
mergeEventsTeamAllowlist: string
+ /** Gate and debounce sizing for re-emitting mappings on already-satisfied merges. */
+ mergeNoopMappingEmissionEnabled: boolean
+ mergeNoopMappingEmissionCacheSize: number
+ mergeNoopMappingEmissionTtlMs: number
}
const DEFAULT_OPTIONS: BatchWritingPersonsStoreOptions = {
@@ -132,6 +138,9 @@ const DEFAULT_OPTIONS: BatchWritingPersonsStoreOptions = {
mergeEventsEnabled: false,
mergeEventsPartitionCount: 64,
mergeEventsTeamAllowlist: '',
+ mergeNoopMappingEmissionEnabled: false,
+ mergeNoopMappingEmissionCacheSize: 500_000,
+ mergeNoopMappingEmissionTtlMs: 60 * 60 * 1000,
}
interface CacheMetrics {
@@ -568,6 +577,12 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
partitionCount: this.options.mergeEventsPartitionCount,
isTeamEnabled: buildIntegerMatcher(this.options.mergeEventsTeamAllowlist, true),
},
+ noopMappingDebounce: this.options.mergeNoopMappingEmissionEnabled
+ ? new MergeMappingDebounce(
+ this.options.mergeNoopMappingEmissionCacheSize,
+ this.options.mergeNoopMappingEmissionTtlMs
+ )
+ : undefined,
}
this.personCache = new BatchWritingPersonsCache()
Object.defineProperties(this, {
@@ -1276,6 +1291,14 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
})
}
+ /**
+ * Bypasses the batch caches on purpose: a healing emission must carry the
+ * committed version, not an optimistic in-batch state.
+ */
+ fetchPersonDistinctIdMappings(teamId: Team['id'], distinctIds: string[]): Promise<PersonDistinctIdMapping[]> {
+ return this.personRepository.fetchPersonDistinctIdMappings(teamId, distinctIds)
+ }
+
async fetchForUpdate(teamId: Team['id'], distinctId: string, batchId: number): Promise<InternalPerson | null> {
this.incrementCount('fetchForUpdate', distinctId)
const cache = this.personCache.obtainForBatchId(batchId)
diff --git a/nodejs/src/ingestion/common/persons/merge-mapping-debounce.ts b/nodejs/src/ingestion/common/persons/merge-mapping-debounce.ts
new file mode 100644
index 000000000000..2d29e1ec3b50
--- /dev/null
+++ b/nodejs/src/ingestion/common/persons/merge-mapping-debounce.ts
@@ -0,0 +1,31 @@
+import { LRUCache } from 'lru-cache'
+
+/**
+ * Debounces re-emission of already-satisfied merge mappings. The cache is
+ * process-local on purpose: a healing emission is only needed when an event
+ * replays after a crash, and the crash restart empties the cache, so replays
+ * always emit while steady-state duplicate merges stay suppressed.
+ */
+export class MergeMappingDebounce {
+ private readonly cache: LRUCache<string, true>
+
+ constructor(maxEntries: number, ttlMs: number) {
+ this.cache = new LRUCache({ max: maxEntries, ttl: ttlMs })
+ }
+
+ /**
+ * Returns the distinct ids not seen within the TTL, without marking them:
+ * callers mark via touch only after their emission succeeds, so a failed
+ * read or produce leaves the ids eligible for the retry to heal.
+ */
+ unseen(teamId: number, distinctIds: string[]): string[] {
+ return distinctIds.filter((distinctId) => !this.cache.has(`${teamId}:${distinctId}`))
+ }
+
+ /** Marks handled mappings so a following no-op does not re-emit them. */
+ touch(teamId: number, distinctIds: string[]): void {
+ for (const distinctId of distinctIds) {
+ this.cache.set(`${teamId}:${distinctId}`, true)
+ }
+ }
+}
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 a0fe26be0780..8c57318bd395 100644
--- a/nodejs/src/ingestion/common/persons/person-create-service.test.ts
+++ b/nodejs/src/ingestion/common/persons/person-create-service.test.ts
@@ -94,7 +94,7 @@ describe('PersonCreateService', () => {
mockPersonStore.createPerson.mockResolvedValue(mockResult)
- const [person, created] = await personCreateService.createPerson(
+ const [person, created, messages] = await personCreateService.createPerson(
createdAt,
properties,
propertiesOnce,
@@ -107,11 +107,9 @@ describe('PersonCreateService', () => {
expect(person).toEqual(mockPerson)
expect(created).toBe(true)
- expect(mockOutputs.produce).toHaveBeenCalledWith('persons', {
- value: Buffer.from('test'),
- key: null,
- teamId,
- })
+ // The caller owns the produce, so a transactional caller can defer it past commit.
+ expect(messages).toEqual(mockResult.messages)
+ expect(mockOutputs.produce).not.toHaveBeenCalled()
})
it('should handle PersonPropertiesSizeViolationError and log ingestion warning', async () => {
diff --git a/nodejs/src/ingestion/common/persons/person-create-service.ts b/nodejs/src/ingestion/common/persons/person-create-service.ts
index 15d76a03b7b5..694e768c13aa 100644
--- a/nodejs/src/ingestion/common/persons/person-create-service.ts
+++ b/nodejs/src/ingestion/common/persons/person-create-service.ts
@@ -1,6 +1,7 @@
import { DateTime } from 'luxon'
import { personCreateConflictResolvedCounter } from '~/common/persons/metrics'
+import { PersonMessage } from '~/common/persons/person-message'
import { PersonPropertiesSizeViolationError } from '~/common/persons/repositories/person-repository'
import { emitIngestionWarning } from '~/ingestion/common/ingestion-warnings'
import { uuidFromDistinctId } from '~/ingestion/common/persons/person-uuid'
@@ -17,7 +18,11 @@ export class PersonCreateService {
) {}
/**
- * @returns [Person, boolean that indicates if person was created or not, true if person was created by this call, false if found existing person from concurrent creation]
+ * Creation messages are returned, never produced here: the caller owns the
+ * produce, so a transactional caller can defer it past commit instead of
+ * holding the transaction open across the Kafka roundtrip.
+ *
+ * @returns [Person, true if person was created by this call (false if found existing person from concurrent creation), ClickHouse messages to produce]
*/
async createPerson(
createdAt: DateTime,
@@ -30,7 +35,7 @@ export class PersonCreateService {
primaryDistinctId: { distinctId: string; version?: number },
extraDistinctIds?: { distinctId: string; version?: number }[],
tx?: PersonsStoreTransactionForBatch
- ): Promise<[InternalPerson, boolean]> {
+ ): Promise<[InternalPerson, boolean, PersonMessage[]]> {
const uuid = uuidFromDistinctId(teamId, primaryDistinctId.distinctId)
const props = { ...propertiesOnce, ...properties, ...{ $creator_event_uuid: creatorEventUuid } }
@@ -60,12 +65,7 @@ export class PersonCreateService {
)
if (result.success) {
- await Promise.all(
- result.messages.map((msg) =>
- this.outputs.produce(msg.output, { value: msg.value, key: null, teamId })
- )
- )
- return [result.person, result.created]
+ return [result.person, result.created, result.messages]
}
// Handle creation conflict - another process created the person concurrently
@@ -75,7 +75,7 @@ export class PersonCreateService {
for (const distinctIdInfo of allDistinctIds) {
const existingPerson = await this.store.fetchForUpdate(teamId, distinctIdInfo.distinctId)
if (existingPerson) {
- return [existingPerson, false]
+ return [existingPerson, false, []]
}
}
@@ -86,7 +86,7 @@ export class PersonCreateService {
// mapping, so no two identities are silently merged.
if (result.conflictingPerson) {
personCreateConflictResolvedCounter.labels({ resolved_by: 'uuid' }).inc()
- return [result.conflictingPerson, false]
+ return [result.conflictingPerson, false, []]
}
// The holder vanished between the failed write and the lookup, so there is
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 1409ff6c9c3c..d3c6fea59382 100644
--- a/nodejs/src/ingestion/common/persons/person-merge-postgres.test.ts
+++ b/nodejs/src/ingestion/common/persons/person-merge-postgres.test.ts
@@ -1,9 +1,15 @@
import { buildIntegerMatcher } from '~/common/config/config'
-import { PERSON_MERGE_EVENTS_OUTPUT } from '~/common/outputs'
+import { PERSON_DISTINCT_IDS_OUTPUT, PERSON_MERGE_EVENTS_OUTPUT } from '~/common/outputs'
import { UUIDT } from '~/common/utils/utils'
import { InternalPerson } from '~/types'
-import { MergeEventsConfig, PostgresPersonMerge, personMergeEventProducedCounter } from './person-merge-postgres'
+import { MergeMappingDebounce } from './merge-mapping-debounce'
+import {
+ MergeEventsConfig,
+ PostgresMergePolicy,
+ PostgresPersonMerge,
+ personMergeEventProducedCounter,
+} from './person-merge-postgres'
import { createDefaultSyncMergeMode } from './person-merge-types'
import { MergePersonsRequest } from './persons-store'
@@ -128,7 +134,137 @@ describe('PostgresPersonMerge merge events', () => {
expect(store.removeDistinctIdFromCache).toHaveBeenCalledWith(2, 'anon')
})
- function buildSingleSourceMerge(store: object, eventUuid: string): PostgresPersonMerge {
+ // A produce awaited inside the merge transaction holds row locks and lifecycle
+ // marks across the Kafka roundtrip, and its ack escapes the batch-end await.
+ it('a one-exists merge produces the mapping after the transaction and surfaces the ack', async () => {
+ const order: string[] = []
+ mockOutputs = {
+ produce: jest.fn().mockImplementation(() => {
+ order.push('produce')
+ return Promise.resolve()
+ }),
+ }
+ const existingPerson = { id: 'p1', uuid: targetPerson.uuid, team_id: 2 } as unknown as InternalPerson
+ const mappingMessage = {
+ output: PERSON_DISTINCT_IDS_OUTPUT,
+ value: Buffer.from('{}'),
+ }
+ const tx = { addDistinctId: jest.fn().mockResolvedValue([mappingMessage]) }
+ const store = {
+ fetchForUpdate: jest
+ .fn()
+ .mockImplementation((_teamId: number, distinctId: string) =>
+ Promise.resolve(distinctId === 'd' ? existingPerson : null)
+ ),
+ inTransaction: jest
+ .fn()
+ .mockImplementation(async (_description: string, body: (tx: unknown) => Promise<unknown>) => {
+ const result = await body(tx)
+ order.push('commit')
+ return result
+ }),
+ }
+ const merge = buildSingleSourceMerge(store, new UUIDT().toString())
+
+ const result = await merge.execute()
+
+ expect(order).toEqual(['commit', 'produce'])
+ expect(mockOutputs.produce).toHaveBeenCalledWith(
+ PERSON_DISTINCT_IDS_OUTPUT,
+ expect.objectContaining({ teamId: 2, value: mappingMessage.value })
+ )
+ expect(result.results).toEqual([{ sourceDistinctId: 'anon', outcome: 'attached' }])
+ await expect(result.kafkaAck).resolves.toBeUndefined()
+ })
+
+ // Same contract as the one-exists case: createPerson returns its messages and the
+ // branch produces after commit, so the creation transaction never spans Kafka.
+ it('a neither-exists merge produces the creation messages after the transaction', async () => {
+ const order: string[] = []
+ mockOutputs = {
+ produce: jest.fn().mockImplementation(() => {
+ order.push('produce')
+ return Promise.resolve()
+ }),
+ }
+ const createdPerson = { id: 'p1', uuid: targetPerson.uuid, team_id: 2, is_identified: true } as InternalPerson
+ const creationMessage = {
+ output: PERSON_DISTINCT_IDS_OUTPUT,
+ value: Buffer.from('{}'),
+ }
+ const tx = {
+ createPerson: jest.fn().mockResolvedValue({
+ success: true,
+ person: createdPerson,
+ created: true,
+ messages: [creationMessage],
+ }),
+ }
+ const store = {
+ fetchForUpdate: jest.fn().mockResolvedValue(null),
+ inTransaction: jest
+ .fn()
+ .mockImplementation(async (_description: string, body: (tx: unknown) => Promise<unknown>) => {
+ const result = await body(tx)
+ order.push('commit')
+ return result
+ }),
+ }
+ const merge = buildSingleSourceMerge(store, new UUIDT().toString())
+
+ const result = await merge.execute()
+
+ expect(order).toEqual(['commit', 'produce'])
+ expect(mockOutputs.produce).toHaveBeenCalledWith(
+ PERSON_DISTINCT_IDS_OUTPUT,
+ expect.objectContaining({ teamId: 2, value: creationMessage.value })
+ )
+ expect(result.results).toEqual([{ sourceDistinctId: 'anon', outcome: 'attached' }])
+ await expect(result.kafkaAck).resolves.toBeUndefined()
+ })
+
+ // Both directions matter: never emitting loses the healing, and emitting on every
+ // duplicate $identify floods the topic and keeps the overrides table from converging.
+ it('an already-satisfied merge re-emits the committed mappings once per debounce window', async () => {
+ mockOutputs = { produce: jest.fn().mockResolvedValue(undefined) }
+ const person = { id: 'p1', uuid: targetPerson.uuid, team_id: 2 } as unknown as InternalPerson
+ const mapping = {
+ distinctId: 'anon',
+ message: { output: PERSON_DISTINCT_IDS_OUTPUT, value: Buffer.from('{"version":1}') },
+ }
+ const store = {
+ fetchForUpdate: jest.fn().mockResolvedValue(person),
+ fetchPersonDistinctIdMappings: jest.fn().mockResolvedValue([mapping]),
+ }
+ const debounce = new MergeMappingDebounce(100, 60_000)
+
+ const cold = await buildSingleSourceMerge(store, new UUIDT().toString(), {
+ noopMappingDebounce: debounce,
+ }).execute()
+ await cold.kafkaAck
+
+ expect(cold.results[0].outcome).toBe('noop_same_person')
+ expect(store.fetchPersonDistinctIdMappings).toHaveBeenCalledWith(2, ['anon', 'd'])
+ expect(mockOutputs.produce).toHaveBeenCalledTimes(1)
+ expect(mockOutputs.produce).toHaveBeenCalledWith(
+ PERSON_DISTINCT_IDS_OUTPUT,
+ expect.objectContaining({ teamId: 2, value: mapping.message.value })
+ )
+
+ const warm = await buildSingleSourceMerge(store, new UUIDT().toString(), {
+ noopMappingDebounce: debounce,
+ }).execute()
+ await warm.kafkaAck
+
+ expect(store.fetchPersonDistinctIdMappings).toHaveBeenCalledTimes(1)
+ expect(mockOutputs.produce).toHaveBeenCalledTimes(1)
+ })
+
+ function buildSingleSourceMerge(
+ store: object,
+ eventUuid: string,
+ policyOverrides: Partial<PostgresMergePolicy> = {}
+ ): PostgresPersonMerge {
const request: MergePersonsRequest = {
teamId: 2,
targetDistinctId: 'd',
@@ -153,6 +289,7 @@ describe('PostgresPersonMerge merge events', () => {
updateAllProperties: false,
isTombstoneTeam: () => false,
mergeEvents: { enabled: false, partitionCount: 64, isTeamEnabled: () => false },
+ ...policyOverrides,
},
request,
0
diff --git a/nodejs/src/ingestion/common/persons/person-merge-postgres.ts b/nodejs/src/ingestion/common/persons/person-merge-postgres.ts
index 56903d0c8cd9..0af1a5225f93 100644
--- a/nodejs/src/ingestion/common/persons/person-merge-postgres.ts
+++ b/nodejs/src/ingestion/common/persons/person-merge-postgres.ts
@@ -15,6 +15,7 @@ import { Properties } from '~/plugin-scaffold'
import { InternalPerson, ValueMatcher } from '~/types'
import type { BatchWritingPersonsStore } from './batch-writing-person-store'
+import { MergeMappingDebounce } from './merge-mapping-debounce'
import { PersonOutputs } from './person-context'
import { PersonCreateService } from './person-create-service'
import { buildPersonMergeEventMessage } from './person-merge-event'
@@ -78,6 +79,12 @@ export const personMergeEventProducedCounter = new Counter({
help: 'Number of person_merge_events messages acked by the broker (gate-on merges only).',
})
+export const mergeNoopMappingEmissionCounter = new Counter({
+ name: 'person_merge_noop_mapping_emission_total',
+ help: 'Distinct ids considered for mapping re-emission on already-satisfied merges.',
+ labelNames: ['action'],
+})
+
/** Thrown inside the fold transaction to roll it back when merge-mode move bounds would be exceeded. */
class MergeFoldLimitError extends Error {}
@@ -122,6 +129,11 @@ export interface PostgresMergePolicy {
/** Teams on the new-world merge behavior: lifecycle-mark claims plus tombstone deletes. */
isTombstoneTeam: ValueMatcher<number>
mergeEvents: MergeEventsConfig
+ /**
+ * When set, already-satisfied merges re-emit the committed mappings (debounced),
+ * healing ClickHouse rows lost between a prior merge's commit and its produce.
+ */
+ noopMappingDebounce?: MergeMappingDebounce
}
/**
@@ -173,10 +185,27 @@ export class PostgresPersonMerge {
if (this.request.sources.length === 0) {
throw new Error('mergePersons requires at least one source')
}
- if (this.request.sources.length > 1) {
- return await this.executeFold()
+ const result =
+ this.request.sources.length > 1
+ ? await this.executeFold()
+ : await this.mergeSingleWithCachePurge(this.request.sources[0])
+ this.touchWrittenMappings(result)
+ return result
+ }
+
+ /** Marks written mappings in the debounce so a following duplicate no-op does not re-emit them. */
+ private touchWrittenMappings(result: MergePersonsResult): void {
+ const debounce = this.policy.noopMappingDebounce
+ if (!debounce) {
+ return
+ }
+ const written = result.results
+ .filter((source) => source.outcome === 'attached' || source.outcome === 'merged')
+ .map((source) => source.sourceDistinctId)
+ if (written.length === 0) {
+ return
}
- return await this.mergeSingleWithCachePurge(this.request.sources[0])
+ debounce.touch(this.teamId, [this.targetDistinctId, ...written])
}
/**
@@ -204,6 +233,35 @@ export class PostgresPersonMerge {
)
}
+ /**
+ * A crash between a prior merge's commit and its produce loses the mapping message
+ * for good, because the replayed event lands in a satisfied branch and would
+ * otherwise produce nothing. Re-emit the committed mappings, debounced.
+ */
+ private async reemitSatisfiedMappings(distinctIds: string[]): Promise<{ kafkaAck: Promise<void> }> {
+ const debounce = this.policy.noopMappingDebounce
+ if (!debounce) {
+ return { kafkaAck: Promise.resolve() }
+ }
+ const toEmit = debounce.unseen(this.teamId, distinctIds)
+ mergeNoopMappingEmissionCounter.labels({ action: 'debounced' }).inc(distinctIds.length - toEmit.length)
+ if (toEmit.length === 0) {
+ return { kafkaAck: Promise.resolve() }
+ }
+ const mappings = await this.store.fetchPersonDistinctIdMappings(this.teamId, toEmit)
+ mergeNoopMappingEmissionCounter.labels({ action: 'emitted' }).inc(mappings.length)
+ if (mappings.length === 0) {
+ debounce.touch(this.teamId, toEmit)
+ return { kafkaAck: Promise.resolve() }
+ }
+ // Mark only on delivery: a failed read or produce replays the event, and the
+ // replay must find the ids unmarked to heal them.
+ const kafkaAck = this.produceMessages(mappings.map((mapping) => mapping.message)).then(() =>
+ debounce.touch(this.teamId, toEmit)
+ )
+ return { kafkaAck }
+ }
+
private async produceMessages(messages: PersonMessage[]): Promise<void> {
await Promise.all(
messages.map((msg) =>
@@ -282,7 +340,7 @@ export class PostgresPersonMerge {
this.discardOverrideCounts()
const lifecycleOpId = lifecycleOpIdFromEvent(teamId, this.request.eventUuid)
- const result = await this.inTransaction('mergeDistinctIds-OneExists', async (tx) => {
+ 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.
@@ -308,23 +366,28 @@ export class PostgresPersonMerge {
const distinctIdVersion = 1
this.recordOverrideCount('oneExists')
- const kafkaMessages = await tx.addDistinctId(existingPerson, distinctIdToAdd, distinctIdVersion)
- await this.produceMessages(kafkaMessages)
+ const messages = await tx.addDistinctId(existingPerson, distinctIdToAdd, distinctIdVersion)
if (this.tombstoneEnabled()) {
await tx.releaseLifecycleMarks(lifecycleOpId, teamId, this.targetDistinctId)
}
- return existingPerson
+ return [existingPerson, messages] as const
})
this.flushOverrideCounts()
+ // Produce only after the transaction commits: a produce awaited inside the
+ // transaction holds row locks and lifecycle marks across the Kafka roundtrip.
+ const kafkaAck = this.produceMessages(kafkaMessages)
return {
survivor: result,
results: [{ sourceDistinctId: otherPersonDistinctId, outcome: 'attached' }],
+ kafkaAck,
}
} else if (otherPerson && mergeIntoPerson) {
// Both Distinct IDs point at an existing Person
if (otherPerson.id == mergeIntoPerson.id) {
- // Nothing to do, they are the same Person
+ // Same person already; re-emit in case a crashed prior merge never
+ // produced the pair's mapping.
+ const { kafkaAck } = await this.reemitSatisfiedMappings([otherPersonDistinctId, mergeIntoDistinctId])
return {
survivor: mergeIntoPerson,
results: [
@@ -334,6 +397,7 @@ export class PostgresPersonMerge {
sourcePersonUuid: otherPerson.uuid,
},
],
+ kafkaAck,
}
}
@@ -350,7 +414,7 @@ export class PostgresPersonMerge {
const distinctId2 = otherPersonDistinctId
this.discardOverrideCounts()
- const [person, needsPersonUpdate] = await this.inTransaction(
+ const [person, needsPersonUpdate, kafkaMessages] = await this.inTransaction(
'mergeDistinctIds-NeitherExist',
async (tx) => {
// See comment above about `distinctIdVersion`: the first Distinct ID derives the
@@ -359,7 +423,7 @@ export class PostgresPersonMerge {
const distinctId2Version = 1
this.recordOverrideCount('neitherExist')
- const [created, wasCreated] = await this.createService.createPerson(
+ const [created, wasCreated, messages] = await this.createService.createPerson(
this.timestamp,
this.request.eventOps.set,
this.request.eventOps.setOnce,
@@ -373,14 +437,16 @@ export class PostgresPersonMerge {
)
// If person was not created (creation conflict) and is not identified,
// we need to update it later
- return [created, !wasCreated && !created.is_identified] as const
+ return [created, !wasCreated && !created.is_identified, messages] as const
}
)
this.flushOverrideCounts()
+ const kafkaAck = this.produceMessages(kafkaMessages)
return {
survivor: person,
results: [{ sourceDistinctId: otherPersonDistinctId, outcome: 'attached' }],
survivorNeedsUpdate: needsPersonUpdate,
+ kafkaAck,
}
}
}
@@ -500,6 +566,7 @@ export class PostgresPersonMerge {
const mergedSourceOutcomes: MergePersonsSourceResult[] = []
const seenSourceIds = new Set<string>([target.id])
const missingSources: MergePersonsSource[] = []
+ const noopSourceDistinctIds: string[] = []
for (const pair of sourcesToFold) {
if (isDistinctIdUnmergeable(pair.distinctId)) {
outcomes.push({ sourceDistinctId: pair.distinctId, outcome: 'skipped_illegal' })
@@ -511,6 +578,7 @@ export class PostgresPersonMerge {
continue
}
if (seenSourceIds.has(source.id)) {
+ noopSourceDistinctIds.push(pair.distinctId)
outcomes.push({
sourceDistinctId: pair.distinctId,
outcome: 'noop_same_person',
@@ -536,7 +604,9 @@ export class PostgresPersonMerge {
}
if (mergeSources.length === 0 && missingSources.length === 0) {
- return { survivor: target, results: outcomes, kafkaAck: bootstrapAck }
+ const { kafkaAck: reemitAck } = await this.reemitSatisfiedMappings(noopSourceDistinctIds)
+ const kafkaAck = bootstrapAck ? joinAcks(bootstrapAck, reemitAck) : reemitAck
+ return { survivor: target, results: outcomes, kafkaAck }
}
// Sequential property precedence: each source merges its properties
@@ -643,7 +713,8 @@ export class PostgresPersonMerge {
// The bootstrap's produce, when there was one, joins the fold's own
// ack so the caller observes every message this merge produced.
const foldAck = this.produceMessages(kafkaMessages)
- const kafkaAck = bootstrapAck ? joinAcks(bootstrapAck, foldAck) : foldAck
+ const { kafkaAck: reemitAck } = await this.reemitSatisfiedMappings(noopSourceDistinctIds)
+ const kafkaAck = bootstrapAck ? joinAcks(bootstrapAck, foldAck, reemitAck) : joinAcks(foldAck, reemitAck)
for (const source of mergeSources) {
// Same fire-and-forget contract as executeTransaction.
void this.producePersonMergeEvent(source, mergedPerson).catch(() => {})
@@ -1094,7 +1165,10 @@ export class PostgresPersonMerge {
)
if (!refreshedPerson) {
- return mergeSuccess(currentTargetPerson, Promise.resolve(), true)
+ // A concurrent merge absorbed the source; re-emit in case its
+ // produce was lost to a crash.
+ const { kafkaAck } = await this.reemitSatisfiedMappings([sourceDistinctId, targetDistinctId])
+ return mergeSuccess(currentTargetPerson, kafkaAck, true)
}
currentSourcePerson = refreshedPerson
@@ -1108,7 +1182,9 @@ export class PostgresPersonMerge {
)
if (!refreshedPerson) {
- return mergeSuccess(currentTargetPerson, Promise.resolve(), true)
+ // Same as the source case above.
+ const { kafkaAck } = await this.reemitSatisfiedMappings([sourceDistinctId, targetDistinctId])
+ return mergeSuccess(currentTargetPerson, kafkaAck, true)
}
currentTargetPerson = refreshedPerson
diff --git a/nodejs/src/ingestion/common/persons/person-property-service.ts b/nodejs/src/ingestion/common/persons/person-property-service.ts
index 029b1eee270a..ca7895aed3bd 100644
--- a/nodejs/src/ingestion/common/persons/person-property-service.ts
+++ b/nodejs/src/ingestion/common/persons/person-property-service.ts
@@ -32,20 +32,21 @@ export class PersonPropertyService {
}
async updateProperties(): Promise<[InternalPerson, Promise<void>]> {
- const [person, propertiesHandled] = await this.createOrGetPerson()
+ const [person, propertiesHandled, createAck] = await this.createOrGetPerson()
if (propertiesHandled) {
- return [person, Promise.resolve()]
+ return [person, createAck]
}
- return await this.updatePersonProperties(person)
+ const [updatedPerson, updateAck] = await this.updatePersonProperties(person)
+ return [updatedPerson, Promise.all([createAck, updateAck]).then(() => undefined)]
}
/**
- * @returns [Person, boolean that indicates if properties were already handled or not]
+ * @returns [Person, boolean that indicates if properties were already handled or not, creation messages' produce ack]
*/
- private async createOrGetPerson(): Promise<[InternalPerson, boolean]> {
+ private async createOrGetPerson(): Promise<[InternalPerson, boolean, Promise<void>]> {
const person = await this.context.personStore.fetchForUpdate(this.context.team.id, this.context.distinctId)
if (person) {
- return [person, false]
+ return [person, false, Promise.resolve()]
}
let properties = {}
@@ -55,7 +56,7 @@ export class PersonPropertyService {
propertiesOnce = this.context.eventProperties['$set_once']
}
- return await this.personCreateService.createPerson(
+ const [createdPerson, created, kafkaMessages] = await this.personCreateService.createPerson(
this.context.timestamp,
properties || {},
propertiesOnce || {},
@@ -66,6 +67,7 @@ export class PersonPropertyService {
this.context.event.uuid,
{ distinctId: this.context.distinctId }
)
+ return [createdPerson, created, this.context.produceMessages(kafkaMessages)]
}
async updatePersonProperties(person: InternalPerson): Promise<[InternalPerson, Promise<void>]> {
diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.ts
index 3d435656d254..4a627aff6dc7 100644
--- a/nodejs/src/ingestion/config.ts
+++ b/nodejs/src/ingestion/config.ts
@@ -192,6 +192,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
+ // Re-emit committed distinct id mappings for merge events that arrive already satisfied,
+ // debounced per (team, distinct id). Heals ClickHouse mapping rows lost to a crash between
+ // a merge's commit and its produce; see MergeMappingDebounce for why the cache is in-memory.
+ 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);
@@ -365,6 +371,9 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {
PERSON_MERGE_FOLD_ENABLED: false,
PERSON_MERGE_FOLD_TEAM_ALLOWLIST: '*',
PERSON_MERGE_TOMBSTONE_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
diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.ts
index 58ead0bdcb3f..41c071e8e606 100644
--- a/nodejs/src/ingestion/ingestion-consumer.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.ts
@@ -242,6 +242,9 @@ export class IngestionConsumer {
mergeEventsEnabled: effectivePersonMergeEventsEnabled(this.config),
mergeEventsPartitionCount: this.config.PERSON_MERGE_EVENTS_PARTITION_COUNT,
mergeEventsTeamAllowlist: this.config.PERSON_MERGE_EVENTS_TEAM_ALLOWLIST,
+ mergeNoopMappingEmissionEnabled: this.config.PERSON_MERGE_NOOP_MAPPING_EMISSION_ENABLED,
+ mergeNoopMappingEmissionCacheSize: this.config.PERSON_MERGE_NOOP_MAPPING_EMISSION_CACHE_SIZE,
+ mergeNoopMappingEmissionTtlMs: this.config.PERSON_MERGE_NOOP_MAPPING_EMISSION_TTL_MS,
})
this.groupStore = new BatchWritingGroupStore(this.deps.groupRepository, this.deps.clickhouseGroupRepository, {
diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.ts
index ab8e8a55bdc9..4cf7109c5c1f 100644
--- a/nodejs/src/servers/ingestion-api-server.ts
+++ b/nodejs/src/servers/ingestion-api-server.ts
@@ -345,6 +345,9 @@ export class IngestionApiServer implements NodeServer {
mergeEventsEnabled: effectivePersonMergeEventsEnabled(this.config),
mergeEventsPartitionCount: this.config.PERSON_MERGE_EVENTS_PARTITION_COUNT,
mergeEventsTeamAllowlist: this.config.PERSON_MERGE_EVENTS_TEAM_ALLOWLIST,
+ mergeNoopMappingEmissionEnabled: this.config.PERSON_MERGE_NOOP_MAPPING_EMISSION_ENABLED,
+ mergeNoopMappingEmissionCacheSize: this.config.PERSON_MERGE_NOOP_MAPPING_EMISSION_CACHE_SIZE,
+ mergeNoopMappingEmissionTtlMs: this.config.PERSON_MERGE_NOOP_MAPPING_EMISSION_TTL_MS,
})
// Which backend person writes land in, deployment-wide: pg (the
// default) builds nothing new; the other modes construct the