: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
fix(ingestion): stop blocking refused merges on the warning ack (#88730)
Nick Best101fa66ce9b2
diff --git a/nodejs/src/ingestion/common/persons/person-merge-service.test.ts b/nodejs/src/ingestion/common/persons/person-merge-service.test.tsnew file mode 100644index 000000000000..0cc3c5a7fe0b--- /dev/null+++ b/nodejs/src/ingestion/common/persons/person-merge-service.test.ts@@ -0,0 +1,94 @@+import { DateTime } from 'luxon'++import { INGESTION_WARNINGS_OUTPUT } from '~/common/outputs'+import { InternalPerson } from '~/types'++import { PersonContext } from './person-context'+import { PersonMergeService } from './person-merge-service'+import { 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: {},+ }+ }++ describe('mergePeople with an already identified source', () => {+ let teamId: number+ let queueMessages: jest.Mock++ beforeEach(() => {+ teamId = teamCounter+++ queueMessages = jest.fn().mockResolvedValue(undefined)+ })++ function refuseMerge(targetDistinctId: string) {+ const context = new PersonContext(+ { uuid: 'event-uuid', event: '$identify', distinct_id: targetDistinctId, properties: {} } as any,+ { id: teamId } as any,+ targetDistinctId,+ DateTime.now(),+ true,+ { queueMessages } as any,+ {} as any,+ 0,+ createDefaultSyncMergeMode(),+ false,+ false+ )+ return new PersonMergeService(context).mergePeople({+ mergeInto: person('target-uuid', true, teamId),+ mergeIntoDistinctId: targetDistinctId,+ otherPerson: person('source-uuid', true, teamId),+ otherPersonDistinctId: 'source',+ })+ }++ it('returns before the warning is acked and hands the ack back as kafkaAck', async () => {+ let ackWarning!: () => void+ queueMessages.mockReturnValue(new Promise<void>((resolve) => (ackWarning = resolve)))++ const result = await refuseMerge('target')++ expect(result).toMatchObject({ success: true, needsPersonUpdate: true })+ if (!result.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))+ await Promise.resolve()+ expect(acked).toBe(false)++ ackWarning()+ await result.kafkaAck+ expect(acked).toBe(true)+ })++ it('does not fail the event when the warning produce fails', async () => {+ queueMessages.mockRejectedValue(new Error('broker down'))++ const result = await refuseMerge('target')++ expect(result.success).toBe(true)+ if (result.success) {+ await expect(result.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 d4ee00680b45..99e0407ee092 100644--- a/nodejs/src/ingestion/common/persons/person-merge-service.ts+++ b/nodejs/src/ingestion/common/persons/person-merge-service.ts@@ -701,7 +701,7 @@ export class PersonMergeService {// If merge isn't allowed, we will ignore it, log an ingestion warning and return success with original personif (!mergeAllowed) {- await emitIngestionWarning(this.context.outputs, this.context.team.id, {+ const warningAck = emitIngestionWarning(this.context.outputs, this.context.team.id, {type: 'cannot_merge_already_identified',details: {sourcePersonDistinctId: otherPersonDistinctId,@@ -713,11 +713,11 @@ export class PersonMergeService {},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, Promise.resolve(), true)+ return mergeSuccess(mergeInto, warningAck, true)}// How the merge works: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 df59af0e8c16..ce785bcf5325 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@@ -8,6 +8,7 @@ import {KAFKA_PERSON_DISTINCT_ID,KAFKA_PERSON_MERGE_EVENTS,} from '~/common/config/kafka-topics'+import { TopicMessage } from '~/common/kafka/producer'import { INGESTION_WARNINGS_OUTPUT } from '~/common/outputs'import { ASYNC_OUTPUT } from '~/common/outputs'import { PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT, PERSON_MERGE_EVENTS_OUTPUT } from '~/common/outputs'@@ -17,6 +18,7 @@ import { PostgresPersonRepository } from '~/common/persons/repositories/postgresimport { fetchDistinctIdValues, fetchDistinctIds } from '~/common/persons/repositories/test-helpers'import { PostgresUse } from '~/common/utils/db/postgres'import { normalizeEvent, normalizeProcessPerson } from '~/common/utils/event'+import { parseJSON } from '~/common/utils/json-parse'import { UUIDT } from '~/common/utils/utils'import { BatchWritingPersonsStore } from '~/ingestion/common/persons/batch-writing-person-store'import { PersonOutputs } from '~/ingestion/common/persons/person-context'@@ -311,6 +313,75 @@ describe('createProcessPersonsStep', () => {}})+ it('returns a refused merge before its warning is acked and defers the ack to the side effects', async () => {+ for (const distinctId of ['identified-source', 'target']) {+ const created = await personRepository.createPerson(+ DateTime.utc(),+ {},+ {},+ {},+ teamId,+ null,+ true,+ new UUIDT().toString(),+ { distinctId }+ )+ expect(created.success).toBe(true)+ }++ let ackWarning!: () => void+ const heldWarning = new Promise<void>((resolve) => (ackWarning = resolve))+ const topicOf = (batch: TopicMessage | TopicMessage[]) => (Array.isArray(batch) ? batch[0] : batch).topic+ const queueMessages = jest.spyOn(mockProducer, 'queueMessages').mockImplementation((batch) => {+ return topicOf(batch) === KAFKA_INGESTION_WARNINGS ? heldWarning : Promise.resolve()+ })++ try {+ const step = createProcessPersonsStep(options, personOutputs)+ const result = await step(+ createInput({+ normalizedEvent: {+ ...pluginEvent,+ event: '$identify',+ distinct_id: 'target',+ properties: { $anon_distinct_id: 'identified-source' },+ },+ })+ )++ expect(isOkResult(result)).toBe(true)+ if (!isOkResult(result)) {+ return+ }++ const warningBatches = queueMessages.mock.calls+ .map(([batch]) => (Array.isArray(batch) ? batch[0] : batch))+ .filter((batch) => batch.topic === KAFKA_INGESTION_WARNINGS)+ expect(warningBatches).toHaveLength(1)+ expect(parseJSON(warningBatches[0].messages[0].value!.toString())).toMatchObject({+ team_id: teamId,+ type: 'cannot_merge_already_identified',+ })++ let settled = false+ void Promise.all(result.sideEffects).then(() => (settled = true))+ await new Promise((resolve) => setImmediate(resolve))+ expect(settled).toBe(false)++ ackWarning()+ await Promise.all(result.sideEffects)+ expect(settled).toBe(true)+ } finally {+ queueMessages.mockRestore()+ }++ const persons = await fetchPostgresPersons(infra.postgres, teamId)+ expect(persons).toHaveLength(2)+ for (const person of persons) {+ expect(await fetchDistinctIdValues(infra.postgres, person)).toHaveLength(1)+ }+ })+it('does not update last_seen_at when person_last_seen_at_enabled is not set', async () => {await createPersonWithDistinctIds('my_id')