: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
feat(ingestion): run person merges through the persons store (#84605)
Zach Brown009a232ab293
diff --git a/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx b/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsxindex 30ebbe655d08..b2953899f40b 100644--- a/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx+++ b/frontend/src/scenes/data-management/ingestion-warnings/IngestionWarningsView.tsx@@ -27,6 +27,8 @@ const HedgehogReadingIsMagic = pngHoggie(readingIsMagicPng)export const WARNING_TYPE_TO_DESCRIPTION: Record<string, string> = {cannot_merge_already_identified: 'Refused to merge an already identified user',cannot_merge_with_illegal_distinct_id: 'Refused to merge with an illegal distinct id',+ merge_move_limit_exceeded: 'A merge exceeded its distinct id move limit and was dropped',+ merge_settled_failure: 'A merge settled without merging and cannot be retried',skipping_event_invalid_uuid: 'Refused to process event with invalid uuid',ignored_invalid_timestamp: 'Ignored an invalid timestamp, event was still ingested',event_timestamp_in_future: 'An event was sent more than 23 hours in the future',@@ -73,6 +75,8 @@ export const WARNING_TYPE_TO_DESCRIPTION: Record<string, string> = {export const WARNING_TYPE_TO_DOCS_ANCHOR: Record<string, string> = {cannot_merge_already_identified: 'refused-to-merge-an-already-identified-user',cannot_merge_with_illegal_distinct_id: 'refused-to-merge-with-an-illegal-distinct-id',+ merge_move_limit_exceeded: 'a-merge-exceeded-its-distinct-id-move-limit-and-was-dropped',+ merge_settled_failure: 'a-merge-settled-without-merging-and-cannot-be-retried',skipping_event_invalid_uuid: 'refused-to-process-event-with-invalid-uuid',ignored_invalid_timestamp: 'ignored-an-invalid-timestamp-event-was-still-ingested',event_timestamp_in_future: 'an-event-was-sent-more-than-23-hours-in-the-future',@@ -121,6 +125,47 @@ export const WARNING_TYPE_RENDERER = {</>)},+ merge_move_limit_exceeded: function Render(warning: IngestionWarning): JSX.Element {+ const details = warning.details as {+ sourcePersonDistinctId: string+ targetPersonDistinctId: string+ eventUuid: string+ }+ return (+ <>+ Refused to merge{' '}+ <Link to={urls.personByDistinctId(details.sourcePersonDistinctId)}>+ {details.sourcePersonDistinctId}+ </Link>{' '}+ into{' '}+ <Link to={urls.personByDistinctId(details.targetPersonDistinctId)}>+ {details.targetPersonDistinctId}+ </Link>{' '}+ because it has more distinct ids than one merge may move (event uuid: <code>{details.eventUuid}</code>).+ </>+ )+ },+ merge_settled_failure: function Render(warning: IngestionWarning): JSX.Element {+ const details = warning.details as {+ sourcePersonDistinctId: string+ targetPersonDistinctId: string+ eventUuid: string+ }+ return (+ <>+ A merge of{' '}+ <Link to={urls.personByDistinctId(details.sourcePersonDistinctId)}>+ {details.sourcePersonDistinctId}+ </Link>{' '}+ into{' '}+ <Link to={urls.personByDistinctId(details.targetPersonDistinctId)}>+ {details.targetPersonDistinctId}+ </Link>{' '}+ settled without merging, and the result is recorded, so a retry cannot change it (event uuid:{' '}+ <code>{details.eventUuid}</code>).+ </>+ )+ },skipping_event_invalid_uuid: function Render(warning: IngestionWarning): JSX.Element {const details = warning.details as {eventUuid: stringdiff --git a/nodejs/src/common/persons/person-utils.ts b/nodejs/src/common/persons/person-utils.tsindex 7409ea711d26..67818f95feba 100644--- a/nodejs/src/common/persons/person-utils.ts+++ b/nodejs/src/common/persons/person-utils.ts@@ -71,3 +71,13 @@ export const isDistinctIdIllegal = (id: string): boolean => {const trimmed = id.trim()return trimmed === '' || CASE_INSENSITIVE_ILLEGAL_IDS.has(id.toLowerCase()) || CASE_SENSITIVE_ILLEGAL_IDS.has(id)}++/**+ * Ids no merge can ever involve. Wider than the illegal list, which is ids+ * that never resolve to a person anywhere: NUL cannot exist in Postgres+ * text (the capture path strips it from event.distinct_id but not from+ * $anon_distinct_id or alias property values), and over 400 code points+ * cannot exist in the varchar(400) column.+ */+export const isDistinctIdUnmergeable = (id: string): boolean =>+ isDistinctIdIllegal(id) || id.includes('\u0000') || [...id].length > 400diff --git a/nodejs/src/ingestion/common/ingestion-warning-types.ts b/nodejs/src/ingestion/common/ingestion-warning-types.tsindex 57ef018f884c..b53a84cc7627 100644--- a/nodejs/src/ingestion/common/ingestion-warning-types.ts+++ b/nodejs/src/ingestion/common/ingestion-warning-types.ts@@ -43,6 +43,12 @@ export const INGESTION_WARNING_TYPES = {cannot_merge_already_identified: { category: 'merge', severity: 'warning' },cannot_merge_with_illegal_distinct_id: { category: 'merge', severity: 'warning' },merge_race_condition: { category: 'merge', severity: 'error' },+ // A source person held more distinct ids than the merge is allowed to+ // move, so its merge did not happen.+ merge_move_limit_exceeded: { category: 'merge', severity: 'error' },+ // The merge backend settled on a verdict that merged nothing, and the+ // verdict is recorded, so this event cannot reach a different answer.+ merge_settled_failure: { category: 'merge', severity: 'error' },// Event validation — malformed or rejected event dataclient_ingestion_warning: { category: 'event', severity: 'info' },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.tsindex 27c4a3ad03a0..671a7f737c7d 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@@ -3289,13 +3289,12 @@ describe('BatchWritingPersonStore', () => {expect(personStore.getCachedPersonForUpdateByDistinctId(teamId, 'batch-bound-property')).toBeUndefined()})- it('tracks merge-update cache writes through the batch-bound store', async () => {- const batchStore = new BatchBoundPersonsStore(personStore, 0)-- await batchStore.updatePersonForMerge(+ it('tracks merge-update cache writes made under a batch', async () => {+ await personStore.updatePersonForMerge(person,{ properties: { merge_marker: 'tracked' } },- 'batch-bound-merge'+ 'batch-bound-merge',+ 0)expect(personStore.getCachedPersonForUpdateByDistinctId(teamId, 'batch-bound-merge')).toBeDefined()diff --git a/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts b/nodejs/src/ingestion/common/persons/batch-writing-person-store.tsindex 695b1d784c24..5ed824c2f9ed 100644--- a/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts+++ b/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts@@ -1,6 +1,7 @@import { DateTime } from 'luxon'import pLimit from 'p-limit'+import { buildIntegerMatcher } from '~/common/config/config'import {observeLatencyByVersion,personCacheOperationsCounter,@@ -41,6 +42,7 @@ import { Properties } from '~/plugin-scaffold'import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt, Team } from '~/types'import { PersonOutputs } from './person-context'+import { PostgresMergePolicy, PostgresPersonMerge } from './person-merge-postgres'import {EventOps,applyEventPropertyUpdates,@@ -48,7 +50,7 @@ import {getMetricKey,refineEventOps,} from './person-update'-import { FlushResult, PersonsStore } from './persons-store'+import { FlushResult, MergePersonsRequest, MergePersonsResult, PersonsStore } from './persons-store'import { PersonsStoreTransaction } from './persons-store-transaction'type MethodName =@@ -110,6 +112,12 @@ export interface BatchWritingPersonsStoreOptions {* always wants a positive interval).*/metricEmissionIntervalMs: number+ /** Teams on the new-world merge behavior (lifecycle-mark claims plus tombstone deletes); '*' for all. */+ mergeTombstoneTeamAllowlist: string+ /** Gate, partition count, and team allowlist ('*' for all) for the cross-partition merge-event producer. */+ mergeEventsEnabled: boolean+ mergeEventsPartitionCount: number+ mergeEventsTeamAllowlist: string}const DEFAULT_OPTIONS: BatchWritingPersonsStoreOptions = {@@ -120,6 +128,10 @@ const DEFAULT_OPTIONS: BatchWritingPersonsStoreOptions = {optimisticUpdateRetryInterval: 50,updateAllProperties: false,metricEmissionIntervalMs: 30_000,+ mergeTombstoneTeamAllowlist: '',+ mergeEventsEnabled: false,+ mergeEventsPartitionCount: 64,+ mergeEventsTeamAllowlist: '',}interface CacheMetrics {@@ -527,6 +539,8 @@ class BatchBoundPersonsCache {* remaining dirty entries.*/export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore {+ readonly backend = 'postgres' as const+private personCache: BatchWritingPersonsCacheprivate fetchPromisesForUpdate: Map<string, Promise<InternalPerson | null>>private fetchPromisesForChecking: Map<string, Promise<InternalPerson | null>>@@ -534,6 +548,7 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStoreprivate databaseOperationCountsPerDistinctId: Map<string, Map<MethodName, number>>private updateLatencyPerDistinctIdSeconds: Map<string, Map<UpdateType, number>>private options: BatchWritingPersonsStoreOptions+ private mergePolicy: PostgresMergePolicy// Periodic metric emitter — emits accumulated per-distinct_id metrics on// a fixed cadence rather than at batch boundaries (which are unreliable// under concurrentBatches > 1).@@ -545,6 +560,15 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStoreoptions?: Partial<BatchWritingPersonsStoreOptions>) {this.options = { ...DEFAULT_OPTIONS, ...options }+ this.mergePolicy = {+ updateAllProperties: this.options.updateAllProperties,+ isTombstoneTeam: buildIntegerMatcher(this.options.mergeTombstoneTeamAllowlist, true),+ mergeEvents: {+ enabled: this.options.mergeEventsEnabled,+ partitionCount: this.options.mergeEventsPartitionCount,+ isTeamEnabled: buildIntegerMatcher(this.options.mergeEventsTeamAllowlist, true),+ },+ }this.personCache = new BatchWritingPersonsCache()Object.defineProperties(this, {personUpdateCache: { get: () => this.personCache.getUpdateCache() },@@ -1421,6 +1445,20 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStorereturn Promise.resolve([updatedPerson, kafkaMessages, false])}+ /**+ * The Postgres backend's merge, run by PostgresPersonMerge against+ * this store's own verbs and transactions.+ */+ mergePersons(request: MergePersonsRequest, batchId: number): Promise<MergePersonsResult> {+ return new PostgresPersonMerge(+ this,+ this.ingestionWarningsOutputs,+ this.mergePolicy,+ request,+ batchId+ ).execute()+ }+async deletePerson(person: InternalPerson,distinctId: string,diff --git a/nodejs/src/ingestion/common/persons/person-context.test.ts b/nodejs/src/ingestion/common/persons/person-context.test.tsdeleted file mode 100644index fd7c6bfb958b..000000000000--- a/nodejs/src/ingestion/common/persons/person-context.test.ts+++ /dev/null@@ -1,112 +0,0 @@-import { DateTime } from 'luxon'--import { buildIntegerMatcher } from '~/common/config/config'-import { PERSON_MERGE_EVENTS_OUTPUT } from '~/common/outputs'-import { UUIDT } from '~/common/utils/utils'-import { InternalPerson } from '~/types'--import { MergeEventsConfig, PersonContext, personMergeEventProducedCounter } from './person-context'-import { createDefaultSyncMergeMode } from './person-merge-types'--describe('PersonContext', () => {- let mockOutputs: { produce: jest.Mock }-- const sourcePerson = { uuid: '01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee' } as InternalPerson- const targetPerson = { uuid: '01928bbb-cccc-dddd-eeee-ffffffffffff' } as InternalPerson-- function buildContext(teamId: number, mergeEventsConfig: MergeEventsConfig): PersonContext {- mockOutputs = { produce: jest.fn().mockResolvedValue(undefined) }- return new PersonContext(- { uuid: new UUIDT().toString(), distinct_id: 'd', properties: {} } as any,- { id: teamId } as any,- 'd',- DateTime.now(),- true,- mockOutputs as any,- {} as any,- 0,- createDefaultSyncMergeMode(),- false,- false,- mergeEventsConfig- )- }-- // The producer must never emit for teams outside the allowlist (the whole point of the gate):- // a regression that widened it would flood the cohort-stream-processor with out-of-scope events.- it.each([- {- name: 'disabled: no-op even for an allowlisted team',- enabled: false,- allowlist: '2',- teamId: 2,- produces: false,- },- {- name: 'enabled + team in the default allowlist produces',- enabled: true,- allowlist: '2',- teamId: 2,- produces: true,- },- {- name: 'enabled + team outside the allowlist is a no-op',- enabled: true,- allowlist: '2',- teamId: 99,- produces: false,- },- {- name: 'enabled + wildcard allowlist produces for any team',- enabled: true,- allowlist: '*',- teamId: 99,- produces: true,- },- {- // Node treats an empty allowlist as match-nothing, the opposite of Rust's "empty means all".- // Clearing the env var expecting the Rust behavior silently stops all emission.- name: 'enabled + empty allowlist is a no-op (empty matches no teams)',- enabled: true,- allowlist: '',- teamId: 2,- produces: false,- },- ])('producePersonMergeEvent $name', async ({ enabled, allowlist, teamId, produces }) => {- const context = buildContext(teamId, {- enabled,- partitionCount: 64,- isTeamEnabled: buildIntegerMatcher(allowlist, true),- })-- await context.producePersonMergeEvent(sourcePerson, targetPerson)-- if (produces) {- expect(mockOutputs.produce).toHaveBeenCalledTimes(1)- expect(mockOutputs.produce).toHaveBeenCalledWith(- PERSON_MERGE_EVENTS_OUTPUT,- expect.objectContaining({ teamId })- )- } else {- expect(mockOutputs.produce).not.toHaveBeenCalled()- }- })-- // The produce is detached from ingestion, so a broker failure must never surface to the caller- // and must not be counted as a delivered produce (the counter tracks broker acks, not attempts).- it('producePersonMergeEvent swallows a produce failure without counting it', async () => {- const context = buildContext(2, {- enabled: true,- partitionCount: 64,- isTeamEnabled: buildIntegerMatcher('2', true),- })- mockOutputs.produce.mockRejectedValue(new Error('broker down'))- const producedBefore = (await personMergeEventProducedCounter.get()).values[0]?.value ?? 0-- await expect(context.producePersonMergeEvent(sourcePerson, targetPerson)).resolves.toBeUndefined()-- expect(mockOutputs.produce).toHaveBeenCalledTimes(1)- const producedAfter = (await personMergeEventProducedCounter.get()).values[0]?.value ?? 0- expect(producedAfter).toBe(producedBefore)- })-})diff --git a/nodejs/src/ingestion/common/persons/person-context.ts b/nodejs/src/ingestion/common/persons/person-context.tsindex d0788db8ffbe..5d2f2ab9bffe 100644--- a/nodejs/src/ingestion/common/persons/person-context.ts+++ b/nodejs/src/ingestion/common/persons/person-context.ts@@ -1,44 +1,24 @@import { DateTime } from 'luxon'-import { Counter } from 'prom-client'import {IngestionWarningsOutput,- PERSON_MERGE_EVENTS_OUTPUT,PersonDistinctIdsOutput,PersonMergeEventsOutput,PersonsOutput,} from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { PersonMessage } from '~/common/persons/person-message'-import { logger } from '~/common/utils/logger'import { PluginEvent, Properties } from '~/plugin-scaffold'-import { InternalPerson, Team, ValueMatcher } from '~/types'+import { Team } from '~/types'-import { buildPersonMergeEventMessage } from './person-merge-event'import type { MergeFoldPlan } from './person-merge-fold'import { MergeMode } from './person-merge-types'import { PersonsStoreForBatch } from './persons-store-for-batch'-export const personMergeEventProducedCounter = new Counter({- name: 'person_merge_event_produced_total',- help: 'Number of person_merge_events messages acked by the broker (gate-on merges only).',-})-export type PersonOutputs = IngestionOutputs<PersonsOutput | PersonDistinctIdsOutput | IngestionWarningsOutput | PersonMergeEventsOutput>-/** Gate + partition-count + team allowlist for the cross-partition merge-event producer. */-export type MergeEventsConfig = {- enabled: boolean- partitionCount: number- /**- * Matches teams allowed to emit merge events, built from PERSON_MERGE_EVENTS_TEAM_ALLOWLIST- * (team 2 by default, '*' for all). The no-arg constructor default below matches no teams.- */- isTeamEnabled: ValueMatcher<number>-}-/*** Lightweight data holder containing all the context needed for person processing.* This replaces the previous PersonState class which mixed data and business logic.@@ -59,15 +39,8 @@ export class PersonContext {public readonly mergeMode: MergeMode,public readonly updateAllProperties: boolean = false, // When true, all property changes trigger person updatespublic readonly shouldUpdateLastSeenAt: boolean = false,- public readonly mergeEventsConfig: MergeEventsConfig = {- enabled: false,- partitionCount: 64,- isTeamEnabled: () => false,- },/** Fold plan shared by this event's consecutive $identify run; see person-merge-fold.ts. */- public readonly mergeFoldPlan?: MergeFoldPlan,- /** New-world merge behavior for this team: lifecycle-mark claims plus tombstone deletes. */- public readonly mergeTombstoneEnabled: boolean = false+ public readonly mergeFoldPlan?: MergeFoldPlan) {this.eventProperties = event.properties!}@@ -79,49 +52,4 @@ export class PersonContext {))}-- /**- * Whether a person_merge_events message should be emitted for this context's team. Gated by the- * global kill switch and scoped to the team allowlist so we do not emit events for teams outside- * the cohort-stream-processor's scope.- */- shouldProduceMergeEvent(): boolean {- return this.mergeEventsConfig.enabled && this.mergeEventsConfig.isTeamEnabled(this.team.id)- }-- /**- * Best-effort emit of a person_merge_events message for the cohort-stream-processor. No-op when- * the gate is off or the team is outside the allowlist. Never throws: a produce failure is- * logged and dropped, so it can never affect ingestion. Delivery is at-most-once; loss is- * accepted until the delivery-guarantees milestone. The message is explicitly partitioned by- * `(team_id, P_old)` so it reaches the worker holding P_old's state — see `buildPersonMergeEventMessage`.- */- async producePersonMergeEvent(sourcePerson: InternalPerson, targetPerson: InternalPerson): Promise<void> {- if (!this.shouldProduceMergeEvent()) {- return- }- try {- const { key, partition, value } = buildPersonMergeEventMessage(- this.team.id,- sourcePerson.uuid,- targetPerson.uuid,- Date.now(),- this.mergeEventsConfig.partitionCount- )- await this.outputs.produce(PERSON_MERGE_EVENTS_OUTPUT, {- value,- key,- partition,- teamId: this.team.id,- })- personMergeEventProducedCounter.inc()- } catch (error) {- logger.warn('person_merge_events produce failed, dropping', {- team_id: this.team.id,- source_person_uuid: sourcePerson.uuid,- target_person_uuid: targetPerson.uuid,- error,- })- }- }}diff --git a/nodejs/src/ingestion/common/persons/person-create-service.test.ts b/nodejs/src/ingestion/common/persons/person-create-service.test.tsindex d70026e70dd3..a0fe26be0780 100644--- a/nodejs/src/ingestion/common/persons/person-create-service.test.ts+++ b/nodejs/src/ingestion/common/persons/person-create-service.test.ts@@ -58,7 +58,7 @@ describe('PersonCreateService', () => {false)- personCreateService = new PersonCreateService(personContext)+ personCreateService = new PersonCreateService(personContext.personStore, personContext.outputs)})describe('createPerson', () => {diff --git a/nodejs/src/ingestion/common/persons/person-create-service.ts b/nodejs/src/ingestion/common/persons/person-create-service.tsindex 8c96cdc353af..15d76a03b7b5 100644--- a/nodejs/src/ingestion/common/persons/person-create-service.ts+++ b/nodejs/src/ingestion/common/persons/person-create-service.ts@@ -7,11 +7,14 @@ import { uuidFromDistinctId } from '~/ingestion/common/persons/person-uuid'import { Properties } from '~/plugin-scaffold'import { InternalPerson, PropertyUpdateOperation } from '~/types'-import { PersonContext } from './person-context'-import { PersonsStoreTransactionForBatch } from './persons-store-for-batch'+import { PersonOutputs } from './person-context'+import { PersonsStoreForBatch, PersonsStoreTransactionForBatch } from './persons-store-for-batch'export class PersonCreateService {- constructor(private context: PersonContext) {}+ constructor(+ private store: PersonsStoreForBatch,+ private outputs: PersonOutputs+ ) {}/*** @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]@@ -43,7 +46,7 @@ export class PersonCreateService {})try {- const result = await (tx || this.context.personStore).createPerson(+ const result = await (tx || this.store).createPerson(createdAt,props,propertiesLastUpdatedAt,@@ -57,7 +60,11 @@ export class PersonCreateService {)if (result.success) {- await this.context.produceMessages(result.messages)+ await Promise.all(+ result.messages.map((msg) =>+ this.outputs.produce(msg.output, { value: msg.value, key: null, teamId })+ )+ )return [result.person, result.created]}@@ -66,10 +73,7 @@ export class PersonCreateService {// Try to fetch the person that was created concurrentlyconst allDistinctIds = [primaryDistinctId, ...(extraDistinctIds || [])]for (const distinctIdInfo of allDistinctIds) {- const existingPerson = await this.context.personStore.fetchForUpdate(- teamId,- distinctIdInfo.distinctId- )+ const existingPerson = await this.store.fetchForUpdate(teamId, distinctIdInfo.distinctId)if (existingPerson) {return [existingPerson, false]}@@ -99,7 +103,7 @@ export class PersonCreateService {throw new Error('Unexpected CreatePersonResult state')} catch (error) {if (error instanceof PersonPropertiesSizeViolationError) {- await emitIngestionWarning(this.context.outputs, teamId, {+ await emitIngestionWarning(this.outputs, teamId, {type: 'person_properties_size_violation',details: {// uuid of the person we tried to create; error.personId is a DB row iddiff --git a/nodejs/src/ingestion/common/persons/person-event-processor.ts b/nodejs/src/ingestion/common/persons/person-event-processor.tsindex 035e5a7405b7..d3003c6c9237 100644--- a/nodejs/src/ingestion/common/persons/person-event-processor.ts+++ b/nodejs/src/ingestion/common/persons/person-event-processor.ts@@ -5,8 +5,8 @@ import { PluginEvent } from '~/plugin-scaffold'import { InternalPerson, Person } from '~/types'import { PersonContext } from './person-context'-import { PersonMergeService } from './person-merge-service'-import { PersonMergeLimitExceededError, PersonMergeRaceConditionError } from './person-merge-types'+import { PersonMergeService, mergeMoveLimitDroppedCounter } from './person-merge-service'+import { PersonMergeLimitExceededError } from './person-merge-types'import { PersonPropertyService } from './person-property-service'/**@@ -34,14 +34,7 @@ export class PersonEventProcessor {identifyOrAliasKafkaAck = mergeResult.kafkaAckneedsPersonUpdate = mergeResult.needsPersonUpdate} else {- const errorResult = this.handleMergeError(mergeResult.error, this.context.event)- if (errorResult) {- return errorResult- }- logger.warn('Merge operation failed, continuing with normal property updates', {- error: mergeResult.error.message,- team_id: this.context.team.id,- })+ return this.handleMergeError(mergeResult.error, this.context.event)}if (personFromMerge && needsPersonUpdate) {@@ -69,7 +62,7 @@ export class PersonEventProcessor {return this.context}- private handleMergeError(error: unknown, event: PluginEvent): PipelineResult<Person, AsyncOutput> | null {+ private handleMergeError(error: unknown, event: PluginEvent): PipelineResult<Person, AsyncOutput> {const mergeMode = this.context.mergeModeif (error instanceof PersonMergeLimitExceededError) {@@ -96,21 +89,46 @@ export class PersonEventProcessor {})return dlq('Merge limit exceeded', error)case 'SYNC':- // SYNC mode should never hit limits - this indicates a bug- logger.error('Unexpected limit exceeded in SYNC mode - this should not happen', {+ // Postgres moves are unbounded in SYNC mode, so only the+ // personhog saga's move limit produces this here. DLQ+ // rather than drop or throw: the payload stays replayable,+ // and a throw would only redeliver into the same limit.+ logger.error('Merge limit exceeded in SYNC mode; routing the event to the DLQ', {team_id: event.team_id,distinct_id: event.distinct_id,+ event_uuid: event.uuid,mergeMode: mergeMode,})- throw error+ mergeMoveLimitDroppedCounter.labels({ path: 'sync' }).inc()+ return dlq(+ 'Merge limit exceeded in SYNC mode',+ error,+ [],+ [+ {+ type: 'merge_move_limit_exceeded',+ details: {+ distinctId: event.distinct_id,+ eventUuid: event.uuid,+ // $identify carries the source id as+ // $anon_distinct_id, the alias events as+ // alias; preferring one blindly would+ // mislabel the warning when a stray copy+ // of the other is present.+ sourcePersonDistinctId: String(+ (event.event === '$identify'+ ? (event.properties?.['$anon_distinct_id'] ?? event.properties?.['alias'])+ : (event.properties?.['alias'] ??+ event.properties?.['$anon_distinct_id'])) ?? event.distinct_id+ ),+ targetPersonDistinctId: event.distinct_id,+ eventDropped: false,+ },+ pipelineStep: 'person-merge',+ },+ ]+ )}- } else if (error instanceof PersonMergeRaceConditionError) {- logger.warn('Race condition detected, ignoring merge', {- error: error.message,- team_id: this.context.team.id,- distinct_id: this.context.distinctId,- })- return null // Continue with normal processing} else {// Unknown errors should be thrown - they indicate bugs or unexpected conditionslogger.error('Unknown merge error - throwing to surface the issue', {diff --git a/nodejs/src/ingestion/common/persons/person-merge-fold.test.ts b/nodejs/src/ingestion/common/persons/person-merge-fold.test.tsindex 99a177abd999..b657e1e4703c 100644--- a/nodejs/src/ingestion/common/persons/person-merge-fold.test.ts+++ b/nodejs/src/ingestion/common/persons/person-merge-fold.test.ts@@ -178,6 +178,17 @@ describe('createMergeFoldPlanningStep', () => {expect(planOf(items[2])).toBe(plan)})+ it('excludes anon ids no backend can store, which would fail the fold transaction', async () => {+ // A NUL cannot exist in Postgres text and over 400 code points+ // cannot fit the column, so folding one in aborts the whole+ // transaction and every pair with it.+ const items = await scan([identify('anon-1'), identify('anon\u0000two'), identify('x'.repeat(401))])++ expect(planOf(items[0])?.pairs.map((p) => p.anonDistinctId)).toEqual(['anon-1'])+ expect(items[1].mergeFold.type).toBe('immediate')+ expect(items[2].mergeFold.type).toBe('immediate')+ })+it('skips planning when only illegal anon distinct ids are in the run', async () => {const items = await scan([identify('anonymous'), identify('null')])diff --git a/nodejs/src/ingestion/common/persons/person-merge-fold.ts b/nodejs/src/ingestion/common/persons/person-merge-fold.tsindex 6c4c926e4527..2d07e0d99c0c 100644--- a/nodejs/src/ingestion/common/persons/person-merge-fold.ts+++ b/nodejs/src/ingestion/common/persons/person-merge-fold.ts@@ -1,5 +1,5 @@import { buildIntegerMatcher } from '~/common/config/config'-import { decideProcessPerson, isDistinctIdIllegal } from '~/common/persons/person-utils'+import { decideProcessPerson, isDistinctIdUnmergeable } from '~/common/persons/person-utils'import type { ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'import { PipelineResult, ok } from '~/ingestion/framework/results'import type { ProcessingStep } from '~/ingestion/framework/steps'@@ -156,10 +156,11 @@ function planRun<T extends MergeFoldScanItem>(if (anonDistinctId === null || anonDistinctId === targetDistinctId || pairByAnonId.has(anonDistinctId)) {continue}- // An illegal anon id never merges; keeping its event on the immediate- // path emits the per-event warning and keeps is_identified untouched,- // exactly as today.- if (isDistinctIdIllegal(anonDistinctId)) {+ // An id no merge can involve never folds; keeping its event on the+ // immediate path emits the per-event warning and keeps is_identified+ // untouched. The same width the merge itself refuses on, so a pair+ // the fold accepted cannot fail the transaction at the column limit.+ if (isDistinctIdUnmergeable(anonDistinctId)) {continue}pairByAnonId.set(anonDistinctId, { anonDistinctId, eventUuid: values[index].event.uuid })diff --git a/nodejs/src/ingestion/common/persons/person-merge-postgres.test.ts b/nodejs/src/ingestion/common/persons/person-merge-postgres.test.tsnew file mode 100644index 000000000000..1409ff6c9c3c--- /dev/null+++ b/nodejs/src/ingestion/common/persons/person-merge-postgres.test.ts@@ -0,0 +1,235 @@+import { buildIntegerMatcher } from '~/common/config/config'+import { 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 { createDefaultSyncMergeMode } from './person-merge-types'+import { MergePersonsRequest } from './persons-store'++describe('PostgresPersonMerge merge events', () => {+ let mockOutputs: { produce: jest.Mock }++ const sourcePerson = { uuid: '01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee' } as InternalPerson+ const targetPerson = { uuid: '01928bbb-cccc-dddd-eeee-ffffffffffff' } as InternalPerson++ function buildMerge(teamId: number, mergeEvents: MergeEventsConfig): PostgresPersonMerge {+ mockOutputs = { produce: jest.fn().mockResolvedValue(undefined) }+ const eventUuid = new UUIDT().toString()+ const request: MergePersonsRequest = {+ teamId,+ targetDistinctId: 'd',+ sources: [{ distinctId: 'anon', eventUuid }],+ eventOps: {+ set: {},+ setOnce: {},+ unset: [],+ denied: false,+ shouldForceUpdate: true,+ eventName: '$identify',+ },+ eventUuid: eventUuid,+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ }+ return new PostgresPersonMerge(+ {} as any,+ mockOutputs as any,+ {+ updateAllProperties: false,+ isTombstoneTeam: () => false,+ mergeEvents,+ },+ request,+ 0+ )+ }++ function produceMergeEvent(merge: PostgresPersonMerge): Promise<void> {+ return (merge as any).producePersonMergeEvent(sourcePerson, targetPerson)+ }++ // The producer must never emit for teams outside the allowlist (the whole point of the gate):+ // a regression that widened it would flood the cohort-stream-processor with out-of-scope events.+ it.each([+ {+ name: 'disabled: no-op even for an allowlisted team',+ enabled: false,+ allowlist: '2',+ teamId: 2,+ produces: false,+ },+ {+ name: 'enabled + team in the default allowlist produces',+ enabled: true,+ allowlist: '2',+ teamId: 2,+ produces: true,+ },+ {+ name: 'enabled + team outside the allowlist is a no-op',+ enabled: true,+ allowlist: '2',+ teamId: 99,+ produces: false,+ },+ {+ name: 'enabled + wildcard allowlist produces for any team',+ enabled: true,+ allowlist: '*',+ teamId: 99,+ produces: true,+ },+ {+ // Node treats an empty allowlist as match-nothing, the opposite of Rust's "empty means all".+ // Clearing the env var expecting the Rust behavior silently stops all emission.+ name: 'enabled + empty allowlist is a no-op (empty matches no teams)',+ enabled: true,+ allowlist: '',+ teamId: 2,+ produces: false,+ },+ ])('producePersonMergeEvent $name', async ({ enabled, allowlist, teamId, produces }) => {+ const merge = buildMerge(teamId, {+ enabled,+ partitionCount: 64,+ isTeamEnabled: buildIntegerMatcher(allowlist, true),+ })++ await produceMergeEvent(merge)++ if (produces) {+ expect(mockOutputs.produce).toHaveBeenCalledTimes(1)+ expect(mockOutputs.produce).toHaveBeenCalledWith(+ PERSON_MERGE_EVENTS_OUTPUT,+ expect.objectContaining({ teamId })+ )+ } else {+ expect(mockOutputs.produce).not.toHaveBeenCalled()+ }+ })++ // Merge verbs update the batch caches optimistically inside transactions;+ // a failure after that leaves mappings that were never committed, and the+ // caller's retry would read them back as truth.+ it('a failed single-source merge purges both distinct ids before rethrowing', async () => {+ mockOutputs = { produce: jest.fn().mockResolvedValue(undefined) }+ const store = {+ fetchForUpdate: jest.fn().mockRejectedValue(new Error('connection lost')),+ removeDistinctIdFromCache: jest.fn(),+ }+ const eventUuid = new UUIDT().toString()+ const merge = buildSingleSourceMerge(store, eventUuid)++ await expect(merge.execute()).rejects.toThrow('connection lost')++ expect(store.removeDistinctIdFromCache).toHaveBeenCalledWith(2, 'd')+ expect(store.removeDistinctIdFromCache).toHaveBeenCalledWith(2, 'anon')+ })++ function buildSingleSourceMerge(store: object, eventUuid: string): PostgresPersonMerge {+ const request: MergePersonsRequest = {+ teamId: 2,+ targetDistinctId: 'd',+ sources: [{ distinctId: 'anon', eventUuid }],+ eventOps: {+ set: {},+ setOnce: {},+ unset: [],+ denied: false,+ shouldForceUpdate: true,+ eventName: '$identify',+ },+ eventUuid: eventUuid,+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ }+ return new PostgresPersonMerge(+ store as never,+ mockOutputs as never,+ {+ updateAllProperties: false,+ isTombstoneTeam: () => false,+ mergeEvents: { enabled: false, partitionCount: 64, isTeamEnabled: () => false },+ },+ request,+ 0+ )+ }++ // The executor refuses the ids Postgres cannot store even when a caller+ // skips the service's pre-filter. A regression to the narrower illegal+ // list would classify these as missing sources, carry them into the fold+ // transaction, and abort the whole fold on the doomed insert.+ it('a fold refuses unstorable source ids without opening a transaction', async () => {+ mockOutputs = { produce: jest.fn().mockResolvedValue(undefined) }+ const target = { id: 't1', uuid: targetPerson.uuid } as InternalPerson+ const store = {+ fetchForUpdate: jest.fn().mockResolvedValue(target),+ fetchPersonsForUpdateByDistinctIds: jest.fn().mockResolvedValue([]),+ }+ const eventUuid = new UUIDT().toString()+ const nulId = 'anon\u0000one'+ const oversizedId = 'x'.repeat(401)+ const request: MergePersonsRequest = {+ teamId: 2,+ targetDistinctId: 'd',+ sources: [+ { distinctId: nulId, eventUuid },+ { distinctId: oversizedId, eventUuid },+ ],+ eventOps: {+ set: {},+ setOnce: {},+ unset: [],+ denied: false,+ shouldForceUpdate: true,+ eventName: '$identify',+ },+ eventUuid,+ allowIdentifiedSources: false,+ mergeMode: createDefaultSyncMergeMode(),+ createdAtMs: 3_600_000,+ }+ const merge = new PostgresPersonMerge(+ store as never,+ mockOutputs as never,+ {+ updateAllProperties: false,+ isTombstoneTeam: () => false,+ mergeEvents: { enabled: false, partitionCount: 64, isTeamEnabled: () => false },+ },+ request,+ 0+ )++ const result = await merge.execute()++ expect(result.foldAborted).toBeUndefined()+ expect(result.survivor).toBe(target)+ expect(result.results).toEqual([+ { sourceDistinctId: nulId, outcome: 'skipped_illegal' },+ { sourceDistinctId: oversizedId, outcome: 'skipped_illegal' },+ ])+ })++ // The produce is detached from ingestion, so a broker failure must never surface to the caller+ // and must not be counted as a delivered produce (the counter tracks broker acks, not attempts).+ it('producePersonMergeEvent swallows a produce failure without counting it', async () => {+ const merge = buildMerge(2, {+ enabled: true,+ partitionCount: 64,+ isTeamEnabled: buildIntegerMatcher('2', true),+ })+ mockOutputs.produce.mockRejectedValue(new Error('broker down'))+ const producedBefore = (await personMergeEventProducedCounter.get()).values[0]?.value ?? 0++ await expect(produceMergeEvent(merge)).resolves.toBeUndefined()++ expect(mockOutputs.produce).toHaveBeenCalledTimes(1)+ const producedAfter = (await personMergeEventProducedCounter.get()).values[0]?.value ?? 0+ expect(producedAfter).toBe(producedBefore)+ })+})diff --git a/nodejs/src/ingestion/common/persons/person-merge-postgres.ts b/nodejs/src/ingestion/common/persons/person-merge-postgres.tsnew file mode 100644index 000000000000..56903d0c8cd9--- /dev/null+++ b/nodejs/src/ingestion/common/persons/person-merge-postgres.ts@@ -0,0 +1,1166 @@+import { DateTime } from 'luxon'+import { Counter, Histogram } from 'prom-client'++import { PERSON_MERGE_EVENTS_OUTPUT } from '~/common/outputs'+import { personMergeFailureCounter } from '~/common/persons/metrics'+import { PersonMessage } from '~/common/persons/person-message'+import { isDistinctIdUnmergeable } from '~/common/persons/person-utils'+import {+ PersonClaimedByLifecycleOpError,+ PersonTombstoneBlockedError,+} from '~/common/persons/repositories/person-repository'+import { logger } from '~/common/utils/logger'+import { promiseRetry } from '~/common/utils/retries'+import { Properties } from '~/plugin-scaffold'+import { InternalPerson, ValueMatcher } from '~/types'++import type { BatchWritingPersonsStore } from './batch-writing-person-store'+import { PersonOutputs } from './person-context'+import { PersonCreateService } from './person-create-service'+import { buildPersonMergeEventMessage } from './person-merge-event'+import {+ PersonMergeLimitExceededError,+ PersonMergeRaceConditionError,+ PersonMergeResult,+ SourcePersonHasDistinctIdsError,+ SourcePersonNotFoundError,+ TargetPersonNotFoundError,+ mergeError,+ mergeSuccess,+} from './person-merge-types'+import { applyEventPropertyUpdates, refineEventOps } from './person-update'+import { lifecycleOpIdFromEvent } from './person-uuid'+import {+ MergeFoldAbortReason,+ MergePersonsRequest,+ MergePersonsResult,+ MergePersonsSource,+ MergePersonsSourceResult,+} from './persons-store'+import {+ BatchBoundPersonsStore,+ BatchBoundPersonsStoreTransaction,+ PersonsStoreForBatch,+ PersonsStoreTransactionForBatch,+} from './persons-store-for-batch'++export const mergeTxnAttemptCounter = new Counter({+ name: 'person_merge_txn_attempt_total',+ help: 'Number of person merge attempts.',+ labelNames: ['call', 'oldPersonIdentified', 'newPersonIdentified'],+})++export const mergeTxnSuccessCounter = new Counter({+ name: 'person_merge_txn_success_total',+ help: 'Number of person merges that succeeded.',+ labelNames: ['call', 'oldPersonIdentified', 'newPersonIdentified'],+})++export const mergeFoldExecutedCounter = new Counter({+ name: 'person_merge_fold_executed_total',+ help: 'Number of folded merge transactions executed.',+})++export const mergeFoldSizeHistogram = new Histogram({+ name: 'person_merge_fold_size',+ help: 'Number of merge pairs folded into one transaction.',+ buckets: [2, 5, 10, 25, 50, 100, 250, 500],+})++export const mergeDistinctIdOverrideCounter = new Counter({+ name: 'person_merge_distinct_id_override_total',+ help: 'Distinct id mapping rows written during merges, each writing a ClickHouse override row.',+ labelNames: ['call'],+})++export const personMergeEventProducedCounter = new Counter({+ name: 'person_merge_event_produced_total',+ help: 'Number of person_merge_events messages acked by the broker (gate-on merges only).',+})++/** Thrown inside the fold transaction to roll it back when merge-mode move bounds would be exceeded. */+class MergeFoldLimitError extends Error {}++/** Thrown inside the fold transaction to roll it back when a concurrent merge invalidated the fetched sources. */+class MergeFoldConflictError extends Error {}++/** Maps a fold failure to the abort reason the caller's fallback counter records. */+function foldAbortReason(error: unknown): MergeFoldAbortReason {+ if (error instanceof MergeFoldLimitError) {+ return 'limit'+ }+ if (+ error instanceof MergeFoldConflictError ||+ error instanceof PersonTombstoneBlockedError ||+ error instanceof PersonClaimedByLifecycleOpError+ ) {+ return 'conflict'+ }+ if ((error as { code?: string })?.code === '40P01') {+ return 'deadlock'+ }+ return 'error'+}++/** One ack the caller can await for a set of produces already in flight. */+async function joinAcks(...acks: Promise<void>[]): Promise<void> {+ await Promise.all(acks)+}++/** Gate + partition-count + team allowlist for the cross-partition merge-event producer. */+export interface MergeEventsConfig {+ enabled: boolean+ partitionCount: number+ /** Matches teams allowed to emit merge events; the pg store builds it from PERSON_MERGE_EVENTS_TEAM_ALLOWLIST. */+ isTeamEnabled: ValueMatcher<number>+}++/** The Postgres backend's merge policy, derived from config at store construction. */+export interface PostgresMergePolicy {+ /** When true, all property changes trigger person updates; mirrors the store option of the same name. */+ updateAllProperties: boolean+ /** Teams on the new-world merge behavior: lifecycle-mark claims plus tombstone deletes. */+ isTombstoneTeam: ValueMatcher<number>+ mergeEvents: MergeEventsConfig+}++/**+ * The Postgres implementation of PersonsStore.mergePersons:+ * classification, lifecycle-mark claims, distinct-id moves, cohort+ * fixups, and source deletion, run against the pg store's own verbs+ * and transactions. One instance serves one request. Settled verdicts+ * come back as per-source outcomes; retryable conflicts (lifecycle+ * claims, tombstone races, creation races) throw for the caller's+ * retry loop, which re-enters with fresh fetches.+ */+export class PostgresPersonMerge {+ private batchStore: PersonsStoreForBatch+ private createService: PersonCreateService++ constructor(+ private store: BatchWritingPersonsStore,+ private outputs: PersonOutputs,+ private policy: PostgresMergePolicy,+ private request: MergePersonsRequest,+ private batchId: number+ ) {+ this.batchStore = new BatchBoundPersonsStore(store, batchId)+ this.createService = new PersonCreateService(this.batchStore, outputs)+ }++ private get teamId(): number {+ return this.request.teamId+ }++ /** The processing distinct id stamped on verb calls; merges always process under the target's id. */+ private get targetDistinctId(): string {+ return this.request.targetDistinctId+ }++ private get eventName(): string {+ return this.request.eventOps.eventName+ }++ private get timestamp(): DateTime {+ return DateTime.fromMillis(this.request.createdAtMs, { zone: 'utc' })+ }++ private tombstoneEnabled(): boolean {+ return this.policy.isTombstoneTeam(this.teamId)+ }++ async execute(): Promise<MergePersonsResult> {+ 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()+ }+ return await this.mergeSingleWithCachePurge(this.request.sources[0])+ }++ /**+ * Runs a single-source merge, purging both ids from the batch caches+ * on any throw: merge verbs update the caches optimistically inside a+ * transaction that has now rolled back, and a retry must re-read+ * committed state rather than a mapping that was never committed.+ */+ private async mergeSingleWithCachePurge(source: MergePersonsSource): Promise<MergePersonsResult> {+ try {+ return await this.mergeSingle(source)+ } catch (error) {+ this.store.removeDistinctIdFromCache(this.teamId, this.targetDistinctId)+ this.store.removeDistinctIdFromCache(this.teamId, source.distinctId)+ throw error+ }+ }++ private inTransaction<T>(+ description: string,+ body: (tx: PersonsStoreTransactionForBatch) => Promise<T>+ ): Promise<T> {+ return this.store.inTransaction(description, (tx) =>+ body(new BatchBoundPersonsStoreTransaction(tx, this.batchId))+ )+ }++ private async produceMessages(messages: PersonMessage[]): Promise<void> {+ await Promise.all(+ messages.map((msg) =>+ this.outputs.produce(msg.output, { value: msg.value, key: null, teamId: this.teamId })+ )+ )+ }++ /**+ * Best-effort emit of a person_merge_events message for the cohort-stream-processor. No-op when+ * the gate is off or the team is outside the allowlist. Never throws: a produce failure is+ * logged and dropped, so it can never affect ingestion. Delivery is at-most-once; loss is+ * accepted until the delivery-guarantees milestone. The message is explicitly partitioned by+ * `(team_id, P_old)` so it reaches the worker holding P_old's state — see `buildPersonMergeEventMessage`.+ */+ private async producePersonMergeEvent(sourcePerson: InternalPerson, targetPerson: InternalPerson): Promise<void> {+ if (!this.policy.mergeEvents.enabled || !this.policy.mergeEvents.isTeamEnabled(this.teamId)) {+ return+ }+ try {+ const { key, partition, value } = buildPersonMergeEventMessage(+ this.teamId,+ sourcePerson.uuid,+ targetPerson.uuid,+ Date.now(),+ this.policy.mergeEvents.partitionCount+ )+ await this.outputs.produce(PERSON_MERGE_EVENTS_OUTPUT, {+ value,+ key,+ partition,+ teamId: this.teamId,+ })+ personMergeEventProducedCounter.inc()+ } catch (error) {+ logger.warn('person_merge_events produce failed, dropping', {+ team_id: this.teamId,+ source_person_uuid: sourcePerson.uuid,+ target_person_uuid: targetPerson.uuid,+ error,+ })+ }+ }++ private async mergeSingle(source: MergePersonsSource): Promise<MergePersonsResult> {+ const otherPersonDistinctId = source.distinctId+ const mergeIntoDistinctId = this.targetDistinctId+ const teamId = this.teamId++ const otherPerson = await this.store.fetchForUpdate(teamId, otherPersonDistinctId, this.batchId)+ const mergeIntoPerson = await this.store.fetchForUpdate(teamId, mergeIntoDistinctId, this.batchId)++ // A note about the `distinctIdVersion` logic you'll find below:+ //+ // Overrides are only created for `posthog_persondistinctid` rows with version > 0, see:+ // https://github.com/PostHog/posthog/blob/92e17ce307a577c4233d4ab252eebc6c2207a5ee/posthog/models/person/sql.py#L269-L287+ //+ // With $process_person_profile=false, events can exist in ClickHouse stamped with the+ // deterministic implied person uuid even though no `posthog_persondistinctid` or+ // `posthog_person` rows exist. So every merge-added mapping for a distinct id without a+ // person gets version 1: the override either re-points real personless events or is a+ // harmless transient row the squash job deletes within days. The exception is the distinct+ // id whose uuid a newly created person is born on — its events already point at the right+ // person, so it keeps version 0 and stays out of the overrides join.++ if ((otherPerson && !mergeIntoPerson) || (!otherPerson && mergeIntoPerson)) {+ // Only one of the two Distinct IDs points at an existing Person++ const [existingPerson, distinctIdToAdd] = (() => {+ if (otherPerson) {+ return [otherPerson!, mergeIntoDistinctId]+ } else {+ return [mergeIntoPerson!, otherPersonDistinctId]+ }+ })()++ this.discardOverrideCounts()+ const lifecycleOpId = lifecycleOpIdFromEvent(teamId, this.request.eventUuid)+ const result = await this.inTransaction('mergeDistinctIds-OneExists', async (tx) => {+ // New-world merges claim the person's lifecycle mark, which keeps a concurrent+ // tombstone from landing between this check and the distinct id insert (an+ // orphaned mapping); old-world merges rely on the delete's FK violation instead.+ if (this.tombstoneEnabled()) {+ await tx.claimLifecycleMarks(+ lifecycleOpId,+ existingPerson.team_id,+ [{ personId: existingPerson.id, personUuid: existingPerson.uuid, role: 'target' }],+ this.targetDistinctId+ )+ if (!(await tx.isPersonLive(existingPerson, this.targetDistinctId))) {+ // Purge the stale cache entries so the caller's retry attempt+ // re-fetches from Postgres instead of replaying the cached,+ // now-tombstoned person into the same failure.+ this.store.removeDistinctIdFromCache(teamId, otherPersonDistinctId)+ this.store.removeDistinctIdFromCache(teamId, mergeIntoDistinctId)+ throw new TargetPersonNotFoundError(+ 'Person was deleted before the merge could add a distinct id'+ )+ }+ }+ // See comment above about `distinctIdVersion`+ const distinctIdVersion = 1+ this.recordOverrideCount('oneExists')++ const kafkaMessages = await tx.addDistinctId(existingPerson, distinctIdToAdd, distinctIdVersion)+ await this.produceMessages(kafkaMessages)+ if (this.tombstoneEnabled()) {+ await tx.releaseLifecycleMarks(lifecycleOpId, teamId, this.targetDistinctId)+ }+ return existingPerson+ })+ this.flushOverrideCounts()+ return {+ survivor: result,+ results: [{ sourceDistinctId: otherPersonDistinctId, outcome: 'attached' }],+ }+ } 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+ return {+ survivor: mergeIntoPerson,+ results: [+ {+ sourceDistinctId: otherPersonDistinctId,+ outcome: 'noop_same_person',+ sourcePersonUuid: otherPerson.uuid,+ },+ ],+ }+ }++ return await this.mergePeople({+ mergeInto: mergeIntoPerson,+ mergeIntoDistinctId: mergeIntoDistinctId,+ otherPerson: otherPerson,+ otherPersonDistinctId: otherPersonDistinctId,+ })+ } else {+ // Neither Distinct ID points at an existing Person++ const distinctId1 = mergeIntoDistinctId+ const distinctId2 = otherPersonDistinctId++ this.discardOverrideCounts()+ const [person, needsPersonUpdate] = await this.inTransaction(+ 'mergeDistinctIds-NeitherExist',+ async (tx) => {+ // See comment above about `distinctIdVersion`: the first Distinct ID derives the+ // new Person's UUID so it never needs an override; the second always gets one.+ const distinctId1Version = 0+ const distinctId2Version = 1+ this.recordOverrideCount('neitherExist')++ const [created, wasCreated] = await this.createService.createPerson(+ this.timestamp,+ this.request.eventOps.set,+ this.request.eventOps.setOnce,+ teamId,+ null,+ true,+ this.request.eventUuid,+ { distinctId: distinctId1, version: distinctId1Version },+ [{ distinctId: distinctId2, version: distinctId2Version }],+ tx+ )+ // 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+ }+ )+ this.flushOverrideCounts()+ return {+ survivor: person,+ results: [{ sourceDistinctId: otherPersonDistinctId, outcome: 'attached' }],+ survivorNeedsUpdate: needsPersonUpdate,+ }+ }+ }++ /**+ * Folded-merge execution for a multi-source request: every source+ * merges into the target inside one transaction. Any failure rolls+ * the fold back untouched and answers foldAborted, so the caller can+ * fall back to per-event sequential merges.+ */+ private async executeFold(): Promise<MergePersonsResult> {+ try {+ return await this.executeFoldInner()+ } catch (error) {+ const reason = foldAbortReason(error)+ // The batch store's caches were updated optimistically inside the+ // rolled-back transaction (distinct id → target mappings); purge+ // them so the sequential fallback re-reads committed state.+ this.store.removeDistinctIdFromCache(this.teamId, this.targetDistinctId)+ for (const source of this.request.sources) {+ this.store.removeDistinctIdFromCache(this.teamId, source.distinctId)+ }+ logger.warn('🤔', 'folded merge failed, falling back to sequential merges', {+ team_id: this.teamId,+ distinct_id: this.targetDistinctId,+ pairs: this.request.sources.length,+ reason,+ error,+ })+ return { survivor: null, results: [], foldAborted: reason }+ }+ }++ /**+ * Counts each folded source's distinct ids inside the transaction and+ * aborts the fold (rolling it back) when:+ * - a source is missing entirely — it was merged away between the locked+ * fetch (whose locks were released at statement end) and the transaction,+ * so its already-computed property contribution would be stale;+ * - a source's count exceeds the LIMIT/ASYNC move limit — those events+ * need their own per-event DLQ/redirect decision;+ * - the total exceeds batched SYNC's per-statement batch size.+ * Returns the expected total so the caller can verify the move touched+ * exactly that many rows. One cheap indexed GROUP BY that rarely trips.+ */+ private async assertFoldSourcesWithinMoveBounds(+ tx: PersonsStoreTransactionForBatch,+ mergeSources: InternalPerson[]+ ): Promise<number> {+ if (mergeSources.length === 0) {+ return 0+ }+ const mergeMode = this.request.mergeMode+ const limit = mergeMode.type === 'SYNC' ? undefined : mergeMode.limit+ const batchSize = mergeMode.type === 'SYNC' ? mergeMode.batchSize : undefined++ const counts = await tx.countDistinctIdsForPersons(+ this.teamId,+ mergeSources.map((source) => source.id),+ this.targetDistinctId+ )+ let total = 0+ for (const source of mergeSources) {+ const count = counts.get(source.id)+ if (count === undefined) {+ throw new MergeFoldConflictError('folded merge source lost its distinct ids concurrently')+ }+ if (limit !== undefined && count > limit) {+ throw new MergeFoldLimitError('folded merge source exceeds distinct id move limit')+ }+ total += count+ }+ if (batchSize !== undefined && total > batchSize) {+ throw new MergeFoldLimitError('folded merge move exceeds sync batch size')+ }+ return total+ }++ private async executeFoldInner(): Promise<MergePersonsResult> {+ const teamId = this.teamId+ const outcomes: MergePersonsSourceResult[] = []+ let bootstrapAck: Promise<void> | undefined++ let target = await this.store.fetchForUpdate(teamId, this.targetDistinctId, this.batchId)+ let sourcesToFold = this.request.sources++ if (!target) {+ // Cold start: no target person yet. Bootstrap it through the+ // sequential path for the triggering event's source (which creates+ // the person or attaches the distinct_id), then fold the remaining+ // sources in their request order.+ const bootstrapSource =+ this.request.sources.find((source) => source.distinctId === this.request.triggerSourceDistinctId) ??+ this.request.sources[0]+ const bootstrap = await promiseRetry(+ () => this.mergeSingleWithCachePurge(bootstrapSource),+ 'merge_distinct_ids'+ )+ if (!bootstrap.survivor) {+ throw new Error('merge fold bootstrap did not produce a target person')+ }+ target = bootstrap.survivor+ outcomes.push(...bootstrap.results)+ bootstrapAck = bootstrap.kafkaAck+ sourcesToFold = this.request.sources.filter((source) => source !== bootstrapSource)+ }++ const sources = await this.store.fetchPersonsForUpdateByDistinctIds(+ teamId,+ sourcesToFold.map((source) => source.distinctId),+ this.batchId+ )+ const sourceByDistinctId = new Map(sources.map((source) => [source.distinct_id, source]))++ // Partition sources, preserving order for property-merge precedence.+ const mergeSources: InternalPerson[] = []+ const mergedSourceOutcomes: MergePersonsSourceResult[] = []+ const seenSourceIds = new Set<string>([target.id])+ const missingSources: MergePersonsSource[] = []+ for (const pair of sourcesToFold) {+ if (isDistinctIdUnmergeable(pair.distinctId)) {+ outcomes.push({ sourceDistinctId: pair.distinctId, outcome: 'skipped_illegal' })+ continue+ }+ const source = sourceByDistinctId.get(pair.distinctId)+ if (!source) {+ missingSources.push(pair)+ continue+ }+ if (seenSourceIds.has(source.id)) {+ outcomes.push({+ sourceDistinctId: pair.distinctId,+ outcome: 'noop_same_person',+ sourcePersonUuid: source.uuid,+ })+ continue+ }+ if (source.is_identified && !this.request.allowIdentifiedSources) {+ outcomes.push({+ sourceDistinctId: pair.distinctId,+ outcome: 'skipped_already_identified',+ sourcePersonUuid: source.uuid,+ })+ continue+ }+ seenSourceIds.add(source.id)+ mergeSources.push(source)+ mergedSourceOutcomes.push({+ sourceDistinctId: pair.distinctId,+ outcome: 'merged',+ sourcePersonUuid: source.uuid,+ })+ }++ if (mergeSources.length === 0 && missingSources.length === 0) {+ return { survivor: target, results: outcomes, kafkaAck: bootstrapAck }+ }++ // Sequential property precedence: each source merges its properties+ // under the accumulated target's (target wins, earlier sources win+ // over later ones). Event $set/$set_once apply on top, as in mergePeople.+ const mergedProperties: Properties = {}+ for (let i = mergeSources.length - 1; i >= 0; i--) {+ Object.assign(mergedProperties, mergeSources[i].properties)+ }+ Object.assign(mergedProperties, target.properties)+ const propertyUpdates = refineEventOps(this.request.eventOps, mergedProperties, this.policy.updateAllProperties)+ const [updatedTempPerson] = applyEventPropertyUpdates(propertyUpdates, {+ ...target,+ properties: mergedProperties,+ })++ const createdAt = DateTime.min(target.created_at, ...mergeSources.map((source) => source.created_at))+ const version = Math.max(target.version, ...mergeSources.map((source) => source.version)) + 1++ const currentTarget = target+ this.discardOverrideCounts()+ const lifecycleOpId = lifecycleOpIdFromEvent(teamId, this.request.eventUuid)+ const [mergedPerson, kafkaMessages] = await this.inTransaction('mergePeopleFold', async (tx) => {+ // New-world folds claim every person, keeping concurrent lifecycle operations+ // (other merges, the delete saga) off the targets and sources until commit.+ if (this.tombstoneEnabled()) {+ await tx.claimLifecycleMarks(+ lifecycleOpId,+ currentTarget.team_id,+ [+ { personId: currentTarget.id, personUuid: currentTarget.uuid, role: 'target' },+ ...mergeSources.map((source, index) => ({+ personId: source.id,+ personUuid: source.uuid,+ role: 'source' as const,+ ordinal: index,+ })),+ ],+ this.targetDistinctId+ )+ if (!(await tx.isPersonLive(currentTarget, this.targetDistinctId))) {+ throw new MergeFoldConflictError('Fold target was deleted concurrently')+ }+ }+ const expectedMoveCount = await this.assertFoldSourcesWithinMoveBounds(tx, mergeSources)++ let person = currentTarget+ let updateMessages: PersonMessage[] = []+ if (mergeSources.length > 0) {+ ;[person, updateMessages] = await tx.updatePersonForMerge(+ currentTarget,+ {+ created_at: createdAt,+ properties: updatedTempPerson.properties,+ is_identified: true,+ version,+ },+ this.targetDistinctId+ )+ }++ const moveResult = await tx.moveDistinctIdsFromPersons(mergeSources, currentTarget, this.targetDistinctId)+ if (!moveResult.success) {+ throw new TargetPersonNotFoundError('Target person no longer exists')+ }+ // A mismatch means a concurrent merge touched the sources+ // between the count and the move; abort so the sequential path+ // (whose zero-moved handling retries with fresh persons) takes+ // over rather than merging stale source properties.+ if (moveResult.distinctIdsMoved.length !== expectedMoveCount) {+ throw new MergeFoldConflictError('folded merge moved an unexpected number of distinct ids')+ }+ this.recordOverrideCount('bothExistMove', moveResult.distinctIdsMoved.length)++ const addMessages: PersonMessage[] = []+ for (const pair of missingSources) {+ // See mergeSingle for the distinctIdVersion logic.+ const distinctIdVersion = 1+ this.recordOverrideCount('fold')+ addMessages.push(...(await tx.addDistinctId(person, pair.distinctId, distinctIdVersion)))+ }++ let deleteMessages: PersonMessage[] = []+ if (mergeSources.length > 0) {+ await tx.updateCohortsAndFeatureFlagsForMergeBatch(+ teamId,+ mergeSources.map((source) => source.id),+ currentTarget.id,+ this.targetDistinctId+ )+ deleteMessages = await tx.deletePersons(mergeSources, this.targetDistinctId)+ }++ if (this.tombstoneEnabled()) {+ await tx.releaseLifecycleMarks(lifecycleOpId, teamId, this.targetDistinctId)+ }+ return [person, [...updateMessages, ...moveResult.messages, ...addMessages, ...deleteMessages]]+ })++ this.flushOverrideCounts()+ mergeFoldExecutedCounter.inc()+ mergeFoldSizeHistogram.observe(this.request.sources.length)++ // 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+ for (const source of mergeSources) {+ // Same fire-and-forget contract as executeTransaction.+ void this.producePersonMergeEvent(source, mergedPerson).catch(() => {})+ }+ outcomes.push(...mergedSourceOutcomes)+ outcomes.push(+ ...missingSources.map(+ (pair): MergePersonsSourceResult => ({+ sourceDistinctId: pair.distinctId,+ outcome: 'attached',+ })+ )+ )+ return { survivor: mergedPerson, results: outcomes, kafkaAck }+ }++ private async mergePeople({+ mergeInto,+ mergeIntoDistinctId,+ otherPerson,+ otherPersonDistinctId,+ }: {+ mergeInto: InternalPerson+ mergeIntoDistinctId: string+ otherPerson: InternalPerson+ otherPersonDistinctId: string+ }): Promise<MergePersonsResult> {+ const olderCreatedAt = DateTime.min(mergeInto.created_at, otherPerson.created_at)++ // $merge_dangerously has no restrictions; $create_alias and $identify+ // will not merge a user who's already identified into anyone else.+ const mergeAllowed = this.request.allowIdentifiedSources || !otherPerson.is_identified+ if (!mergeAllowed) {+ return {+ survivor: mergeInto,+ results: [+ {+ sourceDistinctId: otherPersonDistinctId,+ outcome: 'skipped_already_identified',+ sourcePersonUuid: otherPerson.uuid,+ },+ ],+ }+ }++ // How the merge works:+ // Merging properties:+ // on key conflict we use the properties from the person provided as the first argument in identify or alias calls (mergeInto person),+ // Note it's important for us to compute this before potentially swapping the persons for personID merging purposes in PoEEmbraceJoin mode+ // In case of PoE Embrace the join mode:+ // we want to keep using the older person to reduce the number of partitions that need to be updated during squash+ // to do that we'll swap otherPerson and mergeInto person (after properties merge computation!)+ // additionally update person overrides table in postgres and clickhouse+ // TODO: ^+ // If the merge fails:+ // we'll roll back the transaction and then try from scratch in the origial order of persons provided for property merges+ // that guarantees consistency of how properties are processed regardless of persons created_at timestamps and rollout state+ // we're calling aliasDeprecated as we need to refresh the persons info completely first++ const mergedProperties: Properties = { ...otherPerson.properties, ...mergeInto.properties }+ const propertyUpdates = refineEventOps(this.request.eventOps, mergedProperties, this.policy.updateAllProperties)++ // Create a temporary person object to apply property updates to+ const tempPerson: InternalPerson = { ...mergeInto, properties: mergedProperties }+ const [updatedTempPerson, _] = applyEventPropertyUpdates(propertyUpdates, tempPerson)+ const properties = updatedTempPerson.properties++ const result = await this.handleMergeTransaction(+ mergeInto,+ mergeIntoDistinctId,+ otherPerson,+ otherPersonDistinctId,+ olderCreatedAt, // Keep the oldest created_at (i.e. the first time we've seen either person)+ properties+ )++ if (result.success) {+ return {+ survivor: result.person ?? null,+ results: [+ {+ sourceDistinctId: otherPersonDistinctId,+ outcome: 'merged',+ sourcePersonUuid: otherPerson.uuid,+ },+ ],+ kafkaAck: result.kafkaAck,+ }+ }++ // A race that persisted through every retry: another merge kept+ // winning the persons. The merge drops; the caller emits the+ // race-condition warning and keeps the target as the survivor.+ if (result.error instanceof PersonMergeRaceConditionError) {+ return {+ survivor: mergeInto,+ results: [+ {+ sourceDistinctId: otherPersonDistinctId,+ outcome: 'skipped_race',+ sourcePersonUuid: otherPerson.uuid,+ },+ ],+ }+ }++ let failedOutcome: MergePersonsSourceResult['outcome']+ if (result.error instanceof PersonMergeLimitExceededError) {+ failedOutcome = 'skipped_move_limit'+ } else if (result.error instanceof SourcePersonHasDistinctIdsError) {+ failedOutcome = 'failed_source_has_distinct_ids'+ } else if (result.error instanceof TargetPersonNotFoundError) {+ failedOutcome = 'failed_target_not_found'+ } else if (result.error instanceof SourcePersonNotFoundError) {+ failedOutcome = 'failed_source_not_found'+ } else {+ failedOutcome = 'error'+ }+ return {+ survivor: null,+ results: [+ {+ sourceDistinctId: otherPersonDistinctId,+ outcome: failedOutcome,+ sourcePersonUuid: otherPerson.uuid,+ },+ ],+ }+ }++ private async executeTransaction(+ currentTargetPerson: InternalPerson,+ currentSourcePerson: InternalPerson,+ createdAt: DateTime,+ properties: Properties+ ): Promise<PersonMergeResult> {+ try {+ mergeTxnAttemptCounter+ .labels({+ call: this.eventName, // $identify, $create_alias or $merge_dangerously+ oldPersonIdentified: String(currentSourcePerson.is_identified),+ newPersonIdentified: String(currentTargetPerson.is_identified),+ })+ .inc()++ this.discardOverrideCounts()+ const lifecycleOpId = lifecycleOpIdFromEvent(this.teamId, this.request.eventUuid)+ const [mergedPerson, kafkaMessages] = await this.inTransaction('mergePeople', async (tx) => {+ // New-world merges claim both persons in the lifecycle mark table: at+ // most one live operation (merge or delete saga) may hold a person, so+ // neither can be tombstoned under this transaction. The marks say+ // nothing about tombstones committed before the claim, so assert both+ // persons are still live while holding them. Liveness checks are+ // separate statements because a claim that waited on the mark index+ // resumes with a stale snapshot.+ if (this.tombstoneEnabled()) {+ await tx.claimLifecycleMarks(+ lifecycleOpId,+ currentTargetPerson.team_id,+ [+ {+ personId: currentTargetPerson.id,+ personUuid: currentTargetPerson.uuid,+ role: 'target',+ },+ {+ personId: currentSourcePerson.id,+ personUuid: currentSourcePerson.uuid,+ role: 'source',+ ordinal: 0,+ },+ ],+ this.targetDistinctId+ )+ if (!(await tx.isPersonLive(currentTargetPerson, this.targetDistinctId))) {+ throw new TargetPersonNotFoundError('Target person was deleted concurrently')+ }+ if (!(await tx.isPersonLive(currentSourcePerson, this.targetDistinctId))) {+ throw new SourcePersonNotFoundError('Source person was deleted concurrently')+ }+ }+ const [person, updatePersonMessages] = await tx.updatePersonForMerge(+ currentTargetPerson,+ {+ created_at: createdAt,+ properties: properties,+ is_identified: true,++ // By using the max version between the two Persons, we ensure that if+ // this Person is later split, we can use `this_person.version + 1` for+ // any split-off Persons and know that *that* version will be higher than+ // any previously deleted Person, and so the new Person row will "win" and+ // "undelete" the Person.+ //+ // For example:+ // - Merge Person_1(version:7) into Person_2(version:2)+ // - Person_1 is deleted+ // - Person_2 attains version 8 via this code below+ // - Person_2 is later split, which attempts to re-create Person_1 by using+ // its `distinct_id` to generate the deterministic Person UUID.+ // That new Person_1 will have a version _at least_ as high as 8, and+ // so any previously existing rows in CH or otherwise from+ // Person_1(version:7) will "lose" to this new Person_1.+ version: Math.max(currentTargetPerson.version, currentSourcePerson.version) + 1,+ },+ this.targetDistinctId+ )++ // Move distinct IDs first to establish ownership of the source person quickly.+ // This reduces contention when multiple concurrent merges target the same source,+ // as subsequent lookups via distinct ID will fail faster.+ const allDistinctIdMessages = await this.moveDistinctIdsBasedOnMode(+ tx,+ currentSourcePerson,+ currentTargetPerson+ )++ // Update cohorts and feature flags after distinct IDs are moved.+ // The source person row still exists (deleted below), so FK constraints are satisfied.+ // TODO: Doesn't this table need to add updates to CH too?+ await tx.updateCohortsAndFeatureFlagsForMerge(+ currentSourcePerson.team_id,+ currentSourcePerson.id,+ currentTargetPerson.id,+ this.targetDistinctId+ )++ const deletePersonMessages = await tx.deletePerson(currentSourcePerson, this.targetDistinctId)+ if (this.tombstoneEnabled()) {+ await tx.releaseLifecycleMarks(lifecycleOpId, this.teamId, this.targetDistinctId)+ }+ return [person, [...updatePersonMessages, ...allDistinctIdMessages, ...deletePersonMessages]]+ })++ this.flushOverrideCounts()+ mergeTxnSuccessCounter+ .labels({+ call: this.eventName, // $identify, $create_alias or $merge_dangerously+ oldPersonIdentified: String(currentSourcePerson.is_identified),+ newPersonIdentified: String(currentTargetPerson.is_identified),+ })+ .inc()++ // Fire-and-forget after commit: the person_merge_events emission is detached from the ack+ // chain, so a produce failure can never block, replay, or crash ingestion.+ // producePersonMergeEvent is best-effort and never throws; the call-site catch is a safety+ // net that swallows an escaped rejection so a broken never-throws contract can't reach the+ // unhandledRejection handler and stop the service.+ const kafkaAck = this.produceMessages(kafkaMessages)+ void this.producePersonMergeEvent(currentSourcePerson, mergedPerson).catch(() => {})+ return mergeSuccess(mergedPerson, kafkaAck, true)+ } catch (error) {+ // Map exceptions to result types - these will cause transaction rollback+ if (error instanceof SourcePersonNotFoundError) {+ return mergeError(error)+ } else if (error instanceof TargetPersonNotFoundError) {+ return mergeError(error)+ } else if (error instanceof PersonMergeLimitExceededError) {+ return mergeError(error)+ } else if (error.code === '23503' || error instanceof PersonTombstoneBlockedError) {+ // A concurrent merge added a distinct ID to the source person after we've already+ // moved the distinct IDs we knew about, but before the delete executed — surfaced+ // as a foreign key violation by the hard delete, or as PersonTombstoneBlockedError+ // by the tombstone's live-mapping guard. The retry mechanism will:+ // 1. Refresh the source person data to see all distinct IDs (including newly added ones)+ // 2. Move ALL distinct IDs to the target person+ // 3. Successfully delete the now-empty source person+ return mergeError(+ new SourcePersonHasDistinctIdsError(+ 'Cannot delete source person due to concurrent distinct ID additions'+ )+ )+ } else {+ // Re-throw unexpected errors+ throw error+ }+ }+ }++ // Override-counter increments are buffered and flushed only after the enclosing+ // transaction commits: merges retry and roll back, and rolled-back rows must not+ // inflate a metric used for override-inflow capacity planning.+ private pendingOverrideCounts: { call: string; count: number }[] = []++ private recordOverrideCount(call: string, count: number = 1): void {+ if (count > 0) {+ this.pendingOverrideCounts.push({ call, count })+ }+ }++ private discardOverrideCounts(): void {+ this.pendingOverrideCounts = []+ }++ private flushOverrideCounts(): void {+ for (const { call, count } of this.pendingOverrideCounts) {+ mergeDistinctIdOverrideCounter.labels({ call }).inc(count)+ }+ this.pendingOverrideCounts = []+ }++ private async moveDistinctIdsBasedOnMode(+ tx: PersonsStoreTransactionForBatch,+ currentSourcePerson: InternalPerson,+ currentTargetPerson: InternalPerson+ ): Promise<PersonMessage[]> {+ if (this.request.mergeMode.type === 'SYNC') {+ if (!this.request.mergeMode.batchSize) {+ return await this.moveDistinctIdsWithLimit(tx, currentSourcePerson, currentTargetPerson, undefined)+ }+ return await this.moveDistinctIdsInBatches(+ tx,+ currentSourcePerson,+ currentTargetPerson,+ this.request.mergeMode.batchSize+ )+ } else {+ const limit = this.request.mergeMode.limit+ return await this.moveDistinctIdsWithLimit(tx, currentSourcePerson, currentTargetPerson, limit)+ }+ }++ private async moveDistinctIdsInBatches(+ tx: PersonsStoreTransactionForBatch,+ currentSourcePerson: InternalPerson,+ currentTargetPerson: InternalPerson,+ batchSize: number+ ): Promise<PersonMessage[]> {+ const allDistinctIdMessages: PersonMessage[] = []+ let hasMore = true+ let hasProcessedAnyDistinctIds = false++ while (hasMore) {+ const distinctIdResult = await tx.moveDistinctIds(+ currentSourcePerson,+ currentTargetPerson,+ this.targetDistinctId,+ batchSize+ )++ if (!distinctIdResult.success) {+ if (distinctIdResult.error === 'SourceNotFound') {+ if (hasProcessedAnyDistinctIds) {+ // Source person not found after we've already moved some distinct IDs+ // This means we've moved all distinct IDs+ hasMore = false+ break+ } else {+ // Source person not found on first attempt - this is a real error+ throw new SourcePersonNotFoundError('Source person no longer exists')+ }+ } else if (distinctIdResult.error === 'TargetNotFound') {+ throw new TargetPersonNotFoundError('Target person no longer exists')+ }+ } else {+ allDistinctIdMessages.push(...distinctIdResult.messages)+ hasProcessedAnyDistinctIds = true+ this.recordOverrideCount('bothExistMove', distinctIdResult.distinctIdsMoved.length)++ // Check if we moved fewer than the batch size, indicating we're done+ hasMore = distinctIdResult.distinctIdsMoved.length >= batchSize+ }+ }++ return allDistinctIdMessages+ }++ private async moveDistinctIdsWithLimit(+ tx: PersonsStoreTransactionForBatch,+ currentSourcePerson: InternalPerson,+ currentTargetPerson: InternalPerson,+ limit: number | undefined+ ): Promise<PersonMessage[]> {+ // Original behavior for LIMIT mode or SYNC without batchSize+ const distinctIdResult = await tx.moveDistinctIds(+ currentSourcePerson,+ currentTargetPerson,+ this.targetDistinctId,+ limit+ )++ if (!distinctIdResult.success) {+ if (distinctIdResult.error === 'SourceNotFound') {+ throw new SourcePersonNotFoundError('Source person no longer exists')+ } else if (distinctIdResult.error === 'TargetNotFound') {+ throw new TargetPersonNotFoundError('Target person no longer exists')+ }+ }++ const allDistinctIdMessages = distinctIdResult.success ? distinctIdResult.messages : []++ // If moved count equals the per-call limit, verify if it's a partial move by checking remaining IDs+ const movedCount = distinctIdResult.success ? distinctIdResult.distinctIdsMoved.length : 0+ const hitLimit = limit ? movedCount >= limit : false++ if (hitLimit) {+ const remaining = await tx.fetchPersonDistinctIds(currentSourcePerson, this.targetDistinctId, 1)+ if (remaining.length > 0) {+ personMergeFailureCounter.labels({ call: this.eventName }).inc()+ // Drop the event by throwing an error that the pipeline will map to DLQ/no-retry+ logger.error('🤔', 'person merge move limit hit', {+ team_id: this.teamId,+ distinct_id: this.targetDistinctId,+ })+ throw new PersonMergeLimitExceededError('person_merge_move_limit_hit')+ }+ }+ this.recordOverrideCount('bothExistMove', movedCount)++ return allDistinctIdMessages+ }++ private async handleMergeTransaction(+ targetPerson: InternalPerson,+ targetDistinctId: string,+ sourcePerson: InternalPerson,+ sourceDistinctId: string,+ createdAt: DateTime,+ properties: Properties,+ maxRetries: number = 5+ ): Promise<PersonMergeResult> {+ let currentTargetPerson = targetPerson+ let currentSourcePerson = sourcePerson++ for (let attempt = 0; attempt <= maxRetries; attempt++) {+ const result = await this.executeTransaction(+ currentTargetPerson,+ currentSourcePerson,+ createdAt,+ properties+ )++ if (result.success) {+ return result+ }++ // Handle retryable errors+ if (attempt < maxRetries) {+ if (+ result.error instanceof SourcePersonNotFoundError ||+ result.error instanceof SourcePersonHasDistinctIdsError+ ) {+ const refreshedPerson = await this.refreshPersonData(+ sourceDistinctId,+ currentSourcePerson.id,+ attempt,+ 'source'+ )++ if (!refreshedPerson) {+ return mergeSuccess(currentTargetPerson, Promise.resolve(), true)+ }++ currentSourcePerson = refreshedPerson+ continue+ } else if (result.error instanceof TargetPersonNotFoundError) {+ const refreshedPerson = await this.refreshPersonData(+ targetDistinctId,+ currentTargetPerson.id,+ attempt,+ 'target'+ )++ if (!refreshedPerson) {+ return mergeSuccess(currentTargetPerson, Promise.resolve(), true)+ }++ currentTargetPerson = refreshedPerson+ continue+ } else {+ // Non-retryable error, return the failure result+ return result+ }+ } else {+ // Max retries reached, return the failure result+ return result+ }+ }++ // This should never be reached, but add fallback for race condition+ return mergeError(+ new PersonMergeRaceConditionError(+ `Failed to merge persons due to concurrent merges, ` ++ `source person: ${sourcePerson.id}, target person: ${targetPerson.id}, team: ${this.teamId} ` ++ `source distinct id: ${sourceDistinctId}, target distinct id: ${targetDistinctId}`+ )+ )+ }++ private async refreshPersonData(+ distinctId: string,+ currentPersonId: string,+ attempt: number,+ personType: 'source' | 'target'+ ): Promise<InternalPerson | null> {+ logger.info(`${personType} person not found, retrying with fresh data`, {+ [`${personType}PersonId`]: currentPersonId,+ teamId: this.teamId,+ attempt,+ distinctId,+ })++ // Purge the mapping so the refresh reads committed state instead of the cached person.+ this.store.removeDistinctIdFromCache(this.teamId, distinctId)++ // Fetch the refreshed person data using the new distinct ID+ const refreshedPerson = await this.store.fetchForUpdate(this.teamId, distinctId, this.batchId)++ if (!refreshedPerson) {+ logger.info(`${personType} person no longer exists after refresh, skipping merge`, {+ [`${personType}PersonId`]: currentPersonId,+ teamId: this.teamId,+ attempt,+ })+ return null+ }++ return refreshedPerson+ }+}diff --git a/nodejs/src/ingestion/common/persons/person-merge-service.test.ts b/nodejs/src/ingestion/common/persons/person-merge-service.test.tsindex 386990e3a3a7..41bc21afaf67 100644--- a/nodejs/src/ingestion/common/persons/person-merge-service.test.ts+++ b/nodejs/src/ingestion/common/persons/person-merge-service.test.ts@@ -1,132 +1,498 @@import { DateTime } from 'luxon'-import { INGESTION_WARNINGS_OUTPUT } from '~/common/outputs'-import { InternalPerson } from '~/types'+import { PersonClaimedByLifecycleOpError } from '~/common/persons/repositories/person-repository'+import { parseJSON } from '~/common/utils/json-parse'+import { defaultRetryConfig } from '~/common/utils/retries'+import { PluginEvent } from '~/plugin-scaffold'+import { InternalPerson, Team } from '~/types'import { PersonContext } from './person-context'-import { PersonMergeService } from './person-merge-service'-import { PersonMergeResult, createDefaultSyncMergeMode } from './person-merge-types'--describe('PersonMergeService', () => {- let teamCounter = 1000-- function person(uuid: string, isIdentified: boolean, teamId: number): InternalPerson {- return {- id: uuid,- uuid,- team_id: teamId,- properties: {},- created_at: DateTime.now(),- version: 0,- is_identified: isIdentified,- is_user_id: null,- last_seen_at: null,- properties_last_updated_at: {},- properties_last_operation: {},- }- }+import { MergeFoldPlan } from './person-merge-fold'+import { PersonMergeService, mergeFoldFallbackCounter, mergeSettledFailureCounter } from './person-merge-service'+import {+ PersonMergeCallFailedError,+ PersonMergeLimitExceededError,+ PersonMergeResponseMismatchError,+ SourcePersonHasDistinctIdsError,+ SourcePersonNotFoundError,+ TargetPersonNotFoundError,+ createDefaultSyncMergeMode,+} from './person-merge-types'+import { MergePersonsOutcome, MergePersonsResult } from './persons-store'+import { PersonsStoreForBatch } from './persons-store-for-batch'- let teamId: number- let queueMessages: jest.Mock+async function counterTotal(counter: { get(): Promise<{ values: { value: number }[] }> }): Promise<number> {+ const metric = await counter.get()+ return metric.values.reduce((sum, v) => sum + v.value, 0)+}- beforeEach(() => {- teamId = teamCounter++- queueMessages = jest.fn().mockResolvedValue(undefined)- })+describe('PersonMergeService store-owned merges', () => {+ const timestamp = DateTime.fromMillis(3_600_000, { zone: 'utc' })++ const survivor: InternalPerson = {+ id: '7',+ uuid: 'person-uuid',+ team_id: 1,+ properties: { plan: 'merged' },+ created_at: timestamp,+ version: 5,+ properties_last_updated_at: {},+ properties_last_operation: {},+ is_user_id: null,+ is_identified: true,+ last_seen_at: null,+ }++ let store: {+ mergePersons: jest.Mock+ fetchForUpdate: jest.Mock+ }+ let outputs: { queueMessages: jest.Mock }- function service(targetDistinctId: string): PersonMergeService {+ const makeService = (eventName = '$identify', mergeFoldPlan?: MergeFoldPlan) => {+ const event = {+ event: eventName,+ uuid: 'event-uuid',+ distinct_id: 'd1',+ team_id: 1,+ properties: {+ $anon_distinct_id: 'anon-1',+ alias: 'anon-1',+ $set: { plan: 'pro' },+ $set_once: { first: 'x' },+ },+ } as unknown as PluginEventconst context = new PersonContext(- { uuid: 'event-uuid', event: '$identify', distinct_id: targetDistinctId, properties: {} } as any,- { id: teamId } as any,- targetDistinctId,- DateTime.now(),+ event,+ { id: 1 } as Team,+ 'd1',+ timestamp,true,- { queueMessages } as any,- {} as any,+ outputs as never,+ store as unknown as PersonsStoreForBatch,0,createDefaultSyncMergeMode(),false,- false+ false,+ mergeFoldPlan)return new PersonMergeService(context)}- describe('merge with an illegal distinct id', () => {- it.each([- ['target', 'null', 'user'],- ['source', 'user', 'null'],- ])(- 'returns before the %s warning is acked and hands the ack back as kafkaAck',- async (_side, mergeIntoDistinctId, otherPersonDistinctId) => {- let ackWarning!: () => void- queueMessages.mockReturnValue(new Promise<void>((resolve) => (ackWarning = resolve)))-- const result = await service(mergeIntoDistinctId).merge(- otherPersonDistinctId,- mergeIntoDistinctId,- teamId,- DateTime.now()- )-- expect(result).toMatchObject({ success: true, person: undefined, needsPersonUpdate: true })- if (!result.success) {- throw new Error('unreachable')- }- expect(queueMessages).toHaveBeenCalledWith(INGESTION_WARNINGS_OUTPUT, [{ value: expect.any(Buffer) }])-- let acked = false- void result.kafkaAck.then(() => (acked = true))- await Promise.resolve()- expect(acked).toBe(false)-- ackWarning()- await result.kafkaAck- expect(acked).toBe(true)- }+ const result = (outcome: MergePersonsOutcome): MergePersonsResult => ({+ survivor,+ results: [{ sourceDistinctId: 'anon-1', outcome }],+ })++ beforeEach(() => {+ defaultRetryConfig.RETRY_INTERVAL_DEFAULT = 0+ store = {+ mergePersons: jest.fn().mockResolvedValue(result('merged')),+ fetchForUpdate: jest.fn().mockResolvedValue(null),+ }+ outputs = { queueMessages: jest.fn().mockResolvedValue(undefined) }+ })++ it('passes a pre-epoch event timestamp through unchanged', async () => {+ // Events stamped before 1970 exist. Clamping them here would rewrite+ // the created_at Postgres records for a person a merge creates, so+ // each backend applies its own storable range instead.+ const service = makeService()+ await service.merge('anon-1', 'd1', 1, DateTime.fromMillis(-86_400_000, { zone: 'utc' }))++ expect(store.mergePersons).toHaveBeenCalledWith(expect.objectContaining({ createdAtMs: -86_400_000 }))+ })++ it('sends the store one request carrying the event identity and policy', async () => {+ const service = makeService()+ const mergeResult = await service.merge('anon-1', 'd1', 1, timestamp)++ expect(store.mergePersons).toHaveBeenCalledWith(+ expect.objectContaining({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: [{ distinctId: 'anon-1', eventUuid: 'event-uuid' }],+ eventUuid: 'event-uuid',+ allowIdentifiedSources: false,+ createdAtMs: 3_600_000,+ eventOps: expect.objectContaining({+ set: { plan: 'pro' },+ setOnce: { first: 'x' },+ eventName: '$identify',+ }),+ })+ )+ expect(mergeResult.success && mergeResult.person?.version).toBe(5)+ expect(store.fetchForUpdate).not.toHaveBeenCalled()+ })++ it('a settled merge failure acks with a signal rather than stalling the partition', async () => {+ store.mergePersons.mockResolvedValue(result('error'))+ const service = makeService()++ const mergeResult = await service.handleIdentifyOrAlias()++ // The verdict is recorded against the op id and replayed for the+ // retention window, so failing the batch would stall the partition+ // instead of healing. The warning is what keeps the lost merge findable.+ expect(mergeResult.success).toBe(true)+ const warned = outputs.queueMessages.mock.calls+ .flat(3)+ .filter((entry: any) => entry?.value)+ .map((entry: any) => parseJSON(Buffer.from(entry.value).toString()).type)+ expect(warned).toContain('merge_settled_failure')+ })++ it('attributes a replayed fold verdict to its own source', async () => {+ // A fold that failed after the saga recorded its op replays under the+ // same op id, carrying every source of the original fold.+ store.mergePersons.mockResolvedValue({+ survivor,+ results: [+ { sourceDistinctId: 'anon-9', outcome: 'merged' },+ { sourceDistinctId: 'anon-1', outcome: 'merged' },+ ],+ })+ const service = makeService()++ const mergeResult = await service.merge('anon-1', 'd1', 1, timestamp)++ expect(mergeResult.success && mergeResult.person).toBe(survivor)+ })++ it('$merge_dangerously legally merges identified sources', async () => {+ const service = makeService('$merge_dangerously')+ await service.merge('anon-1', 'd1', 1, timestamp)+ expect(store.mergePersons.mock.calls[0][0].allowIdentifiedSources).toBe(true)+ })++ it('a merge call failure fails the batch instead of acking through the generic catch', async () => {+ // The store wraps verdictless failures in the typed error; the+ // backend-agnostic catch must rethrow it — an ack here loses the+ // merge whenever the saga did not commit. The Postgres path never+ // produces this type, so its handling is untouched.+ store.mergePersons.mockRejectedValue(+ new PersonMergeCallFailedError('personhog merge call failed with no verdict', new Error('transport'))+ )+ const service = makeService()++ await expect(service.handleIdentifyOrAlias()).rejects.toThrow(PersonMergeCallFailedError)+ })++ it.each([+ ['a NUL-bearing source id', 'anon\u0000one'],+ ['an over-length source id', 'x'.repeat(150) + '\u{1F600}'.repeat(300)],+ ])('never merges through %s no backend can store', async (_label, badId) => {+ // Postgres text cannot hold NUL and varchar(400) cannot hold the id,+ // so the server refuses the whole request INVALID_ARGUMENT on every+ // delivery. Settling client-side with the illegal warning is the+ // only convergent answer.+ const service = makeService()+ const mergeResult = await service.merge(badId, 'd1', 1, timestamp)++ expect(mergeResult.success).toBe(true)+ expect(store.mergePersons).not.toHaveBeenCalled()+ const warned = outputs.queueMessages.mock.calls+ .flat(3)+ .filter((entry: any) => entry?.value)+ .map((entry: any) => parseJSON(Buffer.from(entry.value).toString()).type)+ expect(warned).toContain('cannot_merge_with_illegal_distinct_id')+ })++ it('a returned conflict verdict surfaces as the claim error without a retry', async () => {+ // Both backends surface conflicts as throws rather than returned+ // verdicts, so a returned conflict is contract-breaking input the+ // backstop must refuse to ack as a merge.+ store.mergePersons.mockResolvedValue(result('skipped_conflict'))+ const service = makeService()+ await expect(service.merge('anon-1', 'd1', 1, timestamp)).rejects.toBeInstanceOf(+ PersonClaimedByLifecycleOpError+ )+ expect(store.mergePersons).toHaveBeenCalledTimes(1)+ })++ it('an over-limit source returns the limit error result for the merge-mode policy', async () => {+ store.mergePersons.mockResolvedValue(result('skipped_move_limit'))+ const service = makeService()+ const mergeResult = await service.merge('anon-1', 'd1', 1, timestamp)+ expect(!mergeResult.success && mergeResult.error).toBeInstanceOf(PersonMergeLimitExceededError)+ })++ it('an already-identified source warns and keeps the survivor', async () => {+ store.mergePersons.mockResolvedValue(result('skipped_already_identified'))+ const service = makeService()+ const mergeResult = await service.merge('anon-1', 'd1', 1, timestamp)+ expect(mergeResult.success && mergeResult.person?.uuid).toBe('person-uuid')+ expect(outputs.queueMessages).toHaveBeenCalledTimes(1)+ })++ it('a race verdict warns and keeps the target as the survivor', async () => {+ store.mergePersons.mockResolvedValue(result('skipped_race'))+ const service = makeService()+ const mergeResult = await service.merge('anon-1', 'd1', 1, timestamp)+ expect(mergeResult.success && mergeResult.person?.uuid).toBe('person-uuid')+ expect(outputs.queueMessages).toHaveBeenCalledTimes(1)+ })++ it.each([+ ['failed_source_not_found' as const, SourcePersonNotFoundError],+ ['failed_target_not_found' as const, TargetPersonNotFoundError],+ ['failed_source_has_distinct_ids' as const, SourcePersonHasDistinctIdsError],+ ])('a %s verdict returns the typed final error the processor routes on', async (outcome, errorClass) => {+ store.mergePersons.mockResolvedValue({+ survivor: null,+ results: [{ sourceDistinctId: 'anon-1', outcome }],+ })+ const service = makeService()+ const mergeResult = await service.merge('anon-1', 'd1', 1, timestamp)+ expect(!mergeResult.success && mergeResult.error).toBeInstanceOf(errorClass)+ })++ it('a response carrying no verdict for the requested source fails rather than acks', async () => {+ store.mergePersons.mockResolvedValue({+ survivor,+ results: [{ sourceDistinctId: 'someone-else', outcome: 'merged' }],+ })+ const service = makeService()++ // Nothing is recorded against the op id for a malformed response, so a+ // retry can still succeed; acking would lose the merge permanently.+ await expect(service.merge('anon-1', 'd1', 1, timestamp)).rejects.toBeInstanceOf(+ PersonMergeResponseMismatchError)})- describe('mergePeople with an already identified source', () => {- function refuseMerge(targetDistinctId: string): Promise<PersonMergeResult> {- return service(targetDistinctId).mergePeople({- mergeInto: person('target-uuid', true, teamId),- mergeIntoDistinctId: targetDistinctId,- otherPerson: person('source-uuid', true, teamId),- otherPersonDistinctId: 'source',+ describe('folded merges', () => {+ const makePlan = (): MergeFoldPlan => ({+ targetDistinctId: 'd1',+ pairs: [+ { anonDistinctId: 'anon-1', eventUuid: 'event-uuid' },+ { anonDistinctId: 'anon-2', eventUuid: 'event-uuid-2' },+ ],+ status: 'planned',+ })++ it('sends every planned pair as one multi-source request and memoizes the survivor', async () => {+ store.mergePersons.mockResolvedValue({+ survivor,+ results: [+ { sourceDistinctId: 'anon-1', outcome: 'merged' },+ { sourceDistinctId: 'anon-2', outcome: 'merged' },+ ],})- }+ const plan = makePlan()+ const service = makeService('$identify', plan)++ const mergeResult = await service.handleIdentifyOrAlias()++ expect(store.mergePersons).toHaveBeenCalledTimes(1)+ expect(store.mergePersons.mock.calls[0][0].sources).toEqual([+ { distinctId: 'anon-1', eventUuid: 'event-uuid' },+ { distinctId: 'anon-2', eventUuid: 'event-uuid-2' },+ ])+ expect(plan.status).toBe('executed')+ expect(plan.mergedPerson).toBe(survivor)+ expect(mergeResult.success && mergeResult.person).toBe(survivor)+ })++ it('warns on an over-limit source the fold skipped', async () => {+ store.mergePersons.mockResolvedValue({+ survivor,+ results: [+ { sourceDistinctId: 'anon-1', outcome: 'merged' },+ { sourceDistinctId: 'anon-2', outcome: 'skipped_move_limit' },+ ],+ })+ const service = makeService('$identify', makePlan())++ await service.handleIdentifyOrAlias()++ // The source's own event later reads the executed plan and acks, so+ // without this the lost merge leaves no customer-visible trace.+ const warned = outputs.queueMessages.mock.calls+ .flat(3)+ .filter((entry: any) => entry?.value)+ .map((entry: any) => parseJSON(Buffer.from(entry.value).toString()).type)+ expect(warned).toContain('merge_move_limit_exceeded')+ })++ it.each([+ ['skipped_illegal', 'cannot_merge_with_illegal_distinct_id'],+ ['skipped_conflict', 'merge_race_condition'],+ ['skipped_race', 'merge_race_condition'],+ ['skipped_already_identified', 'cannot_merge_already_identified'],+ ])('warns on a %s source the fold skipped', async (outcome, warningType) => {+ store.mergePersons.mockResolvedValue({+ survivor,+ results: [+ { sourceDistinctId: 'anon-1', outcome: 'merged' },+ { sourceDistinctId: 'anon-2', outcome },+ ],+ })+ const service = makeService('$identify', makePlan())++ await service.handleIdentifyOrAlias()- it('returns before the warning is acked and hands the ack back as kafkaAck', async () => {+ const warned = outputs.queueMessages.mock.calls+ .flat(3)+ .filter((entry: any) => entry?.value)+ .map((entry: any) => parseJSON(Buffer.from(entry.value).toString()).type)+ expect(warned).toContain(warningType)+ })++ it('counts a source the fold settled as failed', async () => {+ // The warning type is limiter-debounced across tests, so the+ // settled-loss counter is the stable observable.+ const before = await counterTotal(mergeSettledFailureCounter)+ store.mergePersons.mockResolvedValue({+ survivor,+ results: [+ { sourceDistinctId: 'anon-1', outcome: 'merged' },+ { sourceDistinctId: 'anon-2', outcome: 'error' },+ ],+ })+ const service = makeService('$identify', makePlan())++ await service.handleIdentifyOrAlias()++ expect(await counterTotal(mergeSettledFailureCounter)).toBe(before + 1)+ })++ it('a later event of an executed plan short-circuits without a store call', async () => {+ const plan = makePlan()+ plan.status = 'executed'+ plan.mergedPerson = survivor+ const service = makeService('$identify', plan)++ const mergeResult = await service.handleIdentifyOrAlias()++ expect(store.mergePersons).not.toHaveBeenCalled()+ expect(mergeResult.success && mergeResult.person).toBe(survivor)+ })++ it('an aborted fold abandons the plan and falls back to the single-source merge', async () => {+ store.mergePersons+ .mockResolvedValueOnce({ survivor: null, results: [], foldAborted: 'conflict' })+ .mockResolvedValueOnce(result('merged'))+ const plan = makePlan()+ const service = makeService('$identify', plan)++ const mergeResult = await service.handleIdentifyOrAlias()++ expect(plan.status).toBe('abandoned')+ expect(store.mergePersons).toHaveBeenCalledTimes(2)+ expect(store.mergePersons.mock.calls[1][0].sources).toEqual([+ { distinctId: 'anon-1', eventUuid: 'event-uuid' },+ ])+ expect(mergeResult.success && mergeResult.person).toBe(survivor)+ })++ it('carries the triggering source for the cold-start bootstrap', async () => {+ store.mergePersons.mockResolvedValue({+ survivor,+ results: [+ { sourceDistinctId: 'anon-1', outcome: 'merged' },+ { sourceDistinctId: 'anon-2', outcome: 'merged' },+ ],+ })+ const service = makeService('$identify', makePlan())++ await service.handleIdentifyOrAlias()++ expect(store.mergePersons.mock.calls[0][0].triggerSourceDistinctId).toBe('anon-1')+ })++ it('a committed fold still succeeds when warning emission fails', async () => {+ store.mergePersons.mockResolvedValue({+ survivor,+ results: [+ { sourceDistinctId: 'anon-1', outcome: 'merged' },+ { sourceDistinctId: 'anon-2', outcome: 'skipped_already_identified' },+ ],+ })+ outputs.queueMessages.mockRejectedValue(new Error('broker down'))+ const plan = makePlan()+ const service = makeService('$identify', plan)++ const mergeResult = await service.handleIdentifyOrAlias()++ expect(plan.status).toBe('executed')+ expect(mergeResult.success && mergeResult.person).toBe(survivor)+ })++ it('a thrown claim conflict abandons the fold under the conflict label', async () => {+ defaultRetryConfig.RETRY_INTERVAL_DEFAULT = 0+ const before =+ (await mergeFoldFallbackCounter.get()).values.find((v) => v.labels.reason === 'conflict')?.value ?? 0+ store.mergePersons.mockRejectedValue(new PersonClaimedByLifecycleOpError('held', 1))+ const plan = makePlan()+ const service = makeService('$identify', plan)++ const mergeResult = await service.handleIdentifyOrAlias()++ expect(plan.status).toBe('abandoned')+ const after =+ (await mergeFoldFallbackCounter.get()).values.find((v) => v.labels.reason === 'conflict')?.value ?? 0+ expect(after).toBe(before + 1)+ // The sequential fallback then exhausts its retries on the same+ // claim and drops the merge, which reports success with no person.+ expect(mergeResult.success && mergeResult.person).toBeUndefined()+ })+ })++ describe('non-blocking warning acks', () => {+ it('an unmergeable id returns before the warning is acked and hands the ack back', async () => {let ackWarning!: () => void- queueMessages.mockReturnValue(new Promise<void>((resolve) => (ackWarning = resolve)))+ outputs.queueMessages.mockReturnValue(new Promise<void>((resolve) => (ackWarning = resolve)))+ const service = makeService()- const result = await refuseMerge('target')+ const mergeResult = await service.merge('anon-1', 'null', 1, timestamp)- expect(result).toMatchObject({ success: true, needsPersonUpdate: true })- if (!result.success) {+ expect(mergeResult.success && mergeResult.person).toBeUndefined()+ expect(store.mergePersons).not.toHaveBeenCalled()+ if (!mergeResult.success) {throw new Error('unreachable')}- expect(result.person?.uuid).toBe('target-uuid')- expect(queueMessages).toHaveBeenCalledWith(INGESTION_WARNINGS_OUTPUT, [{ value: expect.any(Buffer) }])-let acked = false- void result.kafkaAck.then(() => (acked = true))+ void mergeResult.kafkaAck.then(() => (acked = true))await Promise.resolve()expect(acked).toBe(false)+ ackWarning()+ await mergeResult.kafkaAck+ expect(acked).toBe(true)+ })++ it('a refused verdict returns before its warning is acked and hands the ack back', async () => {+ let ackWarning!: () => void+ outputs.queueMessages.mockReturnValue(new Promise<void>((resolve) => (ackWarning = resolve)))+ store.mergePersons.mockResolvedValue(result('skipped_already_identified'))+ const service = makeService()++ const mergeResult = await service.merge('anon-1', 'd1', 1, timestamp)+ expect(mergeResult.success && mergeResult.person?.uuid).toBe('person-uuid')+ if (!mergeResult.success) {+ throw new Error('unreachable')+ }+ let acked = false+ void mergeResult.kafkaAck.then(() => (acked = true))+ await Promise.resolve()+ expect(acked).toBe(false)ackWarning()- await result.kafkaAck+ await mergeResult.kafkaAckexpect(acked).toBe(true)})- it('does not fail the event when the warning produce fails', async () => {- queueMessages.mockRejectedValue(new Error('broker down'))+ it('a failed warning produce does not fail the event', async () => {+ outputs.queueMessages.mockRejectedValue(new Error('broker down'))+ store.mergePersons.mockResolvedValue(result('skipped_already_identified'))+ const service = makeService()- const result = await refuseMerge('target')+ const mergeResult = await service.merge('anon-1', 'd1', 1, timestamp)- expect(result.success).toBe(true)- if (result.success) {- await expect(result.kafkaAck).resolves.toBeUndefined()+ expect(mergeResult.success).toBe(true)+ if (mergeResult.success) {+ await expect(mergeResult.kafkaAck).resolves.toBeUndefined()}})})diff --git a/nodejs/src/ingestion/common/persons/person-merge-service.ts b/nodejs/src/ingestion/common/persons/person-merge-service.tsindex 8f8713d3c59f..a370945c5971 100644--- a/nodejs/src/ingestion/common/persons/person-merge-service.ts+++ b/nodejs/src/ingestion/common/persons/person-merge-service.ts@@ -1,9 +1,7 @@import { DateTime } from 'luxon'-import { Counter, Histogram } from 'prom-client'+import { Counter } from 'prom-client'-import { personMergeFailureCounter } from '~/common/persons/metrics'-import { PersonMessage } from '~/common/persons/person-message'-import { isDistinctIdIllegal } from '~/common/persons/person-utils'+import { isDistinctIdUnmergeable } from '~/common/persons/person-utils'import {PersonClaimedByLifecycleOpError,PersonTombstoneBlockedError,@@ -13,15 +11,12 @@ import { logger } from '~/common/utils/logger'import { captureException } from '~/common/utils/posthog'import { promiseRetry } from '~/common/utils/retries'import { emitIngestionWarning } from '~/ingestion/common/ingestion-warnings'-import { Properties } from '~/plugin-scaffold'-import { InternalPerson } from '~/types'import { PersonContext } from './person-context'-import { PersonCreateService } from './person-create-service'-import type { MergeFoldPair, MergeFoldPlan } from './person-merge-fold'import {+ PersonMergeCallFailedError,PersonMergeLimitExceededError,- PersonMergeRaceConditionError,+ PersonMergeResponseMismatchError,PersonMergeResult,SourcePersonHasDistinctIdsError,SourcePersonNotFoundError,@@ -29,30 +24,20 @@ import {mergeError,mergeSuccess,} from './person-merge-types'-import { applyEventPropertyUpdates, extractEventOps, refineEventOps } from './person-update'-import { lifecycleOpIdFromEvent } from './person-uuid'-import { PersonsStoreTransactionForBatch } from './persons-store-for-batch'+import { extractEventOps } from './person-update'+import {+ MergeFoldAbortReason,+ MergePersonsRequest,+ MergePersonsResult,+ MergePersonsSourceResult,+} from './persons-store'export const mergeFinalFailuresCounter = new Counter({name: 'person_merge_final_failure_total',help: 'Number of person merge final failures.',-})--export const mergeTxnAttemptCounter = new Counter({- name: 'person_merge_txn_attempt_total',- help: 'Number of person merge attempts.',- labelNames: ['call', 'oldPersonIdentified', 'newPersonIdentified'],-})--export const mergeTxnSuccessCounter = new Counter({- name: 'person_merge_txn_success_total',- help: 'Number of person merges that succeeded.',- labelNames: ['call', 'oldPersonIdentified', 'newPersonIdentified'],-})--export const mergeFoldExecutedCounter = new Counter({- name: 'person_merge_fold_executed_total',- help: 'Number of folded merge transactions executed.',+ // The error class is the constructor name rather than the message, so a+ // failure carrying team ids or distinct ids cannot inflate cardinality.+ labelNames: ['backend', 'call', 'error'],})export const mergeFoldFallbackCounter = new Counter({@@ -61,10 +46,15 @@ export const mergeFoldFallbackCounter = new Counter({labelNames: ['reason'],})-export const mergeFoldSizeHistogram = new Histogram({- name: 'person_merge_fold_size',- help: 'Number of merge pairs folded into one transaction.',- buckets: [2, 5, 10, 25, 50, 100, 250, 500],+export const mergeSettledFailureCounter = new Counter({+ name: 'person_merge_settled_failure_total',+ help: 'Merges the merge backend settled on a verdict that merged nothing.',+})++export const mergeMoveLimitDroppedCounter = new Counter({+ name: 'person_merge_move_limit_dropped_total',+ help: 'Merges lost to the saga move limit, by the path that hit it.',+ labelNames: ['path'],})export const mergeClaimDroppedCounter = new Counter({@@ -73,28 +63,9 @@ export const mergeClaimDroppedCounter = new Counter({labelNames: ['call'],})-export const mergeDistinctIdOverrideCounter = new Counter({- name: 'person_merge_distinct_id_override_total',- help: 'Distinct id mapping rows written during merges, each writing a ClickHouse override row.',- labelNames: ['call'],-})--/** Thrown inside the fold transaction to roll it back when merge-mode move bounds would be exceeded. */-class MergeFoldLimitError extends Error {}--/** Thrown inside the fold transaction to roll it back when a concurrent merge invalidated the fetched sources. */-class MergeFoldConflictError extends Error {}--/** Maps a fold failure to the fallback counter's reason label. */-function foldFallbackReason(error: unknown): 'limit' | 'conflict' | 'deadlock' | 'error' {- if (error instanceof MergeFoldLimitError) {- return 'limit'- }- if (- error instanceof MergeFoldConflictError ||- error instanceof PersonTombstoneBlockedError ||- error instanceof PersonClaimedByLifecycleOpError- ) {+/** Maps a thrown fold failure to the fallback counter's reason label. */+function foldAbandonReason(error: unknown): MergeFoldAbortReason {+ if (error instanceof PersonClaimedByLifecycleOpError || error instanceof PersonTombstoneBlockedError) {return 'conflict'}if ((error as { code?: string })?.code === '40P01') {@@ -104,14 +75,13 @@ function foldFallbackReason(error: unknown): 'limit' | 'conflict' | 'deadlock' |}/**- * Service responsible for handling person merging operations (identify, alias, merge).- * Extracted from PersonState to focus on merge-specific logic.+ * Service responsible for handling person merging operations (identify,+ * alias, merge). Backend-agnostic: it validates the request, hands the+ * whole merge to the store's own machinery via mergePersons, and maps+ * the per-source outcomes onto one result and warning vocabulary.*/export class PersonMergeService {- private personCreateService: PersonCreateService- constructor(private context: PersonContext) {- this.personCreateService = new PersonCreateService(context)- }+ constructor(private context: PersonContext) {}async handleIdentifyOrAlias(): Promise<PersonMergeResult> {/**@@ -181,6 +151,11 @@ export class PersonMergeService {})return mergeSuccess(undefined, warningAck, true)}+ // Both carry no settled verdict; their class docs explain why the+ // batch must fail and redeliver rather than ack.+ if (e instanceof PersonMergeResponseMismatchError || e instanceof PersonMergeCallFailedError) {+ throw e+ }captureException(e, {tags: { team_id: this.context.team.id, pipeline_step: 'processPersonsStep' },extra: {@@ -190,7 +165,13 @@ export class PersonMergeService {alias: String(this.context.eventProperties['alias']),},})- mergeFinalFailuresCounter.inc()+ mergeFinalFailuresCounter+ .labels({+ backend: this.context.personStore.backend,+ call: this.context.event.event,+ error: e instanceof Error ? e.constructor.name : 'unknown',+ })+ .inc()logger.error('handleIdentifyOrAlias failed', {error: e,team_id: this.context.team.id,@@ -217,163 +198,61 @@ export class PersonMergeService {// Create a success result with undefined person to indicate no merge was neededreturn mergeSuccess(undefined, Promise.resolve(), true)}- if (isDistinctIdIllegal(mergeIntoDistinctId)) {- const warningAck = emitIngestionWarning(this.context.outputs, teamId, {- type: 'cannot_merge_with_illegal_distinct_id',- details: {- illegalDistinctId: mergeIntoDistinctId,- otherDistinctId: otherPersonDistinctId,- distinctId: mergeIntoDistinctId,- eventUuid: this.context.event.uuid,- },- pipelineStep: 'person-merge',- alwaysSend: true,- }).then(() => undefined)+ if (isDistinctIdUnmergeable(mergeIntoDistinctId)) {+ const warningAck = this.emitIllegalDistinctIdWarning(+ mergeIntoDistinctId,+ otherPersonDistinctId,+ this.context.event.uuid+ )return mergeSuccess(undefined, warningAck, true)}- if (isDistinctIdIllegal(otherPersonDistinctId)) {- const warningAck = emitIngestionWarning(this.context.outputs, teamId, {- type: 'cannot_merge_with_illegal_distinct_id',- details: {- illegalDistinctId: otherPersonDistinctId,- otherDistinctId: mergeIntoDistinctId,- distinctId: mergeIntoDistinctId,- eventUuid: this.context.event.uuid,- },- pipelineStep: 'person-merge',- alwaysSend: true,- }).then(() => undefined)+ if (isDistinctIdUnmergeable(otherPersonDistinctId)) {+ const warningAck = this.emitIllegalDistinctIdWarning(+ otherPersonDistinctId,+ mergeIntoDistinctId,+ this.context.event.uuid+ )return mergeSuccess(undefined, warningAck, true)}- const result = await promiseRetry(- () => this.mergeDistinctIds(otherPersonDistinctId, mergeIntoDistinctId, teamId, timestamp),- 'merge_distinct_ids'+ this.context.updateIsIdentified = true+ const request = this.buildRequest(+ mergeIntoDistinctId,+ [{ distinctId: otherPersonDistinctId, eventUuid: this.context.event.uuid }],+ timestamp)- return result+ // The store owns the whole merge, its own record-escape retries+ // included: retryable conflicts surface here as throws, and each+ // re-entry runs against fresh state.+ const result = await promiseRetry(() => this.context.personStore.mergePersons(request), 'merge_distinct_ids')+ return this.mapSingleSourceResult(result, otherPersonDistinctId, mergeIntoDistinctId)}- private async mergeDistinctIds(- otherPersonDistinctId: string,- mergeIntoDistinctId: string,- teamId: number,- timestamp: DateTime- ): Promise<PersonMergeResult> {- this.context.updateIsIdentified = true-- const otherPerson = await this.context.personStore.fetchForUpdate(teamId, otherPersonDistinctId)- const mergeIntoPerson = await this.context.personStore.fetchForUpdate(teamId, mergeIntoDistinctId)-- // A note about the `distinctIdVersion` logic you'll find below:- //- // Overrides are only created for `posthog_persondistinctid` rows with version > 0, see:- // https://github.com/PostHog/posthog/blob/92e17ce307a577c4233d4ab252eebc6c2207a5ee/posthog/models/person/sql.py#L269-L287- //- // With $process_person_profile=false, events can exist in ClickHouse stamped with the- // deterministic implied person uuid even though no `posthog_persondistinctid` or- // `posthog_person` rows exist. So every merge-added mapping for a distinct id without a- // person gets version 1: the override either re-points real personless events or is a- // harmless transient row the squash job deletes within days. The exception is the distinct- // id whose uuid a newly created person is born on — its events already point at the right- // person, so it keeps version 0 and stays out of the overrides join.-- if ((otherPerson && !mergeIntoPerson) || (!otherPerson && mergeIntoPerson)) {- // Only one of the two Distinct IDs points at an existing Person-- const [existingPerson, distinctIdToAdd] = (() => {- if (otherPerson) {- return [otherPerson!, mergeIntoDistinctId]- } else {- return [mergeIntoPerson!, otherPersonDistinctId]- }- })()-- this.discardOverrideCounts()- const lifecycleOpId = lifecycleOpIdFromEvent(this.context.team.id, this.context.event.uuid)- const result = await this.context.personStore.inTransaction('mergeDistinctIds-OneExists', async (tx) => {- // New-world merges claim the person's lifecycle mark, which keeps a concurrent- // tombstone from landing between this check and the distinct id insert (an- // orphaned mapping); old-world merges rely on the delete's FK violation instead.- if (this.context.mergeTombstoneEnabled) {- await tx.claimLifecycleMarks(- lifecycleOpId,- existingPerson.team_id,- [{ personId: existingPerson.id, personUuid: existingPerson.uuid, role: 'target' }],- this.context.distinctId- )- if (!(await tx.isPersonLive(existingPerson, this.context.distinctId))) {- // Purge the stale cache entries so the promiseRetry attempt- // re-fetches from Postgres instead of replaying the cached,- // now-tombstoned person into the same failure.- this.context.personStore.removeDistinctIdFromCache(teamId, otherPersonDistinctId)- this.context.personStore.removeDistinctIdFromCache(teamId, mergeIntoDistinctId)- throw new TargetPersonNotFoundError(- 'Person was deleted before the merge could add a distinct id'- )- }- }- // See comment above about `distinctIdVersion`- const distinctIdVersion = 1- this.recordOverrideCount('oneExists')-- const kafkaMessages = await tx.addDistinctId(existingPerson, distinctIdToAdd, distinctIdVersion)- await this.context.produceMessages(kafkaMessages)- if (this.context.mergeTombstoneEnabled) {- await tx.releaseLifecycleMarks(lifecycleOpId, this.context.team.id, this.context.distinctId)- }- return mergeSuccess(existingPerson, Promise.resolve(), true)- })- this.flushOverrideCounts()- return result- } 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- return mergeSuccess(mergeIntoPerson, Promise.resolve(), true)- }-- const result = await this.mergePeople({- mergeInto: mergeIntoPerson,- mergeIntoDistinctId: mergeIntoDistinctId,- otherPerson: otherPerson,- otherPersonDistinctId: otherPersonDistinctId,- })-- return result- } else {- // Neither Distinct ID points at an existing Person-- const distinctId1 = mergeIntoDistinctId- const distinctId2 = otherPersonDistinctId-- this.discardOverrideCounts()- const result = await this.context.personStore.inTransaction('mergeDistinctIds-NeitherExist', async (tx) => {- // See comment above about `distinctIdVersion`: the first Distinct ID derives the- // new Person's UUID so it never needs an override; the second always gets one.- const distinctId1Version = 0- const distinctId2Version = 1- this.recordOverrideCount('neitherExist')-- const [person, wasCreated] = await this.personCreateService.createPerson(- timestamp,- this.context.eventProperties['$set'] || {},- this.context.eventProperties['$set_once'] || {},- teamId,- null,- true,- this.context.event.uuid,- { distinctId: distinctId1, version: distinctId1Version },- [{ distinctId: distinctId2, version: distinctId2Version }],- tx- )- // If person was not created (creation conflict) and is not identified,- // we need to update it later- const needsPersonUpdate = !wasCreated && !person.is_identified- return mergeSuccess(person, Promise.resolve(), needsPersonUpdate)- })- this.flushOverrideCounts()- return result+ /**+ * One request for either backend, single-source or folded. The event+ * uuid doubles as the op id: retries re-enter with the same id and+ * must not merge twice.+ */+ private buildRequest(+ targetDistinctId: string,+ sources: { distinctId: string; eventUuid: string }[],+ timestamp: DateTime,+ triggerSourceDistinctId?: string+ ): MergePersonsRequest {+ return {+ teamId: this.context.team.id,+ targetDistinctId,+ sources,+ triggerSourceDistinctId,+ eventOps: extractEventOps(this.context.event, this.context.updateAllProperties),+ eventUuid: this.context.event.uuid,+ allowIdentifiedSources: this.context.event.event === '$merge_dangerously',+ mergeMode: this.context.mergeMode,+ // Passed as the event stated it, pre-epoch values included: what a+ // backend can store is the backend's constraint, and clamping here+ // would rewrite the created_at Postgres records for a person born+ // from a merge.+ createdAtMs: timestamp.toMillis(),}}@@ -401,805 +280,372 @@ export class PersonMergeService {return mergeSuccess(plan.mergedPerson, Promise.resolve(), true)}- if (isDistinctIdIllegal(plan.targetDistinctId)) {+ if (isDistinctIdUnmergeable(plan.targetDistinctId)) {// The sequential path emits the per-event warning.plan.status = 'abandoned'mergeFoldFallbackCounter.labels({ reason: 'illegal_target' }).inc()return null}+ this.context.updateIsIdentified = true+ const request = this.buildRequest(+ plan.targetDistinctId,+ plan.pairs.map((pair) => ({ distinctId: pair.anonDistinctId, eventUuid: pair.eventUuid })),+ this.context.timestamp,+ anonDistinctId+ )++ let result: MergePersonsResulttry {- return await this.executeFoldedMerge(plan, anonDistinctId)+ result = await this.context.personStore.mergePersons(request)} catch (error) {- // Any failure falls back to the sequential path: the current event- // re-runs its own merge (a no-op if the fold partially landed), and- // later events in the run process individually with full retries.- plan.status = 'abandoned'- const reason = foldFallbackReason(error)- mergeFoldFallbackCounter.labels({ reason }).inc()- // The batch store's caches were updated optimistically inside the- // rolled-back transaction (distinct id → target mappings); purge- // them so the sequential fallback re-reads committed state.- this.context.personStore.removeDistinctIdFromCache(this.context.team.id, plan.targetDistinctId)- for (const pair of plan.pairs) {- this.context.personStore.removeDistinctIdFromCache(this.context.team.id, pair.anonDistinctId)+ if (error instanceof PersonMergeResponseMismatchError) {+ // A malformed response is not a fold-shaped failure the+ // sequential path can retry around, so it has to reach the+ // batch instead of being absorbed by the fallback.+ throw error}+ // Any other failure falls back to the sequential path: the current+ // event re-runs its own merge (a no-op if the fold partially+ // landed), and later events process individually with full retries.+ this.abandonFold(plan, foldAbandonReason(error))logger.warn('🤔', 'folded merge failed, falling back to sequential merges', {team_id: this.context.team.id,distinct_id: plan.targetDistinctId,pairs: plan.pairs.length,- reason,error,})return null}- }-- /**- * Counts each folded source's distinct ids inside the transaction and- * aborts the fold (rolling it back) when:- * - a source is missing entirely — it was merged away between the locked- * fetch (whose locks were released at statement end) and the transaction,- * so its already-computed property contribution would be stale;- * - a source's count exceeds the LIMIT/ASYNC move limit — those events- * need their own per-event DLQ/redirect decision;- * - the total exceeds batched SYNC's per-statement batch size.- * Returns the expected total so the caller can verify the move touched- * exactly that many rows. One cheap indexed GROUP BY that rarely trips.- */- private async assertFoldSourcesWithinMoveBounds(- tx: PersonsStoreTransactionForBatch,- mergeSources: InternalPerson[]- ): Promise<number> {- if (mergeSources.length === 0) {- return 0+ if (result.foldAborted) {+ // The store already logged its abort with the underlying error.+ this.abandonFold(plan, result.foldAborted)+ return null+ }+ if (!result.survivor) {+ const reason = result.results[0]?.outcome === 'skipped_move_limit' ? 'limit' : 'error'+ this.abandonFold(plan, reason)+ logger.warn('🤔', 'folded merge settled without a survivor, falling back to sequential merges', {+ team_id: this.context.team.id,+ distinct_id: plan.targetDistinctId,+ pairs: plan.pairs.length,+ reason,+ })+ return null}- const mergeMode = this.context.mergeMode- const limit = mergeMode.type === 'SYNC' ? undefined : mergeMode.limit- const batchSize = mergeMode.type === 'SYNC' ? mergeMode.batchSize : undefined- const counts = await tx.countDistinctIdsForPersons(- this.context.team.id,- mergeSources.map((source) => source.id),- this.context.distinctId+ plan.status = 'executed'+ plan.mergedPerson = result.survivor+ // Warning acks ride the result's kafkaAck to the batch-end await+ // rather than blocking here. Warnings are diagnostics; a committed+ // fold must still return its result and ack when they fail.+ const warningsAck = this.emitFoldWarnings(result.results, request).catch((error) => {+ logger.warn('🤔', 'fold warning emission failed', { team_id: this.context.team.id, error })+ })+ return mergeSuccess(+ result.survivor,+ Promise.all([result.kafkaAck ?? Promise.resolve(), warningsAck]).then(() => undefined),+ true)- let total = 0- for (const source of mergeSources) {- const count = counts.get(source.id)- if (count === undefined) {- throw new MergeFoldConflictError('folded merge source lost its distinct ids concurrently')- }- if (limit !== undefined && count > limit) {- throw new MergeFoldLimitError('folded merge source exceeds distinct id move limit')- }- total += count- }- if (batchSize !== undefined && total > batchSize) {- throw new MergeFoldLimitError('folded merge move exceeds sync batch size')- }- return total}- private async executeFoldedMerge(plan: MergeFoldPlan, currentAnonDistinctId: string): Promise<PersonMergeResult> {- const teamId = this.context.team.id- this.context.updateIsIdentified = true-- let target = await this.context.personStore.fetchForUpdate(teamId, plan.targetDistinctId)- let pairsToFold = plan.pairs+ private abandonFold(plan: NonNullable<PersonContext['mergeFoldPlan']>, reason: MergeFoldAbortReason): void {+ plan.status = 'abandoned'+ mergeFoldFallbackCounter.labels({ reason }).inc()+ }- if (!target) {- // Cold start: no target person yet. Bootstrap it through the- // sequential path for the current event's pair (which creates the- // person or attaches the distinct_id), then fold the remaining pairs.- const bootstrap = await promiseRetry(- () =>- this.mergeDistinctIds(currentAnonDistinctId, plan.targetDistinctId, teamId, this.context.timestamp),- 'merge_distinct_ids'+ /**+ * Maps a single-source merge's outcome onto the caller's result and+ * warning vocabulary, so callers see one merge behavior from both+ * backends.+ */+ private mapSingleSourceResult(+ result: MergePersonsResult,+ otherPersonDistinctId: string,+ mergeIntoDistinctId: string+ ): PersonMergeResult {+ // The verdict is looked up by source rather than taken positionally,+ // so a multi-source response can never be read as this source's+ // answer.+ const sourceResult = result.results.find((source) => source.sourceDistinctId === otherPersonDistinctId)+ if (sourceResult === undefined) {+ // A malformed response rather than a settled answer, so it must+ // not take the settled-failure path below.+ throw new PersonMergeResponseMismatchError(+ `merge response for team ${this.context.team.id} carried no verdict for its requested source`)- if (!bootstrap.success || !bootstrap.person) {- throw new Error('merge fold bootstrap did not produce a target person')- }- target = bootstrap.person- pairsToFold = plan.pairs.filter((pair) => pair.anonDistinctId !== currentAnonDistinctId)}-- const sources = await this.context.personStore.fetchPersonsForUpdateByDistinctIds(- teamId,- pairsToFold.map((pair) => pair.anonDistinctId)- )- const sourceByDistinctId = new Map(sources.map((source) => [source.distinct_id, source]))-- // Partition pairs, preserving pair order for property-merge precedence.- const mergeSources: InternalPerson[] = []- const seenSourceIds = new Set<string>([target.id])- const missingPairs: MergeFoldPair[] = []- // Warning produces are awaited at batch end through the result's kafkaAck,- // not here, so a plan full of refused pairs does not serialize round-trips.- const warningAcks: Promise<boolean>[] = []- for (const pair of pairsToFold) {- if (isDistinctIdIllegal(pair.anonDistinctId)) {- warningAcks.push(- emitIngestionWarning(this.context.outputs, teamId, {- type: 'cannot_merge_with_illegal_distinct_id',- details: {- illegalDistinctId: pair.anonDistinctId,- otherDistinctId: plan.targetDistinctId,- distinctId: plan.targetDistinctId,- eventUuid: pair.eventUuid,- },- pipelineStep: 'person-merge',- alwaysSend: true,- })+ const outcome = sourceResult.outcome+ const survivor = result.survivor ?? undefined+ const kafkaAck = result.kafkaAck ?? Promise.resolve()+ switch (outcome) {+ case 'merged':+ case 'attached':+ case 'noop_same_person':+ return mergeSuccess(survivor, kafkaAck, result.survivorNeedsUpdate ?? true)+ case 'skipped_already_identified': {+ // Warning acks ride the result's kafkaAck to the batch-end+ // await rather than blocking the merge here.+ const warningAck = emitIngestionWarning(this.context.outputs, this.context.team.id, {+ type: 'cannot_merge_already_identified',+ details: {+ sourcePersonDistinctId: otherPersonDistinctId,+ targetPersonDistinctId: mergeIntoDistinctId,+ distinctId: mergeIntoDistinctId,+ eventUuid: this.context.event.uuid,+ personId: survivor?.uuid,+ otherPersonId: sourceResult?.sourcePersonUuid,+ },+ pipelineStep: 'person-merge',+ alwaysSend: true,+ })+ logger.warn(+ '🤔',+ 'refused to merge an already identified user via an $identify or $create_alias call',+ { team_id: this.context.team.id })- continue- }- const source = sourceByDistinctId.get(pair.anonDistinctId)- if (!source) {- missingPairs.push(pair)- continue- }- if (seenSourceIds.has(source.id)) {- continue- }- if (source.is_identified) {- // $identify never merges an already-identified source. One- // warning per folded pair (pairs are deduped), not per event.- warningAcks.push(- emitIngestionWarning(this.context.outputs, teamId, {- type: 'cannot_merge_already_identified',- details: {- sourcePersonDistinctId: pair.anonDistinctId,- targetPersonDistinctId: plan.targetDistinctId,- distinctId: plan.targetDistinctId,- eventUuid: pair.eventUuid,- personId: target.uuid,- otherPersonId: source.uuid,- },- pipelineStep: 'person-merge',- alwaysSend: true,- })+ return mergeSuccess(+ survivor,+ Promise.all([kafkaAck, warningAck]).then(() => undefined),+ true)- continue}- seenSourceIds.add(source.id)- mergeSources.push(source)- }- const warningsAck = Promise.all(warningAcks).then(() => undefined)-- if (mergeSources.length === 0 && missingPairs.length === 0) {- plan.status = 'executed'- plan.mergedPerson = target- return mergeSuccess(target, warningsAck, true)- }-- // Sequential property precedence: each pair merges source properties- // under the accumulated target's (target wins, earlier sources win- // over later ones). Event $set/$set_once apply on top, as in mergePeople.- let mergedProperties: Properties = target.properties- for (const source of mergeSources) {- mergedProperties = { ...source.properties, ...mergedProperties }- }- const propertyUpdates = refineEventOps(- extractEventOps(this.context.event, this.context.updateAllProperties),- mergedProperties,- this.context.updateAllProperties- )- const [updatedTempPerson] = applyEventPropertyUpdates(propertyUpdates, {- ...target,- properties: mergedProperties,- })-- const createdAt = DateTime.min(target.created_at, ...mergeSources.map((source) => source.created_at))- const version = Math.max(target.version, ...mergeSources.map((source) => source.version)) + 1-- const currentTarget = target- this.discardOverrideCounts()- const lifecycleOpId = lifecycleOpIdFromEvent(this.context.team.id, this.context.event.uuid)- const [mergedPerson, kafkaMessages] = await this.context.personStore.inTransaction(- 'mergePeopleFold',- async (tx) => {- // New-world folds claim every person, keeping concurrent lifecycle operations- // (other merges, the delete saga) off the targets and sources until commit.- if (this.context.mergeTombstoneEnabled) {- await tx.claimLifecycleMarks(- lifecycleOpId,- currentTarget.team_id,- [- { personId: currentTarget.id, personUuid: currentTarget.uuid, role: 'target' },- ...mergeSources.map((source, index) => ({- personId: source.id,- personUuid: source.uuid,- role: 'source' as const,- ordinal: index,- })),- ],- this.context.distinctId- )- if (!(await tx.isPersonLive(currentTarget, this.context.distinctId))) {- throw new MergeFoldConflictError('Fold target was deleted concurrently')- }- }- const expectedMoveCount = await this.assertFoldSourcesWithinMoveBounds(tx, mergeSources)-- let person = currentTarget- let updateMessages: PersonMessage[] = []- if (mergeSources.length > 0) {- ;[person, updateMessages] = await tx.updatePersonForMerge(- currentTarget,- {- created_at: createdAt,- properties: updatedTempPerson.properties,- is_identified: true,- version,- },- this.context.distinctId- )- }-- const moveResult = await tx.moveDistinctIdsFromPersons(- mergeSources,- currentTarget,- this.context.distinctId+ case 'skipped_illegal': {+ // Both ids are pre-checked in merge(); the saga's own list+ // can be wider, so honor its verdict with the same warning.+ const warningAck = this.emitIllegalDistinctIdWarning(+ otherPersonDistinctId,+ mergeIntoDistinctId,+ this.context.event.uuid+ )+ return mergeSuccess(+ survivor,+ Promise.all([kafkaAck, warningAck]).then(() => undefined),+ true)- if (!moveResult.success) {- throw new TargetPersonNotFoundError('Target person no longer exists')- }- // A mismatch means a concurrent merge touched the sources- // between the count and the move; abort so the sequential path- // (whose zero-moved handling retries with fresh persons) takes- // over rather than merging stale source properties.- if (moveResult.distinctIdsMoved.length !== expectedMoveCount) {- throw new MergeFoldConflictError('folded merge moved an unexpected number of distinct ids')- }- this.recordOverrideCount('bothExistMove', moveResult.distinctIdsMoved.length)-- const addMessages: PersonMessage[] = []- for (const pair of missingPairs) {- // See mergeDistinctIds for the distinctIdVersion logic.- const distinctIdVersion = 1- this.recordOverrideCount('fold')- addMessages.push(...(await tx.addDistinctId(person, pair.anonDistinctId, distinctIdVersion)))- }-- let deleteMessages: PersonMessage[] = []- if (mergeSources.length > 0) {- await tx.updateCohortsAndFeatureFlagsForMergeBatch(- teamId,- mergeSources.map((source) => source.id),- currentTarget.id,- this.context.distinctId- )- deleteMessages = await tx.deletePersons(mergeSources, this.context.distinctId)- }-- if (this.context.mergeTombstoneEnabled) {- await tx.releaseLifecycleMarks(lifecycleOpId, this.context.team.id, this.context.distinctId)- }- return [person, [...updateMessages, ...moveResult.messages, ...addMessages, ...deleteMessages]]}- )-- this.flushOverrideCounts()- plan.status = 'executed'- plan.mergedPerson = mergedPerson- mergeFoldExecutedCounter.inc()- mergeFoldSizeHistogram.observe(plan.pairs.length)-- const kafkaAck = Promise.all([this.context.produceMessages(kafkaMessages), warningsAck]).then(() => undefined)- for (const source of mergeSources) {- // Same fire-and-forget contract as executeTransaction.- void this.context.producePersonMergeEvent(source, mergedPerson).catch(() => {})- }- return mergeSuccess(mergedPerson, kafkaAck, true)- }-- public async mergePeople({- mergeInto,- mergeIntoDistinctId,- otherPerson,- otherPersonDistinctId,- }: {- mergeInto: InternalPerson- mergeIntoDistinctId: string- otherPerson: InternalPerson- otherPersonDistinctId: string- }): Promise<PersonMergeResult> {- const olderCreatedAt = DateTime.min(mergeInto.created_at, otherPerson.created_at)- const mergeAllowed = this.isMergeAllowed(otherPerson)-- // If merge isn't allowed, we will ignore it, log an ingestion warning and return success with original person- if (!mergeAllowed) {- const warningAck = emitIngestionWarning(this.context.outputs, this.context.team.id, {- type: 'cannot_merge_already_identified',- details: {- sourcePersonDistinctId: otherPersonDistinctId,- targetPersonDistinctId: mergeIntoDistinctId,- distinctId: mergeIntoDistinctId,- eventUuid: this.context.event.uuid,- personId: mergeInto.uuid,- otherPersonId: otherPerson.uuid,- },- pipelineStep: 'person-merge',- alwaysSend: true,- }).then(() => undefined)- logger.warn('🤔', 'refused to merge an already identified user via an $identify or $create_alias call', {- team_id: this.context.team.id,- })- return mergeSuccess(mergeInto, warningAck, true)- }-- // How the merge works:- // Merging properties:- // on key conflict we use the properties from the person provided as the first argument in identify or alias calls (mergeInto person),- // Note it's important for us to compute this before potentially swapping the persons for personID merging purposes in PoEEmbraceJoin mode- // In case of PoE Embrace the join mode:- // we want to keep using the older person to reduce the number of partitions that need to be updated during squash- // to do that we'll swap otherPerson and mergeInto person (after properties merge computation!)- // additionally update person overrides table in postgres and clickhouse- // TODO: ^- // If the merge fails:- // we'll roll back the transaction and then try from scratch in the origial order of persons provided for property merges- // that guarantees consistency of how properties are processed regardless of persons created_at timestamps and rollout state- // we're calling aliasDeprecated as we need to refresh the persons info completely first-- const mergedProperties: Properties = { ...otherPerson.properties, ...mergeInto.properties }- const propertyUpdates = refineEventOps(- extractEventOps(this.context.event, this.context.updateAllProperties),- mergedProperties,- this.context.updateAllProperties- )-- // Create a temporary person object to apply property updates to- const tempPerson: InternalPerson = { ...mergeInto, properties: mergedProperties }- const [updatedTempPerson, _] = applyEventPropertyUpdates(propertyUpdates, tempPerson)- const properties = updatedTempPerson.properties-- const result = await this.handleMergeTransaction(- mergeInto,- mergeIntoDistinctId,- otherPerson,- otherPersonDistinctId,- olderCreatedAt, // Keep the oldest created_at (i.e. the first time we've seen either person)- properties- )-- if (result.success) {- return result- }-- // Handle specific error types- if (result.error instanceof PersonMergeRaceConditionError) {- const warningAck = emitIngestionWarning(this.context.outputs, this.context.team.id, {- type: 'merge_race_condition',- details: {- sourcePersonDistinctId: otherPersonDistinctId,- targetPersonDistinctId: mergeIntoDistinctId,- distinctId: mergeIntoDistinctId,- eventUuid: this.context.event.uuid,- personId: mergeInto.uuid,- otherPersonId: otherPerson.uuid,- },- pipelineStep: 'person-merge',- alwaysSend: true,- }).then(() => undefined)- logger.warn('🤔', 'merge race condition detected, too many concurrent merges', {- team_id: this.context.team.id,- })- return mergeSuccess(mergeInto, warningAck, true)- }-- // For other errors (PersonMergeLimitExceededError, etc.), return the error result- return result- }-- private isMergeAllowed(mergeFrom: InternalPerson): boolean {- // $merge_dangerously has no restrictions- // $create_alias and $identify will not merge a user who's already identified into anyone else- return this.context.event.event === '$merge_dangerously' || !mergeFrom.is_identified- }-- private async executeTransaction(- currentTargetPerson: InternalPerson,- currentSourcePerson: InternalPerson,- createdAt: DateTime,- properties: Properties- ): Promise<PersonMergeResult> {- try {- mergeTxnAttemptCounter- .labels({- call: this.context.event.event, // $identify, $create_alias or $merge_dangerously- oldPersonIdentified: String(currentSourcePerson.is_identified),- newPersonIdentified: String(currentTargetPerson.is_identified),+ case 'skipped_race': {+ // A concurrent merge kept winning the persons through every+ // retry; the merge drops and the target stays the survivor.+ const warningAck = emitIngestionWarning(this.context.outputs, this.context.team.id, {+ type: 'merge_race_condition',+ details: {+ sourcePersonDistinctId: otherPersonDistinctId,+ targetPersonDistinctId: mergeIntoDistinctId,+ distinctId: mergeIntoDistinctId,+ eventUuid: this.context.event.uuid,+ personId: survivor?.uuid,+ otherPersonId: sourceResult?.sourcePersonUuid,+ },+ pipelineStep: 'person-merge',+ alwaysSend: true,})- .inc()-- this.discardOverrideCounts()- const lifecycleOpId = lifecycleOpIdFromEvent(this.context.team.id, this.context.event.uuid)- const [mergedPerson, kafkaMessages] = await this.context.personStore.inTransaction(- 'mergePeople',- async (tx) => {- // New-world merges claim both persons in the lifecycle mark table: at- // most one live operation (merge or delete saga) may hold a person, so- // neither can be tombstoned under this transaction. The marks say- // nothing about tombstones committed before the claim, so assert both- // persons are still live while holding them. Liveness checks are- // separate statements because a claim that waited on the mark index- // resumes with a stale snapshot.- if (this.context.mergeTombstoneEnabled) {- await tx.claimLifecycleMarks(- lifecycleOpId,- currentTargetPerson.team_id,- [- {- personId: currentTargetPerson.id,- personUuid: currentTargetPerson.uuid,- role: 'target',- },- {- personId: currentSourcePerson.id,- personUuid: currentSourcePerson.uuid,- role: 'source',- ordinal: 0,- },- ],- this.context.distinctId- )- if (!(await tx.isPersonLive(currentTargetPerson, this.context.distinctId))) {- throw new TargetPersonNotFoundError('Target person was deleted concurrently')- }- if (!(await tx.isPersonLive(currentSourcePerson, this.context.distinctId))) {- throw new SourcePersonNotFoundError('Source person was deleted concurrently')- }- }- const [person, updatePersonMessages] = await tx.updatePersonForMerge(- currentTargetPerson,- {- created_at: createdAt,- properties: properties,- is_identified: true,-- // By using the max version between the two Persons, we ensure that if- // this Person is later split, we can use `this_person.version + 1` for- // any split-off Persons and know that *that* version will be higher than- // any previously deleted Person, and so the new Person row will "win" and- // "undelete" the Person.- //- // For example:- // - Merge Person_1(version:7) into Person_2(version:2)- // - Person_1 is deleted- // - Person_2 attains version 8 via this code below- // - Person_2 is later split, which attempts to re-create Person_1 by using- // its `distinct_id` to generate the deterministic Person UUID.- // That new Person_1 will have a version _at least_ as high as 8, and- // so any previously existing rows in CH or otherwise from- // Person_1(version:7) will "lose" to this new Person_1.- version: Math.max(currentTargetPerson.version, currentSourcePerson.version) + 1,- },- this.context.distinctId- )-- // Move distinct IDs first to establish ownership of the source person quickly.- // This reduces contention when multiple concurrent merges target the same source,- // as subsequent lookups via distinct ID will fail faster.- const allDistinctIdMessages = await this.moveDistinctIdsBasedOnMode(- tx,- currentSourcePerson,- currentTargetPerson- )-- // Update cohorts and feature flags after distinct IDs are moved.- // The source person row still exists (deleted below), so FK constraints are satisfied.- // TODO: Doesn't this table need to add updates to CH too?- await tx.updateCohortsAndFeatureFlagsForMerge(- currentSourcePerson.team_id,- currentSourcePerson.id,- currentTargetPerson.id,- this.context.distinctId- )-- const deletePersonMessages = await tx.deletePerson(currentSourcePerson, this.context.distinctId)- if (this.context.mergeTombstoneEnabled) {- await tx.releaseLifecycleMarks(lifecycleOpId, this.context.team.id, this.context.distinctId)- }- return [person, [...updatePersonMessages, ...allDistinctIdMessages, ...deletePersonMessages]]- }- )-- this.flushOverrideCounts()- mergeTxnSuccessCounter- .labels({- call: this.context.event.event, // $identify, $create_alias or $merge_dangerously- oldPersonIdentified: String(currentSourcePerson.is_identified),- newPersonIdentified: String(currentTargetPerson.is_identified),+ logger.warn('🤔', 'merge race condition detected, too many concurrent merges', {+ team_id: this.context.team.id,})- .inc()-- // Fire-and-forget after commit: the person_merge_events emission is detached from the ack- // chain, so a produce failure can never block, replay, or crash ingestion.- // producePersonMergeEvent is best-effort and never throws; the call-site catch is a safety- // net that swallows an escaped rejection so a broken never-throws contract can't reach the- // unhandledRejection handler and stop the service.- const kafkaAck = this.context.produceMessages(kafkaMessages)- void this.context.producePersonMergeEvent(currentSourcePerson, mergedPerson).catch(() => {})- return mergeSuccess(mergedPerson, kafkaAck, true)- } catch (error) {- // Map exceptions to result types - these will cause transaction rollback- if (error instanceof SourcePersonNotFoundError) {- return mergeError(error)- } else if (error instanceof TargetPersonNotFoundError) {- return mergeError(error)- } else if (error instanceof PersonMergeLimitExceededError) {- return mergeError(error)- } else if (error.code === '23503' || error instanceof PersonTombstoneBlockedError) {- // A concurrent merge added a distinct ID to the source person after we've already- // moved the distinct IDs we knew about, but before the delete executed — surfaced- // as a foreign key violation by the hard delete, or as PersonTombstoneBlockedError- // by the tombstone's live-mapping guard. The retry mechanism will:- // 1. Refresh the source person data to see all distinct IDs (including newly added ones)- // 2. Move ALL distinct IDs to the target person- // 3. Successfully delete the now-empty source person+ return mergeSuccess(+ survivor,+ Promise.all([kafkaAck, warningAck]).then(() => undefined),+ true+ )+ }+ case 'skipped_conflict':+ // Normally converted into a throw inside the retry loop;+ // this backstop keeps the claim-dropped semantics for any+ // path that maps the outcome directly.+ throw new PersonClaimedByLifecycleOpError(+ 'merge saga: a live lifecycle operation holds a person in this merge',+ this.context.team.id+ )+ case 'skipped_move_limit':+ // The over-limit path: the caller's merge-mode policy+ // (redirect, DLQ) decides what happens to the event.+ return mergeError(new PersonMergeLimitExceededError('person_merge_move_limit_hit'))+ case 'failed_source_not_found':+ return mergeError(new SourcePersonNotFoundError('Source person no longer exists'))+ case 'failed_target_not_found':+ return mergeError(new TargetPersonNotFoundError('Target person no longer exists'))+ case 'failed_source_has_distinct_ids':return mergeError(new SourcePersonHasDistinctIdsError('Cannot delete source person due to concurrent distinct ID additions'))- } else {- // Re-throw unexpected errors- throw error- }- }- }-- // Override-counter increments are buffered and flushed only after the enclosing- // transaction commits: merges retry and roll back, and rolled-back rows must not- // inflate a metric used for override-inflow capacity planning.- private pendingOverrideCounts: { call: string; count: number }[] = []-- private recordOverrideCount(call: string, count: number = 1): void {- if (count > 0) {- this.pendingOverrideCounts.push({ call, count })- }- }-- private discardOverrideCounts(): void {- this.pendingOverrideCounts = []- }-- private flushOverrideCounts(): void {- for (const { call, count } of this.pendingOverrideCounts) {- mergeDistinctIdOverrideCounter.labels({ call }).inc(count)- }- this.pendingOverrideCounts = []- }-- private async moveDistinctIdsBasedOnMode(- tx: PersonsStoreTransactionForBatch,- currentSourcePerson: InternalPerson,- currentTargetPerson: InternalPerson- ): Promise<PersonMessage[]> {- if (this.context.mergeMode.type === 'SYNC') {- if (!this.context.mergeMode.batchSize) {- return await this.moveDistinctIdsWithLimit(tx, currentSourcePerson, currentTargetPerson, undefined)- }- return await this.moveDistinctIdsInBatches(- tx,- currentSourcePerson,- currentTargetPerson,- this.context.mergeMode.batchSize- )- } else {- const limit = this.context.mergeMode.limit- return await this.moveDistinctIdsWithLimit(tx, currentSourcePerson, currentTargetPerson, limit)- }- }-- private async moveDistinctIdsInBatches(- tx: PersonsStoreTransactionForBatch,- currentSourcePerson: InternalPerson,- currentTargetPerson: InternalPerson,- batchSize: number- ): Promise<PersonMessage[]> {- const allDistinctIdMessages: PersonMessage[] = []- let hasMore = true- let hasProcessedAnyDistinctIds = false-- while (hasMore) {- const distinctIdResult = await tx.moveDistinctIds(- currentSourcePerson,- currentTargetPerson,- this.context.distinctId,- batchSize- )-- if (!distinctIdResult.success) {- if (distinctIdResult.error === 'SourceNotFound') {- if (hasProcessedAnyDistinctIds) {- // Source person not found after we've already moved some distinct IDs- // This means we've moved all distinct IDs- hasMore = false- break- } else {- // Source person not found on first attempt - this is a real error- throw new SourcePersonNotFoundError('Source person no longer exists')- }- } else if (distinctIdResult.error === 'TargetNotFound') {- throw new TargetPersonNotFoundError('Target person no longer exists')- }- } else {- allDistinctIdMessages.push(...distinctIdResult.messages)- hasProcessedAnyDistinctIds = true- this.recordOverrideCount('bothExistMove', distinctIdResult.distinctIdsMoved.length)-- // Check if we moved fewer than the batch size, indicating we're done- hasMore = distinctIdResult.distinctIdsMoved.length >= batchSize- }- }-- return allDistinctIdMessages- }-- private async moveDistinctIdsWithLimit(- tx: PersonsStoreTransactionForBatch,- currentSourcePerson: InternalPerson,- currentTargetPerson: InternalPerson,- limit: number | undefined- ): Promise<PersonMessage[]> {- // Original behavior for LIMIT mode or SYNC without batchSize- const distinctIdResult = await tx.moveDistinctIds(- currentSourcePerson,- currentTargetPerson,- this.context.distinctId,- limit- )-- if (!distinctIdResult.success) {- if (distinctIdResult.error === 'SourceNotFound') {- throw new SourcePersonNotFoundError('Source person no longer exists')- } else if (distinctIdResult.error === 'TargetNotFound') {- throw new TargetPersonNotFoundError('Target person no longer exists')- }- }-- const allDistinctIdMessages = distinctIdResult.success ? distinctIdResult.messages : []-- // If moved count equals the per-call limit, verify if it's a partial move by checking remaining IDs- const movedCount = distinctIdResult.success ? distinctIdResult.distinctIdsMoved.length : 0- const hitLimit = limit ? movedCount >= limit : false-- if (hitLimit) {- const remaining = await tx.fetchPersonDistinctIds(currentSourcePerson, this.context.distinctId, 1)- if (remaining.length > 0) {- personMergeFailureCounter.labels({ call: this.context.event.event }).inc()- // Drop the event by throwing an error that the pipeline will map to DLQ/no-retry- logger.error('🤔', 'person merge move limit hit', {+ case 'error':+ default: {+ // A verdict, not a transient fault: the merge backend records it+ // against the op id and replays it for the retention window, so+ // neither this event's retry nor its redelivery can reach a+ // different answer, and failing the batch would stall the+ // partition instead of healing. The merge is lost; the event's+ // property updates still apply, and the customer's next+ // $identify carries a fresh op id that can succeed. Acked, but+ // never silently.+ mergeSettledFailureCounter.inc()+ const warningAck = emitIngestionWarning(this.context.outputs, this.context.team.id, {+ type: 'merge_settled_failure',+ details: {+ sourcePersonDistinctId: otherPersonDistinctId,+ targetPersonDistinctId: mergeIntoDistinctId,+ distinctId: mergeIntoDistinctId,+ eventUuid: this.context.event.uuid,+ // The Postgres backend names the person by uuid; the saga+ // reports a row id and no uuid, so both travel and+ // whichever exists identifies the person.+ otherPersonId: sourceResult.sourcePersonUuid,+ sourcePersonId: sourceResult.sourcePersonId,+ outcome,+ },+ pipelineStep: 'person-merge',+ })+ logger.warn('🤔', 'merge settled without merging; the pair stays unmerged', {team_id: this.context.team.id,- distinct_id: this.context.distinctId,+ outcome,+ event_uuid: this.context.event.uuid,})- throw new PersonMergeLimitExceededError('person_merge_move_limit_hit')+ return mergeSuccess(+ undefined,+ Promise.all([kafkaAck, warningAck]).then(() => undefined),+ true+ )}}- this.recordOverrideCount('bothExistMove', movedCount)-- return allDistinctIdMessages}- private async handleMergeTransaction(- targetPerson: InternalPerson,- targetDistinctId: string,- sourcePerson: InternalPerson,- sourceDistinctId: string,- createdAt: DateTime,- properties: Properties,- maxRetries: number = 5- ): Promise<PersonMergeResult> {- let currentTargetPerson = targetPerson- let currentSourcePerson = sourcePerson-- for (let attempt = 0; attempt <= maxRetries; attempt++) {- const result = await this.executeTransaction(- currentTargetPerson,- currentSourcePerson,- createdAt,- properties- )-- if (result.success) {- return result- }-- // Handle retryable errors- if (attempt < maxRetries) {- if (- result.error instanceof SourcePersonNotFoundError ||- result.error instanceof SourcePersonHasDistinctIdsError- ) {- const refreshedPerson = await this.refreshPersonData(- sourceDistinctId,- currentSourcePerson.id,- attempt,- 'source'+ /**+ * Per-source warnings for an executed fold, from the same vocabulary+ * the single-source mapper uses. Merge-shaped outcomes warn nothing;+ * conflicts surface as the race-condition warning rather than a+ * throw, because one held source must not fail the whole fold.+ */+ private async emitFoldWarnings(results: MergePersonsSourceResult[], request: MergePersonsRequest): Promise<void> {+ const eventUuidBySource = new Map(request.sources.map((source) => [source.distinctId, source.eventUuid]))+ // Produces are collected and awaited together so a plan full of+ // refused pairs does not serialize warning round-trips.+ const warningAcks: Promise<unknown>[] = []+ for (const sourceResult of results) {+ const eventUuid = eventUuidBySource.get(sourceResult.sourceDistinctId) ?? this.context.event.uuid+ switch (sourceResult.outcome) {+ case 'skipped_already_identified':+ warningAcks.push(+ emitIngestionWarning(this.context.outputs, this.context.team.id, {+ type: 'cannot_merge_already_identified',+ details: {+ sourcePersonDistinctId: sourceResult.sourceDistinctId,+ targetPersonDistinctId: request.targetDistinctId,+ distinctId: request.targetDistinctId,+ eventUuid,+ personId: this.context.mergeFoldPlan?.mergedPerson?.uuid,+ otherPersonId: sourceResult.sourcePersonUuid,+ },+ pipelineStep: 'person-merge',+ alwaysSend: true,+ }))-- if (!refreshedPerson) {- return mergeSuccess(currentTargetPerson, Promise.resolve(), true)- }-- currentSourcePerson = refreshedPerson- continue- } else if (result.error instanceof TargetPersonNotFoundError) {- const refreshedPerson = await this.refreshPersonData(- targetDistinctId,- currentTargetPerson.id,- attempt,- 'target'+ break+ case 'skipped_illegal':+ warningAcks.push(+ this.emitIllegalDistinctIdWarning(+ sourceResult.sourceDistinctId,+ request.targetDistinctId,+ eventUuid+ ))-- if (!refreshedPerson) {- return mergeSuccess(currentTargetPerson, Promise.resolve(), true)- }-- currentTargetPerson = refreshedPerson- continue- } else {- // Non-retryable error, return the failure result- return result- }- } else {- // Max retries reached, return the failure result- return result+ break+ case 'skipped_conflict':+ case 'skipped_race':+ warningAcks.push(+ emitIngestionWarning(this.context.outputs, this.context.team.id, {+ type: 'merge_race_condition',+ details: {+ sourcePersonDistinctId: sourceResult.sourceDistinctId,+ targetPersonDistinctId: request.targetDistinctId,+ distinctId: request.targetDistinctId,+ eventUuid,+ otherPersonId: sourceResult.sourcePersonUuid,+ },+ pipelineStep: 'person-merge',+ alwaysSend: true,+ })+ )+ break+ case 'skipped_move_limit':+ // Only the saga answers this inside an executed fold; the+ // Postgres merge aborts the whole fold instead. The+ // source's event acks without its merge (and without the+ // ASYNC redirect the sequential path would give it), so+ // the warning is what keeps the loss identifiable.+ mergeMoveLimitDroppedCounter.labels({ path: 'fold' }).inc()+ warningAcks.push(+ emitIngestionWarning(this.context.outputs, this.context.team.id, {+ type: 'merge_move_limit_exceeded',+ details: {+ sourcePersonDistinctId: sourceResult.sourceDistinctId,+ targetPersonDistinctId: request.targetDistinctId,+ distinctId: request.targetDistinctId,+ eventUuid,+ otherPersonId: sourceResult.sourcePersonUuid,+ eventDropped: false,+ },+ pipelineStep: 'person-merge',+ })+ )+ logger.warn('🤔', 'fold skipped an over-limit source; its merge is dropped', {+ team_id: this.context.team.id,+ source_distinct_id: sourceResult.sourceDistinctId,+ target_distinct_id: request.targetDistinctId,+ event_uuid: eventUuid,+ })+ break+ case 'error':+ // The merge for this source did not happen and the op is+ // terminal, so redelivery cannot reach a different+ // answer. The single-source path treats this as a+ // settled failure; a fold has to say so too, or the+ // loss is invisible.+ mergeSettledFailureCounter.inc()+ warningAcks.push(+ emitIngestionWarning(this.context.outputs, this.context.team.id, {+ type: 'merge_settled_failure',+ details: {+ distinctId: this.context.distinctId,+ eventUuid,+ sourcePersonDistinctId: sourceResult.sourceDistinctId,+ targetPersonDistinctId: request.targetDistinctId,+ },+ pipelineStep: 'person-merge',+ })+ )+ logger.warn('🤔', 'fold settled a source as failed; its merge did not happen', {+ team_id: this.context.team.id,+ source_distinct_id: sourceResult.sourceDistinctId,+ target_distinct_id: request.targetDistinctId,+ event_uuid: eventUuid,+ })+ break+ default:+ break}}-- // This should never be reached, but add fallback for race condition- return mergeError(- new PersonMergeRaceConditionError(- `Failed to merge persons due to concurrent merges, ` +- `source person: ${sourcePerson.id}, target person: ${targetPerson.id}, team: ${this.context.team.id} ` +- `source distinct id: ${sourceDistinctId}, target distinct id: ${targetDistinctId}`- )- )+ await Promise.all(warningAcks)}- public async addDistinctId(- person: InternalPerson,- distinctId: string,- version: number,- tx?: PersonsStoreTransactionForBatch+ private emitIllegalDistinctIdWarning(+ illegalDistinctId: string,+ otherDistinctId: string,+ eventUuid: string): Promise<void> {- const kafkaMessages = await (tx || this.context.personStore).addDistinctId(person, distinctId, version)- await this.context.produceMessages(kafkaMessages)- }-- private async refreshPersonData(- distinctId: string,- currentPersonId: string,- attempt: number,- personType: 'source' | 'target'- ): Promise<InternalPerson | null> {- logger.info(`${personType} person not found, retrying with fresh data`, {- [`${personType}PersonId`]: currentPersonId,- teamId: this.context.team.id,- attempt,- distinctId,- })-- // Remove the distinct ID from the cache so that we don't try to use it again, if the store is the batch writing store- // TODO: this should be removed once we clean up the person store code- this.context.personStore.removeDistinctIdFromCache(this.context.team.id, distinctId)-- // Fetch the refreshed person data using the new distinct ID- const refreshedPerson = await this.context.personStore.fetchForUpdate(this.context.team.id, distinctId)-- if (!refreshedPerson) {- logger.info(`${personType} person no longer exists after refresh, skipping merge`, {- [`${personType}PersonId`]: currentPersonId,- teamId: this.context.team.id,- attempt,- })- return null- }-- return refreshedPerson+ return emitIngestionWarning(this.context.outputs, this.context.team.id, {+ type: 'cannot_merge_with_illegal_distinct_id',+ details: {+ illegalDistinctId,+ otherDistinctId,+ distinctId: this.context.distinctId,+ eventUuid,+ },+ pipelineStep: 'person-merge',+ alwaysSend: true,+ }).then(() => undefined)}public getUpdateIsIdentified(): boolean {diff --git a/nodejs/src/ingestion/common/persons/person-merge-types.test.ts b/nodejs/src/ingestion/common/persons/person-merge-types.test.tsnew file mode 100644index 000000000000..b204a013c987--- /dev/null+++ b/nodejs/src/ingestion/common/persons/person-merge-types.test.ts@@ -0,0 +1,26 @@+import { determineMergeMode } from './person-merge-types'++describe('determineMergeMode', () => {+ it('refuses a non-integer move limit at construction', () => {+ // It becomes the saga's move_limit and reaches BigInt() when the+ // request is built, so a fractional value would throw on every merge+ // in the deployment. This runs once, at step construction.+ expect(() => determineMergeMode(1.5, false, 0)).toThrow(+ 'PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT must be an integer'+ )+ })++ it.each([+ [0, undefined],+ [-1, undefined],+ ])('treats a limit of %p as unlimited sync rather than an error', (limit, batchSize) => {+ expect(determineMergeMode(limit, true, 0)).toEqual({ type: 'SYNC', batchSize })+ })++ it.each([+ ['async enabled', true, 'ASYNC'],+ ['async disabled', false, 'LIMIT'],+ ])('%s with a positive limit selects %s', (_label, asyncEnabled, type) => {+ expect(determineMergeMode(50, asyncEnabled, 0)).toEqual({ type, limit: 50 })+ })+})diff --git a/nodejs/src/ingestion/common/persons/person-merge-types.ts b/nodejs/src/ingestion/common/persons/person-merge-types.tsindex 69d25e270956..3504a353fd12 100644--- a/nodejs/src/ingestion/common/persons/person-merge-types.ts+++ b/nodejs/src/ingestion/common/persons/person-merge-types.ts@@ -23,6 +23,37 @@ export class PersonMergeLimitExceededError extends PersonMergeError {}}+/**+ * A merge response that carried no verdict for the source it was asked+ * about. Distinct from a settled failure: nothing is recorded against the+ * op id, so a retry can still reach a real answer, and the batch must fail+ * rather than ack a merge that never happened.+ */+export class PersonMergeResponseMismatchError extends PersonMergeError {+ readonly type = 'RESPONSE_MISMATCH' as const++ constructor(message: string) {+ super(message)+ }+}++/**+ * A merge call that failed with no verdict at all, so the saga's state is+ * unknowable from here. The batch must fail and redeliver: the saga replays+ * recorded outcomes idempotently, so redelivery converges where an ack+ * would lose the merge. Personhog-only; the Postgres merge never throws it.+ */+export class PersonMergeCallFailedError extends PersonMergeError {+ readonly type = 'CALL_FAILED' as const++ constructor(+ message: string,+ public readonly failure: unknown+ ) {+ super(message)+ }+}+/*** Error when race condition is detected during merge*/@@ -154,6 +185,13 @@ export function determineMergeMode(personMergeAsyncEnabled: boolean,personMergeSyncBatchSize: number): MergeMode {+ // The limit becomes the saga's move_limit: a non-integer throws a+ // RangeError at request time and would fail every merge in the+ // deployment, so a bad value fails startup here instead.+ if (personMergeMoveDistinctIdLimit > 0 && !Number.isInteger(personMergeMoveDistinctIdLimit)) {+ throw new Error(`PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT must be an integer, got ${personMergeMoveDistinctIdLimit}`)+ }+// If async merge is enabled, use async mode for over-limit mergesif (personMergeAsyncEnabled && personMergeMoveDistinctIdLimit > 0) {return {diff --git a/nodejs/src/ingestion/common/persons/person-property-service.ts b/nodejs/src/ingestion/common/persons/person-property-service.tsindex 862078ec010f..029b1eee270a 100644--- a/nodejs/src/ingestion/common/persons/person-property-service.ts+++ b/nodejs/src/ingestion/common/persons/person-property-service.ts@@ -13,7 +13,7 @@ import { extractEventOps } from './person-update'export class PersonPropertyService {private personCreateService: PersonCreateServiceconstructor(private context: PersonContext) {- this.personCreateService = new PersonCreateService(context)+ this.personCreateService = new PersonCreateService(context.personStore, context.outputs)}async handleUpdate(): Promise<[InternalPerson, Promise<void>]> {@@ -74,7 +74,7 @@ export class PersonPropertyService {// The service states the event's intent; what the intent means// given current state — diffing, identity OR-merge, last-seen// advance, whether anything is worth writing — is the store's- // concern, resolved against its own world.+ // concern, resolved against its own backend.const ops = extractEventOps(this.context.event, this.context.updateAllProperties)if (this.context.updateIsIdentified) {ops.isIdentified = truediff --git a/nodejs/src/ingestion/common/persons/person-uuid.test.ts b/nodejs/src/ingestion/common/persons/person-uuid.test.tsindex 4d91f89c12c8..9bc70992567d 100644--- a/nodejs/src/ingestion/common/persons/person-uuid.test.ts+++ b/nodejs/src/ingestion/common/persons/person-uuid.test.ts@@ -1,4 +1,4 @@-import { uuidFromDistinctId } from '~/ingestion/common/persons/person-uuid'+import { lifecycleOpIdFromEvent, uuidFromDistinctId } from '~/ingestion/common/persons/person-uuid'jest.setTimeout(5000) // 5 sec timeout@@ -9,3 +9,11 @@ describe('uuidFromDistinctId', () => {expect(uuidFromDistinctId(1, 'test2')).toMatchInlineSnapshot(`"45c17302-ee44-5596-916a-0eba21f4b638"`)})})++describe('lifecycleOpIdFromEvent', () => {+ it('is deterministic per event and scoped per team', () => {+ expect(lifecycleOpIdFromEvent(1, 'event-uuid')).toBe(lifecycleOpIdFromEvent(1, 'event-uuid'))+ expect(lifecycleOpIdFromEvent(1, 'event-uuid')).not.toBe(lifecycleOpIdFromEvent(2, 'event-uuid'))+ expect(lifecycleOpIdFromEvent(1, 'event-uuid')).not.toBe(lifecycleOpIdFromEvent(1, 'other-event'))+ })+})diff --git a/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts b/nodejs/src/ingestion/common/persons/personhog-persons-store.test.tsindex a39ee01ae907..bb1c5a068464 100644--- a/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts+++ b/nodejs/src/ingestion/common/persons/personhog-persons-store.test.ts@@ -64,7 +64,7 @@ describe('PersonhogPersonsStore', () => {expect(sent.setProperties).toEqual({ a: '2', first: 'shadowed' })expect(sent.setOnceProperties).toEqual({})expect(sent.unsetProperties).toEqual(['gone'])- // The changelog is this world's ClickHouse feed: a flush ships+ // The changelog is this backend's ClickHouse feed: a flush ships// segments and publishes nothing.expect(results).toEqual([])})@@ -226,11 +226,6 @@ describe('PersonhogPersonsStore', () => {expect(fetched?.id).toBe('7')})- it('deletes have no personhog path and fail loudly', async () => {- const bound = store.forBatch(0)- await expect(bound.deletePerson(person, 'd1')).rejects.toThrow('no personhog RPC')- })-it('creation resolves through identity and memoizes every distinct id it mapped', async () => {const bound = store.forBatch(0)const result = await bound.createPerson(@@ -434,34 +429,20 @@ describe('PersonhogPersonsStore', () => {expect(results).toEqual([])})- it('has no transactions of its own; the routing store owns them', async () => {+ it('merges fail loudly until the store merge lands', async () => {const bound = store.forBatch(0)- await expect(bound.inTransaction('test', () => Promise.resolve('done'))).rejects.toThrow('no personhog RPC')- })-- it.each([- [- 'updatePersonForMerge',- (b: ReturnType<PersonhogPersonsStore['forBatch']>, p: InternalPerson) =>- b.updatePersonForMerge(p, {}, 'd1'),- ],- [- 'addDistinctId',- (b: ReturnType<PersonhogPersonsStore['forBatch']>, p: InternalPerson) => b.addDistinctId(p, 'd2', 0),- ],- [- 'moveDistinctIds',- (b: ReturnType<PersonhogPersonsStore['forBatch']>, p: InternalPerson) =>- b.moveDistinctIds(p, p, 'd1', undefined, undefined as any),- ],- [- 'moveDistinctIdsFromPersons',- (b: ReturnType<PersonhogPersonsStore['forBatch']>, p: InternalPerson) =>- b.moveDistinctIdsFromPersons([p], p, 'd1', undefined as any),- ],- ])('%s fails loudly while the leader RPC is pending', async (_method, call) => {- const bound = store.forBatch(0)- await expect(call(bound, person)).rejects.toThrow(PersonhogPendingRpcError)+ await expect(+ bound.mergePersons({+ teamId: 1,+ targetDistinctId: 'd1',+ sources: [{ distinctId: 'anon-1', eventUuid: 'uuid-1' }],+ eventOps: ops({}),+ eventUuid: 'op-1',+ allowIdentifiedSources: false,+ mergeMode: { type: 'SYNC', batchSize: undefined },+ createdAtMs: 0,+ })+ ).rejects.toThrow(PersonhogPendingRpcError)})it('maps a direct diff update onto the folded RPC', async () => {diff --git a/nodejs/src/ingestion/common/persons/personhog-persons-store.ts b/nodejs/src/ingestion/common/persons/personhog-persons-store.tsindex d09b3be7a370..22f633dd2312 100644--- a/nodejs/src/ingestion/common/persons/personhog-persons-store.ts+++ b/nodejs/src/ingestion/common/persons/personhog-persons-store.ts@@ -5,9 +5,9 @@ import { Counter } from 'prom-client'import { PersonHogPersonWriteRepository } from '~/common/personhog/personhog-person-write-repository'import { PersonhogPropertiesSizeError } from '~/common/personhog/persons'import { PersonMessage } from '~/common/persons/person-message'-import { InternalPersonWithDistinctId, LifecycleMarkPerson } from '~/common/persons/repositories/person-repository'+import { InternalPersonWithDistinctId } from '~/common/persons/repositories/person-repository'import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'-import { CreatePersonResult, MoveDistinctIdsResult } from '~/common/utils/db/db'+import { CreatePersonResult } from '~/common/utils/db/db'import { logger } from '~/common/utils/logger'import { NoRowsUpdatedError } from '~/common/utils/utils'import { BatchWritingStoreFlushStats } from '~/ingestion/common/stores/batch-writing-store'@@ -15,9 +15,8 @@ import { Properties } from '~/plugin-scaffold'import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt, Team } from '~/types'import { EventOps, applyEventPropertyUpdates, computeOpsScalarUpdates, foldOps, refineEventOps } from './person-update'-import { FlushResult, PersonsStore } from './persons-store'+import { FlushResult, MergePersonsRequest, MergePersonsResult, PersonsBackend, PersonsStore } from './persons-store'import { BatchBoundPersonsStore, PersonsStoreForBatch } from './persons-store-for-batch'-import { PersonsStoreTransaction } from './persons-store-transaction'export const personhogStoreFlushCounter = new Counter({name: 'personhog_store_flush_ops_total',@@ -304,9 +303,9 @@ export class PersonhogPersonsStore implements PersonsStore {}// A local projection for the caller: the same application the- // Postgres world would perform, so the processor returns a+ // Postgres backend would perform, so the processor returns a// sensible person. The leader's application at flush remains the- // authoritative one for this world.+ // authoritative one for this backend.const refined = refineEventOps(ops, person.properties ?? {}, this.options.updateAllProperties, false)const [projected] = applyEventPropertyUpdates(refined, person)const scalarUpdates = computeOpsScalarUpdates(ops, projected)@@ -349,108 +348,12 @@ export class PersonhogPersonsStore implements PersonsStore {return Promise.resolve([projected, []])}- // Deletes exist only to destroy the losing persons of a merge, and- // the shadow gates merge events off this store; once merges move to- // personhog, the merge saga owns those deletions end to end, so no- // store-level delete path will ever be needed here.- /**- * The personhog world has no Postgres transactions; transaction- * semantics for routed deployments live in the routing store, which- * never delegates this member. Reaching it is a wiring bug.- */- inTransaction<T>(_description: string, _transaction: (tx: PersonsStoreTransaction) => Promise<T>): Promise<T> {- return Promise.reject(new PersonhogPendingRpcError('inTransaction', 'merge saga'))- }-- // Merge execution is the merge saga's once it lands; until then every- // mutation in the family is a loud placeholder.-- updatePersonForMerge(- _person: InternalPerson,- _update: Partial<InternalPerson>,- _distinctId: string,- _batchId: number,- _tx?: PersonRepositoryTransaction- ): Promise<[InternalPerson, PersonMessage[], boolean]> {- return Promise.reject(new PersonhogPendingRpcError('updatePersonForMerge', 'merge saga'))- }-- claimLifecycleMarks(- _opId: string,- _teamId: number,- _persons: LifecycleMarkPerson[],- _distinctId: string,- _tx?: PersonRepositoryTransaction- ): Promise<void> {- return Promise.reject(new PersonhogPendingRpcError('claimLifecycleMarks', 'merge saga'))- }-- releaseLifecycleMarks(- _opId: string,- _teamId: number,- _distinctId: string,- _tx?: PersonRepositoryTransaction- ): Promise<void> {- return Promise.reject(new PersonhogPendingRpcError('releaseLifecycleMarks', 'merge saga'))- }-- isPersonLive(_person: InternalPerson, _distinctId: string, _tx?: PersonRepositoryTransaction): Promise<boolean> {- return Promise.reject(new PersonhogPendingRpcError('isPersonLive', 'merge saga'))- }-- addDistinctId(- _person: InternalPerson,- _distinctId: string,- _version: number,- _tx: PersonRepositoryTransaction | undefined,- _batchId: number- ): Promise<PersonMessage[]> {- return Promise.reject(new PersonhogPendingRpcError('addDistinctId', 'merge saga'))+ get backend(): PersonsBackend {+ return 'personhog'}- moveDistinctIds(- _source: InternalPerson,- _target: InternalPerson,- _distinctId: string,- _limit: number | undefined,- _tx: PersonRepositoryTransaction,- _batchId: number- ): Promise<MoveDistinctIdsResult> {- return Promise.reject(new PersonhogPendingRpcError('moveDistinctIds', 'merge saga'))- }-- moveDistinctIdsFromPersons(- _sources: InternalPerson[],- _target: InternalPerson,- _distinctId: string,- _tx: PersonRepositoryTransaction,- _batchId: number- ): Promise<MoveDistinctIdsResult> {- return Promise.reject(new PersonhogPendingRpcError('moveDistinctIdsFromPersons', 'merge saga'))- }-- // Postgres bookkeeping with nothing to answer in this world: shadow- // teams are fresh, so no cohort rows or hash-key overrides exist to- // fix up.-- updateCohortsAndFeatureFlagsForMerge(- _teamID: Team['id'],- _sourcePersonID: InternalPerson['id'],- _targetPersonID: InternalPerson['id'],- _distinctId: string,- _tx?: PersonRepositoryTransaction- ): Promise<void> {- return Promise.resolve()- }-- updateCohortsAndFeatureFlagsForMergeBatch(- _teamID: Team['id'],- _sourcePersonIDs: InternalPerson['id'][],- _targetPersonID: InternalPerson['id'],- _distinctId: string,- _tx?: PersonRepositoryTransaction- ): Promise<void> {- return Promise.resolve()+ mergePersons(_request: MergePersonsRequest, _batchId: number): Promise<MergePersonsResult> {+ return Promise.reject(new PersonhogPendingRpcError('mergePersons', 'merge saga'))}/** The leader enforces the size ceiling at admission; there is nothing to measure here. */@@ -470,22 +373,6 @@ export class PersonhogPersonsStore implements PersonsStore {return { dirtyEntryCount, referencedBatchCount: this.lanes.size, cacheEntryCount }}- deletePersons(- _persons: InternalPerson[],- _distinctId: string,- _tx?: PersonRepositoryTransaction- ): Promise<PersonMessage[]> {- return Promise.reject(new PersonhogPendingRpcError('deletePersons', 'merge saga'))- }-- deletePerson(- _person: InternalPerson,- _distinctId: string,- _tx?: PersonRepositoryTransaction- ): Promise<PersonMessage[]> {- return Promise.reject(new PersonhogPendingRpcError('deletePerson', 'merge saga'))- }-/*** A direct diff update, applied immediately rather than folded: the* caller has already resolved the diff, so it maps one-to-one onto@@ -526,7 +413,7 @@ export class PersonhogPersonsStore implements PersonsStore {if (!updated) {return [person, [], false]}- // No ClickHouse message: the leader's changelog is this world's+ // No ClickHouse message: the leader's changelog is this backend's// person feed, so emitting here would double-publish.return [updated, [], false]}diff --git a/nodejs/src/ingestion/common/persons/persons-store-for-batch.ts b/nodejs/src/ingestion/common/persons/persons-store-for-batch.tsindex c15874c64273..bf6fdc143cd1 100644--- a/nodejs/src/ingestion/common/persons/persons-store-for-batch.ts+++ b/nodejs/src/ingestion/common/persons/persons-store-for-batch.ts@@ -1,16 +1,21 @@import { DateTime } from 'luxon'import { PersonMessage } from '~/common/persons/person-message'-import { InternalPersonWithDistinctId, LifecycleMarkPerson } from '~/common/persons/repositories/person-repository'+import { LifecycleMarkPerson } from '~/common/persons/repositories/person-repository'import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'import { CreatePersonResult, MoveDistinctIdsResult } from '~/common/utils/db/db'import { Properties } from '~/plugin-scaffold'import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt, Team } from '~/types'import { EventOps } from './person-update'-import { FlushResult, PersonsStore } from './persons-store'+import { FlushResult, MergePersonsRequest, MergePersonsResult, PersonsBackend, PersonsStore } from './persons-store'import { PersonsStoreTransaction } from './persons-store-transaction'+/**+ * The Postgres backend's transactional verb surface, with batchId bound.+ * Only the pg store's PostgresPersonMerge opens these transactions; the+ * cross-backend PersonsStore interface has no transactional member.+ */export interface PersonsStoreTransactionForBatch {createPerson(createdAt: DateTime,@@ -106,29 +111,17 @@ export type PersonsStoreForBatch = Omit<PersonsStore,| 'fetchForChecking'| 'fetchForUpdate'- | 'fetchPersonsForUpdateByDistinctIds'| 'applyEventOps'| 'createPerson'- | 'updatePersonForMerge'| 'updatePersonWithPropertiesDiffForUpdate'- | 'addDistinctId'- | 'moveDistinctIds'- | 'moveDistinctIdsFromPersons'+ | 'mergePersons'| 'prefetchPersons'| 'releaseBatch'| 'getFlushStats'- | 'inTransaction'> & {fetchForChecking(teamId: number, distinctId: string): Promise<InternalPerson | null>fetchForUpdate(teamId: number, distinctId: string): Promise<InternalPerson | null>- fetchPersonsForUpdateByDistinctIds(teamId: number, distinctIds: string[]): Promise<InternalPersonWithDistinctId[]>applyEventOps(person: InternalPerson, ops: EventOps, distinctId: string): Promise<[InternalPerson, PersonMessage[]]>- moveDistinctIdsFromPersons(- sources: InternalPerson[],- target: InternalPerson,- distinctId: string,- tx: PersonRepositoryTransaction- ): Promise<MoveDistinctIdsResult>createPerson(createdAt: DateTime,properties: Properties,@@ -141,12 +134,6 @@ export type PersonsStoreForBatch = Omit<primaryDistinctId: { distinctId: string; version?: number },extraDistinctIds?: { distinctId: string; version?: number }[]): Promise<CreatePersonResult>- updatePersonForMerge(- person: InternalPerson,- update: Partial<InternalPerson>,- distinctId: string,- tx?: PersonRepositoryTransaction- ): Promise<[InternalPerson, PersonMessage[], boolean]>updatePersonWithPropertiesDiffForUpdate(person: InternalPerson,propertiesToSet: Properties,@@ -156,20 +143,12 @@ export type PersonsStoreForBatch = Omit<forceUpdate?: boolean,tx?: PersonRepositoryTransaction): Promise<[InternalPerson, PersonMessage[], boolean]>- addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]>- moveDistinctIds(- source: InternalPerson,- target: InternalPerson,- distinctId: string,- limit: number | undefined,- tx: PersonRepositoryTransaction- ): Promise<MoveDistinctIdsResult>+ mergePersons(request: MergePersonsRequest): Promise<MergePersonsResult>prefetchPersons(teamDistinctIds: { teamId: number; distinctId: string; batchId: number }[]): Promise<void>- inTransaction<T>(description: string, transaction: (tx: PersonsStoreTransactionForBatch) => Promise<T>): Promise<T>readonly batchId: number}-class BatchBoundPersonsStoreTransaction implements PersonsStoreTransactionForBatch {+export class BatchBoundPersonsStoreTransaction implements PersonsStoreTransactionForBatch {constructor(private readonly tx: PersonsStoreTransaction,private readonly batchId: number@@ -312,6 +291,10 @@ export class BatchBoundPersonsStore implements PersonsStoreForBatch {public readonly batchId: number) {}+ get backend(): PersonsBackend {+ return this.store.backend+ }+fetchForChecking(teamId: number, distinctId: string): Promise<InternalPerson | null> {return this.store.fetchForChecking(teamId, distinctId, this.batchId)}@@ -328,10 +311,6 @@ export class BatchBoundPersonsStore implements PersonsStoreForBatch {return this.store.fetchForUpdate(teamId, distinctId, this.batchId)}- fetchPersonsForUpdateByDistinctIds(teamId: number, distinctIds: string[]): Promise<InternalPersonWithDistinctId[]> {- return this.store.fetchPersonsForUpdateByDistinctIds(teamId, distinctIds, this.batchId)- }-createPerson(createdAt: DateTime,properties: Properties,@@ -360,84 +339,14 @@ export class BatchBoundPersonsStore implements PersonsStoreForBatch {)}- addDistinctId(person: InternalPerson, distinctId: string, version: number): Promise<PersonMessage[]> {- return this.store.addDistinctId(person, distinctId, version, undefined, this.batchId)- }-- moveDistinctIds(- source: InternalPerson,- target: InternalPerson,- distinctId: string,- limit: number | undefined,- tx: PersonRepositoryTransaction- ): Promise<MoveDistinctIdsResult> {- return this.store.moveDistinctIds(source, target, distinctId, limit, tx, this.batchId)- }-- moveDistinctIdsFromPersons(- sources: InternalPerson[],- target: InternalPerson,- distinctId: string,- tx: PersonRepositoryTransaction- ): Promise<MoveDistinctIdsResult> {- return this.store.moveDistinctIdsFromPersons(sources, target, distinctId, tx, this.batchId)- }-- deletePersons(- persons: InternalPerson[],- distinctId: string,- tx?: PersonRepositoryTransaction- ): Promise<PersonMessage[]> {- return this.store.deletePersons(persons, distinctId, tx)- }-- countDistinctIdsForPersons(- teamId: Team['id'],- personIds: InternalPerson['id'][],- distinctId: string,- tx: PersonRepositoryTransaction- ): Promise<Map<string, number>> {- return this.store.countDistinctIdsForPersons(teamId, personIds, distinctId, tx)- }-- updateCohortsAndFeatureFlagsForMergeBatch(- teamID: Team['id'],- sourcePersonIDs: InternalPerson['id'][],- targetPersonID: InternalPerson['id'],- distinctId: string,- tx?: PersonRepositoryTransaction- ): Promise<void> {- return this.store.updateCohortsAndFeatureFlagsForMergeBatch(- teamID,- sourcePersonIDs,- targetPersonID,- distinctId,- tx- )+ mergePersons(request: MergePersonsRequest): Promise<MergePersonsResult> {+ return this.store.mergePersons(request, this.batchId)}prefetchPersons(teamDistinctIds: { teamId: number; distinctId: string; batchId: number }[]): Promise<void> {return this.store.prefetchPersons(teamDistinctIds)}- inTransaction<T>(- description: string,- transaction: (tx: PersonsStoreTransactionForBatch) => Promise<T>- ): Promise<T> {- return this.store.inTransaction(description, (tx) =>- transaction(new BatchBoundPersonsStoreTransaction(tx, this.batchId))- )- }-- updatePersonForMerge(- person: InternalPerson,- update: Partial<InternalPerson>,- distinctId: string,- tx?: PersonRepositoryTransaction- ): Promise<[InternalPerson, PersonMessage[], boolean]> {- return this.store.updatePersonForMerge(person, update, distinctId, this.batchId, tx)- }-updatePersonWithPropertiesDiffForUpdate(person: InternalPerson,propertiesToSet: Properties,@@ -459,64 +368,10 @@ export class BatchBoundPersonsStore implements PersonsStoreForBatch {)}- deletePerson(- person: InternalPerson,- distinctId: string,- tx?: PersonRepositoryTransaction- ): Promise<PersonMessage[]> {- return this.store.deletePerson(person, distinctId, tx)- }-- claimLifecycleMarks(- opId: string,- teamId: number,- persons: LifecycleMarkPerson[],- distinctId: string,- tx?: PersonRepositoryTransaction- ): Promise<void> {- return this.store.claimLifecycleMarks(opId, teamId, persons, distinctId, tx)- }-- releaseLifecycleMarks(- opId: string,- teamId: number,- distinctId: string,- tx?: PersonRepositoryTransaction- ): Promise<void> {- return this.store.releaseLifecycleMarks(opId, teamId, distinctId, tx)- }-- isPersonLive(person: InternalPerson, distinctId: string, tx?: PersonRepositoryTransaction): Promise<boolean> {- return this.store.isPersonLive(person, distinctId, tx)- }-- updateCohortsAndFeatureFlagsForMerge(- teamID: Team['id'],- sourcePersonID: InternalPerson['id'],- targetPersonID: InternalPerson['id'],- distinctId: string,- tx?: PersonRepositoryTransaction- ): Promise<void> {- return this.store.updateCohortsAndFeatureFlagsForMerge(teamID, sourcePersonID, targetPersonID, distinctId, tx)- }-personPropertiesSize(personId: string, teamId: number): Promise<number> {return this.store.personPropertiesSize(personId, teamId)}- fetchPersonDistinctIds(- person: InternalPerson,- distinctId: string,- limit: number | undefined,- tx: PersonRepositoryTransaction- ): Promise<string[]> {- return this.store.fetchPersonDistinctIds(person, distinctId, limit, tx)- }-- removeDistinctIdFromCache(teamId: number, distinctId: string): void {- return this.store.removeDistinctIdFromCache(teamId, distinctId)- }-flush(): Promise<FlushResult[]> {return this.store.flush()}diff --git a/nodejs/src/ingestion/common/persons/persons-store-transaction.ts b/nodejs/src/ingestion/common/persons/persons-store-transaction.tsindex 6aa0777c58e7..8067634b535b 100644--- a/nodejs/src/ingestion/common/persons/persons-store-transaction.ts+++ b/nodejs/src/ingestion/common/persons/persons-store-transaction.ts@@ -7,15 +7,16 @@ import { CreatePersonResult, MoveDistinctIdsResult } from '~/common/utils/db/db'import { Properties } from '~/plugin-scaffold'import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt, Team } from '~/types'-import { PersonsStore } from './persons-store'+import type { BatchWritingPersonsStore } from './batch-writing-person-store'/**- * PersonsStoreTransaction that delegates to a store with a transaction.- * This can be used by any store that implements PersonsStore.+ * PersonsStoreTransaction that delegates to the Postgres store with a+ * transaction. Transactional verbs are the pg backend's own surface: the+ * cross-backend PersonsStore interface has no transactional member.*/export class PersonsStoreTransaction {constructor(- private store: PersonsStore,+ private store: BatchWritingPersonsStore,private tx: PersonRepositoryTransaction) {}diff --git a/nodejs/src/ingestion/common/persons/persons-store.ts b/nodejs/src/ingestion/common/persons/persons-store.tsindex 2a59c0f731b2..ac5df774aac2 100644--- a/nodejs/src/ingestion/common/persons/persons-store.ts+++ b/nodejs/src/ingestion/common/persons/persons-store.ts@@ -1,15 +1,14 @@import { DateTime } from 'luxon'import { PersonMessage } from '~/common/persons/person-message'-import { InternalPersonWithDistinctId, LifecycleMarkPerson } from '~/common/persons/repositories/person-repository'import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'-import { CreatePersonResult, MoveDistinctIdsResult } from '~/common/utils/db/db'+import { CreatePersonResult } from '~/common/utils/db/db'import { BatchWritingStore } from '~/ingestion/common/stores/batch-writing-store'import { Properties } from '~/plugin-scaffold'-import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt, Team } from '~/types'+import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt } from '~/types'+import { MergeMode } from './person-merge-types'import { EventOps } from './person-update'-import { PersonsStoreTransaction } from './persons-store-transaction'export type FlushResult = {messages: PersonMessage[]@@ -18,39 +17,113 @@ export type FlushResult = {uuid?: string}-export interface PersonsStore extends BatchWritingStore<FlushResult> {+/** One source distinct id to merge into the target, with the event that asked for it. */+export interface MergePersonsSource {+ distinctId: string+ eventUuid: string+}++/**+ * Per-source verdicts a merge can answer. Both backends share the+ * vocabulary; 'skipped_race' and the 'failed_*' verdicts come only+ * from the Postgres merge's retrying transaction, and 'error' only+ * from the saga.+ */+export type MergePersonsOutcome =+ | 'merged'+ | 'noop_same_person'+ | 'attached'+ | 'skipped_illegal'+ | 'skipped_already_identified'+ | 'skipped_conflict'+ | 'skipped_move_limit'+ | 'skipped_race'+ | 'failed_source_not_found'+ | 'failed_target_not_found'+ | 'failed_source_has_distinct_ids'+ | 'error'++export interface MergePersonsSourceResult {+ sourceDistinctId: string+ outcome: MergePersonsOutcome+ /** The source person the verdict speaks about, when the backend resolved one. */+ sourcePersonUuid?: string+ /**+ * The source person this verdict destroyed, present only on a merged+ * source. Merging away is permanent, so a caller may reconcile cached+ * state against it without re-reading, including entries cached under+ * distinct ids the request never named.+ */+ sourcePersonId?: string+}++export interface MergePersonsRequest {+ teamId: number+ targetDistinctId: string/**- * Executes a function within a transaction- * @param description - Description of the transaction for logging- * @param transaction - Function to execute within the transaction, receives a transaction interface+ * Ordered; earlier sources beat later ones on property precedence,+ * the target beats all. More than one source only from a fold plan.*/- inTransaction<T>(description: string, transaction: (tx: PersonsStoreTransaction) => Promise<T>): Promise<T>-+ sources: MergePersonsSource[]/**- * Fetches a person by team ID and distinct ID for checking existence- * Uses read replica when available+ * The source belonging to the event that initiated this request; not+ * always the first source, because a fold plan's first event can be+ * dropped before the person step. When a folded merge finds no target+ * person, the Postgres merge bootstraps this source first.*/- fetchForChecking(teamId: number, distinctId: string, batchId: number): Promise<InternalPerson | null>-+ triggerSourceDistinctId?: string+ /** The merge event's property ops; each backend applies them to the survivor its own way. */+ eventOps: EventOps/**- * Fetches a person by team ID and distinct ID with a row-level lock- * Always uses primary database+ * The merge-triggering event's uuid, the idempotency root: backends+ * derive their durable op ids from it, so a repeated delivery of the+ * same event must present the same value and cannot merge twice.*/- fetchForUpdate(teamId: number, distinctId: string, batchId: number): Promise<InternalPerson | null>-+ eventUuid: string+ /** $merge_dangerously legally merges already-identified sources; $identify does not. */+ allowIdentifiedSources: boolean/**- * Batched fetchForUpdate for folded merges: resolves and row-locks all- * persons behind the given distinct_ids in one statement.+ * The caller's move policy, from the same config the processor's+ * over-limit handling reads. The Postgres merge bounds its+ * distinct-id moves by it; the saga backend uses LIMIT/ASYNC's limit+ * as its move-limit guard and falls back to its own configured+ * guard for SYNC, which the saga cannot run unbounded.*/- fetchPersonsForUpdateByDistinctIds(- teamId: number,- distinctIds: string[],- batchId: number- ): Promise<InternalPersonWithDistinctId[]>+ mergeMode: MergeMode+ /** Merge event created_at, epoch millis; becomes the survivor's when older. */+ createdAtMs: number+}++export type MergeFoldAbortReason = 'limit' | 'conflict' | 'deadlock' | 'error'+export interface MergePersonsResult {+ /** The surviving person; null when the merge settled without one. */+ survivor: InternalPerson | null+ results: MergePersonsSourceResult[]+ /** Post-commit ClickHouse production the caller may chain on; absent when the backend produced before returning. */+ kafkaAck?: Promise<void>/**- * Creates a new person+ * Whether the caller still needs its follow-up property update;+ * false when person creation already applied the event's properties.+ * Absent means true.*/+ survivorNeedsUpdate?: boolean+ /** Multi-source only: the folded transaction rolled back untouched; the caller falls back to per-event merges. */+ foldAborted?: MergeFoldAbortReason+}++/** Which person-storage backend a store writes to. Labels metrics whose causes differ between them. */+export type PersonsBackend = 'postgres' | 'personhog'++export interface PersonsStore extends BatchWritingStore<FlushResult> {+ readonly backend: PersonsBackend++ /** Existence-class read; replica-backed where the backend has one. */+ fetchForChecking(teamId: number, distinctId: string, batchId: number): Promise<InternalPerson | null>++ /** Update-class read from the authoritative side; its answer feeds writes. */+ fetchForUpdate(teamId: number, distinctId: string, batchId: number): Promise<InternalPerson | null>+createPerson(createdAt: DateTime,properties: Properties,@@ -66,17 +139,6 @@ export interface PersonsStore extends BatchWritingStore<FlushResult> {batchId: number): Promise<CreatePersonResult>- /**- * Updates an existing person for merge operations- */- updatePersonForMerge(- person: InternalPerson,- update: Partial<InternalPerson>,- distinctId: string,- batchId: number,- tx?: PersonRepositoryTransaction- ): Promise<[InternalPerson, PersonMessage[], boolean]>-/*** Applies one event's extracted ops to a person, resolving what they* mean against this store's own state: snapshot refinement, the@@ -105,123 +167,16 @@ export interface PersonsStore extends BatchWritingStore<FlushResult> {): Promise<[InternalPerson, PersonMessage[], boolean]>/**- * Deletes a person- */- deletePerson(person: InternalPerson, distinctId: string, tx?: PersonRepositoryTransaction): Promise<PersonMessage[]>-- /**- * Claims the persons in the lifecycle mark table for a merge; at most one live- * operation may hold a person. Held until the transaction commits.+ * Merge the sources into the target through this backend's own merge+ * machinery (the identity service's saga, or the PostgresPersonMerge+ * the Postgres store runs internally). Settled verdicts come back as+ * per-source outcomes; retryable Postgres conflicts throw for the+ * caller's retry loop.*/- claimLifecycleMarks(- opId: string,- teamId: number,- persons: LifecycleMarkPerson[],- distinctId: string,- tx?: PersonRepositoryTransaction- ): Promise<void>+ mergePersons(request: MergePersonsRequest, batchId: number): Promise<MergePersonsResult>- /** Releases a merge's lifecycle marks; same transaction as the claim. */- releaseLifecycleMarks(- opId: string,- teamId: number,- distinctId: string,- tx?: PersonRepositoryTransaction- ): Promise<void>-- /** Whether the person is live; only meaningful while holding its lifecycle mark. */- isPersonLive(person: InternalPerson, distinctId: string, tx?: PersonRepositoryTransaction): Promise<boolean>-- /**- * Adds a distinct ID to a person- */- addDistinctId(- person: InternalPerson,- distinctId: string,- version: number,- tx: PersonRepositoryTransaction | undefined,- batchId: number- ): Promise<PersonMessage[]>-- /**- * Moves distinct IDs from one person to another- */- moveDistinctIds(- source: InternalPerson,- target: InternalPerson,- distinctId: string,- limit: number | undefined,- tx: PersonRepositoryTransaction,- batchId: number- ): Promise<MoveDistinctIdsResult>-- /**- * Batched unlimited moveDistinctIds for folded merges- */- moveDistinctIdsFromPersons(- sources: InternalPerson[],- target: InternalPerson,- distinctId: string,- tx: PersonRepositoryTransaction,- batchId: number- ): Promise<MoveDistinctIdsResult>-- /**- * Batched deletePerson for folded merges; all persons must belong to one team- */- deletePersons(- persons: InternalPerson[],- distinctId: string,- tx?: PersonRepositoryTransaction- ): Promise<PersonMessage[]>-- /**- * Distinct-id counts per person id, for the folded-merge limit pre-check- */- countDistinctIdsForPersons(- teamId: Team['id'],- personIds: InternalPerson['id'][],- distinctId: string,- tx: PersonRepositoryTransaction- ): Promise<Map<string, number>>-- /**- * Updates cohorts and feature flags for merged persons- */- updateCohortsAndFeatureFlagsForMerge(- teamID: Team['id'],- sourcePersonID: InternalPerson['id'],- targetPersonID: InternalPerson['id'],- distinctId: string,- tx?: PersonRepositoryTransaction- ): Promise<void>-- /**- * Batched updateCohortsAndFeatureFlagsForMerge for folded merges- */- updateCohortsAndFeatureFlagsForMergeBatch(- teamID: Team['id'],- sourcePersonIDs: InternalPerson['id'][],- targetPersonID: InternalPerson['id'],- distinctId: string,- tx?: PersonRepositoryTransaction- ): Promise<void>-- /**- * Returns the size of the person properties- */personPropertiesSize(personId: string, teamId: number): Promise<number>- /**- * Fetch distinct ids for a person inside a transaction-aware wrapper- */- fetchPersonDistinctIds(- person: InternalPerson,- distinctId: string,- limit: number | undefined,- tx: PersonRepositoryTransaction- ): Promise<string[]>-/*** Stop any background work (e.g., periodic metric emission) and flush* remaining accumulated metrics. Called on graceful shutdown. Does NOT@@ -230,15 +185,8 @@ export interface PersonsStore extends BatchWritingStore<FlushResult> {shutdown(): Promise<void>/**- * Removes a distinct ID from the cache- */- removeDistinctIdFromCache(teamId: number, distinctId: string): void-- /**- * Prefetches persons by team ID and distinct ID to warm up the cache.- * Each entry may carry its own batchId for cache eviction tracking, allowing a- * single DB fetch to service entries that belong to different concurrent batches.- * @param teamDistinctIds - A list of team IDs and distinct IDs to prefetch+ * Best-effort cache warmer. Entries carry their own batchIds so one+ * fetch can serve concurrent batches' eviction tracking.*/prefetchPersons(teamDistinctIds: { teamId: number; distinctId: string; batchId: number }[]): Promise<void>diff --git a/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts b/nodejs/src/ingestion/common/persons/routing-persons-store.test.tsindex 407b83b8d597..cc37e9d3b1d7 100644--- a/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts+++ b/nodejs/src/ingestion/common/persons/routing-persons-store.test.ts@@ -3,7 +3,7 @@ import { InternalPerson } from '~/types'import { EventOps } from './person-update'import { PersonhogPersonsStore } from './personhog-persons-store'-import { PersonsStore } from './persons-store'+import { MergePersonsResult, PersonsBackend, PersonsStore } from './persons-store'import { RoutingPersonsStore, assertPersonsStoreModeConfig, parsePersonsStoreMode } from './routing-persons-store'jest.mock('~/common/persons/metrics', () => ({@@ -11,37 +11,29 @@ jest.mock('~/common/persons/metrics', () => ({personhogStoreShadowSkipsCounter: { labels: jest.fn().mockReturnValue({ inc: jest.fn() }) },}))+const emptyMergeResult = (): MergePersonsResult => ({ survivor: null, results: [] })+/*** A complete, compile-checked PersonsStore mock: the annotation forces* every interface member to exist, so an interface change breaks this* factory at compile time instead of leaving stale mocks that only fail* when a newly routed method runs.+ *+ * The cover is PersonsStore only. Tests hand this to the personhog slot+ * through a cast, so a member PersonhogPersonsStore adds beyond the+ * interface is not checked here and would surface at runtime.*/-function mockStore(): jest.Mocked<PersonsStore> {+function mockStore(backend: PersonsBackend = 'postgres'): jest.Mocked<PersonsStore> {return {- inTransaction: jest.fn(),+ backend,fetchForChecking: jest.fn().mockResolvedValue(null),fetchForUpdate: jest.fn().mockResolvedValue(null),- fetchPersonsForUpdateByDistinctIds: jest.fn().mockResolvedValue([]),createPerson: jest.fn().mockResolvedValue({ success: true }),- updatePersonForMerge: jest.fn(),applyEventOps: jest.fn(),updatePersonWithPropertiesDiffForUpdate: jest.fn(),- deletePerson: jest.fn().mockResolvedValue([]),- claimLifecycleMarks: jest.fn().mockResolvedValue(undefined),- releaseLifecycleMarks: jest.fn().mockResolvedValue(undefined),- isPersonLive: jest.fn().mockResolvedValue(true),- addDistinctId: jest.fn().mockResolvedValue([]),- moveDistinctIds: jest.fn().mockResolvedValue({ success: true }),- moveDistinctIdsFromPersons: jest.fn().mockResolvedValue({ success: true }),- deletePersons: jest.fn().mockResolvedValue([]),- countDistinctIdsForPersons: jest.fn().mockResolvedValue(new Map()),- updateCohortsAndFeatureFlagsForMerge: jest.fn().mockResolvedValue(undefined),- updateCohortsAndFeatureFlagsForMergeBatch: jest.fn().mockResolvedValue(undefined),+ mergePersons: jest.fn().mockResolvedValue(emptyMergeResult()),personPropertiesSize: jest.fn().mockResolvedValue(0),- fetchPersonDistinctIds: jest.fn().mockResolvedValue([]),shutdown: jest.fn().mockResolvedValue(undefined),- removeDistinctIdFromCache: jest.fn(),prefetchPersons: jest.fn().mockResolvedValue(undefined),flush: jest.fn().mockResolvedValue([]),releaseBatch: jest.fn(),@@ -50,6 +42,20 @@ function mockStore(): jest.Mocked<PersonsStore> {}describe('RoutingPersonsStore', () => {+ it.each([+ // Shadow's personhog calls never reach a caller, so an error a caller+ // sees during a shadow rollout came from Postgres and must say so.+ ['personhog' as const, 'personhog'],+ ['shadow' as const, 'postgres'],+ ])('reports the authoritative backend in %s mode', (mode, expected) => {+ const store = new RoutingPersonsStore(+ mockStore('postgres'),+ mockStore('personhog') as unknown as PersonhogPersonsStore,+ mode+ )+ expect(store.backend).toBe(expected)+ })+const person = (teamId: number, id = '1'): InternalPerson =>({ id, team_id: teamId, properties: {}, is_identified: false }) as unknown as InternalPerson@@ -110,6 +116,15 @@ describe('RoutingPersonsStore', () => {await expect(store.flush()).rejects.toThrow('leader down')})+ it('mergePersons routes to the personhog store', async () => {+ const stores = makeStores()+ const saga = emptyMergeResult()+ stores.personhogMock.mergePersons.mockResolvedValue(saga)+ const store = makeStore(stores, 'personhog')+ await expect(store.mergePersons({} as never, 0)).resolves.toBe(saga)+ expect(stores.pg.mergePersons).not.toHaveBeenCalled()+ })+it('flush never runs the pg side, and returns the personhog results', async () => {const stores = makeStores()const store = makeStore(stores, 'personhog')@@ -151,6 +166,29 @@ describe('RoutingPersonsStore', () => {await expect(store.flush()).resolves.toEqual([])})+ it('mergePersons replays the same request against the personhog backend, pg staying authoritative', async () => {+ const stores = makeStores()+ const pgResult = { survivor: person(1, '7'), results: [] }+ stores.pg.mergePersons.mockResolvedValue(pgResult)+ const store = makeStore(stores, 'shadow')+ const request = { teamId: 1, targetDistinctId: 'd' } as never++ await expect(store.mergePersons(request, 0)).resolves.toBe(pgResult)++ expect(stores.pg.mergePersons).toHaveBeenCalledWith(request, 0)+ expect(stores.personhogMock.mergePersons).toHaveBeenCalledWith(request, 0)+ })++ it('a shadow merge failure is swallowed and counted, never failing the batch', async () => {+ const stores = makeStores()+ stores.pg.mergePersons.mockResolvedValue(emptyMergeResult())+ stores.personhogMock.mergePersons.mockRejectedValue(new Error('identity down'))+ const store = makeStore(stores, 'shadow')++ await expect(store.mergePersons({} as never, 0)).resolves.toEqual(emptyMergeResult())+ expect(personhogStoreShadowErrorsCounter.labels).toHaveBeenCalledWith({ verb: 'mergePersons' })+ })+it('prefetch warms both worlds', async () => {const stores = makeStores()const store = makeStore(stores, 'shadow')@@ -172,7 +210,7 @@ describe('RoutingPersonsStore', () => {})})- describe('shadow writes resolve the personhog world person', () => {+ describe('shadow writes resolve the personhog backend person', () => {it.each([['applyEventOps',@@ -185,7 +223,7 @@ describe('RoutingPersonsStore', () => {store.updatePersonWithPropertiesDiffForUpdate(person(1, '7'), { a: '1' }, [], {}, 'd1', 0),(m: jest.Mocked<PersonsStore>) => m.updatePersonWithPropertiesDiffForUpdate,],- ] as const)('%s ships the shadow world id, not the pg id', async (_verb, call, member) => {+ ] as const)('%s ships the shadow backend id, not the pg id', async (_verb, call, member) => {const stores = makeStores()stores.pg.applyEventOps.mockResolvedValue([person(1, '7'), []])stores.pg.updatePersonWithPropertiesDiffForUpdate.mockResolvedValue([person(1, '7'), [], true])@@ -200,7 +238,7 @@ describe('RoutingPersonsStore', () => {expect((shadowArgs[0] as InternalPerson).id).toBe('99')})- it('skips the shadow write, counted, when the person does not exist in the personhog world', async () => {+ it('skips the shadow write, counted, when the person does not exist in the personhog backend', async () => {const stores = makeStores()stores.pg.applyEventOps.mockResolvedValue([person(1, '7'), []])stores.personhogMock.fetchForUpdate.mockResolvedValue(null)@@ -214,70 +252,6 @@ describe('RoutingPersonsStore', () => {})})- describe('merge execution routes to the team world, never across it', () => {- it.each([- ['deletePersons', (s: RoutingPersonsStore) => s.deletePersons([person(1)], 'd'), 'deletePersons'],- [- 'addDistinctId',- (s: RoutingPersonsStore) => s.addDistinctId(person(1), 'd', 0, undefined, 0),- 'addDistinctId',- ],- [- 'updatePersonForMerge',- (s: RoutingPersonsStore) => s.updatePersonForMerge(person(1), {}, 'd', 0),- 'updatePersonForMerge',- ],- [- 'claimLifecycleMarks',- (s: RoutingPersonsStore) => s.claimLifecycleMarks('op', 1, [], 'd'),- 'claimLifecycleMarks',- ],- ] as const)('%s reaches the personhog store for a routed team', async (_name, call, member) => {- const stores = makeStores()- const store = makeStore(stores, 'personhog')-- await call(store)-- expect(stores.personhogMock[member as keyof PersonsStore]).toHaveBeenCalled()- expect(stores.pg[member as keyof PersonsStore]).not.toHaveBeenCalled()- })-- it('shadow mode runs merges on pg and swallows the personhog placeholder', async () => {- const stores = makeStores()- stores.personhogMock.deletePersons.mockRejectedValue(new Error('no personhog RPC: merge saga'))- const store = makeStore(stores, 'shadow')-- await store.deletePersons([person(1)], 'd')-- expect(stores.pg.deletePersons).toHaveBeenCalled()- expect(personhogStoreShadowErrorsCounter.labels).toHaveBeenCalledWith({ verb: 'deletePersons' })- })- })-- describe('inTransaction routes by mode', () => {- it('personhog mode reaches the personhog store, whose placeholder answers', () => {- const stores = makeStores()- const store = makeStore(stores, 'personhog')- const cb = () => Promise.resolve('x')-- void store.inTransaction('merge', cb)-- expect(stores.personhogMock.inTransaction).toHaveBeenCalledWith('merge', cb)- expect(stores.pg.inTransaction).not.toHaveBeenCalled()- })-- it('shadow mode runs the transaction on pg exactly once, unshadowed', () => {- const stores = makeStores()- const store = makeStore(stores, 'shadow')- const cb = () => Promise.resolve('x')-- void store.inTransaction('merge', cb)-- expect(stores.pg.inTransaction).toHaveBeenCalledWith('merge', cb)- expect(stores.personhogMock.inTransaction).not.toHaveBeenCalled()- })- })-it('shutdown closes the personhog side even when pg shutdown fails', async () => {const stores = makeStores()stores.pg.shutdown.mockRejectedValue(new Error('pg teardown failed'))diff --git a/nodejs/src/ingestion/common/persons/routing-persons-store.ts b/nodejs/src/ingestion/common/persons/routing-persons-store.tsindex 22bdd39567f7..77ecb4b5265f 100644--- a/nodejs/src/ingestion/common/persons/routing-persons-store.ts+++ b/nodejs/src/ingestion/common/persons/routing-persons-store.ts@@ -2,19 +2,17 @@ import { DateTime } from 'luxon'import { personhogStoreShadowErrorsCounter, personhogStoreShadowSkipsCounter } from '~/common/persons/metrics'import { PersonMessage } from '~/common/persons/person-message'-import { InternalPersonWithDistinctId, LifecycleMarkPerson } from '~/common/persons/repositories/person-repository'import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'-import { CreatePersonResult, MoveDistinctIdsResult } from '~/common/utils/db/db'+import { CreatePersonResult } from '~/common/utils/db/db'import { logger } from '~/common/utils/logger'import { BatchWritingStoreFlushStats } from '~/ingestion/common/stores/batch-writing-store'import { Properties } from '~/plugin-scaffold'-import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt, Team } from '~/types'+import { InternalPerson, PropertiesLastOperation, PropertiesLastUpdatedAt } from '~/types'import { EventOps } from './person-update'import { PersonhogPersonsStore } from './personhog-persons-store'-import { FlushResult, PersonsStore } from './persons-store'+import { FlushResult, MergePersonsRequest, MergePersonsResult, PersonsBackend, PersonsStore } from './persons-store'import { BatchBoundPersonsStore, PersonsStoreForBatch } from './persons-store-for-batch'-import { PersonsStoreTransaction } from './persons-store-transaction'export type PersonsStoreMode = 'pg' | 'personhog' | 'shadow'@@ -47,14 +45,15 @@ export function assertPersonsStoreModeConfig(}/**- * Routes person-store verbs between the Postgres world and the personhog- * world. The mode applies to the whole deployment: personhog sends every+ * Routes person-store verbs between the Postgres backend and the personhog+ * one. The mode applies to the whole deployment: personhog sends every* verb to the personhog store, and shadow runs the Postgres call as the* authoritative result with the personhog call after it, its failures- * counted and logged but never failing the batch. Verbs the personhog- * store cannot serve yet answer with its pending-saga placeholders, so- * unsupported paths fail loudly in personhog mode and surface as counted- * shadow errors in shadow mode.+ * counted and logged but never failing the batch. Merges route through+ * `mergePersons` like any other verb: each backend runs its own whole+ * merge (the identity service's saga, or the Postgres store's own), so+ * shadow mode rehearses every merge, folds included, against the+ * personhog backend's own graph.*/export class RoutingPersonsStore implements PersonsStore {constructor(@@ -63,6 +62,12 @@ export class RoutingPersonsStore implements PersonsStore {private mode: 'personhog' | 'shadow') {}+ // Shadow mode's personhog calls never reach a caller, so the errors a+ // caller sees are the authoritative side's.+ get backend(): PersonsBackend {+ return this.mode === 'shadow' ? this.pg.backend : this.personhog.backend+ }+/*** Run the personhog side of a shadowed verb: sequential, awaited, and* never allowed to fail the batch.@@ -79,10 +84,7 @@ export class RoutingPersonsStore implements PersonsStore {/*** The whole mode semantics, once: personhog mode runs the personhog* call, shadow runs pg as the authoritative result and the personhog- * call after it, swallowed. Verbs carrying a live Postgres- * transaction never arrive here, because the transaction wrapper- * pg's inTransaction hands out pins every tx-scoped call to the- * store that opened it.+ * call after it, swallowed.*/private async route<T>(verb: string,@@ -99,9 +101,9 @@ export class RoutingPersonsStore implements PersonsStore {}/**- * Resolve the personhog world's own person for a shadowed write. The+ * Resolve the personhog backend's own person for a shadowed write. The* caller holds the Postgres row, whose numeric id means nothing in- * the personhog world — the two id sequences are independent — so a+ * the personhog backend — the two id sequences are independent — so a* shadow write must re-resolve by distinct id and skip, counted,* when the person does not exist there yet. The fetch memoizes per* batch, so repeated writes to one person cost one resolution.@@ -125,19 +127,6 @@ export class RoutingPersonsStore implements PersonsStore {return new BatchBoundPersonsStore(this, batchId)}- /**- * Routes by mode like every other verb; the callback runs exactly- * once, so shadow mode delegates to Postgres alone rather than- * executing it a second time against the personhog store. In- * personhog mode the store's own placeholder answers until the- * merge saga lands.- */- inTransaction<T>(description: string, transaction: (tx: PersonsStoreTransaction) => Promise<T>): Promise<T> {- return this.mode === 'personhog'- ? this.personhog.inTransaction(description, transaction)- : this.pg.inTransaction(description, transaction)- }-fetchForChecking(teamId: number, distinctId: string, batchId: number): Promise<InternalPerson | null> {return this.route('fetchForChecking',@@ -154,18 +143,6 @@ export class RoutingPersonsStore implements PersonsStore {)}- fetchPersonsForUpdateByDistinctIds(- teamId: number,- distinctIds: string[],- batchId: number- ): Promise<InternalPersonWithDistinctId[]> {- return this.route(- 'fetchPersonsForUpdateByDistinctIds',- () => this.pg.fetchPersonsForUpdateByDistinctIds(teamId, distinctIds, batchId),- () => this.personhog.fetchPersonsForUpdateByDistinctIds(teamId, distinctIds, batchId)- )- }-createPerson(createdAt: DateTime,properties: Properties,@@ -290,194 +267,17 @@ export class RoutingPersonsStore implements PersonsStore {)}- deletePerson(- person: InternalPerson,- distinctId: string,- tx?: PersonRepositoryTransaction- ): Promise<PersonMessage[]> {- return this.route(- 'deletePerson',- () => this.pg.deletePerson(person, distinctId, tx),- () => this.personhog.deletePerson(person, distinctId, tx)- )- }-- claimLifecycleMarks(- opId: string,- teamId: number,- persons: LifecycleMarkPerson[],- distinctId: string,- tx?: PersonRepositoryTransaction- ): Promise<void> {- return this.route(- 'claimLifecycleMarks',- () => this.pg.claimLifecycleMarks(opId, teamId, persons, distinctId, tx),- () => this.personhog.claimLifecycleMarks(opId, teamId, persons, distinctId, tx)- )- }-- releaseLifecycleMarks(- opId: string,- teamId: number,- distinctId: string,- tx?: PersonRepositoryTransaction- ): Promise<void> {- return this.route(- 'releaseLifecycleMarks',- () => this.pg.releaseLifecycleMarks(opId, teamId, distinctId, tx),- () => this.personhog.releaseLifecycleMarks(opId, teamId, distinctId, tx)- )- }-- isPersonLive(person: InternalPerson, distinctId: string, tx?: PersonRepositoryTransaction): Promise<boolean> {- return this.route(- 'isPersonLive',- () => this.pg.isPersonLive(person, distinctId, tx),- () => this.personhog.isPersonLive(person, distinctId, tx)- )- }-- updatePersonForMerge(- person: InternalPerson,- update: Partial<InternalPerson>,- distinctId: string,- batchId: number,- tx?: PersonRepositoryTransaction- ): Promise<[InternalPerson, PersonMessage[], boolean]> {- return this.route(- 'updatePersonForMerge',- () => this.pg.updatePersonForMerge(person, update, distinctId, batchId, tx),- () => this.personhog.updatePersonForMerge(person, update, distinctId, batchId, tx)- )- }-- addDistinctId(- person: InternalPerson,- distinctId: string,- version: number,- tx: PersonRepositoryTransaction | undefined,- batchId: number- ): Promise<PersonMessage[]> {- return this.route(- 'addDistinctId',- () => this.pg.addDistinctId(person, distinctId, version, tx, batchId),- () => this.personhog.addDistinctId(person, distinctId, version, tx, batchId)- )- }-- moveDistinctIds(- source: InternalPerson,- target: InternalPerson,- distinctId: string,- limit: number | undefined,- tx: PersonRepositoryTransaction,- batchId: number- ): Promise<MoveDistinctIdsResult> {- return this.route(- 'moveDistinctIds',- () => this.pg.moveDistinctIds(source, target, distinctId, limit, tx, batchId),- () => this.personhog.moveDistinctIds(source, target, distinctId, limit, tx, batchId)- )- }-- moveDistinctIdsFromPersons(- sources: InternalPerson[],- target: InternalPerson,- distinctId: string,- tx: PersonRepositoryTransaction,- batchId: number- ): Promise<MoveDistinctIdsResult> {- return this.route(- 'moveDistinctIdsFromPersons',- () => this.pg.moveDistinctIdsFromPersons(sources, target, distinctId, tx, batchId),- () => this.personhog.moveDistinctIdsFromPersons(sources, target, distinctId, tx, batchId)- )- }-- deletePersons(- persons: InternalPerson[],- distinctId: string,- tx?: PersonRepositoryTransaction- ): Promise<PersonMessage[]> {- return this.route(- 'deletePersons',- () => this.pg.deletePersons(persons, distinctId, tx),- () => this.personhog.deletePersons(persons, distinctId, tx)- )- }-- countDistinctIdsForPersons(- teamId: Team['id'],- personIds: InternalPerson['id'][],- distinctId: string,- tx: PersonRepositoryTransaction- ): Promise<Map<string, number>> {- return this.route(- 'countDistinctIdsForPersons',- () => this.pg.countDistinctIdsForPersons(teamId, personIds, distinctId, tx),- () => this.personhog.countDistinctIdsForPersons(teamId, personIds, distinctId, tx)- )- }-- updateCohortsAndFeatureFlagsForMerge(- teamID: Team['id'],- sourcePersonID: InternalPerson['id'],- targetPersonID: InternalPerson['id'],- distinctId: string,- tx?: PersonRepositoryTransaction- ): Promise<void> {- return this.route(- 'updateCohortsAndFeatureFlagsForMerge',- () => this.pg.updateCohortsAndFeatureFlagsForMerge(teamID, sourcePersonID, targetPersonID, distinctId, tx),- () =>- this.personhog.updateCohortsAndFeatureFlagsForMerge(- teamID,- sourcePersonID,- targetPersonID,- distinctId,- tx- )- )- }-- updateCohortsAndFeatureFlagsForMergeBatch(- teamID: Team['id'],- sourcePersonIDs: InternalPerson['id'][],- targetPersonID: InternalPerson['id'],- distinctId: string,- tx?: PersonRepositoryTransaction- ): Promise<void> {- return this.route(- 'updateCohortsAndFeatureFlagsForMergeBatch',- () =>- this.pg.updateCohortsAndFeatureFlagsForMergeBatch(- teamID,- sourcePersonIDs,- targetPersonID,- distinctId,- tx- ),- () =>- this.personhog.updateCohortsAndFeatureFlagsForMergeBatch(- teamID,- sourcePersonIDs,- targetPersonID,- distinctId,- tx- )- )- }-- fetchPersonDistinctIds(- person: InternalPerson,- distinctId: string,- limit: number | undefined,- tx: PersonRepositoryTransaction- ): Promise<string[]> {+ /**+ * Merges are distinct-id addressed, so the personhog side needs no+ * person re-resolution: the same request replays the whole merge+ * against that backend's saga, keeping the shadow graph's topology in+ * step with the Postgres one.+ */+ mergePersons(request: MergePersonsRequest, batchId: number): Promise<MergePersonsResult> {return this.route(- 'fetchPersonDistinctIds',- () => this.pg.fetchPersonDistinctIds(person, distinctId, limit, tx),- () => this.personhog.fetchPersonDistinctIds(person, distinctId, limit, tx)+ 'mergePersons',+ () => this.pg.mergePersons(request, batchId),+ () => this.personhog.mergePersons(request, batchId))}@@ -489,11 +289,6 @@ export class RoutingPersonsStore implements PersonsStore {)}- removeDistinctIdFromCache(teamId: number, distinctId: string): void {- this.pg.removeDistinctIdFromCache(teamId, distinctId)- this.personhog.removeDistinctIdFromCache(teamId, distinctId)- }-prefetchPersons(teamDistinctIds: { teamId: number; distinctId: string; batchId: number }[]): Promise<void> {return this.route('prefetchPersons',diff --git a/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.ts b/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.tsindex ae794a1951be..3ceea0be697b 100644--- a/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.ts@@ -3,13 +3,8 @@ export interface EventPipelineRunnerOptions {PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT: numberPERSON_MERGE_ASYNC_ENABLED: booleanPERSON_MERGE_SYNC_BATCH_SIZE: number- PERSON_MERGE_EVENTS_ENABLED: boolean- PERSON_MERGE_EVENTS_PARTITION_COUNT: number- PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: stringPERSON_MERGE_FOLD_ENABLED: booleanPERSON_MERGE_FOLD_TEAM_ALLOWLIST: string- /** Teams whose merges run new-world: lifecycle-mark claims plus tombstone deletes: '*' for all, '' to disable, or comma-separated team IDs */- PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST: stringPERSON_JSONB_SIZE_ESTIMATE_ENABLE: numberPERSON_PROPERTIES_UPDATE_ALL: boolean/** Teams whose $feature_flag_called events default to personless: '*' for all, '' to disable, or comma-separated team IDs */diff --git a/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts b/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.tsindex 6dc61e410254..b7b0eabdf6af 100644--- a/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts@@ -1,8 +1,7 @@import { DateTime } from 'luxon'-import { buildIntegerMatcher } from '~/common/config/config'import { AsyncOutput } from '~/common/outputs'-import { MergeEventsConfig, PersonContext, PersonOutputs } from '~/ingestion/common/persons/person-context'+import { PersonContext, PersonOutputs } from '~/ingestion/common/persons/person-context'import { PersonEventProcessor } from '~/ingestion/common/persons/person-event-processor'import type { MergeFoldDecision } from '~/ingestion/common/persons/person-merge-fold'import { PersonMergeService } from '~/ingestion/common/persons/person-merge-service'@@ -39,13 +38,6 @@ export function createProcessPersonsStep<TInput extends ProcessPersonsInput>(options.PERSON_MERGE_ASYNC_ENABLED,options.PERSON_MERGE_SYNC_BATCH_SIZE)- // Built once at pipeline construction (not per event). '*' allows every team.- const mergeEventsConfig: MergeEventsConfig = {- enabled: options.PERSON_MERGE_EVENTS_ENABLED,- partitionCount: options.PERSON_MERGE_EVENTS_PARTITION_COUNT,- isTeamEnabled: buildIntegerMatcher(options.PERSON_MERGE_EVENTS_TEAM_ALLOWLIST, true),- }- const isMergeTombstoneTeam = buildIntegerMatcher(options.PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST, true)return async function processPersonsStep(input: TInput@@ -70,9 +62,7 @@ export function createProcessPersonsStep<TInput extends ProcessPersonsInput>(mergeMode,options.PERSON_PROPERTIES_UPDATE_ALL,shouldUpdateLastSeenAt,- mergeEventsConfig,- input.mergeFold.type === 'planned' ? input.mergeFold.plan : undefined,- isMergeTombstoneTeam(team.id)+ input.mergeFold.type === 'planned' ? input.mergeFold.plan : undefined)const processor = new PersonEventProcessor(diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.tsindex e31a0439d5e6..58ead0bdcb3f 100644--- a/nodejs/src/ingestion/ingestion-consumer.ts+++ b/nodejs/src/ingestion/ingestion-consumer.ts@@ -238,6 +238,10 @@ export class IngestionConsumer {maxOptimisticUpdateRetries: this.config.PERSON_BATCH_WRITING_MAX_OPTIMISTIC_UPDATE_RETRIES,optimisticUpdateRetryInterval: this.config.PERSON_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS,updateAllProperties: this.config.PERSON_PROPERTIES_UPDATE_ALL,+ mergeTombstoneTeamAllowlist: this.config.PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST,+ mergeEventsEnabled: effectivePersonMergeEventsEnabled(this.config),+ mergeEventsPartitionCount: this.config.PERSON_MERGE_EVENTS_PARTITION_COUNT,+ mergeEventsTeamAllowlist: this.config.PERSON_MERGE_EVENTS_TEAM_ALLOWLIST,})this.groupStore = new BatchWritingGroupStore(this.deps.groupRepository, this.deps.clickhouseGroupRepository, {@@ -304,12 +308,8 @@ export class IngestionConsumer {PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT: this.config.PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT,PERSON_MERGE_ASYNC_ENABLED: this.config.PERSON_MERGE_ASYNC_ENABLED,PERSON_MERGE_SYNC_BATCH_SIZE: this.config.PERSON_MERGE_SYNC_BATCH_SIZE,- PERSON_MERGE_EVENTS_ENABLED: effectivePersonMergeEventsEnabled(this.config),- PERSON_MERGE_EVENTS_PARTITION_COUNT: this.config.PERSON_MERGE_EVENTS_PARTITION_COUNT,- PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: this.config.PERSON_MERGE_EVENTS_TEAM_ALLOWLIST,PERSON_MERGE_FOLD_ENABLED: this.config.PERSON_MERGE_FOLD_ENABLED,PERSON_MERGE_FOLD_TEAM_ALLOWLIST: this.config.PERSON_MERGE_FOLD_TEAM_ALLOWLIST,- PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST: this.config.PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST,PERSON_JSONB_SIZE_ESTIMATE_ENABLE: this.config.PERSON_JSONB_SIZE_ESTIMATE_ENABLE,PERSON_PROPERTIES_UPDATE_ALL: this.config.PERSON_PROPERTIES_UPDATE_ALL,FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: this.config.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex dbf4c4bb981b..ab8e8a55bdc9 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -341,8 +341,12 @@ export class IngestionApiServer implements NodeServer {maxOptimisticUpdateRetries: this.config.PERSON_BATCH_WRITING_MAX_OPTIMISTIC_UPDATE_RETRIES,optimisticUpdateRetryInterval: this.config.PERSON_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS,updateAllProperties: this.config.PERSON_PROPERTIES_UPDATE_ALL,+ mergeTombstoneTeamAllowlist: this.config.PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST,+ mergeEventsEnabled: effectivePersonMergeEventsEnabled(this.config),+ mergeEventsPartitionCount: this.config.PERSON_MERGE_EVENTS_PARTITION_COUNT,+ mergeEventsTeamAllowlist: this.config.PERSON_MERGE_EVENTS_TEAM_ALLOWLIST,})- // Which world person writes land in, deployment-wide: pg (the+ // Which backend person writes land in, deployment-wide: pg (the// default) builds nothing new; the other modes construct the// personhog store, shadow keeping pg authoritative.const personsStoreMode = parsePersonsStoreMode(this.config.PERSONS_STORE_MODE)@@ -411,12 +415,8 @@ export class IngestionApiServer implements NodeServer {PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT: this.config.PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT,PERSON_MERGE_ASYNC_ENABLED: this.config.PERSON_MERGE_ASYNC_ENABLED,PERSON_MERGE_SYNC_BATCH_SIZE: this.config.PERSON_MERGE_SYNC_BATCH_SIZE,- PERSON_MERGE_EVENTS_ENABLED: effectivePersonMergeEventsEnabled(this.config),- PERSON_MERGE_EVENTS_PARTITION_COUNT: this.config.PERSON_MERGE_EVENTS_PARTITION_COUNT,- PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: this.config.PERSON_MERGE_EVENTS_TEAM_ALLOWLIST,PERSON_MERGE_FOLD_ENABLED: this.config.PERSON_MERGE_FOLD_ENABLED,PERSON_MERGE_FOLD_TEAM_ALLOWLIST: this.config.PERSON_MERGE_FOLD_TEAM_ALLOWLIST,- PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST: this.config.PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST,PERSON_JSONB_SIZE_ESTIMATE_ENABLE: this.config.PERSON_JSONB_SIZE_ESTIMATE_ENABLE,PERSON_PROPERTIES_UPDATE_ALL: this.config.PERSON_PROPERTIES_UPDATE_ALL,FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: this.config.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,diff --git a/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts b/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.tsindex 4cce0e4bc628..239daca83e9d 100644--- a/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts+++ b/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts@@ -23,6 +23,7 @@ import { UUIDT } from '~/common/utils/utils'import { BatchWritingPersonsStore } from '~/ingestion/common/persons/batch-writing-person-store'import { PersonOutputs } from '~/ingestion/common/persons/person-context'import { MergeFoldPlan } from '~/ingestion/common/persons/person-merge-fold'+import { uuidFromDistinctId } from '~/ingestion/common/persons/person-uuid'import { BatchBoundPersonsStore } from '~/ingestion/common/persons/persons-store-for-batch'import { EventPipelineRunnerOptions } from '~/ingestion/common/steps/event-processing/event-pipeline-options'import {@@ -51,12 +52,8 @@ describe('createProcessPersonsStep', () => {PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT: 100,PERSON_MERGE_ASYNC_ENABLED: false,PERSON_MERGE_SYNC_BATCH_SIZE: 1,- PERSON_MERGE_EVENTS_ENABLED: false,- PERSON_MERGE_EVENTS_PARTITION_COUNT: 64,- PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: '*',PERSON_MERGE_FOLD_ENABLED: false,PERSON_MERGE_FOLD_TEAM_ALLOWLIST: '*',- PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST: '',PERSON_JSONB_SIZE_ESTIMATE_ENABLE: 0,PERSON_PROPERTIES_UPDATE_ALL: false,FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: '*',@@ -708,6 +705,30 @@ describe('createProcessPersonsStep', () => {expect(distinctIds.sort()).toEqual(['anon-1', 'anon-2', 'user-1'])})+ it('bootstraps a missing target from the triggering pair, not the first planned pair', async () => {+ await createPersonWithProps('anon-1', { a: 1 })+ // anon-2 has no person row, and anon-1's event was dropped before+ // the person step, so anon-2's event triggers the fold.+ const plan = planFor('user-1', 'anon-1', 'anon-2')++ await runIdentifies([identifyEvent('anon-2', 'user-1')], plan, foldOptions)++ expect(plan.status).toBe('executed')+ // The merged property blob is batch-deferred; only moves and+ // deletes commit inside the fold transaction.+ await personsStore.flush()+ const persons = await fetchPostgresPersons(infra.postgres, teamId)+ expect(persons).toHaveLength(1)+ // The trigger's pair had no persons on either side, so the+ // bootstrap creates the target on user-1's deterministic uuid and+ // the fold merges anon-1's person into it; bootstrapping anon-1's+ // pair instead would leave anon-1's person as the survivor.+ expect(persons[0].uuid).toBe(uuidFromDistinctId(teamId, 'user-1'))+ expect(persons[0].properties).toEqual(expect.objectContaining({ a: 1 }))+ const distinctIds = await fetchDistinctIdValues(infra.postgres, persons[0])+ expect(distinctIds.sort()).toEqual(['anon-1', 'anon-2', 'user-1'])+ })+it('folded adds for distinct ids without a person get version 1', async () => {await createPersonWithProps('anon-1', { a: 1 })const plan = planFor('user-1', 'anon-1', 'anon-2')@@ -791,7 +812,9 @@ describe('createProcessPersonsStep', () => {it('abandons the fold when sources changed between fetch and transaction', async () => {await createPersonWithProps('anon-1', { a: 1 })await createPersonWithProps('user-1', {})- const plan = planFor('user-1', 'anon-1')+ // Two pairs so the folded path runs; a single-pair plan merges+ // through the sequential path and never needs the count check.+ const plan = planFor('user-1', 'anon-1', 'anon-2')// Simulate a concurrent merge emptying the source between the// locked fetch and the transaction's count.diff --git a/nodejs/tests/ingestion/person-state-batch.serial.test.ts b/nodejs/tests/ingestion/person-state-batch.serial.test.tsindex 1314bfcbd9bd..ea5762db1880 100644--- a/nodejs/tests/ingestion/person-state-batch.serial.test.ts+++ b/nodejs/tests/ingestion/person-state-batch.serial.test.ts@@ -27,8 +27,9 @@ import { defaultRetryConfig } from '~/common/utils/retries'import { UUIDT } from '~/common/utils/utils'import { BatchWritingPersonsStore } from '~/ingestion/common/persons/batch-writing-person-store'import { PersonOutputs } from '~/ingestion/common/persons/person-context'-import { PersonContext, personMergeEventProducedCounter } from '~/ingestion/common/persons/person-context'+import { PersonContext } from '~/ingestion/common/persons/person-context'import { PersonEventProcessor } from '~/ingestion/common/persons/person-event-processor'+import { personMergeEventProducedCounter } from '~/ingestion/common/persons/person-merge-postgres'import { PersonMergeService } from '~/ingestion/common/persons/person-merge-service'import {SourcePersonNotFoundError,@@ -296,7 +297,7 @@ describe('PersonState.processEvent()', () => {timestampParam = timestamp,team = mainTeam,mergeMode = createDefaultSyncMergeMode(),- mergeEventsConfig?: { enabled: boolean; partitionCount: number; isTeamEnabled?: (teamId: number) => boolean },+ mergeEventsConfig?: { enabled: boolean; partitionCount: number; teamAllowlist?: string },customPersonsStore?: BatchWritingPersonsStore,mergeTombstoneEnabled = false) {@@ -306,12 +307,22 @@ describe('PersonState.processEvent()', () => {...event,}+ // A custom store carries its own merge options; the merge policy+ // params here configure only the store this helper builds.const personsStore =customPersonsStore ??new BatchWritingPersonsStore(customPersonRepository ??(customHub ? new PostgresPersonRepository(customHub.postgres) : personRepository),- createPersonOutputs(kafkaProducer)+ createPersonOutputs(kafkaProducer),+ {+ mergeTombstoneTeamAllowlist: mergeTombstoneEnabled ? '*' : '',+ mergeEventsEnabled: mergeEventsConfig?.enabled ?? false,+ mergeEventsPartitionCount: mergeEventsConfig?.partitionCount ?? 64,+ // Allow-all default so the enabled/produce tests are unaffected by the+ // team gate; pass an allowlist explicitly to exercise it.+ mergeEventsTeamAllowlist: mergeEventsConfig?.teamAllowlist ?? '*',+ })const context = new PersonContext(@@ -325,12 +336,7 @@ describe('PersonState.processEvent()', () => {0,mergeMode,false,- false,- // isTeamEnabled defaults to allow-all so the enabled/produce tests are unaffected by the- // team gate; pass it explicitly to exercise the allowlist.- { isTeamEnabled: () => true, ...(mergeEventsConfig ?? { enabled: false, partitionCount: 64 }) },- undefined,- mergeTombstoneEnabled+ false)return new PersonMergeService(context)}@@ -2773,19 +2779,14 @@ describe('PersonState.processEvent()', () => {distinctId: firstUserDistinctId,})- const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {distinctId: secondUserDistinctId,})const mergeService: PersonMergeService = personMergeService({}, hub, personRepository)jest.spyOn(kafkaProducer, 'produce')- const result = await mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: second,- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(secondUserDistinctId, firstUserDistinctId, teamId, timestamp)expect(result.success).toBe(true)if (!result.success) {throw new Error('Merge should have succeeded')@@ -2859,21 +2860,16 @@ describe('PersonState.processEvent()', () => {it(`does not emit a person_merge_events message when the gate is off (default)`, async () => {mockProducerObserver.resetKafkaProducer()- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})- const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {distinctId: secondUserDistinctId,})// No mergeEventsConfig → gate defaults off.const mergeService = personMergeService({}, hub, personRepository)- const result = await mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: second,- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(secondUserDistinctId, firstUserDistinctId, teamId, timestamp)expect(result.success).toBe(true)if (!result.success) {throw new Error('Merge should have succeeded')@@ -2884,10 +2880,10 @@ describe('PersonState.processEvent()', () => {})it(`emits exactly one person_merge_events message with correct key, partition, and payload when the gate is on`, async () => {- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})- const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {distinctId: secondUserDistinctId,})@@ -2915,12 +2911,7 @@ describe('PersonState.processEvent()', () => {createDefaultSyncMergeMode(),{ enabled: true, partitionCount: 64 })- const result = await mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: second,- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(secondUserDistinctId, firstUserDistinctId, teamId, timestamp)expect(result.success).toBe(true)if (!result.success) {throw new Error('Merge should have succeeded')@@ -2953,10 +2944,10 @@ describe('PersonState.processEvent()', () => {it(`detaches the person_merge_events produce from the ack chain: a stuck produce cannot stall kafkaAck`, async () => {mockProducerObserver.resetKafkaProducer()- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})- const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {distinctId: secondUserDistinctId,})@@ -2987,12 +2978,7 @@ describe('PersonState.processEvent()', () => {createDefaultSyncMergeMode(),{ enabled: true, partitionCount: 64 })- const result = await mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: second,- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(secondUserDistinctId, firstUserDistinctId, teamId, timestamp)expect(result.success).toBe(true)if (!result.success) {throw new Error('Merge should have succeeded')@@ -3012,10 +2998,10 @@ describe('PersonState.processEvent()', () => {})it(`does not emit or count a person_merge_events message for a team outside the allowlist`, async () => {- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})- const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {distinctId: secondUserDistinctId,})@@ -3040,14 +3026,9 @@ describe('PersonState.processEvent()', () => {timestamp,mainTeam,createDefaultSyncMergeMode(),- { enabled: true, partitionCount: 64, isTeamEnabled: () => false }+ { enabled: true, partitionCount: 64, teamAllowlist: '' })- const result = await mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: second,- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(secondUserDistinctId, firstUserDistinctId, teamId, timestamp)expect(result.success).toBe(true)if (!result.success) {throw new Error('Merge should have succeeded')@@ -3063,10 +3044,10 @@ describe('PersonState.processEvent()', () => {it(`does not emit a person_merge_events message when the merge rolls back (moveDistinctIds throws)`, async () => {mockProducerObserver.resetKafkaProducer()- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})- const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {distinctId: secondUserDistinctId,})@@ -3080,18 +3061,15 @@ describe('PersonState.processEvent()', () => {createDefaultSyncMergeMode(),{ enabled: true, partitionCount: 64 })- // Force the transaction to fail before the post-commit emission point.- jest.spyOn(BatchWritingPersonsStore.prototype, 'inTransaction').mockRejectedValueOnce(+ // Force every transaction attempt to fail before the post-commit+ // emission point; merge() retries, so a single rejection would let+ // the retry succeed.+ jest.spyOn(BatchWritingPersonsStore.prototype, 'inTransaction').mockRejectedValue(new Error('moveDistinctIds blew up'))await expect(- mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: second,- otherPersonDistinctId: secondUserDistinctId,- })+ mergeService.merge(secondUserDistinctId, firstUserDistinctId, teamId, timestamp)).rejects.toThrow()expect(getMergeEventMessages()).toHaveLength(0)@@ -3135,7 +3113,7 @@ describe('PersonState.processEvent()', () => {})it(`hitting the move limit drops the event: no merge, no IDs moved, goes to DLQ`, async () => {- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {@@ -3158,12 +3136,7 @@ describe('PersonState.processEvent()', () => {{ type: 'LIMIT' as const, limit: 2 })- const result = await mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: { ...second },- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(secondUserDistinctId, firstUserDistinctId, teamId, timestamp)expect(result.success).toBe(false)if (result.success) {@@ -3184,7 +3157,7 @@ describe('PersonState.processEvent()', () => {it(`exact limit hit: delete source and do not emit warning`, async () => {mockProducerObserver.resetKafkaProducer()- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {@@ -3205,12 +3178,7 @@ describe('PersonState.processEvent()', () => {{ type: 'LIMIT' as const, limit: 2 })- const result = await mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: { ...second },- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(secondUserDistinctId, firstUserDistinctId, teamId, timestamp)expect(result.success).toBe(true)if (!result.success) {throw new Error('Merge should have succeeded')@@ -3236,11 +3204,11 @@ describe('PersonState.processEvent()', () => {})it(`throws if postgres unavailable`, async () => {- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})- const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {distinctId: secondUserDistinctId,})const state: PersonMergeService = personMergeService({}, hub)@@ -3251,17 +3219,13 @@ describe('PersonState.processEvent()', () => {throw error})- await expect(- state.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: second,- otherPersonDistinctId: secondUserDistinctId,- })- ).rejects.toThrow(error)+ await expect(state.merge(secondUserDistinctId, firstUserDistinctId, teamId, timestamp)).rejects.toThrow(+ error+ )await kafkaProducer.flush()- expect(hub.postgres.transaction).toHaveBeenCalledTimes(1)+ // merge() retries transient failures, so every attempt opens a transaction.+ expect(hub.postgres.transaction).toHaveBeenCalledTimes(3)jest.spyOn(hub.postgres, 'transaction').mockRestore()expect(kafkaProducer.produce).not.toHaveBeenCalled()// verify Postgres persons@@ -3299,9 +3263,9 @@ describe('PersonState.processEvent()', () => {jest.spyOn(kafkaProducer, 'produce')// break postgresconst error = new DependencyUnavailableError('testing', 'Postgres', new Error('test'))- jest.spyOn(state, 'mergePeople').mockImplementation(() => {- throw error- })+ // A rejection, not a synchronous throw: the retry wrapper only+ // catches rejections, matching how the async store fails for real.+ jest.spyOn(state.getContext().personStore, 'mergePersons').mockRejectedValue(error)await expect(state.merge(secondUserDistinctId, firstUserDistinctId, teamId, timestamp)).rejects.toThrow(error@@ -3309,8 +3273,8 @@ describe('PersonState.processEvent()', () => {await kafkaProducer.flush()- expect(state.mergePeople).toHaveBeenCalledTimes(3)- jest.spyOn(state, 'mergePeople').mockRestore()+ expect(state.getContext().personStore.mergePersons).toHaveBeenCalledTimes(3)+ jest.spyOn(state.getContext().personStore, 'mergePersons').mockRestore()expect(kafkaProducer.produce).not.toHaveBeenCalled()// verify Postgres personsconst persons = sortPersons(await fetchPostgresPersonsH())@@ -3356,15 +3320,15 @@ describe('PersonState.processEvent()', () => {jest.spyOn(kafkaProducer, 'produce')// break postgresconst error = new DependencyUnavailableError('testing', 'Postgres', new Error('test'))- jest.spyOn(state, 'mergePeople').mockImplementation(() => {- throw error- })+ // A rejection, not a synchronous throw: the retry wrapper only+ // catches rejections, matching how the async store fails for real.+ jest.spyOn(state.getContext().personStore, 'mergePersons').mockRejectedValue(error)await state.handleIdentifyOrAlias()await kafkaProducer.flush()- expect(state.mergePeople).toHaveBeenCalledTimes(3)- jest.spyOn(state, 'mergePeople').mockRestore()+ expect(state.getContext().personStore.mergePersons).toHaveBeenCalledTimes(3)+ jest.spyOn(state.getContext().personStore, 'mergePersons').mockRestore()expect(kafkaProducer.produce).not.toHaveBeenCalled()// verify Postgres personsconst persons = sortPersons(await fetchPostgresPersonsH())@@ -3702,12 +3666,7 @@ describe('PersonState.processEvent()', () => {})// Attempt to merge persons - this should trigger the retry logic- const result = await mergeService.mergePeople({- mergeInto: person2,- mergeIntoDistinctId: secondUserDistinctId,- otherPerson: person1, // This person "no longer exists"- otherPersonDistinctId: firstUserDistinctId,- })+ const result = await mergeService.merge(firstUserDistinctId, secondUserDistinctId, teamId, timestamp)expect(result.success).toBe(true)if (!result.success) {throw new Error('Merge should have succeeded')@@ -3786,12 +3745,7 @@ describe('PersonState.processEvent()', () => {})// Attempt to merge persons - this should trigger the retry logic- const result = await mergeService.mergePeople({- mergeInto: person2,- mergeIntoDistinctId: secondUserDistinctId,- otherPerson: person1, // This person "no longer exists"- otherPersonDistinctId: firstUserDistinctId,- })+ const result = await mergeService.merge(firstUserDistinctId, secondUserDistinctId, teamId, timestamp)expect(result.success).toBe(true)if (!result.success) {throw new Error('Merge should have succeeded')@@ -3846,7 +3800,17 @@ describe('PersonState.processEvent()', () => {// A concurrent operation tombstones the source after our stale fetch, while an// identity write that raced the tombstone left a live mapping pointing at it.// Without the post-claim source liveness check the merge would move that mapping- // and merge the stale source properties into the target.+ // and merge the stale source properties into the target. The stale fetch is+ // seeded into the store's cache: a fresh fetch filters tombstoned persons, and+ // the race this pins is precisely a fetch that predates the tombstone.+ const staleCacheStore = new BatchWritingPersonsStore(personRepository, createPersonOutputs(kafkaProducer), {+ mergeTombstoneTeamAllowlist: '*',+ })+ staleCacheStore.setCachedPersonForUpdate(+ teamId,+ secondUserDistinctId,+ fromInternalPerson(source, secondUserDistinctId)+ )await hub.postgres.query(PostgresUse.PERSONS_WRITE,'UPDATE posthog_person SET is_deleted = true, version = version + 1 WHERE team_id = $1 AND id = $2',@@ -3867,16 +3831,11 @@ describe('PersonState.processEvent()', () => {mainTeam,createDefaultSyncMergeMode(),undefined,- undefined,+ staleCacheStore,true)- const result = await mergeService.mergePeople({- mergeInto: target,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: source,- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(secondUserDistinctId, firstUserDistinctId, teamId, timestamp)// The retry refreshes by the source distinct id, which no longer resolves to a// live person, so the merge converges to a no-op on the untouched target.@@ -4009,21 +3968,12 @@ describe('PersonState.processEvent()', () => {})it('tombstone-mode merge stamps the exact death version on the source row and its death message', async () => {- const target = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})- const source = await createPerson(- hub,- timestamp,- { plan: 'pro' },- {},- {},- teamId,- null,- false,- secondUserUuid,- { distinctId: secondUserDistinctId }- )+ await createPerson(hub, timestamp, { plan: 'pro' }, {}, {}, teamId, null, false, secondUserUuid, {+ distinctId: secondUserDistinctId,+ })const producerObserver = new KafkaProducerObserver(kafkaProducer)// The delete mode is a repository option, separate from the context flag.@@ -4048,12 +3998,7 @@ describe('PersonState.processEvent()', () => {true)- const result = await mergeService.mergePeople({- mergeInto: target,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: source,- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(secondUserDistinctId, firstUserDistinctId, teamId, timestamp)expect(result.success).toBe(true)if (!result.success) {throw new Error('Merge should have succeeded')@@ -4084,7 +4029,7 @@ describe('PersonState.processEvent()', () => {describe('SYNC mode with batch processing', () => {it('merges all distinct IDs when batch size is larger than total distinct IDs', async () => {- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {@@ -4104,12 +4049,7 @@ describe('PersonState.processEvent()', () => {jest.spyOn(repo, 'moveDistinctIds')- const result = await mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: second,- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(secondUserDistinctId, firstUserDistinctId, teamId, timestamp)expect(result.success).toBe(true)if (!result.success) {@@ -4133,7 +4073,7 @@ describe('PersonState.processEvent()', () => {})it('merges all distinct IDs in multiple batches when batch size is smaller than total', async () => {- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {@@ -4155,12 +4095,7 @@ describe('PersonState.processEvent()', () => {jest.spyOn(repo, 'moveDistinctIds')- const result = await mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: second,- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(secondUserDistinctId, firstUserDistinctId, teamId, timestamp)expect(result.success).toBe(true)if (!result.success) {@@ -4191,7 +4126,7 @@ describe('PersonState.processEvent()', () => {})it('handles edge case with batch size of 1', async () => {- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {@@ -4210,12 +4145,7 @@ describe('PersonState.processEvent()', () => {jest.spyOn(repo, 'moveDistinctIds')- const result = await mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: second,- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(secondUserDistinctId, firstUserDistinctId, teamId, timestamp)expect(result.success).toBe(true)if (!result.success) {throw new Error('Merge should have succeeded')@@ -4238,7 +4168,7 @@ describe('PersonState.processEvent()', () => {})it('handles SYNC mode with undefined batch size (unlimited)', async () => {- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {@@ -4259,12 +4189,7 @@ describe('PersonState.processEvent()', () => {jest.spyOn(repo, 'moveDistinctIds')- const result = await mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: second,- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(secondUserDistinctId, firstUserDistinctId, teamId, timestamp)expect(result.success).toBe(true)if (!result.success) {@@ -4313,7 +4238,7 @@ describe('PersonState.processEvent()', () => {describe('SYNC mode', () => {it('merges all distinct IDs in unlimited batches when batchSize is undefined', async () => {- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {@@ -4339,12 +4264,12 @@ describe('PersonState.processEvent()', () => {)jest.spyOn(repo, 'moveDistinctIds')- const result = await mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: second,- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(+ secondUserDistinctId,+ firstUserDistinctId,+ teamId,+ timestamp+ )expect(result.success).toBe(true)if (!result.success) {@@ -4370,7 +4295,7 @@ describe('PersonState.processEvent()', () => {})it('merges distinct IDs in specified batches when batchSize is set', async () => {- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {@@ -4396,12 +4321,12 @@ describe('PersonState.processEvent()', () => {)jest.spyOn(repo, 'moveDistinctIds')- const result = await mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: second,- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(+ secondUserDistinctId,+ firstUserDistinctId,+ teamId,+ timestamp+ )expect(result.success).toBe(true)if (!result.success) {@@ -4427,7 +4352,7 @@ describe('PersonState.processEvent()', () => {})it('merges distinct IDs when count exactly equals batch size', async () => {- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {@@ -4452,12 +4377,12 @@ describe('PersonState.processEvent()', () => {)jest.spyOn(repo, 'moveDistinctIds')- const result = await mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: second,- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(+ secondUserDistinctId,+ firstUserDistinctId,+ teamId,+ timestamp+ )expect(result.success).toBe(true)if (!result.success) {@@ -4484,7 +4409,7 @@ describe('PersonState.processEvent()', () => {describe('LIMIT mode', () => {it('successfully merges when distinct ID count is within limit', async () => {- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {@@ -4508,12 +4433,12 @@ describe('PersonState.processEvent()', () => {limitMode)- const result = await mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: second,- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(+ secondUserDistinctId,+ firstUserDistinctId,+ teamId,+ timestamp+ )expect(result.success).toBe(true)if (!result.success) {@@ -4535,7 +4460,7 @@ describe('PersonState.processEvent()', () => {})it('fails with PersonMergeLimitExceededError when distinct ID count exceeds limit', async () => {- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {@@ -4560,12 +4485,12 @@ describe('PersonState.processEvent()', () => {limitMode)- const result = await mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: second,- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(+ secondUserDistinctId,+ firstUserDistinctId,+ teamId,+ timestamp+ )expect(result.success).toBe(false)if (result.success) {@@ -4588,7 +4513,7 @@ describe('PersonState.processEvent()', () => {})it('successfully merges when distinct ID count exactly equals limit', async () => {- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {@@ -4612,12 +4537,12 @@ describe('PersonState.processEvent()', () => {limitMode)- const result = await mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: second,- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(+ secondUserDistinctId,+ firstUserDistinctId,+ teamId,+ timestamp+ )expect(result.success).toBe(true)if (!result.success) {@@ -4641,7 +4566,7 @@ describe('PersonState.processEvent()', () => {describe('ASYNC mode', () => {it('successfully merges when distinct ID count is within limit', async () => {- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {@@ -4664,12 +4589,12 @@ describe('PersonState.processEvent()', () => {asyncMode)- const result = await mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: second,- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(+ secondUserDistinctId,+ firstUserDistinctId,+ teamId,+ timestamp+ )expect(result.success).toBe(true)if (!result.success) {@@ -4690,7 +4615,7 @@ describe('PersonState.processEvent()', () => {})it('fails with PersonMergeLimitExceededError when distinct ID count exceeds limit', async () => {- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {@@ -4715,12 +4640,12 @@ describe('PersonState.processEvent()', () => {asyncMode)- const result = await mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: second,- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(+ secondUserDistinctId,+ firstUserDistinctId,+ teamId,+ timestamp+ )expect(result.success).toBe(false)if (result.success) {@@ -4743,7 +4668,7 @@ describe('PersonState.processEvent()', () => {})it('successfully merges when distinct ID count exactly equals limit', async () => {- const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {distinctId: firstUserDistinctId,})const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {@@ -4767,12 +4692,12 @@ describe('PersonState.processEvent()', () => {asyncMode)- const result = await mergeService.mergePeople({- mergeInto: first,- mergeIntoDistinctId: firstUserDistinctId,- otherPerson: second,- otherPersonDistinctId: secondUserDistinctId,- })+ const result = await mergeService.merge(+ secondUserDistinctId,+ firstUserDistinctId,+ teamId,+ timestamp+ )expect(result.success).toBe(true)if (!result.success) {@@ -4799,6 +4724,7 @@ describe('PersonState.processEvent()', () => {const fullEvent = {team_id: teamId,properties: {},+ uuid: 'event-uuid',...event,}@@ -4826,7 +4752,7 @@ describe('PersonState.processEvent()', () => {return processor}- it('SYNC mode throws PersonMergeLimitExceededError when limit exceeded', async () => {+ it('SYNC mode routes the event to the DLQ when the saga-side limit is exceeded', async () => {const syncMode = { type: 'SYNC' as const, batchSize: undefined }const processor = createPersonEventProcessor(syncMode, {event: '$identify',@@ -4846,8 +4772,19 @@ describe('PersonState.processEvent()', () => {error: new PersonMergeLimitExceededError('person_merge_move_limit_hit'),})- // In SYNC mode, this should throw the error- await expect(processor.processEvent()).rejects.toThrow('person_merge_move_limit_hit')+ // The Postgres world cannot produce this in SYNC mode, but the+ // personhog saga's move limit can; the event goes to the DLQ —+ // payload preserved for replay once the limit is raised or+ // chunked moves land — rather than being dropped or failing+ // the batch into a redelivery loop.+ const result = await processor.processEvent()+ expect(result.type).toBe(PipelineResultType.DLQ)+ expect(result.warnings).toEqual([+ expect.objectContaining({+ type: 'merge_move_limit_exceeded',+ details: expect.objectContaining({ eventUuid: expect.any(String) }),+ }),+ ])})it('LIMIT mode returns DLQ result when limit exceeded', async () => {diff --git a/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md b/products/ingestion/skills/resolving-ingestion-warnings/SKILL.mdindex 32152cce577b..7f6f3c0d1016 100644--- a/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md+++ b/products/ingestion/skills/resolving-ingestion-warnings/SKILL.md@@ -48,11 +48,13 @@ Those decisions come only from this skill's guidance and your own reasoning.### Person merges (`merge`)-| Type | What happened | Fix |-| --------------------------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `cannot_merge_already_identified` | Merge refused: both persons are already identified. The accounts silently stayed separate | Read [references/fixing-cannot-merge-already-identified.md](references/fixing-cannot-merge-already-identified.md) — covers the identify/reset flow fixes; joining two identified users is a manual one-off decision, never application code |-| `cannot_merge_with_illegal_distinct_id` | Merge refused: the distinct ID is a placeholder (`undefined`, `null`, `[object Object]`, `anonymous`, …) | Read [references/fixing-invalid-distinct-ids.md](references/fixing-invalid-distinct-ids.md) — a variable is unset at the identify/alias callsite |-| `merge_race_condition` | Concurrent merges collided on the same persons; the operation was dropped | Read [references/fixing-merge-race-condition.md](references/fixing-merge-race-condition.md) — dedupe parallel identify calls, and check for a "mega person" merge magnet (thousands of distinct IDs on one person) |+| Type | What happened | Fix |+| --------------------------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `cannot_merge_already_identified` | Merge refused: both persons are already identified. The accounts silently stayed separate | Read [references/fixing-cannot-merge-already-identified.md](references/fixing-cannot-merge-already-identified.md) — covers the identify/reset flow fixes; joining two identified users is a manual one-off decision, never application code |+| `cannot_merge_with_illegal_distinct_id` | Merge refused: the distinct ID is a placeholder (`undefined`, `null`, `[object Object]`, `anonymous`, …) | Read [references/fixing-invalid-distinct-ids.md](references/fixing-invalid-distinct-ids.md) — a variable is unset at the identify/alias callsite |+| `merge_race_condition` | Concurrent merges collided on the same persons; the operation was dropped | Read [references/fixing-merge-race-condition.md](references/fixing-merge-race-condition.md) — dedupe parallel identify calls, and check for a "mega person" merge magnet (thousands of distinct IDs on one person) |+| `merge_move_limit_exceeded` | Merge dropped: the source person has more distinct IDs than one merge may move | A "mega person" merge magnet has accumulated thousands of distinct IDs. Same diagnosis as `merge_race_condition`: find the magnet and stop identifying against it |+| `merge_settled_failure` | The merge settled on a verdict that merged nothing, and the verdict is recorded so a retry cannot change it | Rare and not caller-fixable. Check whether the identity service is healthy; the accounts stay separate and a later identify under a fresh event uuid can still merge them |### Event validation (`event`)diff --git a/rust/common/ingestion_warnings/warning_types.generated.json b/rust/common/ingestion_warnings/warning_types.generated.jsonindex ce5482ad312b..9bf6611378b3 100644--- a/rust/common/ingestion_warnings/warning_types.generated.json+++ b/rust/common/ingestion_warnings/warning_types.generated.json@@ -199,12 +199,24 @@"severity": "error","captureProduced": true},+ {+ "type": "merge_move_limit_exceeded",+ "category": "merge",+ "severity": "error",+ "captureProduced": false+ },{"type": "merge_race_condition","category": "merge","severity": "error","captureProduced": false},+ {+ "type": "merge_settled_failure",+ "category": "merge",+ "severity": "error",+ "captureProduced": false+ },{"type": "message_contained_no_valid_rrweb_events","category": "replay",