Skip to content

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

feat(ingestion): leave settled merge verdict warnings to the identity service in personhog mode (#118123)

Nick Best9e40459449fa
diff --git a/nodejs/src/ingestion/common/persons/person-context.ts b/nodejs/src/ingestion/common/persons/person-context.ts
index 5d2f2ab9bffe..a61612ca781b 100644
--- a/nodejs/src/ingestion/common/persons/person-context.ts
+++ b/nodejs/src/ingestion/common/persons/person-context.ts
@@ -40,7 +40,9 @@ export class PersonContext {
public readonly updateAllProperties: boolean = false, // When true, all property changes trigger person updates
public readonly shouldUpdateLastSeenAt: boolean = false,
/** Fold plan shared by this event's consecutive $identify run; see person-merge-fold.ts. */
- public readonly mergeFoldPlan?: MergeFoldPlan
+ public readonly mergeFoldPlan?: MergeFoldPlan,
+ /** The personhog identity service publishes the merge verdict warnings it settles, so this consumer must not. */
+ public readonly identityEmitsMergeWarnings: boolean = false
) {
this.eventProperties = event.properties!
}
diff --git a/nodejs/src/ingestion/common/persons/person-merge-service.test.ts b/nodejs/src/ingestion/common/persons/person-merge-service.test.ts
index 896c82612ed6..a749b0605f59 100644
--- a/nodejs/src/ingestion/common/persons/person-merge-service.test.ts
+++ b/nodejs/src/ingestion/common/persons/person-merge-service.test.ts
@@ -28,7 +28,7 @@ import {
TargetPersonNotFoundError,
createDefaultSyncMergeMode,
} from './person-merge-types'
-import { MergePersonsOutcome, MergePersonsResult } from './persons-store'
+import { MergePersonsOutcome, MergePersonsResult, PersonsBackend } from './persons-store'
import { PersonsStoreForBatch } from './persons-store-for-batch'
const counterTotal = async (counter: { get: () => Promise<{ values: { value: number }[] }> }): Promise<number> =>
@@ -54,10 +54,15 @@ describe('PersonMergeService store-owned merges', () => {
let store: {
mergePersons: jest.Mock
fetchForUpdate: jest.Mock
+ backend?: PersonsBackend
}
let outputs: { queueMessages: jest.Mock }
- const makeService = (eventName = '$identify', mergeFoldPlan?: MergeFoldPlan) => {
+ const makeService = (
+ eventName = '$identify',
+ mergeFoldPlan?: MergeFoldPlan,
+ identityEmitsMergeWarnings = false
+ ) => {
const event = {
event: eventName,
uuid: 'event-uuid',
@@ -82,7 +87,8 @@ describe('PersonMergeService store-owned merges', () => {
createDefaultSyncMergeMode(),
false,
false,
- mergeFoldPlan
+ mergeFoldPlan,
+ identityEmitsMergeWarnings
)
return new PersonMergeService(context)
}
@@ -659,6 +665,134 @@ describe('PersonMergeService store-owned merges', () => {
})
})
+ describe('when the identity service publishes the verdict warnings', () => {
+ const warnedTypes = (): string[] =>
+ outputs.queueMessages.mock.calls
+ .flat(3)
+ .filter((entry: any) => entry?.value)
+ .map((entry: any) => parseJSON(Buffer.from(entry.value).toString()).type)
+
+ beforeEach(() => {
+ store.backend = 'personhog'
+ })
+
+ it.each(['skipped_already_identified', 'skipped_illegal', 'skipped_race', 'skipped_refused', 'error'])(
+ 'a settled %s verdict acks without a consumer-side warning',
+ async (outcome) => {
+ store.mergePersons.mockResolvedValue(result(outcome as MergePersonsOutcome))
+ const service = makeService('$identify', undefined, true)
+
+ const mergeResult = await service.merge('anon-1', 'd1', 1, timestamp)
+
+ expect(mergeResult.success).toBe(true)
+ expect(warnedTypes()).toEqual([])
+ }
+ )
+
+ it('a settled conflict still counts the drop but leaves the warning to the identity service', async () => {
+ store.mergePersons.mockResolvedValue({
+ survivor: null,
+ results: [{ sourceDistinctId: 'anon-1', outcome: 'skipped_conflict' as const, settled: true }],
+ })
+ mergeClaimDroppedCounter.reset()
+ const service = makeService('$identify', undefined, true)
+
+ await service.merge('anon-1', 'd1', 1, timestamp)
+
+ expect(warnedTypes()).toEqual([])
+ expect(await counterTotal(mergeClaimDroppedCounter)).toBe(1)
+ })
+
+ it.each([
+ [
+ 'an unsettled conflict that outlasts every retry',
+ () =>
+ store.mergePersons.mockResolvedValue({
+ survivor: null,
+ results: [{ sourceDistinctId: 'anon-1', outcome: 'skipped_conflict' as const, settled: false }],
+ }),
+ 'merge_race_condition',
+ ],
+ [
+ 'a call that fails with no verdict',
+ () =>
+ store.mergePersons.mockRejectedValue(
+ new PersonMergeCallFailedError('no verdict', new Error('transport'))
+ ),
+ 'merge_settled_failure',
+ ],
+ [
+ 'a raw refusal',
+ () =>
+ store.mergePersons.mockRejectedValue(
+ new ConnectError(
+ 'op_id was already used for a different request',
+ Code.FailedPrecondition,
+ new Headers({ 'x-semantic-refusal': 'op_id_reused' })
+ )
+ ),
+ 'merge_settled_failure',
+ ],
+ [
+ 'a verdict this build cannot name',
+ () => store.mergePersons.mockResolvedValue(result('unknown')),
+ 'merge_settled_failure',
+ ],
+ ])('%s still warns from the consumer', async (_label, arrange, warningType) => {
+ arrange()
+ const service = makeService('$identify', undefined, true)
+
+ await service.handleIdentifyOrAlias()
+
+ expect(warnedTypes()).toContain(warningType)
+ })
+
+ it('an unmergeable id is still refused and warned before any call', async () => {
+ const service = makeService('$identify', undefined, true)
+
+ await service.merge('anon\u0000one', 'd1', 1, timestamp)
+
+ expect(store.mergePersons).not.toHaveBeenCalled()
+ expect(warnedTypes()).toContain('cannot_merge_with_illegal_distinct_id')
+ })
+
+ it('the setting is inert on the postgres backend', async () => {
+ store.backend = 'postgres'
+ store.mergePersons.mockResolvedValue(result('skipped_already_identified'))
+ const service = makeService('$identify', undefined, true)
+
+ await service.merge('anon-1', 'd1', 1, timestamp)
+
+ expect(warnedTypes()).toContain('cannot_merge_already_identified')
+ })
+
+ it('a fold leaves its settled verdicts to the identity service and still counts them', async () => {
+ const before = await counterTotal(mergeSettledFailureCounter)
+ store.mergePersons.mockResolvedValue({
+ survivor,
+ results: [
+ { sourceDistinctId: 'anon-1', outcome: 'skipped_already_identified' },
+ { sourceDistinctId: 'anon-2', outcome: 'error' },
+ ],
+ })
+ const plan: MergeFoldPlan = {
+ targetDistinctId: 'd1',
+ pairs: [
+ { anonDistinctId: 'anon-1', eventUuid: 'event-uuid' },
+ { anonDistinctId: 'anon-2', eventUuid: 'event-uuid-2' },
+ ],
+ status: 'planned',
+ }
+ const service = makeService('$identify', plan, true)
+
+ await service.handleIdentifyOrAlias()
+
+ expect(plan.status).toBe('executed')
+ expect(warnedTypes()).toEqual([])
+ expect(await counterTotal(mergeSettledFailureCounter)).toBe(before + 1)
+ })
+ })
+
describe('non-blocking warning acks', () => {
it('an unmergeable id returns before the warning is acked and hands the ack back', async () => {
let ackWarning!: () => void
diff --git a/nodejs/src/ingestion/common/persons/person-merge-service.ts b/nodejs/src/ingestion/common/persons/person-merge-service.ts
index 2df4f836054b..6eebb9207623 100644
--- a/nodejs/src/ingestion/common/persons/person-merge-service.ts
+++ b/nodejs/src/ingestion/common/persons/person-merge-service.ts
@@ -97,6 +97,16 @@ function foldAbandonReason(error: unknown): MergeFoldAbortReason {
export class PersonMergeService {
constructor(private context: PersonContext) {}
+ /**
+ * Settled verdicts the identity service decides alone are its warnings
+ * to publish; emitting them here too would show each refusal twice.
+ * Unsettled conflicts, call failures, raw refusals and unknown verdicts
+ * stay here, because only this side knows its retries and policy.
+ */
+ private identityOwnsVerdictWarnings(): boolean {
+ return this.context.personStore.backend === 'personhog' && this.context.identityEmitsMergeWarnings
+ }
+
async handleIdentifyOrAlias(): Promise<PersonMergeResult> {
/**
* strategy:
@@ -551,19 +561,21 @@ export class PersonMergeService {
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,
- })
+ const warningAck = this.identityOwnsVerdictWarnings()
+ ? Promise.resolve()
+ : 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',
@@ -578,11 +590,13 @@ export class PersonMergeService {
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
- )
+ const warningAck = this.identityOwnsVerdictWarnings()
+ ? Promise.resolve()
+ : this.emitIllegalDistinctIdWarning(
+ otherPersonDistinctId,
+ mergeIntoDistinctId,
+ this.context.event.uuid
+ )
return mergeSuccess(
survivor,
Promise.all([kafkaAck, warningAck]).then(() => undefined),
@@ -594,19 +608,21 @@ export class PersonMergeService {
// A rival operation kept the persons through every retry;
// the merge drops with pg's race warning.
mergeClaimDroppedCounter.labels({ call: this.context.event.event }).inc()
- 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,
- })
+ const warningAck = this.identityOwnsVerdictWarnings()
+ ? Promise.resolve()
+ : 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,
+ })
logger.warn('🤔', 'merge race condition detected, too many concurrent merges', {
team_id: this.context.team.id,
})
@@ -641,21 +657,24 @@ export class PersonMergeService {
if (outcome !== 'unknown') {
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,
- // Both travel because each backend names the person
- // differently.
- otherPersonId: sourceResult.sourcePersonUuid,
- sourcePersonId: sourceResult.sourcePersonId,
- outcome,
- },
- pipelineStep: 'person-merge',
- })
+ const warningAck =
+ outcome !== 'unknown' && this.identityOwnsVerdictWarnings()
+ ? Promise.resolve()
+ : emitIngestionWarning(this.context.outputs, this.context.team.id, {
+ type: 'merge_settled_failure',
+ details: {
+ sourcePersonDistinctId: otherPersonDistinctId,
+ targetPersonDistinctId: mergeIntoDistinctId,
+ distinctId: mergeIntoDistinctId,
+ eventUuid: this.context.event.uuid,
+ // Both travel because each backend names the person
+ // differently.
+ otherPersonId: sourceResult.sourcePersonUuid,
+ sourcePersonId: sourceResult.sourcePersonId,
+ outcome,
+ },
+ pipelineStep: 'person-merge',
+ })
logger.warn(
'🤔',
outcome === 'unknown'
@@ -687,10 +706,14 @@ export class PersonMergeService {
// Produces are collected and awaited together so a plan full of
// refused pairs does not serialize warning round-trips.
const warningAcks: Promise<unknown>[] = []
+ const identityOwnsWarnings = this.identityOwnsVerdictWarnings()
for (const sourceResult of results) {
const eventUuid = eventUuidBySource.get(sourceResult.sourceDistinctId) ?? this.context.event.uuid
switch (sourceResult.outcome) {
case 'skipped_already_identified':
+ if (identityOwnsWarnings) {
+ break
+ }
warningAcks.push(
emitIngestionWarning(this.context.outputs, this.context.team.id, {
type: 'cannot_merge_already_identified',
@@ -708,6 +731,9 @@ export class PersonMergeService {
)
break
case 'skipped_illegal':
+ if (identityOwnsWarnings) {
+ break
+ }
warningAcks.push(
this.emitIllegalDistinctIdWarning(
sourceResult.sourceDistinctId,
@@ -721,6 +747,9 @@ export class PersonMergeService {
// The same drop the single-source path counts; skipping
// it here makes the drop rate read low by the folded share.
mergeClaimDroppedCounter.labels({ call: this.context.event.event }).inc()
+ if (identityOwnsWarnings) {
+ break
+ }
warningAcks.push(
emitIngestionWarning(this.context.outputs, this.context.team.id, {
type: 'merge_race_condition',
@@ -741,6 +770,9 @@ export class PersonMergeService {
// answer; a fold must record the settled failure or the
// loss is invisible.
mergeSettledFailureCounter.inc()
+ if (identityOwnsWarnings) {
+ break
+ }
warningAcks.push(
emitIngestionWarning(this.context.outputs, this.context.team.id, {
type: 'merge_settled_failure',
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.ts
index 777b22848e71..9e8eb719c98b 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
@@ -5,6 +5,7 @@ export interface EventPipelineRunnerOptions {
PERSON_MERGE_SYNC_BATCH_SIZE: number
PERSON_MERGE_FOLD_ENABLED: boolean
PERSON_MERGE_FOLD_TEAM_ALLOWLIST: string
+ PERSONHOG_IDENTITY_EMITS_MERGE_WARNINGS: boolean
PERSON_JSONB_SIZE_ESTIMATE_ENABLE: number
PERSON_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.ts
index b7b0eabdf6af..09e6cee17cc0 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
@@ -62,7 +62,8 @@ export function createProcessPersonsStep<TInput extends ProcessPersonsInput>(
mergeMode,
options.PERSON_PROPERTIES_UPDATE_ALL,
shouldUpdateLastSeenAt,
- input.mergeFold.type === 'planned' ? input.mergeFold.plan : undefined
+ input.mergeFold.type === 'planned' ? input.mergeFold.plan : undefined,
+ options.PERSONHOG_IDENTITY_EMITS_MERGE_WARNINGS
)
const processor = new PersonEventProcessor(
diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.ts
index cec046dd58f4..6a532e14c79d 100644
--- a/nodejs/src/ingestion/config.ts
+++ b/nodejs/src/ingestion/config.ts
@@ -175,6 +175,7 @@ export type IngestionConsumerConfig = {
// The saga's per-source move guard in SYNC mode; an over-limit source
// comes back skipped_move_limit for the merge-mode policy.
PERSONHOG_SYNC_MERGE_MOVE_LIMIT: number
+ PERSONHOG_IDENTITY_EMITS_MERGE_WARNINGS: boolean
// Kill switch for emitting person_merge_events to the cohort-stream-processor.
// Enable ordering: (1) create the topic, (2) set INGESTION_OUTPUT_PERSON_MERGE_EVENTS_TOPIC
// (startup topic verification is then fatal by design), (3) flip this on. Flipping this on before
@@ -368,6 +369,7 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {
PERSON_MERGE_ASYNC_ENABLED: false,
PERSON_MERGE_SYNC_BATCH_SIZE: 0,
PERSONHOG_SYNC_MERGE_MOVE_LIMIT: 10_000,
+ PERSONHOG_IDENTITY_EMITS_MERGE_WARNINGS: false,
PERSON_MERGE_EVENTS_ENABLED: false,
PERSON_MERGE_EVENTS_PARTITION_COUNT: 64,
PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: '2',
diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.ts
index a2b238a0e6cd..4cc94a1a1583 100644
--- a/nodejs/src/ingestion/ingestion-consumer.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.ts
@@ -317,6 +317,7 @@ export class IngestionConsumer {
PERSON_MERGE_SYNC_BATCH_SIZE: this.config.PERSON_MERGE_SYNC_BATCH_SIZE,
PERSON_MERGE_FOLD_ENABLED: this.config.PERSON_MERGE_FOLD_ENABLED,
PERSON_MERGE_FOLD_TEAM_ALLOWLIST: this.config.PERSON_MERGE_FOLD_TEAM_ALLOWLIST,
+ PERSONHOG_IDENTITY_EMITS_MERGE_WARNINGS: this.config.PERSONHOG_IDENTITY_EMITS_MERGE_WARNINGS,
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.ts
index 774fa3cafd2f..0808abe704dd 100644
--- a/nodejs/src/servers/ingestion-api-server.ts
+++ b/nodejs/src/servers/ingestion-api-server.ts
@@ -436,6 +436,7 @@ export class IngestionApiServer implements NodeServer {
PERSON_MERGE_SYNC_BATCH_SIZE: this.config.PERSON_MERGE_SYNC_BATCH_SIZE,
PERSON_MERGE_FOLD_ENABLED: this.config.PERSON_MERGE_FOLD_ENABLED,
PERSON_MERGE_FOLD_TEAM_ALLOWLIST: this.config.PERSON_MERGE_FOLD_TEAM_ALLOWLIST,
+ PERSONHOG_IDENTITY_EMITS_MERGE_WARNINGS: this.config.PERSONHOG_IDENTITY_EMITS_MERGE_WARNINGS,
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.ts
index c01e92b620f1..8fc9c7c8dba8 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
@@ -54,6 +54,7 @@ describe('createProcessPersonsStep', () => {
PERSON_MERGE_SYNC_BATCH_SIZE: 1,
PERSON_MERGE_FOLD_ENABLED: false,
PERSON_MERGE_FOLD_TEAM_ALLOWLIST: '*',
+ PERSONHOG_IDENTITY_EMITS_MERGE_WARNINGS: false,
PERSON_JSONB_SIZE_ESTIMATE_ENABLE: 0,
PERSON_PROPERTIES_UPDATE_ALL: false,
FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: '*',