: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
refactor(cohorts): isolate person_merge_events topic producer (#69529)
Matheus Batista6b4d37f01760
diff --git a/nodejs/src/ingestion/common/persons/person-context.test.ts b/nodejs/src/ingestion/common/persons/person-context.test.tsindex 2da7ecc29dd6..fd7c6bfb958b 100644--- a/nodejs/src/ingestion/common/persons/person-context.test.ts+++ b/nodejs/src/ingestion/common/persons/person-context.test.ts@@ -5,7 +5,7 @@ import { PERSON_MERGE_EVENTS_OUTPUT } from '~/common/outputs'import { UUIDT } from '~/common/utils/utils'import { InternalPerson } from '~/types'-import { MergeEventsConfig, PersonContext } from './person-context'+import { MergeEventsConfig, PersonContext, personMergeEventProducedCounter } from './person-context'import { createDefaultSyncMergeMode } from './person-merge-types'describe('PersonContext', () => {@@ -91,4 +91,22 @@ describe('PersonContext', () => {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 a3ab84eb52fd..e9bd7cec57d0 100644--- a/nodejs/src/ingestion/common/persons/person-context.ts+++ b/nodejs/src/ingestion/common/persons/person-context.ts@@ -1,4 +1,5 @@import { DateTime } from 'luxon'+import { Counter } from 'prom-client'import {IngestionWarningsOutput,@@ -9,6 +10,7 @@ import {} 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'@@ -16,6 +18,11 @@ import { buildPersonMergeEventMessage } from './person-merge-event'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>@@ -78,26 +85,38 @@ export class PersonContext {}/**- * Emit a person_merge_events message for the cohort-stream-processor. Resolved no-op when the- * gate is off or the team is outside the allowlist. The message is explicitly partitioned by+ * 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}- 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,- })+ 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-merge-event.ts b/nodejs/src/ingestion/common/persons/person-merge-event.tsindex fb2897f76bc1..0e14e5118377 100644--- a/nodejs/src/ingestion/common/persons/person-merge-event.ts+++ b/nodejs/src/ingestion/common/persons/person-merge-event.ts@@ -1,4 +1,5 @@import { murmur2Partition } from '~/common/kafka/murmur2'+import { logger } from '~/common/utils/logger'/*** Wire shape of a committed `P_old -> P_new` person merge event.@@ -61,3 +62,31 @@ export function buildPersonMergeEventMessage(value: Buffer.from(JSON.stringify(event)),}}++let warnedUnconfiguredMergeEventsTopic = false++/**+ * Effective enable for person_merge_events: the kill switch AND a configured output topic. The topic+ * defaults to '' (unwired), and producing to an empty topic would warn on every gated merge, so an+ * unset topic disables emission. Warns once when the gate is on but the topic is unconfigured. The+ * topic field is required so every caller must plumb it through, turning a mis-wired config into a+ * build error rather than a silent self-disable.+ */+export function effectivePersonMergeEventsEnabled(config: {+ PERSON_MERGE_EVENTS_ENABLED: boolean+ INGESTION_OUTPUT_PERSON_MERGE_EVENTS_TOPIC: string+}): boolean {+ if (!config.PERSON_MERGE_EVENTS_ENABLED) {+ return false+ }+ if (!config.INGESTION_OUTPUT_PERSON_MERGE_EVENTS_TOPIC) {+ if (!warnedUnconfiguredMergeEventsTopic) {+ warnedUnconfiguredMergeEventsTopic = true+ logger.warn(+ 'PERSON_MERGE_EVENTS_ENABLED is set but INGESTION_OUTPUT_PERSON_MERGE_EVENTS_TOPIC is empty; not emitting person_merge_events'+ )+ }+ return false+ }+ return true+}diff --git a/nodejs/src/ingestion/common/persons/person-merge-service.ts b/nodejs/src/ingestion/common/persons/person-merge-service.tsindex 7b99365ae093..1ae9539c15ab 100644--- a/nodejs/src/ingestion/common/persons/person-merge-service.ts+++ b/nodejs/src/ingestion/common/persons/person-merge-service.ts@@ -43,10 +43,6 @@ export const mergeTxnSuccessCounter = new Counter({labelNames: ['call', 'oldPersonIdentified', 'newPersonIdentified'],})-export const personMergeEventProducedCounter = new Counter({- name: 'person_merge_event_produced_total',- help: 'Number of person_merge_events produce attempts after a committed merge (gate-on merges only).',-})// used to prevent identify from being used with generic IDs// that we can safely assume stem from a bug or mistakeconst BARE_CASE_INSENSITIVE_ILLEGAL_IDS = [@@ -525,16 +521,13 @@ export class PersonMergeService {}).inc()- // Produce-after-commit: the merge event is emitted only after the Postgres txn commits,- // alongside the clickhouse_person messages. A crash between commit and ack loses it; the- // downstream protocol is idempotent on replay but cannot recover a never-produced event.- if (this.context.shouldProduceMergeEvent()) {- personMergeEventProducedCounter.inc()- }- const kafkaAck = Promise.all([- this.context.produceMessages(kafkaMessages),- this.context.producePersonMergeEvent(currentSourcePerson, mergedPerson),- ]).then(() => undefined)+ // 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 rollbackdiff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.tsindex 556773cb4359..fe68c9c27bf5 100644--- a/nodejs/src/ingestion/config.ts+++ b/nodejs/src/ingestion/config.ts@@ -143,6 +143,9 @@ export type IngestionConsumerConfig = {PERSON_MERGE_ASYNC_ENABLED: booleanPERSON_MERGE_SYNC_BATCH_SIZE: number// 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+ // the topic env is set is a no-op — see effectivePersonMergeEventsEnabled.PERSON_MERGE_EVENTS_ENABLED: boolean// Must equal the person_merge_events topic partition count and the Rust COHORT_PARTITION_COUNT.PERSON_MERGE_EVENTS_PARTITION_COUNT: numberdiff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.tsindex d7a8041d39a9..00b22f658a20 100644--- a/nodejs/src/ingestion/ingestion-consumer.ts+++ b/nodejs/src/ingestion/ingestion-consumer.ts@@ -38,6 +38,7 @@ import { TeamManager } from '~/common/utils/team-manager'import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'import { BatchWritingGroupStore } from '~/ingestion/common/groups/batch-writing-group-store'import { BatchWritingPersonsStore } from '~/ingestion/common/persons/batch-writing-person-store'+import { effectivePersonMergeEventsEnabled } from '~/ingestion/common/persons/person-merge-event'import { PersonsStore } from '~/ingestion/common/persons/persons-store'import { createOkContext } from '~/ingestion/framework/helpers'import { TopHog } from '~/ingestion/framework/tophog'@@ -60,10 +61,13 @@ import { OverflowLaneOverflowRedirect } from './common/overflow-redirect/overfloimport { OverflowRedirectService } from './common/overflow-redirect/overflow-redirect-service'import { RedisOverflowRepository } from './common/overflow-redirect/overflow-redis-repository'import { AiEventSubpipelineFactory } from './common/subpipelines/ai-subpipeline.contract'-import { IngestionConsumerConfig } from './config'+import { IngestionConsumerConfig, IngestionOutputsConfig } from './config'export type IngestionConsumerFullConfig = IngestionConsumerConfig &- Pick<CommonConfig, 'KAFKA_CLIENT_RACK' | 'CDP_HOG_WATCHER_SAMPLE_RATE'>+ Pick<CommonConfig, 'KAFKA_CLIENT_RACK' | 'CDP_HOG_WATCHER_SAMPLE_RATE'> &+ // The general server builds the consumer from a config that includes IngestionOutputsConfig; the+ // merge-events gate reads the topic, so surface it here rather than relying on the runtime shape.+ Pick<IngestionOutputsConfig, 'INGESTION_OUTPUT_PERSON_MERGE_EVENTS_TOPIC'>export interface IngestionConsumerDeps {postgres: PostgresRouter@@ -279,7 +283,7 @@ 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: this.config.PERSON_MERGE_EVENTS_ENABLED,+ 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_JSONB_SIZE_ESTIMATE_ENABLE: this.config.PERSON_JSONB_SIZE_ESTIMATE_ENABLE,diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex 058c03c03002..29c9e321338d 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -35,6 +35,7 @@ import {getDefaultKafkaUpstreamProducerEnvConfig,} from '~/ingestion/common/outputs/producers'import { BatchWritingPersonsStore } from '~/ingestion/common/persons/batch-writing-person-store'+import { effectivePersonMergeEventsEnabled } from '~/ingestion/common/persons/person-merge-event'import { PersonsStore } from '~/ingestion/common/persons/persons-store'import { createOkContext } from '~/ingestion/framework/helpers'import { TopHog } from '~/ingestion/framework/tophog'@@ -371,7 +372,7 @@ 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: this.config.PERSON_MERGE_EVENTS_ENABLED,+ 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_JSONB_SIZE_ESTIMATE_ENABLE: this.config.PERSON_JSONB_SIZE_ESTIMATE_ENABLE,diff --git a/nodejs/tests/helpers/ingestion-e2e.ts b/nodejs/tests/helpers/ingestion-e2e.tsindex 5cb606ff57df..29c0075044ab 100644--- a/nodejs/tests/helpers/ingestion-e2e.ts+++ b/nodejs/tests/helpers/ingestion-e2e.ts@@ -24,7 +24,12 @@ import { PubSub } from '~/common/utils/pubsub'import { TeamManager } from '~/common/utils/team-manager'import { UUIDT } from '~/common/utils/utils'import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'-import { IngestionConsumerConfig, getDefaultIngestionConsumerConfig } from '~/ingestion/config'+import {+ IngestionConsumerConfig,+ IngestionOutputsConfig,+ getDefaultIngestionConsumerConfig,+ getDefaultIngestionOutputsConfig,+} from '~/ingestion/config'import {ErrorTrackingConsumerConfig,getDefaultErrorTrackingConsumerConfig,@@ -333,6 +338,7 @@ export interface IngesterLike {/** The full config an ingestion test sees — PluginsServerConfig plus every ingestion domain's config. */export type IngestionTestConfig = PluginsServerConfig &IngestionConsumerConfig &+ IngestionOutputsConfig &ErrorTrackingConsumerConfig &MetricsIngestionConsumerConfig &SessionRecordingConfig &@@ -388,6 +394,7 @@ export async function createIngestionTestInfra(const serverConfig: IngestionTestConfig = {...defaultConfig,...getDefaultIngestionConsumerConfig(),+ ...getDefaultIngestionOutputsConfig(),...getDefaultErrorTrackingConsumerConfig(),...getDefaultMetricsIngestionConsumerConfig(),...getDefaultSessionRecordingConfig(),diff --git a/nodejs/tests/ingestion/person-state-batch.test.ts b/nodejs/tests/ingestion/person-state-batch.test.tsindex 0ed8f34b4290..db2ba238b4ea 100644--- a/nodejs/tests/ingestion/person-state-batch.test.ts+++ b/nodejs/tests/ingestion/person-state-batch.test.ts@@ -26,9 +26,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 } from '~/ingestion/common/persons/person-context'+import { PersonContext, personMergeEventProducedCounter } from '~/ingestion/common/persons/person-context'import { PersonEventProcessor } from '~/ingestion/common/persons/person-event-processor'-import { PersonMergeService, personMergeEventProducedCounter } from '~/ingestion/common/persons/person-merge-service'+import { PersonMergeService } from '~/ingestion/common/persons/person-merge-service'import {SourcePersonNotFoundError,TargetPersonNotFoundError,@@ -2993,7 +2993,7 @@ describe('PersonState.processEvent()', () => {if (!result.success) {throw new Error('Merge should have succeeded')}- // kafkaAck wraps both the person messages and the merge event; it must resolve.+ // kafkaAck wraps only the person messages; the merge event is produced fire-and-forget.await flushPersonStoreToKafka(kafkaProducer, mergeService.getContext().personStore, result.kafkaAck)const mergeProduceCalls = produceSpy.mock.calls.filter(@@ -3019,6 +3019,66 @@ describe('PersonState.processEvent()', () => {expect(typeof payload.merged_at_ms).toBe('number')})+ 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, {+ distinctId: firstUserDistinctId,+ })+ const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {+ distinctId: secondUserDistinctId,+ })++ // Hang the shadow-topic produce; person/distinct-id messages still hit the real broker. A+ // detached kafkaAck resolves regardless, so if this test ever times out, someone re-bundled+ // the merge event back into the kafkaAck Promise.all and re-coupled it to offset commits.+ const realProduce = KafkaProducerWrapper.prototype.produce+ let releaseShadowProduce: () => void = () => {}+ const shadowProduce = new Promise<void>((resolve) => {+ releaseShadowProduce = () => resolve()+ })+ const produceSpy = jest+ .spyOn(kafkaProducer, 'produce')+ .mockImplementation((message) =>+ message.topic === KAFKA_PERSON_MERGE_EVENTS+ ? shadowProduce+ : realProduce.call(kafkaProducer, message)+ )++ try {+ const mergeService = personMergeService(+ {},+ hub,+ personRepository,+ true,+ timestamp,+ mainTeam,+ createDefaultSyncMergeMode(),+ { enabled: true, partitionCount: 64 }+ )+ const result = await mergeService.mergePeople({+ mergeInto: first,+ mergeIntoDistinctId: firstUserDistinctId,+ otherPerson: second,+ otherPersonDistinctId: secondUserDistinctId,+ })+ expect(result.success).toBe(true)+ if (!result.success) {+ throw new Error('Merge should have succeeded')+ }++ await expect(+ flushPersonStoreToKafka(kafkaProducer, mergeService.getContext().personStore, result.kafkaAck)+ ).resolves.toBeDefined()++ // Person messages were still delivered to the real broker.+ expect(produceSpy.mock.calls.filter((call) => call[0].topic === KAFKA_PERSON).length).toBeGreaterThan(0)+ } finally {+ // Let the fire-and-forget produce settle so it doesn't leak past the test.+ releaseShadowProduce()+ await shadowProduce+ }+ })+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, {distinctId: firstUserDistinctId,