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.

chore(cohorts): add team allowlist to person merge producer (#69514)

Matheus Batista7fc0d77719a7
diff --git a/nodejs/src/ingestion/common/persons/person-context.test.ts b/nodejs/src/ingestion/common/persons/person-context.test.ts
new file mode 100644
index 000000000000..2da7ecc29dd6
--- /dev/null
+++ b/nodejs/src/ingestion/common/persons/person-context.test.ts
@@ -0,0 +1,94 @@
+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 } 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()
+ }
+ })
+})
diff --git a/nodejs/src/ingestion/common/persons/person-context.ts b/nodejs/src/ingestion/common/persons/person-context.ts
index ed4f3780b246..a3ab84eb52fd 100644
--- a/nodejs/src/ingestion/common/persons/person-context.ts
+++ b/nodejs/src/ingestion/common/persons/person-context.ts
@@ -10,7 +10,7 @@ import {
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { PersonMessage } from '~/common/persons/person-message'
import { PluginEvent, Properties } from '~/plugin-scaffold'
-import { InternalPerson, Team } from '~/types'
+import { InternalPerson, Team, ValueMatcher } from '~/types'
import { buildPersonMergeEventMessage } from './person-merge-event'
import { MergeMode } from './person-merge-types'
@@ -20,8 +20,16 @@ export type PersonOutputs = IngestionOutputs<
PersonsOutput | PersonDistinctIdsOutput | IngestionWarningsOutput | PersonMergeEventsOutput
>
-/** Gate + partition-count for the cross-partition merge-event producer. */
-export type MergeEventsConfig = { enabled: boolean; partitionCount: number }
+/** 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.
@@ -43,7 +51,11 @@ export class PersonContext {
public readonly mergeMode: MergeMode,
public readonly updateAllProperties: boolean = false, // When true, all property changes trigger person updates
public readonly shouldUpdateLastSeenAt: boolean = false,
- public readonly mergeEventsConfig: MergeEventsConfig = { enabled: false, partitionCount: 64 }
+ public readonly mergeEventsConfig: MergeEventsConfig = {
+ enabled: false,
+ partitionCount: 64,
+ isTeamEnabled: () => false,
+ }
) {
this.eventProperties = event.properties!
}
@@ -56,13 +68,22 @@ 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)
+ }
+
/**
* Emit a person_merge_events message for the cohort-stream-processor. Resolved no-op when the
- * gate is off. The message is explicitly partitioned by `(team_id, P_old)` so it reaches the
- * worker holding P_old's state — see `buildPersonMergeEventMessage`.
+ * gate is off or the team is outside the allowlist. 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.mergeEventsConfig.enabled) {
+ if (!this.shouldProduceMergeEvent()) {
return
}
const { key, partition, value } = buildPersonMergeEventMessage(
diff --git a/nodejs/src/ingestion/common/persons/person-merge-service.ts b/nodejs/src/ingestion/common/persons/person-merge-service.ts
index b41aa99df897..7b99365ae093 100644
--- a/nodejs/src/ingestion/common/persons/person-merge-service.ts
+++ b/nodejs/src/ingestion/common/persons/person-merge-service.ts
@@ -528,7 +528,7 @@ export class PersonMergeService {
// 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.mergeEventsConfig.enabled) {
+ if (this.context.shouldProduceMergeEvent()) {
personMergeEventProducedCounter.inc()
}
const kafkaAck = Promise.all([
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 b2473f0d2835..ae35c4be325c 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_EVENTS_ENABLED: boolean
PERSON_MERGE_EVENTS_PARTITION_COUNT: number
+ PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: string
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 15ce470b99cd..e5027b23587d 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,7 +1,8 @@
import { DateTime } from 'luxon'
+import { buildIntegerMatcher } from '~/common/config/config'
import { AsyncOutput } from '~/common/outputs'
-import { PersonContext, PersonOutputs } from '~/ingestion/common/persons/person-context'
+import { MergeEventsConfig, PersonContext, PersonOutputs } from '~/ingestion/common/persons/person-context'
import { PersonEventProcessor } from '~/ingestion/common/persons/person-event-processor'
import { PersonMergeService } from '~/ingestion/common/persons/person-merge-service'
import { determineMergeMode } from '~/ingestion/common/persons/person-merge-types'
@@ -35,6 +36,12 @@ 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),
+ }
return async function processPersonsStep(
input: TInput
@@ -59,10 +66,7 @@ export function createProcessPersonsStep<TInput extends ProcessPersonsInput>(
mergeMode,
options.PERSON_PROPERTIES_UPDATE_ALL,
shouldUpdateLastSeenAt,
- {
- enabled: options.PERSON_MERGE_EVENTS_ENABLED,
- partitionCount: options.PERSON_MERGE_EVENTS_PARTITION_COUNT,
- }
+ mergeEventsConfig
)
const processor = new PersonEventProcessor(
diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.ts
index fe74dab394d2..556773cb4359 100644
--- a/nodejs/src/ingestion/config.ts
+++ b/nodejs/src/ingestion/config.ts
@@ -146,6 +146,10 @@ export type IngestionConsumerConfig = {
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: number
+ // Which teams to emit person_merge_events for: comma-separated team IDs, or '*' for all teams.
+ // Defaults to team 2 only. Unlike the Rust REALTIME_COHORT_TEAM_ALLOWLIST, an empty value here
+ // means "no teams", not "all teams"; use '*' to open the gate.
+ PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: string
// Group batch writing config
GROUP_BATCH_WRITING_MAX_CONCURRENT_UPDATES: number
@@ -258,6 +262,7 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {
PERSON_MERGE_SYNC_BATCH_SIZE: 0,
PERSON_MERGE_EVENTS_ENABLED: false,
PERSON_MERGE_EVENTS_PARTITION_COUNT: 64,
+ PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: '2',
// Group batch writing config
GROUP_BATCH_WRITING_MAX_CONCURRENT_UPDATES: 10,
diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.ts
index 7c012e5711f1..d7a8041d39a9 100644
--- a/nodejs/src/ingestion/ingestion-consumer.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.ts
@@ -281,6 +281,7 @@ export class IngestionConsumer {
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_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,
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 a6d023fac922..058c03c03002 100644
--- a/nodejs/src/servers/ingestion-api-server.ts
+++ b/nodejs/src/servers/ingestion-api-server.ts
@@ -373,6 +373,7 @@ export class IngestionApiServer implements NodeServer {
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_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,
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 de5a1bbab7e6..a29063341373 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
@@ -48,6 +48,7 @@ describe('createProcessPersonsStep', () => {
PERSON_MERGE_SYNC_BATCH_SIZE: 1,
PERSON_MERGE_EVENTS_ENABLED: false,
PERSON_MERGE_EVENTS_PARTITION_COUNT: 64,
+ PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: '*',
PERSON_JSONB_SIZE_ESTIMATE_ENABLE: 0,
PERSON_PROPERTIES_UPDATE_ALL: false,
FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: '*',
diff --git a/nodejs/tests/ingestion/person-state-batch.test.ts b/nodejs/tests/ingestion/person-state-batch.test.ts
index dc900f220a73..0ed8f34b4290 100644
--- a/nodejs/tests/ingestion/person-state-batch.test.ts
+++ b/nodejs/tests/ingestion/person-state-batch.test.ts
@@ -28,7 +28,7 @@ import { BatchWritingPersonsStore } from '~/ingestion/common/persons/batch-writi
import { PersonOutputs } from '~/ingestion/common/persons/person-context'
import { PersonContext } from '~/ingestion/common/persons/person-context'
import { PersonEventProcessor } from '~/ingestion/common/persons/person-event-processor'
-import { PersonMergeService } from '~/ingestion/common/persons/person-merge-service'
+import { PersonMergeService, personMergeEventProducedCounter } from '~/ingestion/common/persons/person-merge-service'
import {
SourcePersonNotFoundError,
TargetPersonNotFoundError,
@@ -295,7 +295,7 @@ describe('PersonState.processEvent()', () => {
timestampParam = timestamp,
team = mainTeam,
mergeMode = createDefaultSyncMergeMode(),
- mergeEventsConfig?: { enabled: boolean; partitionCount: number },
+ mergeEventsConfig?: { enabled: boolean; partitionCount: number; isTeamEnabled?: (teamId: number) => boolean },
customPersonsStore?: BatchWritingPersonsStore
) {
const fullEvent = {
@@ -324,7 +324,9 @@ describe('PersonState.processEvent()', () => {
mergeMode,
false,
false,
- mergeEventsConfig ?? { enabled: false, partitionCount: 64 }
+ // 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 }) }
)
return new PersonMergeService(context)
}
@@ -2921,6 +2923,8 @@ describe('PersonState.processEvent()', () => {
const getMergeEventMessages = () =>
mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_PERSON_MERGE_EVENTS)
+ const producedMergeEventCount = async () => (await personMergeEventProducedCounter.get()).values[0]?.value ?? 0
+
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, {
@@ -2968,6 +2972,7 @@ describe('PersonState.processEvent()', () => {
: realProduce.call(kafkaProducer, message)
)
+ const producedBefore = await producedMergeEventCount()
const mergeService = personMergeService(
{},
hub,
@@ -2995,6 +3000,8 @@ describe('PersonState.processEvent()', () => {
(call) => call[0].topic === KAFKA_PERSON_MERGE_EVENTS
)
expect(mergeProduceCalls).toHaveLength(1)
+ // The counter must track actual production, so it shares the allowlist gate with the produce.
+ expect(await producedMergeEventCount()).toBe(producedBefore + 1)
// second (P_old) is the deleted source; first (P_new) is the target.
const expectedKey = `${teamId}:${secondUserUuid}`
@@ -3012,6 +3019,56 @@ describe('PersonState.processEvent()', () => {
expect(typeof payload.merged_at_ms).toBe('number')
})
+ 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,
+ })
+ const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {
+ distinctId: secondUserDistinctId,
+ })
+
+ // Same in-process resolution as the positive case, so a regression that produced anyway
+ // surfaces as a failed assertion rather than a missing-topic broker error.
+ const realProduce = KafkaProducerWrapper.prototype.produce
+ const produceSpy = jest
+ .spyOn(kafkaProducer, 'produce')
+ .mockImplementation((message) =>
+ message.topic === KAFKA_PERSON_MERGE_EVENTS
+ ? Promise.resolve()
+ : realProduce.call(kafkaProducer, message)
+ )
+
+ const producedBefore = await producedMergeEventCount()
+ // Gate is on, but the team is outside the allowlist: neither the produce nor the counter fires.
+ const mergeService = personMergeService(
+ {},
+ hub,
+ personRepository,
+ true,
+ timestamp,
+ mainTeam,
+ createDefaultSyncMergeMode(),
+ { enabled: true, partitionCount: 64, isTeamEnabled: () => false }
+ )
+ 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 flushPersonStoreToKafka(kafkaProducer, mergeService.getContext().personStore, result.kafkaAck)
+
+ const mergeProduceCalls = produceSpy.mock.calls.filter(
+ (call) => call[0].topic === KAFKA_PERSON_MERGE_EVENTS
+ )
+ expect(mergeProduceCalls).toHaveLength(0)
+ expect(await producedMergeEventCount()).toBe(producedBefore)
+ })
+
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, {
diff --git a/nodejs/tests/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.integration.test.ts b/nodejs/tests/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.integration.test.ts
index 778e608f070f..f66403d00c2f 100644
--- a/nodejs/tests/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.integration.test.ts
+++ b/nodejs/tests/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.integration.test.ts
@@ -96,6 +96,7 @@ function buildPipeline(configOverrides: Partial<AiEventSubpipelineConfig> = {})
PERSON_MERGE_SYNC_BATCH_SIZE: 0,
PERSON_MERGE_EVENTS_ENABLED: false,
PERSON_MERGE_EVENTS_PARTITION_COUNT: 64,
+ PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: '*',
PERSON_JSONB_SIZE_ESTIMATE_ENABLE: 0,
PERSON_PROPERTIES_UPDATE_ALL: false,
FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: '*',