: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): break out client warnings into a separate pipeline (#60063)
Paweł Ledwoń7de8c3380d05
diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex 25022b441cb9..ec718b308781 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -488,6 +488,7 @@ services:events_plugin_ingestion_dlq \events_plugin_ingestion_overflow \events_plugin_ingestion_async \+ ingestion-clientwarnings-main-1 \clickhouse_groups \clickhouse_person \clickhouse_person_distinct_id \diff --git a/docker-compose.hobby.yml b/docker-compose.hobby.ymlindex edc743911cfb..f6580ebae691 100644--- a/docker-compose.hobby.yml+++ b/docker-compose.hobby.yml@@ -529,6 +529,7 @@ services:events_plugin_ingestion_dlq \events_plugin_ingestion_overflow \events_plugin_ingestion_async \+ ingestion-clientwarnings-main-1 \clickhouse_groups \clickhouse_person \clickhouse_person_distinct_id \diff --git a/nodejs/src/ingestion/__snapshots__/ingestion-consumer.test.ts.snap b/nodejs/src/ingestion/__snapshots__/ingestion-consumer.test.ts.snapindex 44258abd69c9..c2d5b52aabcd 100644--- a/nodejs/src/ingestion/__snapshots__/ingestion-consumer.test.ts.snap+++ b/nodejs/src/ingestion/__snapshots__/ingestion-consumer.test.ts.snap@@ -432,23 +432,6 @@ exports[`IngestionConsumer typical event processing ai event 1`] = `]`;-exports[`IngestionConsumer typical event processing client ingestion warning 1`] = `-[- {- "headers": undefined,- "key": null,- "topic": "clickhouse_ingestion_warnings_test",- "value": {- "details": "{"eventUuid":"<REPLACED-UUID-0>","event":"$$client_ingestion_warning","distinctId":"user-1","message":"test"}",- "source": "plugin-server",- "team_id": 2,- "timestamp": "2025-01-01 00:00:00.000",- "type": "client_ingestion_warning",- },- },-]-`;-exports[`IngestionConsumer typical event processing event with common distinct_id that gets dropped 1`] = `[{diff --git a/nodejs/src/ingestion/analytics/client-ingestion-warning-subpipeline.ts b/nodejs/src/ingestion/analytics/client-ingestion-warning-subpipeline.tsdeleted file mode 100644index ba715fbf1a47..000000000000--- a/nodejs/src/ingestion/analytics/client-ingestion-warning-subpipeline.ts+++ /dev/null@@ -1,15 +0,0 @@-import { PluginEvent } from '~/plugin-scaffold'--import { createHandleClientIngestionWarningStep } from '../event-processing/handle-client-ingestion-warning-step'-import { PipelineBuilder, StartPipelineBuilder } from '../pipelines/builders/pipeline-builders'--export interface ClientIngestionWarningSubpipelineInput {- event: PluginEvent-}--export function createClientIngestionWarningSubpipeline<- TInput extends ClientIngestionWarningSubpipelineInput,- TContext,->(builder: StartPipelineBuilder<TInput, TContext>): PipelineBuilder<TInput, void, TContext> {- return builder.pipe(createHandleClientIngestionWarningStep())-}diff --git a/nodejs/src/ingestion/analytics/index.ts b/nodejs/src/ingestion/analytics/index.tsindex f52591eb9c52..47137d2f61ef 100644--- a/nodejs/src/ingestion/analytics/index.ts+++ b/nodejs/src/ingestion/analytics/index.ts@@ -1,8 +1,3 @@-export {- createClientIngestionWarningSubpipeline,- type ClientIngestionWarningSubpipelineInput,-} from './client-ingestion-warning-subpipeline'-export { createEventSubpipeline, type EventSubpipelineConfig, type EventSubpipelineInput } from './event-subpipeline'export {diff --git a/nodejs/src/ingestion/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/analytics/joined-ingestion-pipeline.tsindex 05af847cf0b5..a5ecc1bd497d 100644--- a/nodejs/src/ingestion/analytics/joined-ingestion-pipeline.ts+++ b/nodejs/src/ingestion/analytics/joined-ingestion-pipeline.ts@@ -11,6 +11,7 @@ import { BatchWritingGroupStore } from '../../worker/ingestion/groups/batch-writimport { PersonsStore } from '../../worker/ingestion/persons/persons-store'import { EventFilterManager } from '../common/event-filters'import { AppMetricsOutput, DlqOutput, GroupsOutput, IngestionWarningsOutput, OverflowOutput } from '../common/outputs'+import { createDenyEventsStep } from '../common/steps/deny-events'import {EventFiltersBatchContext,createEventFiltersBatchAppMetricsBeforeBatchStep,@@ -19,7 +20,6 @@ import {import { CookielessManager } from '../cookieless/cookieless-manager'import {createApplyEventRestrictionsStep,- createDropExceptionEventsStep,createEnrichSurveyPersonPropertiesStep,createParseHeadersStep,createParseKafkaMessageStep,@@ -213,12 +213,15 @@ export function createJoinedIngestionPipeline<// Header-only steps: parse Kafka headers and apply token-level restrictions.// Cheap; runs per-event before we touch the body..sequentially((b) =>- b.pipe(createParseHeadersStep()).pipe(- createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {- overflowEnabled,- preservePartitionLocality,- })- )+ b+ .pipe(createParseHeadersStep())+ .pipe(createDenyEventsStep(['$exception', '$$client_ingestion_warning']))+ .pipe(+ createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {+ overflowEnabled,+ preservePartitionLocality,+ })+ ))// Rate-limit non-cookieless events to overflow before parsing the body.// Cookieless events (headers.distinct_id === sentinel) pass through and are@@ -234,7 +237,6 @@ export function createJoinedIngestionPipeline<.sequentially((b) =>b.pipe(createParseKafkaMessageStep())- .pipe(createDropExceptionEventsStep()).pipe(createResolveTeamStep(teamManager)).pipe(createValidateHistoricalMigrationStep()).pipe(createValidateAiEventTokensStep())diff --git a/nodejs/src/ingestion/analytics/per-distinct-id-pipeline.ts b/nodejs/src/ingestion/analytics/per-distinct-id-pipeline.tsindex 635246eccb16..6f9a32830c58 100644--- a/nodejs/src/ingestion/analytics/per-distinct-id-pipeline.ts+++ b/nodejs/src/ingestion/analytics/per-distinct-id-pipeline.ts@@ -14,10 +14,6 @@ import { SplitAiEventsStepConfig } from '../event-processing/split-ai-events-steimport { IngestionOutputs } from '../outputs/ingestion-outputs'import { PipelineBuilder, StartPipelineBuilder } from '../pipelines/builders/pipeline-builders'import { TopHogWrapper } from '../pipelines/extensions/tophog'-import {- ClientIngestionWarningSubpipelineInput,- createClientIngestionWarningSubpipeline,-} from './client-ingestion-warning-subpipeline'import { EventSubpipelineInput, createEventSubpipeline } from './event-subpipeline'import { HeatmapSubpipelineInput, createHeatmapSubpipeline } from './heatmap-subpipeline'import {@@ -29,10 +25,7 @@ import {PersonsOutput,} from './outputs'-export type PerDistinctIdPipelineInput = EventSubpipelineInput &- HeatmapSubpipelineInput &- ClientIngestionWarningSubpipelineInput &- AiEventSubpipelineInput+export type PerDistinctIdPipelineInput = EventSubpipelineInput & HeatmapSubpipelineInput & AiEventSubpipelineInputexport interface PerDistinctIdPipelineConfig {options: EventPipelineRunnerOptions@@ -54,10 +47,9 @@ export interface PerDistinctIdPipelineContext {team: Team}-type EventBranch = 'client_ingestion_warning' | 'heatmap' | 'ai' | 'event'+type EventBranch = 'heatmap' | 'ai' | 'event'const EVENT_BRANCH_MAP = new Map<string, EventBranch>([- ['$$client_ingestion_warning', 'client_ingestion_warning'],['$$heatmap', 'heatmap'],...[...AI_EVENT_TYPES].map((t): [string, EventBranch] => [t, 'ai']),])@@ -87,7 +79,6 @@ export function createPerDistinctIdPipeline<TInput extends PerDistinctIdPipeline(e) =>e.branching(classifyEvent, (branches) =>branches- .branch('client_ingestion_warning', (b) => createClientIngestionWarningSubpipeline(b)).branch('heatmap', (b) =>createHeatmapSubpipeline(b, {options,diff --git a/nodejs/src/ingestion/analytics/testing-per-distinct-id-pipeline.ts b/nodejs/src/ingestion/analytics/testing-per-distinct-id-pipeline.tsindex 6014b60fe7f9..c36e3e98e33a 100644--- a/nodejs/src/ingestion/analytics/testing-per-distinct-id-pipeline.ts+++ b/nodejs/src/ingestion/analytics/testing-per-distinct-id-pipeline.ts@@ -5,10 +5,6 @@ import { AI_EVENT_TYPES } from '../ai'import { IngestionWarningsOutput } from '../common/outputs'import { IngestionOutputs } from '../outputs/ingestion-outputs'import { PipelineBuilder, StartPipelineBuilder } from '../pipelines/builders/pipeline-builders'-import {- ClientIngestionWarningSubpipelineInput,- createClientIngestionWarningSubpipeline,-} from './client-ingestion-warning-subpipeline'import { EventOutput, HeatmapsOutput } from './outputs'import { TestingAiEventSubpipelineInput, createTestingAiEventSubpipeline } from './testing-ai-event-subpipeline'import { TestingEventSubpipelineInput, createTestingEventSubpipeline } from './testing-event-subpipeline'@@ -16,7 +12,6 @@ import { TestingHeatmapSubpipelineInput, createTestingHeatmapSubpipeline } fromexport type TestingPerDistinctIdPipelineInput = TestingEventSubpipelineInput &TestingHeatmapSubpipelineInput &- ClientIngestionWarningSubpipelineInput &TestingAiEventSubpipelineInputexport interface TestingPerDistinctIdPipelineConfig {@@ -29,10 +24,9 @@ export interface TestingPerDistinctIdPipelineContext {team: Team}-type EventBranch = 'client_ingestion_warning' | 'heatmap' | 'ai' | 'event'+type EventBranch = 'heatmap' | 'ai' | 'event'const EVENT_BRANCH_MAP = new Map<string, EventBranch>([- ['$$client_ingestion_warning', 'client_ingestion_warning'],['$$heatmap', 'heatmap'],...[...AI_EVENT_TYPES].map((t): [string, EventBranch] => [t, 'ai']),])@@ -51,7 +45,6 @@ export function createTestingPerDistinctIdPipeline<TInput extends TestingPerDist(e) =>e.branching<EventBranch, void>(classifyEvent, (branches) =>branches- .branch('client_ingestion_warning', (b) => createClientIngestionWarningSubpipeline(b)).branch('heatmap', (b) =>createTestingHeatmapSubpipeline(b, {outputs,diff --git a/nodejs/src/ingestion/analytics/testing-pre-team-preprocessing-subpipeline.ts b/nodejs/src/ingestion/analytics/testing-pre-team-preprocessing-subpipeline.tsindex 2da8a9325a7e..8a7f4223dd3d 100644--- a/nodejs/src/ingestion/analytics/testing-pre-team-preprocessing-subpipeline.ts+++ b/nodejs/src/ingestion/analytics/testing-pre-team-preprocessing-subpipeline.ts@@ -4,8 +4,8 @@ import { PluginEvent } from '~/plugin-scaffold'import { TeamManager } from '~/utils/team-manager'import { EventHeaders, Team } from '../../types'+import { createDenyEventsStep } from '../common/steps/deny-events'import {- createDropExceptionEventsStep,createEnrichSurveyPersonPropertiesStep,createParseHeadersStep,createParseKafkaMessageStep,@@ -40,8 +40,8 @@ export function createTestingPreTeamPreprocessingSubpipeline<return builder.pipe(createParseHeadersStep())+ .pipe(createDenyEventsStep(['$exception', '$$client_ingestion_warning'])).pipe(createParseKafkaMessageStep())- .pipe(createDropExceptionEventsStep()).pipe(createResolveTeamStep(teamManager)).pipe(createValidateHistoricalMigrationStep()).pipe(createValidateAiEventTokensStep())diff --git a/nodejs/src/ingestion/clientwarnings/consumer-e2e.test.ts b/nodejs/src/ingestion/clientwarnings/consumer-e2e.test.tsnew file mode 100644index 000000000000..7855ad5764b9--- /dev/null+++ b/nodejs/src/ingestion/clientwarnings/consumer-e2e.test.ts@@ -0,0 +1,145 @@+import { Message } from 'node-rdkafka'++import { Clickhouse } from '~/tests/helpers/clickhouse'+import { waitForExpect } from '~/tests/helpers/expectations'+import {+ EventBuilder,+ IngesterLike,+ createKafkaMessages,+ createTestWithTeamIngester,+ fetchIngestionWarnings,+ waitForClickHouseKafkaConsumer,+} from '~/tests/helpers/ingestion-e2e'+import { resetKafka } from '~/tests/helpers/kafka'+import { resetTestDatabase } from '~/tests/helpers/sql'++import {+ getDefaultKafkaIngestionProducerEnvConfig,+ getDefaultKafkaProducerEnvConfig,+ getDefaultKafkaWarpstreamProducerEnvConfig,+} from '../common/config'+import { KafkaProducerRegistryComponent } from '../common/outputs/registry'+import { Component, newScope } from '../common/scopes'+import { getDefaultIngestionOutputsConfig } from '../config'+import { ClientWarningsConsumerConfig, ClientWarningsSharedScope, createClientWarningsConsumer } from './consumer'++type CapturedBatchHandler = (messages: Message[]) => Promise<{ backgroundTask?: Promise<unknown> } | void>++// Captures the per-batch handler that `KafkaConsumerComponent` wires into the+// Kafka consumer at start, so the test can drive batches through the real+// pipeline without a live consumer. Prefixed `mock` so the jest.mock factory+// is allowed to reference it.+let mockCapturedHandler: CapturedBatchHandler | undefined++jest.mock('~/kafka/consumer', () => {+ const actual = jest.requireActual('~/kafka/consumer')+ const { HealthCheckResultOk } = jest.requireActual('~/types')+ return {+ ...actual,+ createKafkaConsumer: jest.fn(() => ({+ connect: (handler: CapturedBatchHandler) => {+ mockCapturedHandler = handler+ return Promise.resolve()+ },+ disconnect: () => Promise.resolve(),+ isHealthy: () => new HealthCheckResultOk(),+ offsetsStore: () => undefined,+ })),+ }+})++jest.mock('../../utils/logger')++function constComponent<T extends object>(value: T): Component<T> {+ return { start: () => Promise.resolve({ value, stop: () => Promise.resolve() }) }+}++class ClientWarningsTestIngester implements IngesterLike {+ private stopScope?: () => Promise<void>++ constructor(private readonly consumerScope: ReturnType<typeof createClientWarningsConsumer>) {}++ async start(): Promise<void> {+ const { stop } = await this.consumerScope.start()+ this.stopScope = stop+ }++ async stop(): Promise<void> {+ await this.stopScope?.()+ }++ async handleKafkaBatch(messages: Message[]): Promise<{ backgroundTask?: Promise<unknown> }> {+ if (!mockCapturedHandler) {+ throw new Error('Kafka consumer batch handler was not captured — did the consumer start?')+ }+ return (await mockCapturedHandler(messages)) ?? {}+ }+}++describe('ClientWarnings consumer E2E', () => {+ const testWithTeamIngester = createTestWithTeamIngester({}, (infra) => {+ const config: ClientWarningsConsumerConfig = {+ ...infra.config,+ ...getDefaultIngestionOutputsConfig(),+ INGESTION_CONSUMER_GROUP_ID: 'clientwarnings-e2e-test',+ INGESTION_CONSUMER_CONSUME_TOPIC: 'clientwarnings-e2e-test',+ INGESTION_PIPELINE: 'clientwarnings',+ INGESTION_LANE: null,+ KAFKA_BATCH_START_LOGGING_ENABLED: false,+ }++ // Empty producer env values fall back to the rdkafka defaults (broker+ // `kafka:9092`), which is the same broker the rest of the test suite+ // produces to — so the registry's warnings producer reaches ClickHouse.+ const registryConfig = {+ ...getDefaultKafkaProducerEnvConfig(),+ ...getDefaultKafkaWarpstreamProducerEnvConfig(),+ ...getDefaultKafkaIngestionProducerEnvConfig(),+ }+ const sharedScope: ClientWarningsSharedScope = newScope('clientwarnings-e2e-shared', (b) =>+ b+ .add('postgres', constComponent(infra.postgres))+ .add('redisPool', constComponent(infra.redisPool))+ .add('teamManager', constComponent(infra.teamManager))+ .add(+ 'producerRegistry',+ new KafkaProducerRegistryComponent(infra.config.KAFKA_CLIENT_RACK, registryConfig)+ )+ )++ return new ClientWarningsTestIngester(createClientWarningsConsumer(config, sharedScope))+ })++ let clickhouse: Clickhouse++ beforeAll(async () => {+ clickhouse = Clickhouse.create()+ await resetKafka()+ await resetTestDatabase()+ await clickhouse.resetTestDatabase()+ await waitForClickHouseKafkaConsumer(clickhouse)+ })++ afterAll(async () => {+ await resetTestDatabase()+ await clickhouse.resetTestDatabase()+ clickhouse.close()+ })++ testWithTeamIngester('produces a client_ingestion_warning to ClickHouse', {}, async ({ ingester, team, token }) => {+ const event = new EventBuilder(team)+ .withEvent('$$client_ingestion_warning')+ .withProperties({ $$client_ingestion_warning_message: 'test message' })+ .build()++ const { backgroundTask } = await ingester.handleKafkaBatch(createKafkaMessages([event], token))+ await backgroundTask++ await waitForExpect(async () => {+ const warnings = await fetchIngestionWarnings(clickhouse, team.id)+ expect(warnings.length).toBe(1)+ expect(warnings[0].type).toBe('client_ingestion_warning')+ expect(warnings[0].details.message).toBe('test message')+ }, 30_000)+ })+})diff --git a/nodejs/src/ingestion/clientwarnings/consumer.test.ts b/nodejs/src/ingestion/clientwarnings/consumer.test.tsnew file mode 100644index 000000000000..b93bd5b23900--- /dev/null+++ b/nodejs/src/ingestion/clientwarnings/consumer.test.ts@@ -0,0 +1,64 @@+import { RedisPool } from '../../types'+import { PostgresRouter } from '../../utils/db/postgres'+import { TeamManagerComponent } from '../../utils/team-manager'+import { ProducerName } from '../common/outputs'+import { newScope } from '../common/scopes'+import { IngestionOutputsConfig } from '../config'+import { KafkaProducerRegistry } from '../outputs/kafka-producer-registry'+import { ClientWarningsConsumerConfig, ClientWarningsSharedScope, createClientWarningsConsumer } from './consumer'+import * as pipelineModule from './pipeline'++jest.mock('./pipeline')++describe('createClientWarningsConsumer', () => {+ function makeConfig(): ClientWarningsConsumerConfig {+ return {+ INGESTION_CONSUMER_GROUP_ID: 'g',+ INGESTION_CONSUMER_CONSUME_TOPIC: 't',+ INGESTION_PIPELINE: 'analytics',+ INGESTION_LANE: 'main',+ KAFKA_BATCH_START_LOGGING_ENABLED: false,+ DROP_EVENTS_BY_TOKEN_DISTINCT_ID: '',+ ...({} as IngestionOutputsConfig),+ }+ }++ function makeSharedScope(): ClientWarningsSharedScope {+ // The consumer factory extends this scope but doesn't start it+ // (start happens at the caller), so the shape only has to be+ // type-correct — the components' bodies don't run.+ return newScope('shared-test', (b) =>+ b+ .add('postgres', {+ start: () => Promise.resolve({ value: {} as PostgresRouter, stop: () => Promise.resolve() }),+ })+ .add('redisPool', {+ start: () => Promise.resolve({ value: {} as RedisPool, stop: () => Promise.resolve() }),+ })+ .add('teamManager', new TeamManagerComponent({} as PostgresRouter))+ .add('producerRegistry', {+ start: () =>+ Promise.resolve({+ value: {} as KafkaProducerRegistry<ProducerName>,+ stop: () => Promise.resolve(),+ }),+ })+ )+ }++ beforeEach(() => {+ ;(pipelineModule.createClientWarningsPipeline as jest.Mock) = jest.fn().mockReturnValue({+ feed: jest.fn(),+ next: jest.fn(),+ })+ })++ it('defers pipeline construction until scope.start()', () => {+ createClientWarningsConsumer(makeConfig(), makeSharedScope())++ // The pipeline factory runs inside the extend callback at start+ // time, after the scope's services come up — not at consumer+ // construction time.+ expect(pipelineModule.createClientWarningsPipeline).not.toHaveBeenCalled()+ })+})diff --git a/nodejs/src/ingestion/clientwarnings/consumer.ts b/nodejs/src/ingestion/clientwarnings/consumer.tsnew file mode 100644index 000000000000..a33d79a70145--- /dev/null+++ b/nodejs/src/ingestion/clientwarnings/consumer.ts@@ -0,0 +1,52 @@+import { RedisPool } from '../../types'+import { PostgresRouter } from '../../utils/db/postgres'+import { EventIngestionRestrictionManagerComponent } from '../../utils/event-ingestion-restrictions'+import { TeamManager } from '../../utils/team-manager'+import { EventFilterManagerComponent } from '../common/event-filters'+import { CommonIngestionConsumerConfig, CommonIngestionConsumerScope } from '../common/ingestion-consumer'+import { ProducerName } from '../common/outputs'+import { Scope, extend } from '../common/scopes'+import { PromiseSchedulerComponent } from '../common/utils/promise-scheduler'+import { IngestionConsumerConfig, IngestionOutputsConfig } from '../config'+import { IngestionOutputsComponent } from '../outputs/ingestion-outputs'+import { KafkaProducerRegistry } from '../outputs/kafka-producer-registry'+import { createOutputsRegistry } from './outputs/registry'+import { createClientWarningsPipeline } from './pipeline'++export type ClientWarningsConsumerConfig = CommonIngestionConsumerConfig &+ IngestionOutputsConfig &+ Pick<IngestionConsumerConfig, 'DROP_EVENTS_BY_TOKEN_DISTINCT_ID'>++export type ClientWarningsSharedScope = Scope<{+ postgres: PostgresRouter+ redisPool: RedisPool+ teamManager: TeamManager+ producerRegistry: KafkaProducerRegistry<ProducerName>+}>++export function createClientWarningsConsumer(+ config: ClientWarningsConsumerConfig,+ sharedScope: ClientWarningsSharedScope+) {+ const staticDropEventTokens = config.DROP_EVENTS_BY_TOKEN_DISTINCT_ID.split(',').filter((x) => !!x)+ const scope = extend(sharedScope, 'clientwarnings', (container, builder) =>+ builder+ .add('promiseScheduler', new PromiseSchedulerComponent())+ .add(+ 'eventIngestionRestrictionManager',+ new EventIngestionRestrictionManagerComponent(container.redisPool, {+ pipeline: 'clientwarnings',+ staticDropEventTokens,+ })+ )+ .add('eventFilterManager', new EventFilterManagerComponent(container.postgres))+ .add(+ 'outputs',+ new IngestionOutputsComponent(() => createOutputsRegistry().build(container.producerRegistry, config))+ )+ )++ return new CommonIngestionConsumerScope('clientwarnings', config, scope, ({ container }) =>+ createClientWarningsPipeline(container)+ )+}diff --git a/nodejs/src/ingestion/clientwarnings/index.ts b/nodejs/src/ingestion/clientwarnings/index.tsnew file mode 100644index 000000000000..e67ed96d2573--- /dev/null+++ b/nodejs/src/ingestion/clientwarnings/index.ts@@ -0,0 +1,3 @@+export { createClientWarningsConsumer } from './consumer'+export type { ClientWarningsConsumerConfig, ClientWarningsSharedScope } from './consumer'+export { createClientWarningsPipeline } from './pipeline'diff --git a/nodejs/src/ingestion/clientwarnings/outputs/registry.ts b/nodejs/src/ingestion/clientwarnings/outputs/registry.tsnew file mode 100644index 000000000000..77040e211fc7--- /dev/null+++ b/nodejs/src/ingestion/clientwarnings/outputs/registry.ts@@ -0,0 +1,36 @@+import { APP_METRICS_OUTPUT, DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT } from '../../common/outputs'+import { IngestionOutputsBuilder } from '../../outputs/ingestion-outputs-builder'++/**+ * Register the outputs the clientwarnings pipeline produces to. Call+ * `.build(registry, config)` to resolve against the shared producer+ * registry.+ */+export function createOutputsRegistry() {+ return new IngestionOutputsBuilder()+ .registerDualWrite(INGESTION_WARNINGS_OUTPUT, {+ topicKey: 'INGESTION_OUTPUT_INGESTION_WARNINGS_TOPIC',+ producerKey: 'INGESTION_OUTPUT_INGESTION_WARNINGS_PRODUCER',+ secondaryTopicKey: 'INGESTION_OUTPUT_INGESTION_WARNINGS_SECONDARY_TOPIC',+ secondaryProducerKey: 'INGESTION_OUTPUT_INGESTION_WARNINGS_SECONDARY_PRODUCER',+ modeKey: 'INGESTION_OUTPUT_INGESTION_WARNINGS_SECONDARY_MODE',+ percentageKey: 'INGESTION_OUTPUT_INGESTION_WARNINGS_SECONDARY_PERCENTAGE',+ })+ .registerDualWrite(DLQ_OUTPUT, {+ topicKey: 'INGESTION_OUTPUT_DLQ_TOPIC',+ producerKey: 'INGESTION_OUTPUT_DLQ_PRODUCER',+ secondaryTopicKey: 'INGESTION_OUTPUT_DLQ_SECONDARY_TOPIC',+ secondaryProducerKey: 'INGESTION_OUTPUT_DLQ_SECONDARY_PRODUCER',+ modeKey: 'INGESTION_OUTPUT_DLQ_SECONDARY_MODE',+ percentageKey: 'INGESTION_OUTPUT_DLQ_SECONDARY_PERCENTAGE',+ })+ .registerDualWriteWithDenylist(APP_METRICS_OUTPUT, {+ topicKey: 'INGESTION_OUTPUT_APP_METRICS_TOPIC',+ producerKey: 'INGESTION_OUTPUT_APP_METRICS_PRODUCER',+ secondaryTopicKey: 'INGESTION_OUTPUT_APP_METRICS_SECONDARY_TOPIC',+ secondaryProducerKey: 'INGESTION_OUTPUT_APP_METRICS_SECONDARY_PRODUCER',+ modeKey: 'INGESTION_OUTPUT_APP_METRICS_SECONDARY_MODE',+ percentageKey: 'INGESTION_OUTPUT_APP_METRICS_SECONDARY_PERCENTAGE',+ teamDenylistKey: 'INGESTION_OUTPUT_APP_METRICS_SECONDARY_TEAM_DENYLIST',+ })+}diff --git a/nodejs/src/ingestion/clientwarnings/pipeline.ts b/nodejs/src/ingestion/clientwarnings/pipeline.tsnew file mode 100644index 000000000000..b5592e69e2ff--- /dev/null+++ b/nodejs/src/ingestion/clientwarnings/pipeline.ts@@ -0,0 +1,96 @@+import { Message } from 'node-rdkafka'++import { EventIngestionRestrictionManager } from '../../utils/event-ingestion-restrictions'+import { PromiseScheduler } from '../../utils/promise-scheduler'+import { TeamManager } from '../../utils/team-manager'+import { EventFilterManager } from '../common/event-filters'+import { AppMetricsOutput, DlqOutput, IngestionWarningsOutput } from '../common/outputs'+import { createAllowEventsStep } from '../common/steps/allow-events'+import {+ EventFiltersBatchContext,+ createApplyEventFiltersStep,+ createEventFiltersBatchAppMetricsBeforeBatchStep,+ createFlushEventFiltersBatchAppMetricsStep,+} from '../common/steps/event-filters-steps'+import { addTeamToContext } from '../common/subpipelines/helpers'+import {+ createParseHeadersStep,+ createParseKafkaMessageStep,+ createResolveTeamStep,+ createValidateEventMetadataStep,+ createValidateEventPropertiesStep,+ createValidateHistoricalMigrationStep,+} from '../event-preprocessing'+import { createApplyBasicEventRestrictionsStep } from '../event-preprocessing/apply-event-restrictions'+import { createDropOldEventsStep } from '../event-processing/drop-old-events-step'+import { createHandleClientIngestionWarningStep } from '../event-processing/handle-client-ingestion-warning-step'+import { IngestionOutputs } from '../outputs/ingestion-outputs'+import { newBatchingPipeline } from '../pipelines/builders'+import { PipelineConfig } from '../pipelines/result-handling-pipeline'++export interface ClientWarningsPipelineConfig {+ outputs: IngestionOutputs<IngestionWarningsOutput | DlqOutput | AppMetricsOutput>+ teamManager: TeamManager+ // The managers come from a started `Lifecycle`'s service map, where+ // `start` and `stop` are stripped from the type — the pipeline only+ // needs their business methods.+ eventIngestionRestrictionManager: EventIngestionRestrictionManager+ eventFilterManager: EventFilterManager+ promiseScheduler: PromiseScheduler+}++interface ClientWarningsPipelineInput {+ message: Message+}++interface ClientWarningsPipelineContext {+ message: Message+}++export function createClientWarningsPipeline<+ TInput extends ClientWarningsPipelineInput,+ TContext extends ClientWarningsPipelineContext,+>(config: ClientWarningsPipelineConfig) {+ const { outputs, teamManager, eventIngestionRestrictionManager, eventFilterManager, promiseScheduler } = config++ const pipelineConfig: PipelineConfig = {+ outputs,+ promiseScheduler,+ }++ return newBatchingPipeline<TInput, void, TContext, EventFiltersBatchContext, TContext>(+ (beforeBatch) => beforeBatch.pipe(createEventFiltersBatchAppMetricsBeforeBatchStep(outputs)),+ (batch) =>+ batch+ .messageAware((b) =>+ b+ .sequentially((b) =>+ b+ .pipe(createParseHeadersStep())+ .pipe(createAllowEventsStep(['$$client_ingestion_warning']))+ .pipe(createApplyBasicEventRestrictionsStep(eventIngestionRestrictionManager))+ .pipe(createParseKafkaMessageStep())+ .pipe(createResolveTeamStep(teamManager))+ .pipe(createValidateHistoricalMigrationStep())+ )+ .filterMap(addTeamToContext, (b) =>+ b+ .teamAware((b) =>+ b.sequentially((b) =>+ b+ .pipe(createValidateEventMetadataStep())+ .pipe(createValidateEventPropertiesStep())+ .pipe(createApplyEventFiltersStep(eventFilterManager))+ .pipe(createDropOldEventsStep())+ .pipe(createHandleClientIngestionWarningStep())+ )+ )+ .handleIngestionWarnings(outputs)+ )+ )+ .handleResults(pipelineConfig)+ .handleSideEffects(promiseScheduler, { await: false }),+ (afterBatch) => afterBatch.pipe(createFlushEventFiltersBatchAppMetricsStep()),+ { concurrentBatches: 1 }+ )+}diff --git a/nodejs/src/ingestion/common/event-filters/index.ts b/nodejs/src/ingestion/common/event-filters/index.tsindex 0ef109f2e646..33997e2ac6fc 100644--- a/nodejs/src/ingestion/common/event-filters/index.ts+++ b/nodejs/src/ingestion/common/event-filters/index.ts@@ -1,4 +1,4 @@-export { EventFilterManager } from './manager'+export { EventFilterManager, EventFilterManagerComponent } from './manager'export { EventFiltersBatchAppMetrics } from './batch-app-metrics'export { evaluateFilterTree, treeHasConditions } from './evaluate'export { FilterNodeSchema, EventFilterRowSchema, EventFilterModeSchema } from './schema'diff --git a/nodejs/src/ingestion/common/event-filters/manager.integration.test.ts b/nodejs/src/ingestion/common/event-filters/manager.integration.test.tsindex 40186940f348..80aebcc95a3f 100644--- a/nodejs/src/ingestion/common/event-filters/manager.integration.test.ts+++ b/nodejs/src/ingestion/common/event-filters/manager.integration.test.ts@@ -4,7 +4,7 @@ import { createOrganization, createTeam, insertRow, resetTestDatabase } from '..import { defaultConfig } from '../../../config/config'import { PostgresRouter, PostgresUse } from '../../../utils/db/postgres'import { evaluateFilterTree } from './evaluate'-import { EventFilterManager } from './manager'+import { EventFilterManager, EventFilterManagerComponent } from './manager'import { and, cond, not, or } from './test-helpers'async function insertFilter(@@ -66,70 +66,84 @@ describe('EventFilterManager integration', () => {await postgres.end()})- async function createManagerAndWaitForLoad(): Promise<EventFilterManager> {- const manager = new EventFilterManager(postgres)- // Wait for the background refresher to complete its initial load- await new Promise((r) => setTimeout(r, 200))- return manager+ async function createManagerAndWaitForLoad(): Promise<{+ manager: EventFilterManager+ stop: () => Promise<void>+ }> {+ const scope = new EventFilterManagerComponent(postgres)+ const started = await scope.start()+ return { manager: started.value, stop: started.stop }}it('loads a live filter from postgres and evaluates it', async () => {await insertFilter(postgres, teamId, 'live', cond('event_name', 'exact', '$internal'))- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()const filter = manager.getFilter(teamId)expect(filter).not.toBeNull()expect(filter!.mode).toBe('live')expect(evaluateFilterTree(filter!.filter_tree, { event_name: '$internal' })).toBe(true)expect(evaluateFilterTree(filter!.filter_tree, { event_name: '$pageview' })).toBe(false)++ await stop()})it('loads a dry_run filter from postgres', async () => {await insertFilter(postgres, teamId, 'dry_run', cond('event_name', 'exact', '$test'))- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()const filter = manager.getFilter(teamId)expect(filter).not.toBeNull()expect(filter!.mode).toBe('dry_run')++ await stop()})it('does not load disabled filters', async () => {await insertFilter(postgres, teamId, 'disabled', cond('event_name', 'exact', 'pageview'))- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()++ await stop()})it('does not load filters with null filter_tree', async () => {await insertFilter(postgres, teamId, 'live', null)- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()++ await stop()})it('returns null for filter with empty tree (no conditions)', async () => {await insertFilter(postgres, teamId, 'live', { type: 'or', children: [] })- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()++ await stop()})it('returns null for unknown team', async () => {- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(999999)).toBeNull()++ await stop()})it('loads filters for multiple teams', async () => {await insertFilter(postgres, teamId, 'live', cond('event_name', 'exact', 'a'))await insertFilter(postgres, teamId2, 'dry_run', cond('distinct_id', 'contains', 'bot'))- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()const f1 = manager.getFilter(teamId)const f2 = manager.getFilter(teamId2)@@ -138,6 +152,8 @@ describe('EventFilterManager integration', () => {expect(f2).not.toBeNull()expect(f1!.mode).toBe('live')expect(f2!.mode).toBe('dry_run')++ await stop()})it('skips rows with invalid filter_tree structure', async () => {@@ -148,10 +164,12 @@ describe('EventFilterManager integration', () => {})await insertFilter(postgres, teamId2, 'live', cond('event_name', 'exact', 'good'))- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()expect(manager.getFilter(teamId2)).not.toBeNull()++ await stop()})// These tests verify that corrupt or unexpected data in Postgres@@ -166,10 +184,12 @@ describe('EventFilterManager integration', () => {})await insertFilter(postgres, teamId2, 'live', cond('event_name', 'exact', 'good'))- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()expect(manager.getFilter(teamId2)).not.toBeNull()++ await stop()})it('skips filter_tree that is a JSON array instead of object', async () => {@@ -181,9 +201,11 @@ describe('EventFilterManager integration', () => {]),})- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()++ await stop()})it('skips filter_tree that is a JSON number', async () => {@@ -193,9 +215,11 @@ describe('EventFilterManager integration', () => {filter_tree: '42',})- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()++ await stop()})it('skips filter_tree with unknown node type', async () => {@@ -205,9 +229,11 @@ describe('EventFilterManager integration', () => {filter_tree: JSON.stringify({ type: 'xor', children: [] }),})- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()++ await stop()})it('skips filter_tree with invalid field in condition', async () => {@@ -217,9 +243,11 @@ describe('EventFilterManager integration', () => {filter_tree: JSON.stringify({ type: 'condition', field: 'session_id', operator: 'exact', value: 'x' }),})- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()++ await stop()})it('skips filter_tree with invalid operator in condition', async () => {@@ -229,9 +257,11 @@ describe('EventFilterManager integration', () => {filter_tree: JSON.stringify({ type: 'condition', field: 'event_name', operator: 'regex', value: 'x' }),})- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()++ await stop()})it('skips filter_tree with empty value in condition', async () => {@@ -241,9 +271,11 @@ describe('EventFilterManager integration', () => {filter_tree: JSON.stringify({ type: 'condition', field: 'event_name', operator: 'exact', value: '' }),})- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()++ await stop()})it('skips filter_tree with numeric value in condition', async () => {@@ -253,9 +285,11 @@ describe('EventFilterManager integration', () => {filter_tree: JSON.stringify({ type: 'condition', field: 'event_name', operator: 'exact', value: 123 }),})- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()++ await stop()})it('skips filter_tree with missing children in AND node', async () => {@@ -265,9 +299,11 @@ describe('EventFilterManager integration', () => {filter_tree: JSON.stringify({ type: 'and' }),})- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()++ await stop()})it('skips filter_tree with missing child in NOT node', async () => {@@ -277,9 +313,11 @@ describe('EventFilterManager integration', () => {filter_tree: JSON.stringify({ type: 'not' }),})- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()++ await stop()})it('skips row with unknown mode value', async () => {@@ -289,9 +327,11 @@ describe('EventFilterManager integration', () => {filter_tree: JSON.stringify(cond('event_name', 'exact', 'pageview')),})- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()++ await stop()})it('skips deeply nested but structurally invalid tree', async () => {@@ -308,9 +348,11 @@ describe('EventFilterManager integration', () => {}),})- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()++ await stop()})it('one bad row does not prevent loading other teams', async () => {@@ -323,12 +365,14 @@ describe('EventFilterManager integration', () => {// Team 2: validawait insertFilter(postgres, teamId2, 'live', cond('event_name', 'exact', 'drop_me'))- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()const f2 = manager.getFilter(teamId2)expect(f2).not.toBeNull()expect(evaluateFilterTree(f2!.filter_tree, { event_name: 'drop_me' })).toBe(true)++ await stop()})it('extra unknown fields in filter_tree are tolerated', async () => {@@ -346,11 +390,13 @@ describe('EventFilterManager integration', () => {}),})- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()const filter = manager.getFilter(teamId)expect(filter).not.toBeNull()expect(evaluateFilterTree(filter!.filter_tree, { event_name: 'test' })).toBe(true)++ await stop()})})@@ -359,20 +405,23 @@ describe('EventFilterManager integration', () => {describe('filters without real conditions return null', () => {it('empty AND group', async () => {await insertFilter(postgres, teamId, 'live', { type: 'and', children: [] })- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()+ await stop()})it('empty OR group', async () => {await insertFilter(postgres, teamId, 'live', { type: 'or', children: [] })- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()+ await stop()})it('NOT wrapping empty group', async () => {await insertFilter(postgres, teamId, 'live', not({ type: 'or', children: [] }))- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()+ await stop()})it('nested empty groups', async () => {@@ -380,26 +429,30 @@ describe('EventFilterManager integration', () => {type: 'or',children: [{ type: 'and', children: [{ type: 'or', children: [] }] }],})- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).toBeNull()+ await stop()})it('single condition is not empty', async () => {await insertFilter(postgres, teamId, 'live', cond('event_name', 'exact', 'pageview'))- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).not.toBeNull()+ await stop()})it('nested condition is not empty', async () => {await insertFilter(postgres, teamId, 'live', and(cond('event_name', 'exact', 'pageview')))- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).not.toBeNull()+ await stop()})it('NOT wrapping condition is not empty', async () => {await insertFilter(postgres, teamId, 'live', not(cond('event_name', 'exact', 'pageview')))- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()expect(manager.getFilter(teamId)).not.toBeNull()+ await stop()})})@@ -408,46 +461,54 @@ describe('EventFilterManager integration', () => {const tree = and(cond('event_name', 'exact', 'pageview'), cond('distinct_id', 'exact', 'bot-1'))await insertFilter(postgres, teamId, 'live', tree)- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()const filter = manager.getFilter(teamId)!expect(evaluateFilterTree(filter.filter_tree, { event_name: 'pageview', distinct_id: 'bot-1' })).toBe(true)expect(evaluateFilterTree(filter.filter_tree, { event_name: 'pageview', distinct_id: 'user' })).toBe(false)expect(evaluateFilterTree(filter.filter_tree, { event_name: 'click', distinct_id: 'bot-1' })).toBe(false)++ await stop()})it('OR with two conditions', async () => {const tree = or(cond('event_name', 'exact', 'pageview'), cond('event_name', 'exact', 'click'))await insertFilter(postgres, teamId, 'live', tree)- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()const filter = manager.getFilter(teamId)!expect(evaluateFilterTree(filter.filter_tree, { event_name: 'pageview' })).toBe(true)expect(evaluateFilterTree(filter.filter_tree, { event_name: 'click' })).toBe(true)expect(evaluateFilterTree(filter.filter_tree, { event_name: 'submit' })).toBe(false)++ await stop()})it('NOT inverts condition', async () => {const tree = not(cond('event_name', 'exact', 'keep'))await insertFilter(postgres, teamId, 'live', tree)- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()const filter = manager.getFilter(teamId)!expect(evaluateFilterTree(filter.filter_tree, { event_name: 'keep' })).toBe(false)expect(evaluateFilterTree(filter.filter_tree, { event_name: 'other' })).toBe(true)++ await stop()})it('contains operator', async () => {const tree = cond('distinct_id', 'contains', 'bot-')await insertFilter(postgres, teamId, 'live', tree)- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()const filter = manager.getFilter(teamId)!expect(evaluateFilterTree(filter.filter_tree, { distinct_id: 'bot-crawler' })).toBe(true)expect(evaluateFilterTree(filter.filter_tree, { distinct_id: 'real-user' })).toBe(false)++ await stop()})// Mirrors Python test_complex_tree_with_many_test_cases:@@ -460,7 +521,7 @@ describe('EventFilterManager integration', () => {)await insertFilter(postgres, teamId, 'live', tree)- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()const filter = manager.getFilter(teamId)!// $autocapture from regular user -> drop@@ -495,6 +556,8 @@ describe('EventFilterManager integration', () => {expect(evaluateFilterTree(filter.filter_tree, { distinct_id: 'user-1' })).toBe(false)// distinct_id missing -> NOT(false)=true, OR still needs to matchexpect(evaluateFilterTree(filter.filter_tree, { event_name: '$autocapture' })).toBe(true)++ await stop()})// Mirrors Python test_test_case_with_distinct_id@@ -502,7 +565,7 @@ describe('EventFilterManager integration', () => {const tree = and(cond('event_name', 'exact', 'pageview'), cond('distinct_id', 'contains', 'bot'))await insertFilter(postgres, teamId, 'live', tree)- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()const filter = manager.getFilter(teamId)!expect(evaluateFilterTree(filter.filter_tree, { event_name: 'pageview', distinct_id: 'bot-123' })).toBe(@@ -511,18 +574,22 @@ describe('EventFilterManager integration', () => {expect(evaluateFilterTree(filter.filter_tree, { event_name: 'pageview', distinct_id: 'user-1' })).toBe(false)++ await stop()})it('NOT wrapping OR (allowlist pattern)', async () => {const tree = not(or(cond('event_name', 'exact', 'allowed_1'), cond('event_name', 'exact', 'allowed_2')))await insertFilter(postgres, teamId, 'live', tree)- const manager = await createManagerAndWaitForLoad()+ const { manager, stop } = await createManagerAndWaitForLoad()const filter = manager.getFilter(teamId)!expect(evaluateFilterTree(filter.filter_tree, { event_name: 'allowed_1' })).toBe(false)expect(evaluateFilterTree(filter.filter_tree, { event_name: 'allowed_2' })).toBe(false)expect(evaluateFilterTree(filter.filter_tree, { event_name: 'other' })).toBe(true)++ await stop()})})})diff --git a/nodejs/src/ingestion/common/event-filters/manager.test.ts b/nodejs/src/ingestion/common/event-filters/manager.test.tsindex 5cff679a9d32..42ddc51fec9c 100644--- a/nodejs/src/ingestion/common/event-filters/manager.test.ts+++ b/nodejs/src/ingestion/common/event-filters/manager.test.ts@@ -1,9 +1,15 @@-import { EventFilterManager } from './manager'+import { EventFilterManager, EventFilterManagerComponent } from './manager'describe('EventFilterManager', () => {const mockPostgres = {query: jest.fn(),- } as any+ }++ async function buildManager(): Promise<{ manager: EventFilterManager; stop: () => Promise<void> }> {+ const scope = new EventFilterManagerComponent(mockPostgres as any)+ const started = await scope.start()+ return { manager: started.value, stop: started.stop }+ }beforeEach(() => {jest.clearAllMocks()@@ -11,9 +17,9 @@ describe('EventFilterManager', () => {it('returns null for unknown team', async () => {mockPostgres.query.mockResolvedValue({ rows: [] })- const manager = new EventFilterManager(mockPostgres)- await new Promise((r) => setTimeout(r, 100))+ const { manager, stop } = await buildManager()expect(manager.getFilter(999)).toBeNull()+ await stop()})it('returns filter for team in live mode', async () => {@@ -30,13 +36,14 @@ describe('EventFilterManager', () => {},],})- const manager = new EventFilterManager(mockPostgres)- await new Promise((r) => setTimeout(r, 100))+ const { manager, stop } = await buildManager()const filter = manager.getFilter(1)expect(filter).not.toBeNull()expect(filter!.id).toBe('filter-1')expect(filter!.mode).toBe('live')++ await stop()})it('returns filter for team in dry_run mode', async () => {@@ -55,12 +62,13 @@ describe('EventFilterManager', () => {},],})- const manager = new EventFilterManager(mockPostgres)- await new Promise((r) => setTimeout(r, 100))+ const { manager, stop } = await buildManager()const filter = manager.getFilter(1)expect(filter).not.toBeNull()expect(filter!.mode).toBe('dry_run')++ await stop()})it('returns null for filter with no conditions (empty tree)', async () => {@@ -74,10 +82,11 @@ describe('EventFilterManager', () => {},],})- const manager = new EventFilterManager(mockPostgres)- await new Promise((r) => setTimeout(r, 100))+ const { manager, stop } = await buildManager()expect(manager.getFilter(1)).toBeNull()++ await stop()})it('skips rows with invalid filter_tree', async () => {@@ -102,12 +111,13 @@ describe('EventFilterManager', () => {},],})- const manager = new EventFilterManager(mockPostgres)- await new Promise((r) => setTimeout(r, 100))+ const { manager, stop } = await buildManager()expect(manager.getFilter(1)).toBeNull()expect(manager.getFilter(2)).not.toBeNull()expect(manager.getFilter(2)!.id).toBe('good-filter')++ await stop()})it('skips rows with empty condition value', async () => {@@ -126,10 +136,11 @@ describe('EventFilterManager', () => {},],})- const manager = new EventFilterManager(mockPostgres)- await new Promise((r) => setTimeout(r, 100))+ const { manager, stop } = await buildManager()expect(manager.getFilter(1)).toBeNull()++ await stop()})it('handles multiple teams', async () => {@@ -149,11 +160,12 @@ describe('EventFilterManager', () => {},],})- const manager = new EventFilterManager(mockPostgres)- await new Promise((r) => setTimeout(r, 100))+ const { manager, stop } = await buildManager()expect(manager.getFilter(1)!.id).toBe('f1')expect(manager.getFilter(2)!.id).toBe('f2')expect(manager.getFilter(3)).toBeNull()++ await stop()})})diff --git a/nodejs/src/ingestion/common/event-filters/manager.ts b/nodejs/src/ingestion/common/event-filters/manager.tsindex 99ee5f75f2b0..54fb87708817 100644--- a/nodejs/src/ingestion/common/event-filters/manager.ts+++ b/nodejs/src/ingestion/common/event-filters/manager.ts@@ -1,21 +1,28 @@import { BackgroundRefresher } from '../../../utils/background-refresher'import { PostgresRouter, PostgresUse } from '../../../utils/db/postgres'import { logger } from '../../../utils/logger'+import { Component } from '../scopes'import { treeHasConditions } from './evaluate'import { EventFilterRowSchema, EventFilterRule } from './schema'/**- * Manages per-team event filter config loaded from Postgres.- * One filter per team. Uses BackgroundRefresher to load all active filters- * (mode = 'dry_run' or 'live').+ * Manages per-team event filter config loaded from Postgres. One filter+ * per team, cached via a `BackgroundRefresher` that reloads all active+ * filters every 60s. The constructor does not prime the cache; call+ * `prime()` (or wrap construction in `EventFilterManagerComponent`) to+ * await the initial load.*/export class EventFilterManager {private refresher: BackgroundRefresher<Map<number, EventFilterRule>>- constructor(private postgres: PostgresRouter) {+ constructor(private readonly postgres: PostgresRouter) {this.refresher = new BackgroundRefresher(async () => this.fetchAllFilters(), 60_000)+ }- void this.refresher.get().catch((error) => {+ async prime(): Promise<void> {+ // Failures are logged but don't surface — `tryGet` will retry in the+ // background on subsequent reads.+ await this.refresher.get().catch((error) => {logger.error('Failed to initialize event filter config', { error })})}@@ -62,3 +69,19 @@ export class EventFilterManager {return map}}++/**+ * Scope entry for `EventFilterManager`. `start()` constructs the manager+ * and awaits the initial cache prime before handing it back. Stop is a+ * no-op — dropping the manager and refresher references lets GC reclaim+ * them.+ */+export class EventFilterManagerComponent implements Component<EventFilterManager> {+ constructor(private readonly postgres: PostgresRouter) {}++ async start(): Promise<{ value: EventFilterManager; stop: () => Promise<void> }> {+ const manager = new EventFilterManager(this.postgres)+ await manager.prime()+ return { value: manager, stop: () => Promise.resolve() }+ }+}diff --git a/nodejs/src/ingestion/common/ingestion-consumer.ts b/nodejs/src/ingestion/common/ingestion-consumer.tsnew file mode 100644index 000000000000..b3962c2ab065--- /dev/null+++ b/nodejs/src/ingestion/common/ingestion-consumer.ts@@ -0,0 +1,205 @@+import { Message } from 'node-rdkafka'+import { Gauge } from 'prom-client'++import { instrumentFn } from '~/common/tracing/tracing-utils'++import { HealthCheckResult, PluginServerService } from '../../types'+import { logger } from '../../utils/logger'+import { IngestionConsumerConfig } from '../config'+import { BatchResult, FeedResult } from '../pipelines/batching-pipeline'+import { createOkContext } from '../pipelines/helpers'+import { OkResultWithContext } from '../pipelines/pipeline.interface'+import { Scope, extend } from './scopes'+import { KafkaConsumerComponent, KafkaConsumerInterface } from './utils/kafka-consumer'+import { PromiseScheduler } from './utils/promise-scheduler'++type MessageInput = { message: Message }+type MessageContext = { message: Message }++export interface IngestionBatchingPipeline {+ feed(elements: OkResultWithContext<MessageInput, MessageContext>[]): Promise<FeedResult>+ next(): Promise<BatchResult<unknown> | null>+}++export interface PipelineFactoryContext<S extends Record<string, object>> {+ container: S+}++export type PipelineFactory<S extends Record<string, object>> = (+ ctx: PipelineFactoryContext<S>+) => IngestionBatchingPipeline++/**+ * Constraint on a scope's container: must expose a `promiseScheduler`.+ * The common consumer pulls it from the container to schedule pipeline+ * side effects. The scheduler is owned by the user-provided scope so its+ * lifetime spans the consumer's lifetime.+ */+export type ContainerWithPromiseScheduler = Record<string, object> & { promiseScheduler: PromiseScheduler }++export type CommonIngestionConsumerConfig = Pick<+ IngestionConsumerConfig,+ | 'INGESTION_CONSUMER_GROUP_ID'+ | 'INGESTION_CONSUMER_CONSUME_TOPIC'+ | 'INGESTION_PIPELINE'+ | 'INGESTION_LANE'+ | 'KAFKA_BATCH_START_LOGGING_ENABLED'+>++const latestOffsetTimestampGauge = new Gauge({+ name: 'common_ingestion_latest_processed_timestamp_ms',+ help: 'Timestamp of the latest offset that has been committed.',+ labelNames: ['topic', 'partition', 'groupId'],+ aggregator: 'max',+})++/**+ * Setup-side of a common ingestion consumer. Constructing it extends the+ * user-provided scope with a `kafkaConsumer` entry; `start()` brings up+ * the parent scope, builds the pipeline (sync), connects the Kafka+ * consumer, and returns a live `CommonIngestionConsumer` that owns the+ * started handle.+ */+export class CommonIngestionConsumerScope<S extends ContainerWithPromiseScheduler> {+ private readonly innerScope: Scope<S & { kafkaConsumer: KafkaConsumerInterface }>++ constructor(+ private readonly name: string,+ config: CommonIngestionConsumerConfig,+ scope: Scope<S>,+ pipelineFactory: PipelineFactory<S>+ ) {+ const consumerName = this.name+ this.innerScope = extend(scope, `${consumerName}-consumer`, (container, builder) => {+ const pipeline = pipelineFactory({ container })+ const handler = new KafkaBatchHandler(config, consumerName, pipeline, container.promiseScheduler)+ return builder.add(+ 'kafkaConsumer',+ new KafkaConsumerComponent(+ config.INGESTION_CONSUMER_GROUP_ID,+ config.INGESTION_CONSUMER_CONSUME_TOPIC,+ (messages) => handler.handle(messages)+ )+ )+ })+ }++ async start(): Promise<{ consumer: CommonIngestionConsumer; stop: () => Promise<void> }> {+ const started = await this.innerScope.start()+ const consumer = new CommonIngestionConsumer(this.name, started.container.kafkaConsumer)+ return { consumer, stop: started.stop }+ }+}++/**+ * Live, started common ingestion consumer. Exposes only what surrounding+ * code actually needs from the started scope: the Kafka consumer (for+ * health) and the per-process healthcheck. Lifetime is owned by the+ * scope handle returned alongside it from `CommonIngestionConsumerScope.start()`.+ */+export class CommonIngestionConsumer {+ constructor(+ readonly name: string,+ private readonly kafkaConsumer: KafkaConsumerInterface+ ) {}++ isHealthy(): HealthCheckResult {+ return this.kafkaConsumer.isHealthy()+ }+}++/**+ * Builds a `PluginServerService` descriptor for a started common+ * ingestion consumer. The scope handle's `stop` is supplied explicitly+ * so lifecycle ownership stays with the scope, not the consumer.+ */+export function ingestionConsumerService(+ consumer: CommonIngestionConsumer,+ stop: () => Promise<void>+): PluginServerService {+ return {+ id: consumer.name,+ onShutdown: stop,+ healthcheck: () => consumer.isHealthy(),+ }+}++/**+ * Per-consumer wrapper that owns the deps a Kafka batch handler needs+ * (config, name, pipeline, promise scheduler) and exposes a single+ * `handle(messages)` method matching what `KafkaConsumerComponent` expects.+ * Internal — only constructed inside `CommonIngestionConsumerScope`.+ */+class KafkaBatchHandler {+ constructor(+ private readonly config: CommonIngestionConsumerConfig,+ private readonly name: string,+ private readonly pipeline: IngestionBatchingPipeline,+ private readonly promiseScheduler: PromiseScheduler+ ) {}++ async handle(messages: Message[]): Promise<{ backgroundTask?: Promise<unknown> }> {+ if (this.config.KAFKA_BATCH_START_LOGGING_ENABLED) {+ this.logBatchStart(messages)+ }++ const batch = messages.map((message) => createOkContext({ message }, { message }))++ const feedResult = await this.pipeline.feed(batch)+ if (!feedResult.ok) {+ throw new Error(`Pipeline rejected batch: ${feedResult.reason}`)+ }++ let result = await this.pipeline.next()+ while (result !== null) {+ for (const sideEffect of result.sideEffects ?? []) {+ void this.promiseScheduler.schedule(sideEffect)+ }+ result = await this.pipeline.next()+ }++ for (const message of messages) {+ if (message.timestamp) {+ latestOffsetTimestampGauge+ .labels({+ partition: message.partition,+ topic: message.topic,+ groupId: this.config.INGESTION_CONSUMER_GROUP_ID,+ })+ .set(message.timestamp)+ }+ }++ return {+ backgroundTask: instrumentFn('commonIngestionConsumer.awaitScheduledWork', async () => {+ await this.promiseScheduler.waitForAll()+ }),+ }+ }++ private logBatchStart(messages: Message[]): void {+ const podName = process.env.HOSTNAME || 'unknown'+ const partitionEarliestMessages = new Map<number, Message>()+ const partitionBatchSizes = new Map<number, number>()++ messages.forEach((message) => {+ const existing = partitionEarliestMessages.get(message.partition)+ if (!existing || message.offset < existing.offset) {+ partitionEarliestMessages.set(message.partition, message)+ }+ partitionBatchSizes.set(message.partition, (partitionBatchSizes.get(message.partition) || 0) + 1)+ })++ const partitionData = Array.from(partitionEarliestMessages.entries()).map(([partition, message]) => ({+ partition,+ offset: message.offset,+ batchSize: partitionBatchSizes.get(partition) || 0,+ }))++ logger.info('📖', `KAFKA_BATCH_START: ${this.name}`, {+ pod: podName,+ totalMessages: messages.length,+ partitions: partitionData,+ })+ }+}diff --git a/nodejs/src/ingestion/common/outputs/registry.ts b/nodejs/src/ingestion/common/outputs/registry.tsindex a3b52193a5dc..ccd430b748a1 100644--- a/nodejs/src/ingestion/common/outputs/registry.ts+++ b/nodejs/src/ingestion/common/outputs/registry.ts@@ -1,5 +1,6 @@-import { DEFAULT_PRODUCER, INGESTION_PRODUCER, WARPSTREAM_PRODUCER } from '.'+import { DEFAULT_PRODUCER, INGESTION_PRODUCER, ProducerName, WARPSTREAM_PRODUCER } from '.'+import { KafkaProducerRegistry } from '../../outputs/kafka-producer-registry'import { KafkaProducerRegistryBuilder } from '../../outputs/kafka-producer-registry-builder'import { DEFAULT_PRODUCER_CONFIG_MAP, INGESTION_PRODUCER_CONFIG_MAP, WARPSTREAM_PRODUCER_CONFIG_MAP } from '../config'@@ -10,3 +11,24 @@ export function createProducerRegistry(kafkaClientRack: string | undefined) {.register(WARPSTREAM_PRODUCER, WARPSTREAM_PRODUCER_CONFIG_MAP).register(INGESTION_PRODUCER, INGESTION_PRODUCER_CONFIG_MAP)}++type ProducerRegistryConfig = Parameters<ReturnType<typeof createProducerRegistry>['build']>[0]++/**+ * Lifecycle owner for the shared Kafka producer registry. `start()`+ * connects all registered producers; `stop()` disconnects them.+ */+export class KafkaProducerRegistryComponent {+ constructor(+ private readonly kafkaClientRack: string | undefined,+ private readonly config: ProducerRegistryConfig+ ) {}++ async start(): Promise<{ value: KafkaProducerRegistry<ProducerName>; stop: () => Promise<void> }> {+ const registry = await createProducerRegistry(this.kafkaClientRack).build(this.config)+ return {+ value: registry,+ stop: () => registry.disconnectAll(),+ }+ }+}diff --git a/nodejs/src/ingestion/common/scopes/caller-set.test.ts b/nodejs/src/ingestion/common/scopes/caller-set.test.tsnew file mode 100644index 000000000000..69d02b62046b--- /dev/null+++ b/nodejs/src/ingestion/common/scopes/caller-set.test.ts@@ -0,0 +1,38 @@+import { CallerSet } from './caller-set'++describe('CallerSet', () => {+ it('tracks the number of active callers', () => {+ const set = new CallerSet()+ expect(set.size()).toBe(0)++ const releaseA = set.register()+ const releaseB = set.register()+ expect(set.size()).toBe(2)++ releaseA()+ expect(set.size()).toBe(1)++ releaseB()+ expect(set.size()).toBe(0)+ })++ it('returns true only on the first release of a caller', () => {+ const set = new CallerSet()+ const release = set.register()++ expect(release()).toBe(true)+ expect(release()).toBe(false)+ expect(release()).toBe(false)+ })++ it('does not double-count a single-shot release against size', () => {+ const set = new CallerSet()+ const release = set.register()+ set.register()++ release()+ release()++ expect(set.size()).toBe(1)+ })+})diff --git a/nodejs/src/ingestion/common/scopes/caller-set.ts b/nodejs/src/ingestion/common/scopes/caller-set.tsnew file mode 100644index 000000000000..766c0ceb88ea--- /dev/null+++ b/nodejs/src/ingestion/common/scopes/caller-set.ts@@ -0,0 +1,24 @@+// Refcount with single-shot release callbacks.++export class CallerSet {+ private callers = new Set<number>()+ private nextId = 0++ register(): () => boolean {+ const id = this.nextId+++ this.callers.add(id)+ let released = false+ return () => {+ if (released) {+ return false+ }+ released = true+ this.callers.delete(id)+ return true+ }+ }++ size(): number {+ return this.callers.size+ }+}diff --git a/nodejs/src/ingestion/common/scopes/component.ts b/nodejs/src/ingestion/common/scopes/component.tsnew file mode 100644index 000000000000..bb2f2f6bdd22--- /dev/null+++ b/nodejs/src/ingestion/common/scopes/component.ts@@ -0,0 +1,22 @@+/** A started value paired with the `stop` callback that tears it down. */+export interface Started<T> {+ value: T+ stop: () => Promise<void>+}++/**+ * Defines the lifecycle of a single container value. `start()` produces the+ * value plus a `stop` callback that tears it down. Anyone holding the value+ * only sees the business interface — the start/stop pair stays with the+ * component. This lets the scope plumb dependencies (services, pools, config)+ * through a single container without each entry needing to wear a+ * start/stop hat.+ */+export interface Component<T> {+ start(): Promise<Started<T>>+}++export type ValueOf<C> = C extends Component<infer T> ? T : never++/** Maps each container key to the `Component` that produces its value. */+export type ComponentMap<S> = { [K in keyof S]: Component<S[K]> }diff --git a/nodejs/src/ingestion/common/scopes/empty-scope.ts b/nodejs/src/ingestion/common/scopes/empty-scope.tsnew file mode 100644index 000000000000..689faea7e5b1--- /dev/null+++ b/nodejs/src/ingestion/common/scopes/empty-scope.ts@@ -0,0 +1,18 @@+import { Startable, StartedScope } from './scope'++/**+ * The bottom of every scope tree: a parent that contributes nothing. Its+ * container is empty and its lifecycle is a no-op, so a root scope is just+ * a `ScopeRunner` extending over this. Deliberately silent — it emits no+ * logs and holds no refcount, since it has a single consumer and nothing+ * to tear down.+ */+export class EmptyScope implements Startable<Record<never, object>> {+ start(): Promise<StartedScope<Record<never, object>>> {+ return Promise.resolve({+ name: '∅',+ container: {},+ stop: () => Promise.resolve(),+ })+ }+}diff --git a/nodejs/src/ingestion/common/scopes/index.ts b/nodejs/src/ingestion/common/scopes/index.tsnew file mode 100644index 000000000000..52a8a7f60927--- /dev/null+++ b/nodejs/src/ingestion/common/scopes/index.ts@@ -0,0 +1,4 @@+export type { Component } from './component'+export { ScopeBuilder } from './scope-builder'+export { Scope, newScope, extend } from './scope'+export type { StartedScope } from './scope'diff --git a/nodejs/src/ingestion/common/scopes/runner.test.ts b/nodejs/src/ingestion/common/scopes/runner.test.tsnew file mode 100644index 000000000000..cc1c1d814426--- /dev/null+++ b/nodejs/src/ingestion/common/scopes/runner.test.ts@@ -0,0 +1,164 @@+import { Component } from './component'+import { EmptyScope } from './empty-scope'+import { ScopeRunner } from './runner'+import { ScopeBuilder } from './scope-builder'+import { makeComponent } from './test-fixtures'++describe('ScopeRunner', () => {+ it('starts entries and assembles the container', async () => {+ const log: string[] = []+ const a = makeComponent('a', log)+ const b = makeComponent('b', log)++ const runner = new ScopeRunner(+ new EmptyScope(),+ () => ScopeBuilder.empty().add('a', a).add('b', b).components(),+ 'phase'+ )+ const { value } = await runner.start()++ expect(log).toEqual(['start:a', 'start:b'])+ expect(value).toEqual({ a: { name: 'a' }, b: { name: 'b' } })+ })++ it('tears down all started entries', async () => {+ const log: string[] = []+ const a = makeComponent('a', log)+ const b = makeComponent('b', log)+ const c = makeComponent('c', log)++ const runner = new ScopeRunner(+ new EmptyScope(),+ () => ScopeBuilder.empty().add('a', a).add('b', b).add('c', c).components(),+ 'phase'+ )+ const { stop } = await runner.start()+ await stop()++ // Siblings are torn down in parallel, so stop ordering is not deterministic.+ expect(log.slice(0, 3)).toEqual(['start:a', 'start:b', 'start:c'])+ expect(log.slice(3).sort()).toEqual(['stop:a', 'stop:b', 'stop:c'])+ expect([a, b, c].map((component) => component.stopCalls)).toEqual([1, 1, 1])+ })++ it('stops every entry even when stops throw, accumulating errors into an AggregateError', async () => {+ const log: string[] = []+ const failingStop = (name: string, message: string): Component<{ name: string }> => ({+ start: jest.fn(() => {+ log.push(`start:${name}`)+ return Promise.resolve({+ value: { name },+ stop: () => {+ log.push(`stop:${name}`)+ return Promise.reject(new Error(message))+ },+ })+ }),+ })+ const a = makeComponent('a', log)+ const b = failingStop('b', 'b stop failed')+ const c = failingStop('c', 'c stop failed')++ const runner = new ScopeRunner(+ new EmptyScope(),+ () => ScopeBuilder.empty().add('a', a).add('b', b).add('c', c).components(),+ 'phase'+ )+ const { stop } = await runner.start()++ // Both c and b throw, but neither aborts teardown, so a still stops —+ // no leaked resources — and both errors come back in the AggregateError.+ const error = await stop().then(+ () => null,+ (e: unknown) => e+ )+ if (!(error instanceof AggregateError)) {+ throw new Error(`expected an AggregateError, got ${String(error)}`)+ }+ expect(error.errors.map((e: Error) => e.message).sort()).toEqual(['b stop failed', 'c stop failed'])+ expect(log.slice(0, 3)).toEqual(['start:a', 'start:b', 'start:c'])+ expect(log.slice(3).sort()).toEqual(['stop:a', 'stop:b', 'stop:c'])+ })++ it('lets a child override a parent key while still running both lifecycles', async () => {+ const log: string[] = []+ const parentA = makeComponent('parentA', log)+ const childA = makeComponent('childA', log)++ const parent = ScopeBuilder.empty().add('a', parentA).build('parent')+ const child = new ScopeRunner(parent, () => ({ a: childA }), 'child')++ const started = await child.start()+ // The child's value wins in the merged container, but both components+ // were started and both get torn down — the parent isn't orphaned.+ expect(started.value.a).toEqual({ name: 'childA' })+ expect(parentA.startCalls).toBe(1)+ expect(childA.startCalls).toBe(1)++ await started.stop()+ expect(parentA.stopCalls).toBe(1)+ expect(childA.stopCalls).toBe(1)+ expect(log).toEqual(['start:parentA', 'start:childA', 'stop:childA', 'stop:parentA'])+ })++ it('rolls back already-started entries when a later one fails to start', async () => {+ const log: string[] = []+ const a = makeComponent('a', log)+ const b: Component<{ name: string }> = {+ start: jest.fn(() => {+ log.push('start:b')+ return Promise.reject(new Error('b failed'))+ }),+ }++ const runner = new ScopeRunner(+ new EmptyScope(),+ () => ScopeBuilder.empty().add('a', a).add('b', b).components(),+ 'phase'+ )++ await expect(runner.start()).rejects.toThrow('b failed')+ // Only entries that successfully started are rolled back, in reverse.+ expect(log).toEqual(['start:a', 'start:b', 'stop:a'])+ })++ it('surfaces the start error even when rollback teardown also fails', async () => {+ const log: string[] = []+ const a: Component<{ name: string }> = {+ start: jest.fn(() => {+ log.push('start:a')+ return Promise.resolve({+ value: { name: 'a' },+ stop: () => {+ log.push('stop:a')+ return Promise.reject(new Error('a stop failed'))+ },+ })+ }),+ }+ const b: Component<{ name: string }> = {+ start: jest.fn(() => {+ log.push('start:b')+ return Promise.reject(new Error('b failed to start'))+ }),+ }++ const runner = new ScopeRunner(+ new EmptyScope(),+ () => ScopeBuilder.empty().add('a', a).add('b', b).components(),+ 'phase'+ )++ // The rollback stop of `a` throws too. The start failure stays the+ // primary cause (first error), with the rollback error folded in.+ const error = await runner.start().then(+ () => null,+ (e: unknown) => e+ )+ if (!(error instanceof AggregateError)) {+ throw new Error(`expected an AggregateError, got ${String(error)}`)+ }+ expect(error.errors.map((e: Error) => e.message)).toEqual(['b failed to start', 'a stop failed'])+ expect(log).toEqual(['start:a', 'start:b', 'stop:a'])+ })+})diff --git a/nodejs/src/ingestion/common/scopes/runner.ts b/nodejs/src/ingestion/common/scopes/runner.tsnew file mode 100644index 000000000000..19bbdb8ff57b--- /dev/null+++ b/nodejs/src/ingestion/common/scopes/runner.ts@@ -0,0 +1,124 @@+import { logger } from '../../../utils/logger'+import { Component, ComponentMap, Started } from './component'+import type { Startable } from './scope'++/**+ * A `Component` that runs a child layer on top of a parent scope. On+ * `start` it acquires the parent (refcounted), builds the child's component+ * map from the parent's container, boots those components in parallel, and+ * exposes `parent ∪ child`. If a child entry fails, the already-started+ * children are rolled back, the parent is released, and the first error is+ * rethrown. The returned `stop` tears children down in parallel, then+ * releases the parent. A root scope is this runner over an `EmptyScope`.+ */+export class ScopeRunner<SParent extends Record<string, object>, SChild extends Record<string, object>>+ implements Component<SParent & SChild>+{+ constructor(+ private readonly parent: Startable<SParent>,+ private readonly childComponents: (parentContainer: SParent) => ComponentMap<SChild>,+ private readonly name: string+ ) {}++ async start(): Promise<Started<SParent & SChild>> {+ const parentHandle = await this.parent.start()+ try {+ const children = await this.startChildren(parentHandle.container)+ return {+ value: { ...parentHandle.container, ...children.value },+ stop: async (): Promise<void> => {+ try {+ await children.stop()+ } finally {+ await parentHandle.stop()+ }+ },+ }+ } catch (err) {+ try {+ await parentHandle.stop()+ } catch (parentStopErr) {+ logger.error(`Scope[${this.name}]: parent stop failed during rollback`, { error: parentStopErr })+ }+ throw err+ }+ }++ private async startChildren(parentContainer: SParent): Promise<Started<SChild>> {+ const components: ComponentMap<SChild> = this.childComponents(parentContainer)+ const entries: Array<[string, Component<object>]> = Object.entries(components)+ logger.info(`Scope[${this.name}]: starting ${entries.length} entries in parallel`)++ const results = await Promise.allSettled(+ entries.map(async ([name, component]) => {+ logger.info(`Scope[${this.name}]: starting ${name}`)+ return await component.start()+ })+ )++ const started: Array<Started<object> & { name: string }> = []+ const failures: Array<{ name: string; error: unknown }> = []++ for (let i = 0; i < results.length; i++) {+ const result = results[i]+ const name = entries[i][0]+ if (result.status === 'fulfilled') {+ started.push({ name, value: result.value.value, stop: result.value.stop })+ } else {+ failures.push({ name, error: result.reason })+ }+ }++ if (failures.length > 0) {+ for (const f of failures) {+ logger.error(`Scope[${this.name}]: ${f.name} start failed`, { error: f.error })+ }+ logger.error(`Scope[${this.name}]: start failed, rolling back ${started.length} started value(s)`)+ // Keep the start failure as the primary cause; if rolling back the+ // partially-started scope also fails, fold those errors in rather+ // than dropping them or letting them mask the root cause.+ try {+ await this.teardown(started)+ } catch (rollbackErr) {+ const rollbackErrors = rollbackErr instanceof AggregateError ? rollbackErr.errors : [rollbackErr]+ throw new AggregateError(+ [failures[0].error, ...rollbackErrors],+ `Scope[${this.name}]: start failed and rollback teardown failed`+ )+ }+ throw failures[0].error+ }++ // `components` is typed `ComponentMap<SChild>`, so each entry's value+ // is the `SChild[K]` for its key — the assembled record is therefore+ // `SChild`. The assertion only bridges `Object.fromEntries` erasing+ // per-key types.+ const value = Object.fromEntries(started.map((s) => [s.name, s.value])) as SChild+ return { value, stop: () => this.teardown(started) }+ }++ private async teardown(started: Array<{ name: string; stop: () => Promise<void> }>): Promise<void> {+ // Siblings within a scope are built independently from the parent+ // container, so they have no ordering dependencies on each other and can+ // be stopped in parallel (the parent is released afterwards, separately).+ // Stop every component even if one throws, so a single failed stop can't+ // leak the resources owned by another. Every stop error is collected and+ // rethrown together once teardown is done.+ const results = await Promise.allSettled(+ started.map(async (s) => {+ logger.info(`Scope[${this.name}]: stopping ${s.name}`)+ try {+ await s.stop()+ } catch (err) {+ logger.error(`Scope[${this.name}]: ${s.name} stop failed`, { error: err })+ throw err+ }+ })+ )++ const errors = results.flatMap((result) => (result.status === 'rejected' ? [result.reason] : []))+ if (errors.length > 0) {+ throw new AggregateError(errors, `Scope[${this.name}]: ${errors.length} component(s) failed to stop`)+ }+ }+}diff --git a/nodejs/src/ingestion/common/scopes/scope-builder.test.ts b/nodejs/src/ingestion/common/scopes/scope-builder.test.tsnew file mode 100644index 000000000000..615ccc0ddd0e--- /dev/null+++ b/nodejs/src/ingestion/common/scopes/scope-builder.test.ts@@ -0,0 +1,49 @@+import { ScopeBuilder } from './scope-builder'+import { makeComponent } from './test-fixtures'++describe('ScopeBuilder', () => {+ it('builds a scope whose container holds every added entry', async () => {+ const log: string[] = []+ const a = makeComponent('a', log)+ const b = makeComponent('b', log)++ const scope = ScopeBuilder.empty().add('a', a).add('b', b).build('phase')+ const started = await scope.start()++ expect(started.name).toBe('phase')+ expect(started.container).toEqual({ a: { name: 'a' }, b: { name: 'b' } })++ await started.stop()+ })++ it('does not start any component until the built scope is started', () => {+ const log: string[] = []+ const a = makeComponent('a', log)++ ScopeBuilder.empty().add('a', a).build('phase')++ expect(a.startCalls).toBe(0)+ expect(log).toEqual([])+ })++ it('rejects re-adding an existing key at the type level', async () => {+ const log: string[] = []+ const a = makeComponent('a', log)+ const b = makeComponent('b', log)++ const scope = ScopeBuilder.empty()+ .add('a', a)+ // @ts-expect-error re-adding an existing key collapses the `name` param to `never`+ .add('a', b)+ .build('phase')++ // The guard is purely at the type level — at runtime the later entry+ // overwrites the earlier one in the map, so only `b` ever starts.+ const started = await scope.start()+ expect(started.container).toEqual({ a: { name: 'b' } })+ expect(a.startCalls).toBe(0)+ expect(b.startCalls).toBe(1)++ await started.stop()+ })+})diff --git a/nodejs/src/ingestion/common/scopes/scope-builder.ts b/nodejs/src/ingestion/common/scopes/scope-builder.tsnew file mode 100644index 000000000000..81e18a78d71e--- /dev/null+++ b/nodejs/src/ingestion/common/scopes/scope-builder.ts@@ -0,0 +1,38 @@+import { Component, ComponentMap, ValueOf } from './component'+import { EmptyScope } from './empty-scope'+import { ScopeRunner } from './runner'+import { Scope } from './scope'++/**+ * Per-scope accumulator. `add` records a `Component` for each entry;+ * the corresponding value lands in the container only after the scope+ * starts. Until then, the builder is just a typed recipe.+ */+export class ScopeBuilder<S extends Record<string, object> = Record<never, object>> {+ private constructor(private readonly map: ComponentMap<S>) {}++ static empty(): ScopeBuilder<Record<never, object>> {+ return new ScopeBuilder<Record<never, object>>({})+ }++ add<Name extends string, C extends Component<object>>(+ name: Name & (Name extends keyof S ? never : Name),+ component: C+ ): ScopeBuilder<S & Record<Name, ValueOf<C>>> {+ // Adding the `name` key with its `component` produces exactly+ // `ComponentMap<S & Record<Name, ValueOf<C>>>`, but a computed-key+ // spread only types as a string index signature, so assert the shape+ // the method signature already guarantees.+ const map: Record<string, Component<object>> = { ...this.map, [name]: component }+ return new ScopeBuilder<S & Record<Name, ValueOf<C>>>(map as ComponentMap<S & Record<Name, ValueOf<C>>>)+ }++ /** The accumulated components, consumed by the runner when the scope starts. */+ components(): ComponentMap<S> {+ return this.map+ }++ build(name: string): Scope<S> {+ return new Scope<S>(name, new ScopeRunner<Record<never, object>, S>(new EmptyScope(), () => this.map, name))+ }+}diff --git a/nodejs/src/ingestion/common/scopes/scope.test.ts b/nodejs/src/ingestion/common/scopes/scope.test.tsnew file mode 100644index 000000000000..0f34b793e0fb--- /dev/null+++ b/nodejs/src/ingestion/common/scopes/scope.test.ts@@ -0,0 +1,286 @@+import { Component } from './component'+import { extend, newScope } from './scope'+import { makeComponent } from './test-fixtures'++describe('Scope', () => {+ it('starts and exposes its name and container', async () => {+ const log: string[] = []+ const a = makeComponent('a', log)+ const b = makeComponent('b', log)++ const scope = newScope('phase', (builder) => builder.add('a', a).add('b', b))+ const started = await scope.start()++ expect(started.name).toBe('phase')+ expect(started.container).toEqual({ a: { name: 'a' }, b: { name: 'b' } })++ await started.stop()+ })++ it('makes stop idempotent on a single handle', async () => {+ const log: string[] = []+ const a = makeComponent('a', log)++ const scope = newScope('phase', (builder) => builder.add('a', a))+ const { stop } = await scope.start()++ await stop()+ await stop()++ expect(a.stopCalls).toBe(1)+ })++ it('starts the component only once across multiple start calls', async () => {+ const log: string[] = []+ const a = makeComponent('a', log)++ const scope = newScope('phase', (builder) => builder.add('a', a))+ const h1 = await scope.start()+ const h2 = await scope.start()++ expect(a.startCalls).toBe(1)+ expect(h1.container).toBe(h2.container)++ await h1.stop()+ await h2.stop()+ })++ it('keeps running until the last caller releases', async () => {+ const log: string[] = []+ const a = makeComponent('a', log)++ const scope = newScope('phase', (builder) => builder.add('a', a))+ const h1 = await scope.start()+ const h2 = await scope.start()++ await h1.stop()+ expect(a.stopCalls).toBe(0)++ await h2.stop()+ expect(a.stopCalls).toBe(1)+ expect(log).toEqual(['start:a', 'stop:a'])+ })++ it('restarts cleanly after a full stop', async () => {+ const log: string[] = []+ const a = makeComponent('a', log)++ const scope = newScope('phase', (builder) => builder.add('a', a))+ const h1 = await scope.start()+ await h1.stop()++ const h2 = await scope.start()+ await h2.stop()++ expect(a.startCalls).toBe(2)+ expect(a.stopCalls).toBe(2)+ expect(log).toEqual(['start:a', 'stop:a', 'start:a', 'stop:a'])+ })++ it('shares the same start operation across concurrent start calls', async () => {+ const log: string[] = []+ let resolveStart: (() => void) | undefined+ const stopA = jest.fn((): Promise<void> => {+ log.push('stop:a')+ return Promise.resolve()+ })+ const a: Component<{ name: string }> = {+ start: jest.fn(() => {+ log.push('start:a:begin')+ return new Promise<{ value: { name: string }; stop: () => Promise<void> }>((resolve) => {+ resolveStart = () => {+ log.push('start:a:end')+ resolve({ value: { name: 'a' }, stop: stopA })+ }+ })+ }),+ }++ const scope = newScope('phase', (builder) => builder.add('a', a))++ const p1 = scope.start()+ const p2 = scope.start()++ // Both starts are pending against the same in-flight boot — start:a+ // has been called exactly once.+ await new Promise((resolve) => setImmediate(resolve))+ expect(log).toEqual(['start:a:begin'])+ expect(a.start).toHaveBeenCalledTimes(1)++ resolveStart!()+ const [h1, h2] = await Promise.all([p1, p2])++ await h1.stop()+ expect(stopA).toHaveBeenCalledTimes(0)+ await h2.stop()+ expect(stopA).toHaveBeenCalledTimes(1)+ })++ it('waits for in-flight stop before starting fresh', async () => {+ const log: string[] = []+ let startCalls = 0+ let stopCalls = 0+ let resolveFirstStop: (() => void) | undefined+ const a: Component<{ name: string }> = {+ start: jest.fn(() => {+ startCalls+++ log.push('start:a')+ return Promise.resolve({+ value: { name: 'a' },+ stop: (): Promise<void> => {+ stopCalls+++ // Only the first stop blocks; subsequent stops resolve+ // immediately so the test can clean up without hanging.+ if (stopCalls === 1) {+ log.push('stop:a:begin')+ return new Promise<void>((resolve) => {+ resolveFirstStop = () => {+ log.push('stop:a:end')+ resolve()+ }+ })+ }+ log.push('stop:a')+ return Promise.resolve()+ },+ })+ }),+ }++ const scope = newScope('phase', (builder) => builder.add('a', a))+ const h1 = await scope.start()+ const stopPromise = h1.stop()++ // While stop is in flight, kick off a new start. It should wait for+ // the stop to finish before bringing the component back up.+ const restart = scope.start()+ await new Promise((resolve) => setImmediate(resolve))+ expect(log).toEqual(['start:a', 'stop:a:begin'])++ resolveFirstStop!()+ await stopPromise+ const h2 = await restart++ expect(log).toEqual(['start:a', 'stop:a:begin', 'stop:a:end', 'start:a'])++ await h2.stop()+ expect(startCalls).toBe(2)+ expect(stopCalls).toBe(2)+ })++ it('supports manual composition of two independent scopes', async () => {+ const log: string[] = []+ const a = makeComponent('a', log)+ const b = makeComponent('b', log)++ const server = newScope('server', (builder) => builder.add('a', a))+ const { container: serverContainer, stop: stopServer } = await server.start()++ // Caller wires the next scope using the prior container's business value.+ expect(serverContainer.a).toEqual({ name: 'a' })+ const consumer = newScope('consumer', (builder) => builder.add('b', b))+ const { stop: stopConsumer } = await consumer.start()++ expect(log).toEqual(['start:a', 'start:b'])++ await stopConsumer()+ await stopServer()+ expect(log).toEqual(['start:a', 'start:b', 'stop:b', 'stop:a'])+ })+})++describe('extend', () => {+ it('extends a parent scope with a child scope', async () => {+ const log: string[] = []+ const a = makeComponent('a', log)+ const b = makeComponent('b', log)++ const parent = newScope('parent', (builder) => builder.add('a', a))+ const child = extend(parent, 'child', (services, builder) => {+ // Services from the parent must be available here.+ expect(services.a).toEqual({ name: 'a' })+ return builder.add('b', b)+ })++ const started = await child.start()++ expect(log).toEqual(['start:a', 'start:b'])+ expect(started.name).toBe('child')+ expect(started.container).toEqual({ a: { name: 'a' }, b: { name: 'b' } })++ await started.stop()+ // Child first, then parent.+ expect(log).toEqual(['start:a', 'start:b', 'stop:b', 'stop:a'])+ })++ it('refcounts the parent across multiple extensions', async () => {+ const log: string[] = []+ const a = makeComponent('a', log)+ const b = makeComponent('b', log)+ const c = makeComponent('c', log)++ const parent = newScope('parent', (builder) => builder.add('a', a))+ const childB = extend(parent, 'childB', (_services, builder) => builder.add('b', b))+ const childC = extend(parent, 'childC', (_services, builder) => builder.add('c', c))++ const hB = await childB.start()+ const hC = await childC.start()++ // Parent boots exactly once even though both extensions started.+ expect(a.startCalls).toBe(1)+ expect(b.startCalls).toBe(1)+ expect(c.startCalls).toBe(1)++ await hB.stop()+ // Releasing one extension doesn't tear the parent down — the other+ // extension still holds it.+ expect(a.stopCalls).toBe(0)+ expect(b.stopCalls).toBe(1)++ await hC.stop()+ // Last extension released; parent now stops.+ expect(a.stopCalls).toBe(1)+ expect(c.stopCalls).toBe(1)+ })++ it('rolls back the parent when the child fails to start', async () => {+ const log: string[] = []+ const a = makeComponent('a', log)+ const failing: Component<{ name: string }> = {+ start: jest.fn(() => Promise.reject(new Error('child boom'))),+ }++ const parent = newScope('parent', (builder) => builder.add('a', a))+ const child = extend(parent, 'child', (_services, builder) => builder.add('bad', failing))++ await expect(child.start()).rejects.toThrow('child boom')++ // Parent was started, then released when the child failed.+ expect(a.startCalls).toBe(1)+ expect(a.stopCalls).toBe(1)+ })++ it('reconstructs the child on each restart', async () => {+ const log: string[] = []+ const a = makeComponent('a', log)+ let buildCalls = 0++ const parent = newScope('parent', (builder) => builder.add('a', a))+ const child = extend(parent, 'child', (_services, builder) => {+ buildCalls+++ const b = makeComponent(`b${buildCalls}`, log)+ return builder.add('b', b)+ })++ const h1 = await child.start()+ await h1.stop()++ const h2 = await child.start()+ await h2.stop()++ expect(buildCalls).toBe(2)+ expect(a.startCalls).toBe(2)+ expect(a.stopCalls).toBe(2)+ expect(log).toEqual(['start:a', 'start:b1', 'stop:b1', 'stop:a', 'start:a', 'start:b2', 'stop:b2', 'stop:a'])+ })+})diff --git a/nodejs/src/ingestion/common/scopes/scope.ts b/nodejs/src/ingestion/common/scopes/scope.tsnew file mode 100644index 000000000000..813876006e97--- /dev/null+++ b/nodejs/src/ingestion/common/scopes/scope.ts@@ -0,0 +1,148 @@+import { logger } from '../../../utils/logger'+import { CallerSet } from './caller-set'+import { Component } from './component'+import { ScopeRunner } from './runner'+import { ScopeBuilder } from './scope-builder'++/**+ * Returned by `Scope.start()`. The handle's `stop` removes this caller+ * from the refcount and is single-shot — calling it twice has no effect+ * after the first call.+ */+export interface StartedScope<S extends Record<string, object>> {+ readonly name: string+ readonly container: S+ readonly stop: () => Promise<void>+}++/**+ * Anything a `ScopeRunner` can sit on top of: it starts into a container+ * and a stop. Both `Scope` (refcounted, logged) and `EmptyScope` (the+ * silent bottom of every tree) satisfy it.+ */+export interface Startable<S extends Record<string, object>> {+ start(): Promise<StartedScope<S>>+}++/**+ * The owning system: wraps a `Component` in a refcount so concurrent and+ * repeated callers share a single boot, and the underlying component is+ * torn down only once the last caller releases. Start and stop never run+ * concurrently: an in-flight transition is awaited before the next one is+ * evaluated, and the started state is re-checked afterwards.+ */+export class Scope<S extends Record<string, object> = Record<never, object>> implements Startable<S> {+ private readonly callers = new CallerSet()+ private transition: Promise<void> | null = null+ private current?: { value: S; stop: () => Promise<void> }++ constructor(+ readonly name: string,+ private readonly component: Component<S>+ ) {}++ async start(): Promise<StartedScope<S>> {+ const release = this.callers.register()+ logger.info(`Scope[${this.name}]: start requested (callers=${this.callers.size()})`)+ try {+ await this.ensureStarted()+ } catch (err) {+ release()+ logger.error(`Scope[${this.name}]: start failed`, { error: err })+ throw err+ }+ logger.info(`Scope[${this.name}]: started`)+ const container = this.current!.value+ return {+ name: this.name,+ container,+ stop: () => this.releaseCaller(release),+ }+ }++ private async ensureStarted(): Promise<void> {+ while (this.transition) {+ await this.transition+ }+ if (this.current) {+ return+ }+ const boot = this.component.start().then((result) => {+ this.current = result+ })+ this.transition = boot.finally(() => {+ this.transition = null+ })+ await this.transition+ }++ private async releaseCaller(release: () => boolean): Promise<void> {+ if (!release()) {+ return+ }+ logger.info(`Scope[${this.name}]: stop requested (callers=${this.callers.size()})`)+ try {+ await this.ensureStoppedWhenIdle()+ } catch (err) {+ logger.error(`Scope[${this.name}]: stop failed`, { error: err })+ throw err+ }+ logger.info(`Scope[${this.name}]: stopped`)+ }++ private async ensureStoppedWhenIdle(): Promise<void> {+ while (this.transition) {+ await this.transition+ }+ if (this.callers.size() > 0 || !this.current) {+ return+ }+ const result = this.current+ const teardown = result.stop().finally(() => {+ this.current = undefined+ })+ this.transition = teardown.finally(() => {+ this.transition = null+ })+ await this.transition+ }+}++/**+ * Builds a root scope with the given name. The `configure` callback+ * receives an empty builder and returns the builder with the scope's+ * entries registered. A root is just an extension over the empty bottom,+ * so its container has no parent entries.+ */+export function newScope<S extends Record<string, object>>(+ name: string,+ configure: (builder: ScopeBuilder<Record<never, object>>) => ScopeBuilder<S>+): Scope<S> {+ return configure(ScopeBuilder.empty()).build(name)+}++/**+ * Builds a child scope on top of `parent`. The `configure` callback+ * receives the parent's started container and a fresh builder, and returns+ * the builder with the child's entries registered. The child's container+ * is `parent ∪ child`; a child entry that reuses a parent key overrides it+ * in the merged container, while both still run their own lifecycles.+ *+ * On `start`: the parent is started (or refcounted onto), then the callback+ * runs with the resolved container and the child entries are started.+ * On `stop`: the child entries are stopped, then the parent is released.+ */+export function extend<S extends Record<string, object>, S2 extends Record<string, object>>(+ parent: Scope<S>,+ name: string,+ configure: (parentContainer: S, builder: ScopeBuilder<Record<never, object>>) => ScopeBuilder<S2>+): Scope<S & S2> {+ return new Scope<S & S2>(+ name,+ new ScopeRunner<S, S2>(+ parent,+ (parentContainer) => configure(parentContainer, ScopeBuilder.empty()).components(),+ name+ )+ )+}diff --git a/nodejs/src/ingestion/common/scopes/test-fixtures.ts b/nodejs/src/ingestion/common/scopes/test-fixtures.tsnew file mode 100644index 000000000000..23d4dd8d722d--- /dev/null+++ b/nodejs/src/ingestion/common/scopes/test-fixtures.ts@@ -0,0 +1,24 @@+import { Component } from './component'++export type TrackedComponent = Component<{ name: string }> & { startCalls: number; stopCalls: number }++/** A `Component` that appends `start:<name>`/`stop:<name>` to `log` and counts calls. */+export function makeComponent(name: string, log: string[]): TrackedComponent {+ const component: TrackedComponent = {+ startCalls: 0,+ stopCalls: 0,+ start: jest.fn(() => {+ component.startCalls+++ log.push(`start:${name}`)+ return Promise.resolve({+ value: { name },+ stop: (): Promise<void> => {+ component.stopCalls+++ log.push(`stop:${name}`)+ return Promise.resolve()+ },+ })+ }),+ }+ return component+}diff --git a/nodejs/src/ingestion/common/steps/allow-events.test.ts b/nodejs/src/ingestion/common/steps/allow-events.test.tsnew file mode 100644index 000000000000..7a9d58dfd8c6--- /dev/null+++ b/nodejs/src/ingestion/common/steps/allow-events.test.ts@@ -0,0 +1,50 @@+import { createTestEventHeaders } from '../../../../tests/helpers/event-headers'+import { dlq, ok } from '../../pipelines/results'+import { createAllowEventsStep } from './allow-events'++function makeInput(eventName: string | undefined) {+ return {+ headers: createTestEventHeaders({+ token: 'token123',+ distinct_id: 'user123',+ timestamp: '2021-01-01T00:00:00Z',+ event: eventName,+ }),+ }+}++describe('createAllowEventsStep', () => {+ const step = createAllowEventsStep(['$$client_ingestion_warning'])++ it('passes through events whose name is in the allow list', async () => {+ const input = makeInput('$$client_ingestion_warning')++ const result = await step(input)++ expect(result).toEqual(ok(input))+ })++ it('DLQs events whose name is not in the allow list', async () => {+ const input = makeInput('$pageview')++ const result = await step(input)++ expect(result).toEqual(dlq('event_not_in_allowlist'))+ })++ it('passes through events with no event header (no name to match)', async () => {+ const input = makeInput(undefined)++ const result = await step(input)++ expect(result).toEqual(ok(input))+ })++ it('DLQs every named event when the allow list is empty', async () => {+ const emptyStep = createAllowEventsStep([])++ const result = await emptyStep(makeInput('$pageview'))++ expect(result).toEqual(dlq('event_not_in_allowlist'))+ })+})diff --git a/nodejs/src/ingestion/common/steps/allow-events.ts b/nodejs/src/ingestion/common/steps/allow-events.tsnew file mode 100644index 000000000000..02b787dd9329--- /dev/null+++ b/nodejs/src/ingestion/common/steps/allow-events.ts@@ -0,0 +1,24 @@+import { EventHeaders } from '../../../types'+import { dlq, ok } from '../../pipelines/results'+import { ProcessingStep } from '../../pipelines/steps'++/**+ * DLQs any event whose header `event` name is not in the allow list.+ * Reads from the parsed Kafka headers so it can run before message-body+ * parsing — use in a consumer's pipeline to enforce that only its+ * target event type(s) flow through. Anything else is misrouted and+ * goes to the DLQ for investigation. Events with no `event` header+ * pass through (no name to match against).+ */+export function createAllowEventsStep<T extends { headers: EventHeaders }>(+ allowed: readonly string[]+): ProcessingStep<T, T> {+ const allowedSet = new Set(allowed)+ return function allowEventsStep(input) {+ const name = input.headers.event+ if (name === undefined || allowedSet.has(name)) {+ return Promise.resolve(ok(input))+ }+ return Promise.resolve(dlq('event_not_in_allowlist'))+ }+}diff --git a/nodejs/src/ingestion/common/steps/deny-events.test.ts b/nodejs/src/ingestion/common/steps/deny-events.test.tsnew file mode 100644index 000000000000..86e76506d3ef--- /dev/null+++ b/nodejs/src/ingestion/common/steps/deny-events.test.ts@@ -0,0 +1,55 @@+import { createTestEventHeaders } from '../../../../tests/helpers/event-headers'+import { dlq, ok } from '../../pipelines/results'+import { createDenyEventsStep } from './deny-events'++function makeInput(eventName: string | undefined) {+ return {+ headers: createTestEventHeaders({+ token: 'token123',+ distinct_id: 'user123',+ timestamp: '2021-01-01T00:00:00Z',+ event: eventName,+ }),+ }+}++describe('createDenyEventsStep', () => {+ const step = createDenyEventsStep(['$exception', '$$client_ingestion_warning'])++ it('DLQs events whose name is in the deny list', async () => {+ const result = await step(makeInput('$exception'))++ expect(result).toEqual(dlq('event_in_denylist'))+ })++ it('DLQs every denied event type', async () => {+ const result = await step(makeInput('$$client_ingestion_warning'))++ expect(result).toEqual(dlq('event_in_denylist'))+ })++ it('passes through events whose name is not in the deny list', async () => {+ const input = makeInput('$pageview')++ const result = await step(input)++ expect(result).toEqual(ok(input))+ })++ it('passes through events with no event header (no name to match)', async () => {+ const input = makeInput(undefined)++ const result = await step(input)++ expect(result).toEqual(ok(input))+ })++ it('passes through everything when the deny list is empty', async () => {+ const emptyStep = createDenyEventsStep([])+ const input = makeInput('$exception')++ const result = await emptyStep(input)++ expect(result).toEqual(ok(input))+ })+})diff --git a/nodejs/src/ingestion/common/steps/deny-events.ts b/nodejs/src/ingestion/common/steps/deny-events.tsnew file mode 100644index 000000000000..ff9565e43054--- /dev/null+++ b/nodejs/src/ingestion/common/steps/deny-events.ts@@ -0,0 +1,24 @@+import { EventHeaders } from '../../../types'+import { dlq, ok } from '../../pipelines/results'+import { ProcessingStep } from '../../pipelines/steps'++/**+ * DLQs any event whose header `event` name is in the deny list. Reads+ * from the parsed Kafka headers so it can run before message-body+ * parsing — use in a consumer's pipeline to block specific event types+ * that belong in a different consumer. Anything matching the list is+ * misrouted and goes to the DLQ for investigation. Events with no+ * `event` header pass through (no name to match against).+ */+export function createDenyEventsStep<T extends { headers: EventHeaders }>(+ denied: readonly string[]+): ProcessingStep<T, T> {+ const deniedSet = new Set(denied)+ return function denyEventsStep(input) {+ const name = input.headers.event+ if (name !== undefined && deniedSet.has(name)) {+ return Promise.resolve(dlq('event_in_denylist'))+ }+ return Promise.resolve(ok(input))+ }+}diff --git a/nodejs/src/ingestion/common/subpipelines/helpers.ts b/nodejs/src/ingestion/common/subpipelines/helpers.tsnew file mode 100644index 000000000000..52a15f33e753--- /dev/null+++ b/nodejs/src/ingestion/common/subpipelines/helpers.ts@@ -0,0 +1,34 @@+import { EventHeaders, Team } from '../../../types'+import { OkResultWithContext } from '../../pipelines/pipeline.interface'++/**+ * Helper for `filterMap` after team resolution: lifts the resolved team from+ * the OK result value into the pipeline context, so downstream `teamAware`+ * blocks can read `context.team`.+ */+export function addTeamToContext<T extends { team: Team }, C>(+ element: OkResultWithContext<T, C>+): OkResultWithContext<T, C & { team: Team }> {+ return {+ result: element.result,+ context: {+ ...element.context,+ team: element.result.value.team,+ },+ }+}++/**+ * Group key for partitioning events within a batch by `(token, distinct_id)`.+ * Used by `groupBy` to ensure events for the same distinct id are processed+ * sequentially (preserves person/event ordering) while different distinct ids+ * run concurrently.+ */+export function getTokenAndDistinctId(input: {+ headers: EventHeaders+ event: { distinct_id?: string | null }+}): string {+ const token = input.headers.token ?? ''+ const distinctId = input.event.distinct_id ?? ''+ return `${token}:${distinctId}`+}diff --git a/nodejs/src/ingestion/common/utils/kafka-consumer.ts b/nodejs/src/ingestion/common/utils/kafka-consumer.tsnew file mode 100644index 000000000000..63ff044fc841--- /dev/null+++ b/nodejs/src/ingestion/common/utils/kafka-consumer.ts@@ -0,0 +1,38 @@+import { Message } from 'node-rdkafka'++import { instrumentFn } from '~/common/tracing/tracing-utils'++import { KafkaConsumerInterface, createKafkaConsumer } from '../../../kafka/consumer'+import { Component } from '../scopes'++export { createKafkaConsumer } from '../../../kafka/consumer'+export type { KafkaConsumerInterface } from '../../../kafka/consumer'++/**+ * Owns a Kafka consumer's lifetime as a scope entry. Start creates the+ * consumer and connects it to the provided per-batch handler; stop+ * disconnects it. Failures during connect cause the surrounding scope+ * to roll back already-started entries.+ */+export class KafkaConsumerComponent implements Component<KafkaConsumerInterface> {+ constructor(+ private readonly groupId: string,+ private readonly topic: string,+ private readonly handler: (messages: Message[]) => Promise<{ backgroundTask?: Promise<unknown> }>+ ) {}++ async start(): Promise<{ value: KafkaConsumerInterface; stop: () => Promise<void> }> {+ const kafkaConsumer = createKafkaConsumer({ groupId: this.groupId, topic: this.topic })+ await kafkaConsumer.connect(+ async (messages: Message[]) =>+ await instrumentFn(+ { key: 'commonIngestionConsumer.handleEachBatch', sendException: false },+ async () => await this.handler(messages)+ )+ )+ return {+ value: kafkaConsumer,+ stop: () => kafkaConsumer.disconnect(),+ }+ }+}diff --git a/nodejs/src/ingestion/common/utils/promise-scheduler.ts b/nodejs/src/ingestion/common/utils/promise-scheduler.tsnew file mode 100644index 000000000000..4254c13f9450--- /dev/null+++ b/nodejs/src/ingestion/common/utils/promise-scheduler.ts@@ -0,0 +1,21 @@+import { PromiseScheduler } from '../../../utils/promise-scheduler'+import { Component } from '../scopes'++export { PromiseScheduler } from '../../../utils/promise-scheduler'++/**+ * Wraps an internally-owned `PromiseScheduler` as a scope entry. Start is+ * a no-op (the scheduler is alive from construction); stop drains all+ * pending background work via `waitForAll()` so any side effects+ * scheduled during processing get awaited before the scope tears down.+ */+export class PromiseSchedulerComponent implements Component<PromiseScheduler> {+ private readonly scheduler = new PromiseScheduler()++ start(): Promise<{ value: PromiseScheduler; stop: () => Promise<void> }> {+ return Promise.resolve({+ value: this.scheduler,+ stop: () => this.scheduler.waitForAll().then(() => undefined),+ })+ }+}diff --git a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.tsindex 0acf70f5e3f1..ead38ffc858d 100644--- a/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts+++ b/nodejs/src/ingestion/error-tracking/error-tracking-consumer.ts@@ -13,7 +13,10 @@ import { ErrorTrackingSettingsManager } from '~/utils/error-tracking-settings-maimport { TransformationResult } from '../../cdp/hog-transformations/hog-transformer.service'import { KafkaConsumerInterface, createKafkaConsumer } from '../../kafka/consumer'import { HealthCheckResult, IngestionLane, PluginServerService } from '../../types'-import { EventIngestionRestrictionManager } from '../../utils/event-ingestion-restrictions'+import {+ EventIngestionRestrictionManager,+ EventIngestionRestrictionManagerComponent,+} from '../../utils/event-ingestion-restrictions'import { logger } from '../../utils/logger'import { PromiseScheduler } from '../../utils/promise-scheduler'import { TeamManager } from '../../utils/team-manager'@@ -132,7 +135,9 @@ export class ErrorTrackingConsumer {>protected cymbalClient: CymbalClientprotected promiseScheduler: PromiseScheduler- protected eventIngestionRestrictionManager: EventIngestionRestrictionManager+ private eventIngestionRestrictionManagerComponent: EventIngestionRestrictionManagerComponent+ protected eventIngestionRestrictionManager!: EventIngestionRestrictionManager+ private stopEventIngestionRestrictionManager?: () => Promise<void>protected overflowRedirectService?: OverflowRedirectServiceprotected overflowLaneTTLRefreshService?: OverflowRedirectServiceprotected topHog?: TopHog@@ -158,7 +163,7 @@ export class ErrorTrackingConsumer {this.promiseScheduler = new PromiseScheduler()- this.eventIngestionRestrictionManager = new EventIngestionRestrictionManager(deps.redisPool, {+ this.eventIngestionRestrictionManagerComponent = new EventIngestionRestrictionManagerComponent(deps.redisPool, {pipeline: 'errortracking',})@@ -248,6 +253,9 @@ export class ErrorTrackingConsumer {cymbalUrl: this.config.cymbalBaseUrl,})+ const started = await this.eventIngestionRestrictionManagerComponent.start()+ this.eventIngestionRestrictionManager = started.value+ this.stopEventIngestionRestrictionManager = started.stop// Initialize pipeline with dependenciesawait this.initializePipeline()@@ -392,6 +400,8 @@ export class ErrorTrackingConsumer {await this.kafkaConsumer.disconnect()+ await this.stopEventIngestionRestrictionManager?.()+logger.info('👍', `${this.name} - stopped`)}diff --git a/nodejs/src/ingestion/event-preprocessing/apply-event-restrictions.test.ts b/nodejs/src/ingestion/event-preprocessing/apply-event-restrictions.test.tsindex c8127240a7d7..54b2d2393b6c 100644--- a/nodejs/src/ingestion/event-preprocessing/apply-event-restrictions.test.ts+++ b/nodejs/src/ingestion/event-preprocessing/apply-event-restrictions.test.ts@@ -3,7 +3,11 @@ import { EventHeaders } from '../../types'import { EventIngestionRestrictionManager, Restriction } from '../../utils/event-ingestion-restrictions'import { OVERFLOW_OUTPUT } from '../common/outputs'import { dlq, drop, ok, redirect } from '../pipelines/results'-import { RoutingConfig, createApplyEventRestrictionsStep } from './apply-event-restrictions'+import {+ RoutingConfig,+ createApplyBasicEventRestrictionsStep,+ createApplyEventRestrictionsStep,+} from './apply-event-restrictions'describe('createApplyEventRestrictionsStep', () => {let eventIngestionRestrictionManager: EventIngestionRestrictionManager@@ -422,3 +426,176 @@ describe('createApplyEventRestrictionsStep', () => {})})})++describe('createApplyBasicEventRestrictionsStep', () => {+ let eventIngestionRestrictionManager: EventIngestionRestrictionManager+ let step: ReturnType<typeof createApplyBasicEventRestrictionsStep>++ beforeEach(() => {+ eventIngestionRestrictionManager = {+ getAppliedRestrictions: jest.fn().mockReturnValue(new Set()),+ } as unknown as EventIngestionRestrictionManager++ step = createApplyBasicEventRestrictionsStep(eventIngestionRestrictionManager)+ })++ describe('header passing', () => {+ it('passes token and distinct_id correctly', async () => {+ const input = {+ message: {} as any,+ headers: createTestEventHeaders({+ token: 'test-token',+ distinct_id: 'test-user',+ }),+ }++ await step(input)++ expect(eventIngestionRestrictionManager.getAppliedRestrictions).toHaveBeenCalledWith(+ 'test-token',+ expect.objectContaining({ distinct_id: 'test-user' })+ )+ })++ it('passes all headers correctly', async () => {+ const input = {+ message: {} as any,+ headers: createTestEventHeaders({+ token: 'test-token',+ distinct_id: 'test-user',+ session_id: 'session-123',+ event: '$pageview',+ uuid: 'event-uuid-123',+ }),+ }++ await step(input)++ expect(eventIngestionRestrictionManager.getAppliedRestrictions).toHaveBeenCalledWith(+ 'test-token',+ expect.objectContaining({+ distinct_id: 'test-user',+ session_id: 'session-123',+ event: '$pageview',+ uuid: 'event-uuid-123',+ })+ )+ })+ })++ describe('drop events', () => {+ it('returns drop when DROP_EVENT restriction is applied', async () => {+ const input = {+ message: {} as any,+ headers: createTestEventHeaders({+ token: 'blocked-token',+ distinct_id: 'user-123',+ }),+ }+ jest.mocked(eventIngestionRestrictionManager.getAppliedRestrictions).mockReturnValue(+ new Set([Restriction.DROP_EVENT])+ )++ const result = await step(input)++ expect(result).toEqual(drop('blocked_token'))+ })+ })++ describe('DLQ redirect', () => {+ it('returns dlq when REDIRECT_TO_DLQ restriction is applied', async () => {+ const input = {+ message: {} as any,+ headers: createTestEventHeaders({+ token: 'dlq-token',+ distinct_id: 'user-123',+ }),+ }+ jest.mocked(eventIngestionRestrictionManager.getAppliedRestrictions).mockReturnValue(+ new Set([Restriction.REDIRECT_TO_DLQ])+ )++ const result = await step(input)++ expect(result).toEqual(dlq('restricted_to_dlq'))+ })+ })++ describe('overflow is not handled', () => {+ it('returns ok when only FORCE_OVERFLOW restriction is applied', async () => {+ const input = {+ message: {} as any,+ headers: createTestEventHeaders({+ token: 'overflow-token',+ distinct_id: 'user-123',+ }),+ }+ jest.mocked(eventIngestionRestrictionManager.getAppliedRestrictions).mockReturnValue(+ new Set([Restriction.FORCE_OVERFLOW])+ )++ const result = await step(input)++ expect(result).toEqual(ok(input))+ })+ })++ describe('priority ordering', () => {+ it('drop takes priority over DLQ', async () => {+ const input = {+ message: {} as any,+ headers: createTestEventHeaders({+ token: 'token',+ distinct_id: 'user',+ }),+ }++ jest.mocked(eventIngestionRestrictionManager.getAppliedRestrictions).mockReturnValue(+ new Set([Restriction.DROP_EVENT, Restriction.REDIRECT_TO_DLQ])+ )++ const result = await step(input)++ expect(result).toEqual(drop('blocked_token'))+ })++ it('returns ok when nothing matches', async () => {+ const input = {+ message: {} as any,+ headers: createTestEventHeaders({+ token: 'token',+ distinct_id: 'user',+ }),+ }++ const result = await step(input)++ expect(result).toEqual(ok(input))+ })+ })++ describe('edge cases', () => {+ it('handles undefined headers', async () => {+ const input = {+ message: {} as any,+ headers: {} as EventHeaders,+ }++ const result = await step(input)++ expect(result).toEqual(ok(input))+ expect(eventIngestionRestrictionManager.getAppliedRestrictions).toHaveBeenCalledWith(undefined, {})+ })++ it('handles empty headers', async () => {+ const input = {+ message: {} as any,+ headers: createTestEventHeaders(),+ }++ const result = await step(input)++ expect(result).toEqual(ok(input))+ })+ })+})diff --git a/nodejs/src/ingestion/event-preprocessing/apply-event-restrictions.ts b/nodejs/src/ingestion/event-preprocessing/apply-event-restrictions.tsindex b2dfa002a3d4..0dbaf3d9cf6f 100644--- a/nodejs/src/ingestion/event-preprocessing/apply-event-restrictions.ts+++ b/nodejs/src/ingestion/event-preprocessing/apply-event-restrictions.ts@@ -16,6 +16,32 @@ export type RoutingConfig = {preservePartitionLocality: boolean}+/**+ * Drop + DLQ token restrictions only, no overflow handling. For pipelines+ * that don't have an overflow topic (e.g. client warnings). Type signature+ * has no side outputs, so callers don't need to include `OverflowOutput` in+ * their pipeline's outputs union just to satisfy the step.+ */+export function createApplyBasicEventRestrictionsStep<T extends { headers: EventHeaders }>(+ manager: EventIngestionRestrictionManager+): ProcessingStep<T, T> {+ return function applyBasicEventRestrictionsStep(input) {+ const { headers } = input++ const restrictions = manager.getAppliedRestrictions(headers.token, headers)++ if (restrictions.has(RestrictionType.DROP_EVENT)) {+ return Promise.resolve(drop('blocked_token'))+ }++ if (restrictions.has(RestrictionType.REDIRECT_TO_DLQ)) {+ return Promise.resolve(dlq('restricted_to_dlq'))+ }++ return Promise.resolve(ok(input))+ }+}+export function createApplyEventRestrictionsStep<T extends { headers: EventHeaders }>(manager: EventIngestionRestrictionManager,routingConfig: RoutingConfigdiff --git a/nodejs/src/ingestion/event-preprocessing/drop-exception-events.test.ts b/nodejs/src/ingestion/event-preprocessing/drop-exception-events.test.tsdeleted file mode 100644index f2446fb3e9f3..000000000000--- a/nodejs/src/ingestion/event-preprocessing/drop-exception-events.test.ts+++ /dev/null@@ -1,159 +0,0 @@-import { createTestEventHeaders } from '../../../tests/helpers/event-headers'-import { drop, ok } from '../pipelines/results'-import { createDropExceptionEventsStep } from './drop-exception-events'--describe('createDropExceptionEventsStep', () => {- const step = createDropExceptionEventsStep()-- describe('exception event handling', () => {- it('should drop $exception events', async () => {- const input = {- event: {- event: {- event: '$exception',- distinct_id: 'user123',- team_id: 1,- ip: '127.0.0.1',- site_url: 'https://example.com',- now: '2021-01-01T00:00:00Z',- uuid: '123e4567-e89b-12d3-a456-426614174000',- },- headers: createTestEventHeaders({- token: 'token123',- distinct_id: 'user123',- timestamp: '2021-01-01T00:00:00Z',- }),- },- }-- const result = await step(input)-- expect(result).toEqual(drop('exception_event'))- })-- it('should allow non-exception events', async () => {- const input = {- event: {- event: {- event: '$pageview',- distinct_id: 'user123',- team_id: 1,- ip: '127.0.0.1',- site_url: 'https://example.com',- now: '2021-01-01T00:00:00Z',- uuid: '123e4567-e89b-12d3-a456-426614174000',- },- headers: createTestEventHeaders({- token: 'token123',- distinct_id: 'user123',- timestamp: '2021-01-01T00:00:00Z',- }),- },- }-- const result = await step(input)-- expect(result).toEqual(ok(input))- })-- it('should allow regular events', async () => {- const input = {- event: {- event: {- event: 'button_clicked',- distinct_id: 'user123',- team_id: 1,- ip: '127.0.0.1',- site_url: 'https://example.com',- now: '2021-01-01T00:00:00Z',- uuid: '123e4567-e89b-12d3-a456-426614174000',- },- headers: createTestEventHeaders({- token: 'token123',- distinct_id: 'user123',- timestamp: '2021-01-01T00:00:00Z',- }),- },- }-- const result = await step(input)-- expect(result).toEqual(ok(input))- })-- it('should allow identify events', async () => {- const input = {- event: {- event: {- event: '$identify',- distinct_id: 'user123',- team_id: 1,- ip: '127.0.0.1',- site_url: 'https://example.com',- now: '2021-01-01T00:00:00Z',- uuid: '123e4567-e89b-12d3-a456-426614174000',- },- headers: createTestEventHeaders({- token: 'token123',- distinct_id: 'user123',- timestamp: '2021-01-01T00:00:00Z',- }),- },- }-- const result = await step(input)-- expect(result).toEqual(ok(input))- })-- it('should allow group identify events', async () => {- const input = {- event: {- event: {- event: '$groupidentify',- distinct_id: 'user123',- team_id: 1,- ip: '127.0.0.1',- site_url: 'https://example.com',- now: '2021-01-01T00:00:00Z',- uuid: '123e4567-e89b-12d3-a456-426614174000',- },- headers: createTestEventHeaders({- token: 'token123',- distinct_id: 'user123',- timestamp: '2021-01-01T00:00:00Z',- }),- },- }-- const result = await step(input)-- expect(result).toEqual(ok(input))- })-- it('should allow heatmap events', async () => {- const input = {- event: {- event: {- event: '$$heatmap',- distinct_id: 'user123',- team_id: 1,- ip: '127.0.0.1',- site_url: 'https://example.com',- now: '2021-01-01T00:00:00Z',- uuid: '123e4567-e89b-12d3-a456-426614174000',- },- headers: createTestEventHeaders({- token: 'token123',- distinct_id: 'user123',- timestamp: '2021-01-01T00:00:00Z',- }),- },- }-- const result = await step(input)-- expect(result).toEqual(ok(input))- })- })-})diff --git a/nodejs/src/ingestion/event-preprocessing/drop-exception-events.ts b/nodejs/src/ingestion/event-preprocessing/drop-exception-events.tsdeleted file mode 100644index eda84b16e864..000000000000--- a/nodejs/src/ingestion/event-preprocessing/drop-exception-events.ts+++ /dev/null@@ -1,15 +0,0 @@-import { IncomingEvent } from '../../types'-import { drop, ok } from '../pipelines/results'-import { ProcessingStep } from '../pipelines/steps'--export function createDropExceptionEventsStep<T extends { event: IncomingEvent }>(): ProcessingStep<T, T> {- return async function dropExceptionEventsStep(input) {- const { event } = input-- if (event.event.event === '$exception') {- return Promise.resolve(drop('exception_event'))- }-- return Promise.resolve(ok(input))- }-}diff --git a/nodejs/src/ingestion/event-preprocessing/index.ts b/nodejs/src/ingestion/event-preprocessing/index.tsindex 8b5c29b0aeac..0b44d6a7a5c1 100644--- a/nodejs/src/ingestion/event-preprocessing/index.ts+++ b/nodejs/src/ingestion/event-preprocessing/index.ts@@ -1,7 +1,6 @@export { createApplyCookielessProcessingStep } from './apply-cookieless-processing'export { createApplyEventRestrictionsStep } from './apply-event-restrictions'export { createApplyPersonProcessingRestrictionsStep } from './apply-person-processing-restrictions'-export { createDropExceptionEventsStep } from './drop-exception-events'export { createEnrichSurveyPersonPropertiesStep } from './enrich-survey-person-properties'export { createParseHeadersStep } from './parse-headers'export { createParseKafkaMessageStep } from './parse-kafka-message'diff --git a/nodejs/src/ingestion/event-processing/flush-batch-stores-step.ts b/nodejs/src/ingestion/event-processing/flush-batch-stores-step.tsindex 433010ca1ab0..8632b9d3e1be 100644--- a/nodejs/src/ingestion/event-processing/flush-batch-stores-step.ts+++ b/nodejs/src/ingestion/event-processing/flush-batch-stores-step.ts@@ -61,7 +61,7 @@ export function createFlushBatchStoresStep<TOutput, COutput, CBatch, R extends spersonsStore.reset()groupStore.reset()- return ok({ elements: input.elements, batchContext: input.batchContext }, producePromises)+ return ok(input, producePromises)} catch (error) {// If flush fails, the error will bubble up and fail the entire batch// This maintains the existing behavior where flush errors are fataldiff --git a/nodejs/src/ingestion/ingestion-consumer.test.ts b/nodejs/src/ingestion/ingestion-consumer.test.tsindex 6b44b77bf397..1583176e948d 100644--- a/nodejs/src/ingestion/ingestion-consumer.test.ts+++ b/nodejs/src/ingestion/ingestion-consumer.test.ts@@ -565,7 +565,7 @@ describe('IngestionConsumer', () => {})describe('dropping events', () => {- it('should drop $exception events', async () => {+ it('should DLQ $exception events (wrong consumer)', async () => {const messages = createKafkaMessages([createEvent({event: '$exception',@@ -578,7 +578,23 @@ describe('IngestionConsumer', () => {expect(mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')).toHaveLength(0)expect(mockProducerObserver.getProducedKafkaMessagesForTopic('events_plugin_ingestion_dlq_test')- ).toHaveLength(0)+ ).toHaveLength(1)+ })++ it('should DLQ $$client_ingestion_warning events (wrong consumer)', async () => {+ const messages = createKafkaMessages([+ createEvent({+ event: '$$client_ingestion_warning',+ properties: { $$client_ingestion_warning_message: 'test' },+ }),+ ])++ await ingester.handleKafkaBatch(messages)++ expect(mockProducerObserver.getProducedKafkaMessagesForTopic('clickhouse_events_json_test')).toHaveLength(0)+ expect(+ mockProducerObserver.getProducedKafkaMessagesForTopic('events_plugin_ingestion_dlq_test')+ ).toHaveLength(1)})it('should capture ingestion warning for $groupidentify with too long $group_key', async () => {@@ -1138,15 +1154,6 @@ describe('IngestionConsumer', () => {// Snapshot should contain update2 and update3 but not update1],],- [- 'client ingestion warning',- () => [- createEvent({- event: '$$client_ingestion_warning',- properties: { $$client_ingestion_warning_message: 'test' },- }),- ],- ],['groups',() => [diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.tsindex dbbd704a1fd1..216bfc8346ed 100644--- a/nodejs/src/ingestion/ingestion-consumer.ts+++ b/nodejs/src/ingestion/ingestion-consumer.ts@@ -14,7 +14,10 @@ import {RedisPool,} from '../types'import { PostgresRouter } from '../utils/db/postgres'-import { EventIngestionRestrictionManager } from '../utils/event-ingestion-restrictions'+import {+ EventIngestionRestrictionManager,+ EventIngestionRestrictionManagerComponent,+} from '../utils/event-ingestion-restrictions'import { EventSchemaEnforcementManager } from '../utils/event-schema-enforcement-manager'import { logger } from '../utils/logger'import { PromiseScheduler } from '../utils/promise-scheduler'@@ -41,7 +44,7 @@ import {PersonDistinctIdsOutput,PersonsOutput,} from './analytics/outputs'-import { EventFilterManager } from './common/event-filters'+import { EventFilterManager, EventFilterManagerComponent } from './common/event-filters'import {AppMetricsOutput,DlqOutput,@@ -125,8 +128,12 @@ export class IngestionConsumer {private tokenDistinctIdsToForceOverflow: string[] = []private personsStore: PersonsStorepublic groupStore: BatchWritingGroupStore- private eventFilterManager: EventFilterManager- private eventIngestionRestrictionManager: EventIngestionRestrictionManager+ private eventFilterManagerComponent: EventFilterManagerComponent+ private eventFilterManager!: EventFilterManager+ private stopEventFilterManager?: () => Promise<void>+ private eventIngestionRestrictionManagerComponent: EventIngestionRestrictionManagerComponent+ private eventIngestionRestrictionManager!: EventIngestionRestrictionManager+ private stopEventIngestionRestrictionManager?: () => Promise<void>private eventSchemaEnforcementManager: EventSchemaEnforcementManagerpublic readonly promiseScheduler = new PromiseScheduler()private topHog!: TopHog@@ -158,13 +165,13 @@ export class IngestionConsumer {this.tokenDistinctIdsToForceOverflow = config.INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID.split(',').filter((x) => !!x)- this.eventIngestionRestrictionManager = new EventIngestionRestrictionManager(deps.redisPool, {+ this.eventIngestionRestrictionManagerComponent = new EventIngestionRestrictionManagerComponent(deps.redisPool, {pipeline: 'analytics',staticDropEventTokens: this.tokenDistinctIdsToDrop,staticSkipPersonTokens: this.tokenDistinctIdsToSkipPersons,staticForceOverflowTokens: this.tokenDistinctIdsToForceOverflow,})- this.eventFilterManager = new EventFilterManager(deps.postgres)+ this.eventFilterManagerComponent = new EventFilterManagerComponent(deps.postgres)this.eventSchemaEnforcementManager = new EventSchemaEnforcementManager(deps.postgres)this.name = `ingestion-consumer-${this.topic}`@@ -236,6 +243,12 @@ export class IngestionConsumer {}public async start(): Promise<void> {+ const startedRestrictions = await this.eventIngestionRestrictionManagerComponent.start()+ this.eventIngestionRestrictionManager = startedRestrictions.value+ this.stopEventIngestionRestrictionManager = startedRestrictions.stop+ const startedFilters = await this.eventFilterManagerComponent.start()+ this.eventFilterManager = startedFilters.value+ this.stopEventFilterManager = startedFilters.stopawait this.hogTransformer.start()this.topHog.start()@@ -313,6 +326,8 @@ export class IngestionConsumer {await this.topHog.stop()logger.info('🔁', `${this.name} - stopping hog transformer`)await this.hogTransformer.stop()+ await this.stopEventFilterManager?.()+ await this.stopEventIngestionRestrictionManager?.()logger.info('👍', `${this.name} - stopped!`)}diff --git a/nodejs/src/ingestion/ingestion-e2e.test.ts b/nodejs/src/ingestion/ingestion-e2e.test.tsindex f0305fbe55b5..7a9cc5fa47f8 100644--- a/nodejs/src/ingestion/ingestion-e2e.test.ts+++ b/nodejs/src/ingestion/ingestion-e2e.test.ts@@ -1,19 +1,22 @@import { DateTime } from 'luxon'-import { Message } from 'node-rdkafka'-import { v4 } from 'uuid'import { waitForExpect } from '~/tests/helpers/expectations'import { resetKafka } from '~/tests/helpers/kafka'import { Clickhouse } from '../../tests/helpers/clickhouse'+import {+ EventBuilder,+ createKafkaMessages,+ createTestWithTeamIngester,+ fetchEvents,+ fetchIngestionWarnings,+ waitForClickHouseKafkaConsumer,+ waitForKafkaMessages,+} from '../../tests/helpers/ingestion-e2e'import { createTestIngestionOutputs, createTestMonitoringOutputs } from '../../tests/helpers/ingestion-outputs'import { createUserTeamAndOrganization, fetchPostgresPersons, resetTestDatabase } from '../../tests/helpers/sql'import { createHogTransformerService } from '../cdp/hog-transformations/hog-transformer.service'-import { KAFKA_INGESTION_WARNINGS } from '../config/kafka-topics'-import { KafkaProducerWrapper } from '../kafka/producer'-import { Hub, InternalPerson, PipelineEvent, PluginsServerConfig, ProjectId, RawClickHouseEvent, Team } from '../types'-import { closeHub, createHub } from '../utils/db/hub'-import { parseRawClickHouseEvent } from '../utils/event'+import { InternalPerson } from '../types'import { parseJSON } from '../utils/json-parse'import { UUIDT } from '../utils/utils'import { ClickhouseGroupRepository } from '../worker/ingestion/groups/repositories/clickhouse-group-repository'@@ -30,265 +33,39 @@ jest.mock('~/utils/token-bucket', () => {}})-const waitForKafkaMessages = async (kafkaProducer: KafkaProducerWrapper) => {- await kafkaProducer.flush()-}--// After resetKafka() recreates topics, ClickHouse's Kafka engine consumers need to-// reconnect. With the default auto.offset.reset=latest, any messages produced before-// reconnection are permanently missed. We repeatedly produce probe messages until-// ClickHouse consumes one, which guarantees at least one lands after reconnection.-async function waitForClickHouseKafkaConsumer(clickhouse: Clickhouse): Promise<void> {- const producer = await KafkaProducerWrapper.create(undefined)- const probeTeamId = -1-- try {- await waitForExpect(async () => {- await producer.queueMessages({- topic: KAFKA_INGESTION_WARNINGS,- messages: [- {- value: JSON.stringify({- team_id: probeTeamId,- type: 'probe',- source: 'test-warmup',- details: '{}',- timestamp: DateTime.utc().toFormat('yyyy-MM-dd HH:mm:ss'),- }),- },- ],- })- await producer.flush()-- const result = await clickhouse.query<{ count: number }>(- `SELECT count() as count FROM ingestion_warnings WHERE team_id = ${probeTeamId}`- )- expect(Number(result[0]?.count ?? 0)).toBeGreaterThan(0)- }, 30_000)- } finally {- await producer.disconnect()- }-}--class EventBuilder {- private event: Partial<PipelineEvent> = {}-- constructor(team: Team, distinctId: string = new UUIDT().toString()) {- this.event = {- event: 'custom event',- properties: {},- timestamp: new Date().toISOString(),- now: new Date().toISOString(),- ip: null,- site_url: 'https://example.com',- uuid: new UUIDT().toString(),- }- this.event.distinct_id = distinctId- this.event.team_id = team.id- }-- withEvent(event: string) {- this.event.event = event- return this- }-- withProperties(properties: Record<string, any>) {- this.event.properties = properties- return this- }-- withOverrides(overrides: Record<string, any>) {- this.event = { ...this.event, ...overrides }- return this- }-- withTimestamp(timestamp: number) {- const date = DateTime.fromMillis(timestamp)- this.event.timestamp = date.toString()- this.event.now = date.toString()- return this- }-- withNow(now: number) {- const date = DateTime.fromMillis(now)- this.event.now = date.toString()- return this- }-- withGroupProperties(groupType: string, groupKey: string, groupSet?: Record<string, any>) {- this.event.properties = {- ...this.event.properties,- $group_type: groupType,- $group_key: groupKey,- ...(groupSet ? { $group_set: groupSet } : {}),- }- return this- }-- build(): PipelineEvent {- return this.event as PipelineEvent- }-}-jest.mock('../utils/logger')-const DEFAULT_TEAM: Team = {- id: 2,- project_id: 2 as ProjectId,- organization_id: '2',- uuid: v4(),- name: '2',- anonymize_ips: true,- api_token: 'api_token',- secret_api_token: null,- session_recording_opt_in: true,- person_processing_opt_out: null,- heatmaps_opt_in: null,- ingested_event: true,- person_display_name_properties: null,- test_account_filters: null,- cookieless_server_hash_mode: null,- timezone: 'UTC',- available_features: [],- drop_events_older_than_seconds: null,- extra_settings: null,-}--let offsetIncrementer = 0--let currentToken: string--const createKafkaMessage = (event: PipelineEvent, timestamp: number = DateTime.now().toMillis()): Message => {- // TRICKY: This is the slightly different format that capture sends- const token = currentToken- const captureEvent = {- uuid: event.uuid,- distinct_id: event.distinct_id,- ip: event.ip,- now: event.now,- token,- data: JSON.stringify(event),- }-- // Build headers to match what the Rust capture service sends- // timestamp: milliseconds since epoch as string (already normalized with clock skew correction)- // now: ISO timestamp string of when the event was received by capture- const headers: { [key: string]: Buffer }[] = [- { token: Buffer.from(token) },- { distinct_id: Buffer.from(event.distinct_id!) },- ]- if (event.timestamp) {- // The timestamp header is in milliseconds since epoch, as a string- const timestampMs = DateTime.fromISO(event.timestamp).toMillis()- headers.push({ timestamp: Buffer.from(timestampMs.toString()) })- }- if (event.now) {- // The now header is an ISO timestamp string- headers.push({ now: Buffer.from(event.now) })- }-- return {- key: `${token}:${event.distinct_id}`,- value: Buffer.from(JSON.stringify(captureEvent)),- size: 1,- topic: 'test',- offset: offsetIncrementer++,- timestamp: timestamp + offsetIncrementer,- partition: 1,- headers,- }-}--export const createKafkaMessages = (events: PipelineEvent[]): Message[] => {- return events.map((e) => createKafkaMessage(e))-}--const createTestWithTeamIngester = (baseConfig: Partial<PluginsServerConfig> = {}) => {- return (- name: string,- config: { teamOverrides?: Partial<Team>; pluginServerConfig?: Partial<PluginsServerConfig> } = {},- testFn: (- ingester: IngestionConsumer,- hub: Hub,- team: Team,- kafkaProducer: KafkaProducerWrapper- ) => Promise<void>- ) => {- test(name, async () => {- const hub = await createHub({- ...baseConfig,- ...config.pluginServerConfig,- })- const kafkaProducer = await KafkaProducerWrapper.create(hub.KAFKA_CLIENT_RACK)-- const teamId = Math.floor((Date.now() % 1000000000) + Math.random() * 1000000)- const userId = teamId- const organizationId = new UUIDT().toString()-- const newTeam: Team = {- ...DEFAULT_TEAM,- id: teamId,- project_id: teamId as ProjectId,- organization_id: organizationId,- uuid: v4(),- name: teamId.toString(),- ...config.teamOverrides,- }- const userUuid = new UUIDT().toString()- const organizationMembershipId = new UUIDT().toString()-- await createUserTeamAndOrganization(- hub.postgres,- newTeam.id,- userId,- userUuid,- newTeam.organization_id,- organizationMembershipId,- config.teamOverrides- )-- // Fetch the team from the database to ensure we have the actual persisted data- const fetchedTeam = await hub.teamManager.getTeam(newTeam.id)- if (!fetchedTeam) {- throw new Error(`Failed to fetch team ${newTeam.id} from database`)- }-+describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED: true }])(+ 'Event Pipeline E2E tests (prefetch=$PERSONS_PREFETCH_ENABLED)',+ (prefetchConfig) => {+ const testWithTeamIngester = createTestWithTeamIngester(prefetchConfig, (infra, kafkaProducer) => {const outputs = createTestIngestionOutputs(kafkaProducer)- const ingester = new IngestionConsumer(hub, {- ...hub,- hogTransformer: createHogTransformerService(hub, {- ...hub,- monitoringOutputs: createTestMonitoringOutputs(kafkaProducer),- }),+ const ingester = new IngestionConsumer(infra.config, {+ postgres: infra.postgres,+ redisPool: infra.redisPool,+ teamManager: infra.teamManager,+ groupTypeManager: infra.groupTypeManager,+ groupRepository: infra.groupRepository,+ personRepository: infra.personRepository,+ cookielessManager: infra.cookielessManager,outputs,clickhouseGroupRepository: new ClickhouseGroupRepository(outputs),+ hogTransformer: createHogTransformerService(infra.config, {+ geoipService: infra.geoipService,+ postgres: infra.postgres,+ pubSub: infra.pubSub,+ encryptedFields: infra.encryptedFields,+ integrationManager: infra.integrationManager,+ monitoringOutputs: createTestMonitoringOutputs(kafkaProducer),+ teamManager: infra.teamManager,+ }),})- // NOTE: We don't actually use kafka so we skip instantiation for faster tests- ingester['kafkaConsumer'] = {- connect: jest.fn(),- disconnect: jest.fn(),- isHealthy: jest.fn(),- } as any-- jest.spyOn(hub.groupRepository, 'fetchGroup')- jest.spyOn(hub.groupRepository, 'insertGroup')- jest.spyOn(hub.groupRepository, 'updateGroup')- jest.spyOn(hub.groupRepository, 'updateGroupOptimistically')-- currentToken = fetchedTeam.api_token- await ingester.start()- await testFn(ingester, hub, fetchedTeam, kafkaProducer)- await ingester.stop()- await kafkaProducer.disconnect()- await closeHub(hub)+ jest.spyOn(infra.groupRepository, 'fetchGroup')+ jest.spyOn(infra.groupRepository, 'insertGroup')+ jest.spyOn(infra.groupRepository, 'updateGroup')+ jest.spyOn(infra.groupRepository, 'updateGroupOptimistically')+ return ingester})- }-}--describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED: true }])(- 'Event Pipeline E2E tests (prefetch=$PERSONS_PREFETCH_ENABLED)',- (prefetchConfig) => {- const testWithTeamIngester = createTestWithTeamIngester(prefetchConfig)let clickhouse: ClickhousebeforeAll(async () => {console.log('Creating Clickhouse client')@@ -306,46 +83,18 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:clickhouse.close()})- testWithTeamIngester(- 'should handle $$client_ingestion_warning events',- {},- async (ingester, hub, team, _kafkaProducer) => {- const events = [- new EventBuilder(team)- .withEvent('$$client_ingestion_warning')- .withProperties({ $$client_ingestion_warning_message: 'test message' })- .build(),- ]-- const { backgroundTask } = await ingester.handleKafkaBatch(createKafkaMessages(events))- await backgroundTask-- await waitForExpect(async () => {- await waitForKafkaMessages(_kafkaProducer)- const warnings = await fetchIngestionWarnings(hub, team.id)- expect(warnings).toEqual([- expect.objectContaining({- type: 'client_ingestion_warning',- team_id: team.id,- details: expect.objectContaining({ message: 'test message' }),- }),- ])- })- }- )-testWithTeamIngester('should process events without a team_id',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, kafkaProducer, token }) => {const events = [new EventBuilder(team).withEvent('test event').build()]- await ingester.handleKafkaBatch(createKafkaMessages(events))+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toBe(1)expect(events[0].team_id).toBe(team.id)})@@ -355,7 +104,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('can set and update group properties with $groupidentify events',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {const groupKey = 'group_key'const distinctId = new UUIDT().toString()@@ -366,11 +115,11 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events))+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const group = await hub.groupRepository.fetchGroup(team.id, 0, groupKey)+ const group = await infra.groupRepository.fetchGroup(team.id, 0, groupKey)expect(group).toEqual(expect.objectContaining({team_id: team.id,@@ -389,12 +138,12 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(updateEvents))+ await ingester.handleKafkaBatch(createKafkaMessages(updateEvents, token))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const group = await hub.groupRepository.fetchGroup(team.id, 0, groupKey)+ const group = await infra.groupRepository.fetchGroup(team.id, 0, groupKey)expect(group).toEqual(expect.objectContaining({team_id: team.id,@@ -407,7 +156,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:})await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(2)expect(events[0].event).toEqual('$groupidentify')expect(events[0].properties.$group_set).toEqual({ foo: 'bar' })@@ -417,14 +166,14 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// Should have fetched the group 4 times:// 1 for each event and 2 in test check- expect(hub.groupRepository.fetchGroup).toHaveBeenCalledTimes(4)+ expect(infra.groupRepository.fetchGroup).toHaveBeenCalledTimes(4)})testWithTeamIngester('can handle high amount of $groupidentify in same batch',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {const n = 150const distinctId = new UUIDT().toString()const events = []@@ -439,26 +188,26 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:)}- await ingester.handleKafkaBatch(createKafkaMessages(events))+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(n)})- expect(hub.groupRepository.fetchGroup).toHaveBeenCalledTimes(1)- expect(hub.groupRepository.insertGroup).toHaveBeenCalledTimes(1)- expect(hub.groupRepository.updateGroup).toHaveBeenCalledTimes(0)- expect(hub.groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)+ expect(infra.groupRepository.fetchGroup).toHaveBeenCalledTimes(1)+ expect(infra.groupRepository.insertGroup).toHaveBeenCalledTimes(1)+ expect(infra.groupRepository.updateGroup).toHaveBeenCalledTimes(0)+ expect(infra.groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)})testWithTeamIngester('can handle multiple $groupidentify in same batch',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {const timestamp = DateTime.now().toMillis()const distinctId = new UUIDT().toString()const groupKey = 'group_key'@@ -481,11 +230,11 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events))+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))await waitForExpect(async () => {- await waitForKafkaMessages(_kafkaProducer)- const events = await fetchEvents(hub, team.id)+ await waitForKafkaMessages(kafkaProducer)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(3)expect(events[0].event).toEqual('$groupidentify')expect(events[0].properties.$group_set).toEqual({ k1: 'v1' })@@ -495,13 +244,13 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:expect(events[2].properties.$group_set).toEqual({ k2: 'v3', k4: 'v3' })})- expect(hub.groupRepository.fetchGroup).toHaveBeenCalledTimes(1)- expect(hub.groupRepository.insertGroup).toHaveBeenCalledTimes(1)- expect(hub.groupRepository.updateGroup).toHaveBeenCalledTimes(0)- expect(hub.groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)+ expect(infra.groupRepository.fetchGroup).toHaveBeenCalledTimes(1)+ expect(infra.groupRepository.insertGroup).toHaveBeenCalledTimes(1)+ expect(infra.groupRepository.updateGroup).toHaveBeenCalledTimes(0)+ expect(infra.groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)await waitForExpect(async () => {- const group = await hub.groupRepository.fetchGroup(team.id, 0, groupKey)+ const group = await infra.groupRepository.fetchGroup(team.id, 0, groupKey)expect(group).toEqual(expect.objectContaining({team_id: team.id,@@ -519,15 +268,15 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('can handle $groupidentify with no properties',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, kafkaProducer, token }) => {const events = [new EventBuilder(team).withEvent('$groupidentify').withProperties({}).build()]- await ingester.handleKafkaBatch(createKafkaMessages(events))+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(1)expect(events[0].event).toEqual('$groupidentify')expect(events[0].properties).toEqual({})@@ -538,7 +287,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('can handle multiple $groupidentify for different distinct ids',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {const n = 50const distinctIds = []for (let i = 0; i < n; i++) {@@ -562,18 +311,18 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:}// handle 100 events in one batch- await ingester.handleKafkaBatch(createKafkaMessages(events))+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(n * 2)})for (const distinctId of distinctIds) {await waitForExpect(async () => {- const group = await hub.groupRepository.fetchGroup(team.id, 0, distinctId)+ const group = await infra.groupRepository.fetchGroup(team.id, 0, distinctId)expect(group).toEqual(expect.objectContaining({team_id: team.id,@@ -590,7 +339,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('can handle multiple $groupidentify for different distinct ids',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {const n = 50const distinctIds = []for (let i = 0; i < n; i++) {@@ -614,18 +363,18 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:}// handle 100 events in one batch- await ingester.handleKafkaBatch(createKafkaMessages(events))+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(n * 2)})for (const distinctId of distinctIds) {await waitForExpect(async () => {- const group = await hub.groupRepository.fetchGroup(team.id, 0, distinctId)+ const group = await infra.groupRepository.fetchGroup(team.id, 0, distinctId)expect(group).toEqual(expect.objectContaining({team_id: team.id,@@ -642,37 +391,40 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('can $set and update person properties when reading event',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, token }) => {const distinctId = new UUIDT().toString()const timestamp = DateTime.now().toMillis()await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set: { prop: 'value' },- })- .withTimestamp(timestamp)- .build(),- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set: { prop: 'updated value' },- })- .withTimestamp(timestamp + 1)- .build(),- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set: { value: 'new value' },- })- .withTimestamp(timestamp + 2)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set: { prop: 'value' },+ })+ .withTimestamp(timestamp)+ .build(),+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set: { prop: 'updated value' },+ })+ .withTimestamp(timestamp + 1)+ .build(),+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set: { value: 'new value' },+ })+ .withTimestamp(timestamp + 2)+ .build(),+ ],+ token+ ))await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(3)expect(events[0].event).toEqual('$identify')expect(events[0].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))@@ -689,42 +441,45 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('$identify and $set events force person property updates even for filtered properties',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, token }) => {const distinctId = new UUIDT().toString()const timestamp = DateTime.now().toMillis()// Chain of events: normal event with filtered props, then $identify with filtered props, then another normal eventawait ingester.handleKafkaBatch(- createKafkaMessages([- // Event 1: Normal pageview with filtered properties (should be ignored on its own)- new EventBuilder(team, distinctId)- .withEvent('$pageview')- .withProperties({- $set: { $browser: 'Chrome', utm_source: 'google' },- })- .withTimestamp(timestamp)- .build(),- // Event 2: $identify with ONLY filtered properties (should force update)- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set: { $browser: 'Safari', $geoip_city_name: 'San Francisco' },- })- .withTimestamp(timestamp + 1)- .build(),- // Event 3: Another normal event with filtered properties- new EventBuilder(team, distinctId)- .withEvent('$pageview')- .withProperties({- $set: { utm_source: 'facebook' },- })- .withTimestamp(timestamp + 2)- .build(),- ])+ createKafkaMessages(+ [+ // Event 1: Normal pageview with filtered properties (should be ignored on its own)+ new EventBuilder(team, distinctId)+ .withEvent('$pageview')+ .withProperties({+ $set: { $browser: 'Chrome', utm_source: 'google' },+ })+ .withTimestamp(timestamp)+ .build(),+ // Event 2: $identify with ONLY filtered properties (should force update)+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set: { $browser: 'Safari', $geoip_city_name: 'San Francisco' },+ })+ .withTimestamp(timestamp + 1)+ .build(),+ // Event 3: Another normal event with filtered properties+ new EventBuilder(team, distinctId)+ .withEvent('$pageview')+ .withProperties({+ $set: { utm_source: 'facebook' },+ })+ .withTimestamp(timestamp + 2)+ .build(),+ ],+ token+ ))await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(3)// Event 0 (first pageview): Should have properties from first event only@@ -751,7 +506,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:})// Verify the final state of the person in the database- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()expect(person!.properties).toEqual({$browser: 'Safari',@@ -770,34 +525,37 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('$set events force person property updates even for filtered properties',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, token }) => {const distinctId = new UUIDT().toString()const timestamp = DateTime.now().toMillis()// Similar test but with $set event instead of $identifyawait ingester.handleKafkaBatch(- createKafkaMessages([- // Event 1: Normal event with filtered properties- new EventBuilder(team, distinctId)- .withEvent('$pageview')- .withProperties({- $set: { $browser: 'Chrome' },- })- .withTimestamp(timestamp)- .build(),- // Event 2: $set event with filtered properties (should force update)- new EventBuilder(team, distinctId)- .withEvent('$set')- .withProperties({- $set: { utm_source: 'twitter', $geoip_country_code: 'US' },- })- .withTimestamp(timestamp + 1)- .build(),- ])+ createKafkaMessages(+ [+ // Event 1: Normal event with filtered properties+ new EventBuilder(team, distinctId)+ .withEvent('$pageview')+ .withProperties({+ $set: { $browser: 'Chrome' },+ })+ .withTimestamp(timestamp)+ .build(),+ // Event 2: $set event with filtered properties (should force update)+ new EventBuilder(team, distinctId)+ .withEvent('$set')+ .withProperties({+ $set: { utm_source: 'twitter', $geoip_country_code: 'US' },+ })+ .withTimestamp(timestamp + 1)+ .build(),+ ],+ token+ ))await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(2)// Event 0 (first pageview): Should have properties from first event only@@ -815,7 +573,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:})// Verify the final state of the person in the database- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()expect(person!.properties).toEqual({$browser: 'Chrome',@@ -834,36 +592,39 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('PERSON_PROPERTIES_UPDATE_ALL flag enables updates for normally filtered properties',{ pluginServerConfig: { PERSON_PROPERTIES_UPDATE_ALL: true } },- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, token }) => {const distinctId = new UUIDT().toString()const timestamp = DateTime.now().toMillis()// With PERSON_PROPERTIES_UPDATE_ALL=true, even normal pageview events should update// filtered properties like $browser, $geoip_*, etc.await ingester.handleKafkaBatch(- createKafkaMessages([- // Event 1: Normal pageview that creates the person with initial properties- new EventBuilder(team, distinctId)- .withEvent('$pageview')- .withProperties({- $set: { $browser: 'Chrome', $geoip_city_name: 'New York' },- })- .withTimestamp(timestamp)- .build(),- // Event 2: Another normal pageview with updated filtered properties- // With the flag enabled, these should trigger a person update- new EventBuilder(team, distinctId)- .withEvent('$pageview')- .withProperties({- $set: { $browser: 'Safari', $geoip_city_name: 'San Francisco' },- })- .withTimestamp(timestamp + 1)- .build(),- ])+ createKafkaMessages(+ [+ // Event 1: Normal pageview that creates the person with initial properties+ new EventBuilder(team, distinctId)+ .withEvent('$pageview')+ .withProperties({+ $set: { $browser: 'Chrome', $geoip_city_name: 'New York' },+ })+ .withTimestamp(timestamp)+ .build(),+ // Event 2: Another normal pageview with updated filtered properties+ // With the flag enabled, these should trigger a person update+ new EventBuilder(team, distinctId)+ .withEvent('$pageview')+ .withProperties({+ $set: { $browser: 'Safari', $geoip_city_name: 'San Francisco' },+ })+ .withTimestamp(timestamp + 1)+ .build(),+ ],+ token+ ))await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(2)// Event 0 (first pageview): Should have initial properties@@ -882,7 +643,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:})// Verify the final state of the person in the database reflects the updates- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()expect(person!.properties).toEqual({$browser: 'Safari',@@ -896,46 +657,49 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('allowed geoip properties ($geoip_country_name, $geoip_city_name) trigger person updates alongside blocked geoip properties',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, token }) => {const distinctId = new UUIDT().toString()const timestamp = DateTime.now().toMillis()// When $geoip_country_name or $geoip_city_name changes, all geoip properties in the batch// should be updated, even the normally-blocked ones like $geoip_latitudeawait ingester.handleKafkaBatch(- createKafkaMessages([- // Event 1: Create person with initial geoip properties- new EventBuilder(team, distinctId)- .withEvent('$pageview')- .withProperties({- $set: {- $geoip_country_name: 'Canada',- $geoip_city_name: 'Toronto',- $geoip_latitude: 43.6532,- $geoip_longitude: -79.3832,- },- })- .withTimestamp(timestamp)- .build(),- // Event 2: Update geoip properties including allowed ones (country/city)- // Since $geoip_country_name changes, all geoip properties should be updated- new EventBuilder(team, distinctId)- .withEvent('$pageview')- .withProperties({- $set: {- $geoip_country_name: 'United States',- $geoip_city_name: 'San Francisco',- $geoip_latitude: 37.7749,- $geoip_longitude: -122.4194,- },- })- .withTimestamp(timestamp + 1)- .build(),- ])+ createKafkaMessages(+ [+ // Event 1: Create person with initial geoip properties+ new EventBuilder(team, distinctId)+ .withEvent('$pageview')+ .withProperties({+ $set: {+ $geoip_country_name: 'Canada',+ $geoip_city_name: 'Toronto',+ $geoip_latitude: 43.6532,+ $geoip_longitude: -79.3832,+ },+ })+ .withTimestamp(timestamp)+ .build(),+ // Event 2: Update geoip properties including allowed ones (country/city)+ // Since $geoip_country_name changes, all geoip properties should be updated+ new EventBuilder(team, distinctId)+ .withEvent('$pageview')+ .withProperties({+ $set: {+ $geoip_country_name: 'United States',+ $geoip_city_name: 'San Francisco',+ $geoip_latitude: 37.7749,+ $geoip_longitude: -122.4194,+ },+ })+ .withTimestamp(timestamp + 1)+ .build(),+ ],+ token+ ))await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(2)// Event 0 (first pageview): Should have initial geoip properties@@ -958,7 +722,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:})// Verify the final state of the person in the database reflects the updates- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()expect(person!.properties).toEqual({$creator_event_uuid: events[0].uuid,@@ -974,53 +738,56 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('can handle events with $process_person_profile=false',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, token }) => {const distinctId = new UUIDT().toString()const timestamp = DateTime.now().toMillis()await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- distinct_id: distinctId,- $set: { prop: 'value' },- })- .withTimestamp(timestamp)- .build(),- new EventBuilder(team, distinctId)- .withEvent('custom event')- .withProperties({- distinctId: distinctId,- $process_person_profile: false,- $group_0: 'group_key',- $set: {- c: 3,- },- $set_once: {- d: 4,- },- $unset: ['prop'],- })- .withOverrides({- $set: {- a: 1,- },- $set_once: {- b: 2,- },- })- .withTimestamp(timestamp + 1)- .build(),- new EventBuilder(team, distinctId)- .withEvent('custom event')- .withProperties({})- .withTimestamp(timestamp + 2)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ distinct_id: distinctId,+ $set: { prop: 'value' },+ })+ .withTimestamp(timestamp)+ .build(),+ new EventBuilder(team, distinctId)+ .withEvent('custom event')+ .withProperties({+ distinctId: distinctId,+ $process_person_profile: false,+ $group_0: 'group_key',+ $set: {+ c: 3,+ },+ $set_once: {+ d: 4,+ },+ $unset: ['prop'],+ })+ .withOverrides({+ $set: {+ a: 1,+ },+ $set_once: {+ b: 2,+ },+ })+ .withTimestamp(timestamp + 1)+ .build(),+ new EventBuilder(team, distinctId)+ .withEvent('custom event')+ .withProperties({})+ .withTimestamp(timestamp + 2)+ .build(),+ ],+ token+ ))await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(3)expect(events[0].event).toEqual('$identify')expect(events[0].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))@@ -1035,32 +802,35 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('force_upgrade triggers when personless event sent after person creation',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, token }) => {const distinctId = new UUIDT().toString()const timestamp = DateTime.now().toMillis()await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- distinct_id: distinctId,- $set: { prop: 'value' },- })- .withTimestamp(timestamp)- .build(),- new EventBuilder(team, distinctId)- .withEvent('custom event')- .withProperties({- $process_person_profile: false,- })- .withTimestamp(timestamp + 120000) // 2 minutes later (beyond 1-minute grace period)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ distinct_id: distinctId,+ $set: { prop: 'value' },+ })+ .withTimestamp(timestamp)+ .build(),+ new EventBuilder(team, distinctId)+ .withEvent('custom event')+ .withProperties({+ $process_person_profile: false,+ })+ .withTimestamp(timestamp + 120000) // 2 minutes later (beyond 1-minute grace period)+ .build(),+ ],+ token+ ))await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(2)expect(events[0].event).toEqual('$identify')expect(events[0].person_mode).toEqual('full')@@ -1074,34 +844,37 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('can handle multiple personless events for different users in same batch',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, token }) => {const distinctId1 = new UUIDT().toString()const distinctId2 = new UUIDT().toString()const distinctId3 = new UUIDT().toString()const timestamp = DateTime.now().toMillis()await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId1)- .withEvent('pageview')- .withProperties({ $process_person_profile: false })- .withTimestamp(timestamp)- .build(),- new EventBuilder(team, distinctId2)- .withEvent('pageview')- .withProperties({ $process_person_profile: false })- .withTimestamp(timestamp + 1)- .build(),- new EventBuilder(team, distinctId3)- .withEvent('pageview')- .withProperties({ $process_person_profile: false })- .withTimestamp(timestamp + 2)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId1)+ .withEvent('pageview')+ .withProperties({ $process_person_profile: false })+ .withTimestamp(timestamp)+ .build(),+ new EventBuilder(team, distinctId2)+ .withEvent('pageview')+ .withProperties({ $process_person_profile: false })+ .withTimestamp(timestamp + 1)+ .build(),+ new EventBuilder(team, distinctId3)+ .withEvent('pageview')+ .withProperties({ $process_person_profile: false })+ .withTimestamp(timestamp + 2)+ .build(),+ ],+ token+ ))await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(3)expect(events.every((e) => e.event === 'pageview')).toBe(true)expect(events.every((e) => e.person_mode === 'propertyless')).toBe(true)@@ -1113,32 +886,35 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('can handle repeated personless events for same user in same batch',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, token }) => {const distinctId = new UUIDT().toString()const timestamp = DateTime.now().toMillis()await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('pageview')- .withProperties({ $process_person_profile: false, page: '/home' })- .withTimestamp(timestamp)- .build(),- new EventBuilder(team, distinctId)- .withEvent('pageview')- .withProperties({ $process_person_profile: false, page: '/about' })- .withTimestamp(timestamp + 1)- .build(),- new EventBuilder(team, distinctId)- .withEvent('pageview')- .withProperties({ $process_person_profile: false, page: '/contact' })- .withTimestamp(timestamp + 2)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('pageview')+ .withProperties({ $process_person_profile: false, page: '/home' })+ .withTimestamp(timestamp)+ .build(),+ new EventBuilder(team, distinctId)+ .withEvent('pageview')+ .withProperties({ $process_person_profile: false, page: '/about' })+ .withTimestamp(timestamp + 1)+ .build(),+ new EventBuilder(team, distinctId)+ .withEvent('pageview')+ .withProperties({ $process_person_profile: false, page: '/contact' })+ .withTimestamp(timestamp + 2)+ .build(),+ ],+ token+ ))await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(3)expect(events.every((e) => e.person_mode === 'propertyless')).toBe(true)// All events should have the same deterministic person UUID@@ -1151,24 +927,27 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('can $set and update person properties with top level $set',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, token }) => {const distinctId = new UUIDT().toString()await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- distinct_id: distinctId,- })- .withOverrides({- $set: { prop: 'value' },- })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ distinct_id: distinctId,+ })+ .withOverrides({+ $set: { prop: 'value' },+ })+ .build(),+ ],+ token+ ))await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(1)expect(events[0].event).toEqual('$identify')expect(events[0].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))@@ -1179,7 +958,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('should guarantee that person properties are set in the order of the events',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, token }) => {const distinctId = new UUIDT().toString()const timestamp = DateTime.now().toMillis()@@ -1208,10 +987,10 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events))+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(3)expect(events[0].event).toEqual('$identify')expect(events[0].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))@@ -1228,7 +1007,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('should be able to $set_once person properties but not update',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, token }) => {const distinctId = new UUIDT().toString()const events = [new EventBuilder(team, distinctId)@@ -1241,10 +1020,10 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events))+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(2)expect(events[0].event).toEqual('$identify')expect(events[0].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))@@ -1257,7 +1036,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('should be able to $set_once person properties but not update, at the top level',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, token }) => {const distinctId = new UUIDT().toString()const events = [new EventBuilder(team, distinctId)@@ -1273,10 +1052,10 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:new EventBuilder(team, distinctId).withEvent('custom event').withProperties({}).build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events))+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(3)expect(events[0].event).toEqual('$identify')expect(events[0].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))@@ -1291,7 +1070,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('should identify previous events with $anon_distinct_id',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, token }) => {const initialDistinctId = new UUIDT().toString()const personIdentifier = '[email protected]'@@ -1306,10 +1085,10 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events))+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(2)expect(events[0].person_id).toEqual(events[1].person_id)})@@ -1319,7 +1098,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('should perserve all events if merge fails',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, kafkaProducer, token }) => {const illegalDistinctId = '0'const distinctId = new UUIDT().toString()@@ -1328,12 +1107,12 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:new EventBuilder(team, distinctId).withEvent('custom event 2').withProperties({}).build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events))+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPersons(hub, team.id)+ const persons = await fetchPersons(team.id)expect(persons.length).toEqual(2)})@@ -1348,10 +1127,10 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(mergeEvents))+ await ingester.handleKafkaBatch(createKafkaMessages(mergeEvents, token))await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(3)// Assert that there are 2 different persons in person_id columnconst personIds = new Set(events.map((event) => event.person_id))@@ -1360,14 +1139,12 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:})- testWithTeamIngester(- 'should preserve properties if merge fails',- {},- async (ingester, hub, team, _kafkaProducer) => {- const illegalDistinctId = '0'- const distinctId = new UUIDT().toString()- await ingester.handleKafkaBatch(- createKafkaMessages([+ testWithTeamIngester('should preserve properties if merge fails', {}, async ({ ingester, team, token }) => {+ const illegalDistinctId = '0'+ const distinctId = new UUIDT().toString()+ await ingester.handleKafkaBatch(+ createKafkaMessages(+ [new EventBuilder(team, distinctId).withEvent('$merge_dangerously').withProperties({@@ -1377,21 +1154,22 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:}).build(),new EventBuilder(team, distinctId).withEvent('custom event').withProperties({}).build(),- ])+ ],+ token)+ )- await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)- expect(events.length).toEqual(2)- expect(events[1].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))- })- }- )+ await waitForExpect(async () => {+ const events = await fetchEvents(clickhouse, team.id)+ expect(events.length).toEqual(2)+ expect(events[1].person_properties).toEqual(expect.objectContaining({ prop: 'value' }))+ })+ })testWithTeamIngester('should merge all events into same person id',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, kafkaProducer, token }) => {const initialDistinctId = 'id1'const secondDistinctId = 'id2'const personIdentifier = 'person_id'@@ -1405,12 +1183,12 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.withProperties({}).build()- await ingester.handleKafkaBatch(createKafkaMessages([event1, event2]))+ await ingester.handleKafkaBatch(createKafkaMessages([event1, event2], token))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPersons(hub, team.id)+ const persons = await fetchPersons(team.id)expect(persons).toEqual(expect.arrayContaining([expect.objectContaining({@@ -1428,28 +1206,31 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:})await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, personIdentifier)- .withEvent('$identify')- .withProperties({- distinct_id: personIdentifier,- $anon_distinct_id: initialDistinctId,- })- .build(),- new EventBuilder(team, personIdentifier)- .withEvent('$identify')- .withProperties({- distinct_id: personIdentifier,- $anon_distinct_id: secondDistinctId,- })- .build(),- ])- )-- await waitForKafkaMessages(_kafkaProducer)+ createKafkaMessages(+ [+ new EventBuilder(team, personIdentifier)+ .withEvent('$identify')+ .withProperties({+ distinct_id: personIdentifier,+ $anon_distinct_id: initialDistinctId,+ })+ .build(),+ new EventBuilder(team, personIdentifier)+ .withEvent('$identify')+ .withProperties({+ distinct_id: personIdentifier,+ $anon_distinct_id: secondDistinctId,+ })+ .build(),+ ],+ token+ )+ )++ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(4)// assert all events have the same person_idconst personIds = new Set(events.map((event) => event.person_id))@@ -1461,50 +1242,65 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('should resolve to same person id chained merges',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, kafkaProducer, token }) => {const initialDistinctId = 'initialId'const secondDistinctId = 'secondId'const thirdDistinctId = 'thirdId'await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, initialDistinctId).withEvent('custom event').withProperties({}).build(),- new EventBuilder(team, secondDistinctId).withEvent('custom event 2').withProperties({}).build(),- new EventBuilder(team, thirdDistinctId).withEvent('custom event 3').withProperties({}).build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, initialDistinctId)+ .withEvent('custom event')+ .withProperties({})+ .build(),+ new EventBuilder(team, secondDistinctId)+ .withEvent('custom event 2')+ .withProperties({})+ .build(),+ new EventBuilder(team, thirdDistinctId)+ .withEvent('custom event 3')+ .withProperties({})+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(3)expect(new Set(events.map((event) => event.person_id)).size).toEqual(3)})await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, initialDistinctId)- .withEvent('$identify')- .withProperties({- distinct_id: initialDistinctId,- $anon_distinct_id: secondDistinctId,- })- .build(),- new EventBuilder(team, initialDistinctId)- .withEvent('$identify')- .withProperties({- distinct_id: initialDistinctId,- $anon_distinct_id: thirdDistinctId,- })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, initialDistinctId)+ .withEvent('$identify')+ .withProperties({+ distinct_id: initialDistinctId,+ $anon_distinct_id: secondDistinctId,+ })+ .build(),+ new EventBuilder(team, initialDistinctId)+ .withEvent('$identify')+ .withProperties({+ distinct_id: initialDistinctId,+ $anon_distinct_id: thirdDistinctId,+ })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(5)expect(new Set(events.map((event) => event.person_id)).size).toEqual(1)})@@ -1514,70 +1310,91 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('should resolve to same person id even with complex chained merges',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, kafkaProducer, token }) => {const initialDistinctId = new UUIDT().toString()const secondDistinctId = new UUIDT().toString()const thirdDistinctId = new UUIDT().toString()const forthDistinctId = new UUIDT().toString()await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, initialDistinctId).withEvent('custom event').withProperties({}).build(),- new EventBuilder(team, secondDistinctId).withEvent('custom event 2').withProperties({}).build(),- new EventBuilder(team, thirdDistinctId).withEvent('custom event 3').withProperties({}).build(),- new EventBuilder(team, forthDistinctId).withEvent('custom event 4').withProperties({}).build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, initialDistinctId)+ .withEvent('custom event')+ .withProperties({})+ .build(),+ new EventBuilder(team, secondDistinctId)+ .withEvent('custom event 2')+ .withProperties({})+ .build(),+ new EventBuilder(team, thirdDistinctId)+ .withEvent('custom event 3')+ .withProperties({})+ .build(),+ new EventBuilder(team, forthDistinctId)+ .withEvent('custom event 4')+ .withProperties({})+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPersons(hub, team.id)+ const persons = await fetchPersons(team.id)expect(persons.length).toBe(4)})await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, initialDistinctId)- .withEvent('$identify')- .withProperties({- distinct_id: initialDistinctId,- $anon_distinct_id: secondDistinctId,- })- .build(),- new EventBuilder(team, thirdDistinctId)- .withEvent('$identify')- .withProperties({- distinct_id: thirdDistinctId,- $anon_distinct_id: forthDistinctId,- })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, initialDistinctId)+ .withEvent('$identify')+ .withProperties({+ distinct_id: initialDistinctId,+ $anon_distinct_id: secondDistinctId,+ })+ .build(),+ new EventBuilder(team, thirdDistinctId)+ .withEvent('$identify')+ .withProperties({+ distinct_id: thirdDistinctId,+ $anon_distinct_id: forthDistinctId,+ })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toBe(6)})await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, secondDistinctId)- .withEvent('$merge_dangerously')- .withProperties({- distinct_id: secondDistinctId,- alias: thirdDistinctId,- })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, secondDistinctId)+ .withEvent('$merge_dangerously')+ .withProperties({+ distinct_id: secondDistinctId,+ alias: thirdDistinctId,+ })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toBe(7)expect(new Set(events.map((event) => event.person_id)).size).toBe(1)})@@ -1587,7 +1404,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('should produce ingestion warnings for messages over 1MB',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, kafkaProducer, token }) => {// For this we basically want the processor to try and produce a new// message larger than 1MB. We do this by creating a person with a lot of// properties. We will end up denormalizing the person properties onto the@@ -1612,19 +1429,19 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:new EventBuilder(team, distinctId).withEvent('$identify').withProperties(personProperties).build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events))+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const ingestionWarnings = await fetchIngestionWarnings(hub, team.id)+ const ingestionWarnings = await fetchIngestionWarnings(clickhouse, team.id)expect(ingestionWarnings.length).toBe(1)expect(ingestionWarnings[0].details.eventUuid).toBe(events[0].uuid)})})- const fetchPersons = async (hub: Hub, teamId: number) => {+ const fetchPersons = async (teamId: number) => {const persons = await clickhouse.fetchPersons(teamId)return persons.map((person) => ({...person,@@ -1632,112 +1449,8 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:}))}- const fetchEvents = async (hub: Hub, teamId: number) => {- // Force ClickHouse to merge parts to ensure FINAL consistency with retry logic- await retryClickHouseOperation(- () => clickhouse.exec(`OPTIMIZE TABLE person_distinct_id_overrides FINAL`),- 'OPTIMIZE TABLE person_distinct_id_overrides FINAL',- 3, // max retries- false // non-fatal operation- )-- // Query events with retry logic for connection stability- const queryResult = (await retryClickHouseOperation(- () =>- clickhouse.query(`- SELECT *,- if(notEmpty(overrides.person_id), overrides.person_id, e.person_id) as person_id- FROM events e- FINAL- LEFT OUTER JOIN (- SELECT- distinct_id,- argMax(person_id, version) as person_id- FROM person_distinct_id_overrides- FINAL- WHERE team_id = ${teamId}- GROUP BY distinct_id- ) AS overrides USING distinct_id- WHERE team_id = ${teamId}- ORDER BY timestamp ASC- `),- 'fetchEvents query',- 3, // max retries- true // fatal operation- )) as unknown as RawClickHouseEvent[]-- return queryResult.map(parseRawClickHouseEvent)- }-- // Utility function for retrying ClickHouse operations with exponential backoff- const retryClickHouseOperation = async <T>(- operation: () => Promise<T>,- operationName: string,- maxRetries: number = 3,- throwOnFailure: boolean = true- ): Promise<T | null> => {- let lastError: Error | null = null-- for (let attempt = 1; attempt <= maxRetries; attempt++) {- try {- return await operation()- } catch (error: any) {- lastError = error-- const isSocketError =- error?.message?.includes('socket hang up') ||- error?.message?.includes('ECONNRESET') ||- error?.message?.includes('ETIMEDOUT')-- if (isSocketError && attempt < maxRetries) {- const backoffMs = Math.min(1000 * Math.pow(2, attempt - 1), 10000) // Exponential backoff, max 10s- console.warn(- `[DEBUG] ClickHouse ${operationName} failed (attempt ${attempt}/${maxRetries}), retrying in ${backoffMs}ms:`,- error?.message- )- await new Promise((resolve) => setTimeout(resolve, backoffMs))- continue- }-- console.warn(- `[DEBUG] ClickHouse ${operationName} failed (attempt ${attempt}/${maxRetries}):`,- error?.message- )- break- }- }-- if (throwOnFailure && lastError) {- throw lastError- } else if (lastError) {- console.warn(- `[DEBUG] ClickHouse ${operationName} failed after all retries (non-fatal):`,- lastError?.message- )- return null- }-- return null- }-- const fetchIngestionWarnings = async (hub: Hub, teamId: number) => {- const queryResult = (await retryClickHouseOperation(- () =>- clickhouse.query(`- SELECT *- FROM ingestion_warnings- WHERE team_id = ${teamId}- `),- 'fetchIngestionWarnings query',- 3, // max retries- true // fatal operation- )) as any[]-- return queryResult.map((warning: any) => ({ ...warning, details: parseJSON(warning.details) }))- }-// TODO: Re-enable after re-adding FK constraints to posthog_persondistinctid- // testWithTeamIngester('alias events ordering scenario 1: original order', {}, async (ingester, hub, team, _kafkaProducer) => {+ // testWithTeamIngester('alias events ordering scenario 1: original order', {}, async ({ ingester, infra, team, kafkaProducer, token }) => {// const testName = DateTime.now().toFormat('yyyy-MM-dd-HH-mm-ss')// const user1DistinctId = 'user1-distinct-id'// const user2DistinctId = 'user2-distinct-id'@@ -1803,11 +1516,11 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// .build(),// ]- // await ingester.handleKafkaBatch(createKafkaMessages(events))- // await waitForKafkaMessages(_kafkaProducer)+ // await ingester.handleKafkaBatch(createKafkaMessages(events, token))+ // await waitForKafkaMessages(kafkaProducer)// await waitForExpect(async () => {- // const events = await fetchEvents(hub, team.id)+ // const events = await fetchEvents(clickhouse, team.id)// expect(events.length).toBe(6)// // TODO: Add specific assertions based on expected behavior@@ -1817,9 +1530,9 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// // fetch the person properties// await waitForExpect(async () => {- // const persons = await fetchPostgresPersons(hub.postgres, team.id)+ // const persons = await fetchPostgresPersons(infra.postgres, team.id)// expect(persons.length).toBe(1)- // const personsClickhouse = await fetchPersons(hub, team.id)+ // const personsClickhouse = await fetchPersons(team.id)// expect(personsClickhouse.length).toBe(1)// expect(persons[0].properties).toMatchObject(// expect.objectContaining({@@ -1839,7 +1552,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// test_name: testName,// })// )- // const distinctIdsPersons = await fetchDistinctIds(hub.postgres, {+ // const distinctIdsPersons = await fetchDistinctIds(infra.postgres, {// id: persons[0].id,// team_id: team.id,// } as InternalPerson)@@ -1852,7 +1565,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// })// TODO: Re-enable after re-adding FK constraints to posthog_persondistinctid- // testWithTeamIngester('alias events ordering scenario 2: alias first', {}, async (ingester, hub, team, _kafkaProducer) => {+ // testWithTeamIngester('alias events ordering scenario 2: alias first', {}, async ({ ingester, infra, team, kafkaProducer, token }) => {// const testName = DateTime.now().toFormat('yyyy-MM-dd-HH-mm-ss')// const user1DistinctId = 'user1-distinct-id'// const user2DistinctId = 'user2-distinct-id'@@ -1919,11 +1632,11 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// .build(),// ]- // await ingester.handleKafkaBatch(createKafkaMessages(events))- // await waitForKafkaMessages(_kafkaProducer)+ // await ingester.handleKafkaBatch(createKafkaMessages(events, token))+ // await waitForKafkaMessages(kafkaProducer)// await waitForExpect(async () => {- // const events = await fetchEvents(hub, team.id)+ // const events = await fetchEvents(clickhouse, team.id)// expect(events.length).toBe(6)// // TODO: Add specific assertions based on expected behavior@@ -1933,9 +1646,9 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// // fetch the person properties// await waitForExpect(async () => {- // const persons = await fetchPostgresPersons(hub.postgres, team.id)+ // const persons = await fetchPostgresPersons(infra.postgres, team.id)// expect(persons.length).toBe(1)- // const personsClickhouse = await fetchPersons(hub, team.id)+ // const personsClickhouse = await fetchPersons(team.id)// expect(personsClickhouse.length).toBe(1)// expect(persons[0].properties).toMatchObject(// expect.objectContaining({@@ -1955,7 +1668,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// test_name: testName,// })// )- // const distinctIdsPersons = await fetchDistinctIds(hub.postgres, {+ // const distinctIdsPersons = await fetchDistinctIds(infra.postgres, {// id: persons[0].id,// team_id: team.id,// } as InternalPerson)@@ -1968,7 +1681,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// })// TODO: Re-enable after re-adding FK constraints to posthog_persondistinctid- // testWithTeamIngester('alias events ordering scenario 2: user 2 first', {}, async (ingester, hub, team, _kafkaProducer) => {+ // testWithTeamIngester('alias events ordering scenario 2: user 2 first', {}, async ({ ingester, infra, team, kafkaProducer, token }) => {// const testName = DateTime.now().toFormat('yyyy-MM-dd-HH-mm-ss')// const user1DistinctId = 'user1-distinct-id'// const user2DistinctId = 'user2-distinct-id'@@ -2036,11 +1749,11 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// .build(),// ]- // await ingester.handleKafkaBatch(createKafkaMessages(events))- // await waitForKafkaMessages(_kafkaProducer)+ // await ingester.handleKafkaBatch(createKafkaMessages(events, token))+ // await waitForKafkaMessages(kafkaProducer)// await waitForExpect(async () => {- // const events = await fetchEvents(hub, team.id)+ // const events = await fetchEvents(clickhouse, team.id)// expect(events.length).toBe(6)// // TODO: Add specific assertions based on expected behavior@@ -2050,9 +1763,9 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// // fetch the person properties// await waitForExpect(async () => {- // const persons = await fetchPostgresPersons(hub.postgres, team.id)+ // const persons = await fetchPostgresPersons(infra.postgres, team.id)// expect(persons.length).toBe(1)- // const personsClickhouse = await fetchPersons(hub, team.id)+ // const personsClickhouse = await fetchPersons(team.id)// expect(personsClickhouse.length).toBe(1)// expect(persons[0].properties).toMatchObject(// expect.objectContaining({@@ -2072,7 +1785,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// test_name: testName,// })// )- // const distinctIdsPersons = await fetchDistinctIds(hub.postgres, {+ // const distinctIdsPersons = await fetchDistinctIds(infra.postgres, {// id: persons[0].id,// team_id: team.id,// } as InternalPerson)@@ -2087,7 +1800,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('alias events ordering scenario 2: user 2 first, separate batch',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {const testName = DateTime.now().toFormat('yyyy-MM-dd-HH-mm-ss')const user1DistinctId = 'user1-distinct-id'const user2DistinctId = 'user2-distinct-id'@@ -2157,14 +1870,14 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events))- await waitForKafkaMessages(_kafkaProducer)+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))+ await waitForKafkaMessages(kafkaProducer)- await ingester.handleKafkaBatch(createKafkaMessages(events2))- await waitForKafkaMessages(_kafkaProducer)+ await ingester.handleKafkaBatch(createKafkaMessages(events2, token))+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toBe(6)// TODO: Add specific assertions based on expected behavior@@ -2174,9 +1887,9 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// fetch the person propertiesawait waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(2)- const personsClickhouse = await fetchPersons(hub, team.id)+ const personsClickhouse = await fetchPersons(team.id)expect(personsClickhouse.length).toBe(2)expect(persons.map((person) => person.properties)).toEqual(expect.arrayContaining([@@ -2216,7 +1929,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:)const person1 = persons.find((person) => person.properties.name === 'User 1')!const person2 = persons.find((person) => person.properties.name === 'User 2')!- const distinctIdsPersons1 = await fetchDistinctIds(hub.postgres, {+ const distinctIdsPersons1 = await fetchDistinctIds(infra.postgres, {id: person1.id,team_id: team.id,} as InternalPerson)@@ -2225,7 +1938,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:expect(distinctIdsPersons1.map((distinctId) => distinctId.distinct_id)).toEqual(expect.arrayContaining([user1DistinctId]))- const distinctIdsPersons2 = await fetchDistinctIds(hub.postgres, {+ const distinctIdsPersons2 = await fetchDistinctIds(infra.postgres, {id: person2.id,team_id: team.id,} as InternalPerson)@@ -2241,7 +1954,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('Should set and $unset person properties, different batches',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {const user1DistinctId = 'user1-distinct-id'const events = [@@ -2256,13 +1969,13 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events))- await waitForKafkaMessages(_kafkaProducer)+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)- const personsClickhouse = await fetchPersons(hub, team.id)+ const personsClickhouse = await fetchPersons(team.id)expect(personsClickhouse.length).toBe(1)expect(persons[0].properties).toMatchObject(expect.objectContaining({@@ -2287,13 +2000,13 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events2))- await waitForKafkaMessages(_kafkaProducer)+ await ingester.handleKafkaBatch(createKafkaMessages(events2, token))+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)- const personsClickhouse = await fetchPersons(hub, team.id)+ const personsClickhouse = await fetchPersons(team.id)expect(personsClickhouse.length).toBe(1)expect(persons[0].properties).toMatchObject(expect.objectContaining({@@ -2314,7 +2027,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('Should set and $unset person properties, same batch',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {const user1DistinctId = 'user1-distinct-id'const events = [@@ -2335,13 +2048,13 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events))- await waitForKafkaMessages(_kafkaProducer)+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)- const personsClickhouse = await fetchPersons(hub, team.id)+ const personsClickhouse = await fetchPersons(team.id)expect(personsClickhouse.length).toBe(1)expect(persons[0].properties).toMatchObject(expect.objectContaining({@@ -2362,7 +2075,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('should process events with various timestamps when dropping is disabled',{ teamOverrides: { drop_events_older_than_seconds: null } },- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, kafkaProducer, token }) => {const currentTime = DateTime.now().toMillis()const events = [// Current time event@@ -2403,11 +2116,11 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events))- await waitForKafkaMessages(_kafkaProducer)+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)// All events should be processed when dropping is disabledexpect(events.length).toBe(6)@@ -2426,7 +2139,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('should drop old events when dropping is enabled',{ teamOverrides: { drop_events_older_than_seconds: 3600 } },- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, kafkaProducer, token }) => {const currentTime = DateTime.now().toMillis()const events = [// Current time event - should pass@@ -2473,11 +2186,11 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events))- await waitForKafkaMessages(_kafkaProducer)+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)// Only events under 1 hour old should be processedexpect(events.length).toBe(4)@@ -2496,7 +2209,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// Check that ingestion warnings were created for dropped eventsawait waitForExpect(async () => {- const warnings = await fetchIngestionWarnings(hub, team.id)+ const warnings = await fetchIngestionWarnings(clickhouse, team.id)expect(warnings.length).toBe(3)const warningTypes = warnings.map((w) => w.type)@@ -2514,7 +2227,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('should process all events when drop threshold is set to 0',{ teamOverrides: { drop_events_older_than_seconds: 0 } },- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, kafkaProducer, token }) => {const currentTime = DateTime.now().toMillis()const events = [// Current time event - should pass@@ -2555,11 +2268,11 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events))- await waitForKafkaMessages(_kafkaProducer)+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)// All events should be processed when threshold is 0 (no dropping)expect(events.length).toBe(6)@@ -2575,7 +2288,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// Check that no ingestion warnings were created (no events should be dropped)await waitForExpect(async () => {- const warnings = await fetchIngestionWarnings(hub, team.id)+ const warnings = await fetchIngestionWarnings(clickhouse, team.id)expect(warnings.length).toBe(0)})}@@ -2584,7 +2297,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('we do not alias users if distinct id changes but we are already identified, with no anonymous event',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {// This test is similar to the previous one, except it does not include an initial anonymous event.const anonymousId = 'anonymous_id'@@ -2614,18 +2327,18 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events))- await waitForKafkaMessages(_kafkaProducer)+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(2)// Both persons should be identifiedexpect(persons.map((person) => person.is_identified)).toEqual([true, true])// Check that events are grouped correctly by person- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)const eventsByPersonId = new Map<string, string[]>()for (const event of events) {@@ -2651,7 +2364,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('we do not leave things in inconsistent state if $identify is run concurrently',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {// There are a few places where we have the pattern of://// 1. fetch from postgres@@ -2680,11 +2393,11 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events))- await waitForKafkaMessages(_kafkaProducer)+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(2)expect(persons.map((person) => person.is_identified)).toEqual([true, true])})@@ -2694,7 +2407,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('we can alias an anonymous person to an anonymous person',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {const anonymous1 = 'anonymous-1'const anonymous2 = 'anonymous-2'@@ -2708,18 +2421,18 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events))- await waitForKafkaMessages(_kafkaProducer)+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)// Make sure there is one identified personexpect(persons.map((person) => person.is_identified)).toEqual([true])// Check that events are grouped correctly by person- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toBe(3)// All events should belong to the same person@@ -2735,7 +2448,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('we can alias two non-existent persons',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {const anonymous1 = 'anonymous-1'const anonymous2 = 'anonymous-2'@@ -2746,18 +2459,18 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events))- await waitForKafkaMessages(_kafkaProducer)+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)expect(persons[0].is_identified).toBe(true)- const distinctIds = await fetchDistinctIds(hub.postgres, persons[0])+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([anonymous1, anonymous2])- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toBe(1)expect(events[0].event).toBe('$create_alias')})@@ -2767,39 +2480,43 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('$merge_dangerously merges two persons into one',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {const oldDistinctId = 'old_distinct_id'const newDistinctId = 'new_distinct_id'// Create a person for old_distinct_idawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, oldDistinctId).withEvent('custom event').withProperties({}).build(),- ])+ createKafkaMessages(+ [new EventBuilder(team, oldDistinctId).withEvent('custom event').withProperties({}).build()],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)})// Send $merge_dangerously from new_distinct_id with alias: old_distinct_idawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, newDistinctId)- .withEvent('$merge_dangerously')- .withProperties({ alias: oldDistinctId })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, newDistinctId)+ .withEvent('$merge_dangerously')+ .withProperties({ alias: oldDistinctId })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)- const distinctIds = await fetchDistinctIds(hub.postgres, persons[0])+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([newDistinctId, oldDistinctId])})}@@ -2808,137 +2525,157 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('$create_alias links existing person to new distinct id',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {const oldDistinctId = 'old_distinct_id'const newDistinctId = 'new_distinct_id'// Create a person for old_distinct_idawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, oldDistinctId).withEvent('custom event').withProperties({}).build(),- ])+ createKafkaMessages(+ [new EventBuilder(team, oldDistinctId).withEvent('custom event').withProperties({}).build()],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)})// Send $create_alias from new_distinct_id with alias: old_distinct_idawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, newDistinctId)- .withEvent('$create_alias')- .withProperties({ alias: oldDistinctId })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, newDistinctId)+ .withEvent('$create_alias')+ .withProperties({ alias: oldDistinctId })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)- const distinctIds = await fetchDistinctIds(hub.postgres, persons[0])+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([newDistinctId, oldDistinctId])})})- testWithTeamIngester('alias works in reverse direction', {}, async (ingester, hub, team, _kafkaProducer) => {- const oldDistinctId = 'old_distinct_id'- const newDistinctId = 'new_distinct_id'+ testWithTeamIngester(+ 'alias works in reverse direction',+ {},+ async ({ ingester, infra, team, kafkaProducer, token }) => {+ const oldDistinctId = 'old_distinct_id'+ const newDistinctId = 'new_distinct_id'- // Create a person for old_distinct_id- await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, oldDistinctId).withEvent('custom event').withProperties({}).build(),- ])- )- await waitForKafkaMessages(_kafkaProducer)+ // Create a person for old_distinct_id+ await ingester.handleKafkaBatch(+ createKafkaMessages(+ [new EventBuilder(team, oldDistinctId).withEvent('custom event').withProperties({}).build()],+ token+ )+ )+ await waitForKafkaMessages(kafkaProducer)- // Send $create_alias from old_distinct_id with alias: new_distinct_id (reversed)- await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, oldDistinctId)- .withEvent('$create_alias')- .withProperties({ alias: newDistinctId })- .build(),- ])- )- await waitForKafkaMessages(_kafkaProducer)+ // Send $create_alias from old_distinct_id with alias: new_distinct_id (reversed)+ await ingester.handleKafkaBatch(+ createKafkaMessages(+ [+ new EventBuilder(team, oldDistinctId)+ .withEvent('$create_alias')+ .withProperties({ alias: newDistinctId })+ .build(),+ ],+ token+ )+ )+ await waitForKafkaMessages(kafkaProducer)- await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)- expect(persons.length).toBe(1)+ await waitForExpect(async () => {+ const persons = await fetchPostgresPersons(infra.postgres, team.id)+ expect(persons.length).toBe(1)- const distinctIds = await fetchDistinctIds(hub.postgres, persons[0])- expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([newDistinctId, oldDistinctId])- })- })+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])+ expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([newDistinctId, oldDistinctId])+ })+ }+ )testWithTeamIngester('chained alias merges three persons into one',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {const oldDistinctId = 'old_distinct_id'const newDistinctId = 'new_distinct_id'const oldDistinctId2 = 'old_distinct_id_2'// Create person for old_distinct_idawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, oldDistinctId).withEvent('custom event').withProperties({}).build(),- ])+ createKafkaMessages(+ [new EventBuilder(team, oldDistinctId).withEvent('custom event').withProperties({}).build()],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)// First alias: link new_distinct_id to old_distinct_idawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, newDistinctId)- .withEvent('$create_alias')- .withProperties({ alias: oldDistinctId })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, newDistinctId)+ .withEvent('$create_alias')+ .withProperties({ alias: oldDistinctId })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)})// Create a second personawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, oldDistinctId2).withEvent('custom event 2').withProperties({}).build(),- ])+ createKafkaMessages(+ [new EventBuilder(team, oldDistinctId2).withEvent('custom event 2').withProperties({}).build()],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(2)})// Second alias: merge old_distinct_id_2 into new_distinct_idawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, newDistinctId)- .withEvent('$create_alias')- .withProperties({ alias: oldDistinctId2 })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, newDistinctId)+ .withEvent('$create_alias')+ .withProperties({ alias: oldDistinctId2 })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)- const distinctIds = await fetchDistinctIds(hub.postgres, persons[0])+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([newDistinctId,oldDistinctId,@@ -2951,22 +2688,25 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('$create_alias before any person exists creates one person with both distinct ids',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, 'new_distinct_id')- .withEvent('$create_alias')- .withProperties({ alias: 'old_distinct_id' })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, 'new_distinct_id')+ .withEvent('$create_alias')+ .withProperties({ alias: 'old_distinct_id' })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)- const distinctIds = await fetchDistinctIds(hub.postgres, persons[0])+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual(['new_distinct_id', 'old_distinct_id'])})}@@ -2975,37 +2715,43 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('$create_alias merges two existing persons into one',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {// Create two separate personsawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, 'old_distinct_id').withEvent('event 1').build(),- new EventBuilder(team, 'new_distinct_id').withEvent('event 2').build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, 'old_distinct_id').withEvent('event 1').build(),+ new EventBuilder(team, 'new_distinct_id').withEvent('event 2').build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(2)})// Alias them togetherawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, 'new_distinct_id')- .withEvent('$create_alias')- .withProperties({ alias: 'old_distinct_id' })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, 'new_distinct_id')+ .withEvent('$create_alias')+ .withProperties({ alias: 'old_distinct_id' })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)- const distinctIds = await fetchDistinctIds(hub.postgres, persons[0])+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual(['new_distinct_id', 'old_distinct_id'])})}@@ -3014,57 +2760,66 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('alias merges person properties correctly',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {const newDistinctId = 'new_distinct_id'const oldDistinctId = 'old_distinct_id'// Create two persons with different propertiesawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, newDistinctId)- .withEvent('$pageview')- .withProperties({- $set: { key_on_both: 'new value both', key_on_new: 'new value' },- })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, newDistinctId)+ .withEvent('$pageview')+ .withProperties({+ $set: { key_on_both: 'new value both', key_on_new: 'new value' },+ })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, oldDistinctId)- .withEvent('$pageview')- .withProperties({- $set: { key_on_both: 'old value both', key_on_old: 'old value' },- })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, oldDistinctId)+ .withEvent('$pageview')+ .withProperties({+ $set: { key_on_both: 'old value both', key_on_old: 'old value' },+ })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(2)expect(persons.map((p) => p.is_identified)).toEqual([false, false])})// Alias them: new_distinct_id's values should win for shared keysawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, newDistinctId)- .withEvent('$create_alias')- .withProperties({ alias: oldDistinctId })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, newDistinctId)+ .withEvent('$create_alias')+ .withProperties({ alias: oldDistinctId })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)- const distinctIds = await fetchDistinctIds(hub.postgres, persons[0])+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([newDistinctId, oldDistinctId])expect(persons[0].properties).toEqual(@@ -3081,19 +2836,20 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('$identify with illegal distinct ids does not merge persons',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {const anonymousId = 'im-an-anonymous-id'// Create a person for the anonymous IDawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, anonymousId).withEvent('custom event').withProperties({}).build(),- ])+ createKafkaMessages(+ [new EventBuilder(team, anonymousId).withEvent('custom event').withProperties({}).build()],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)})@@ -3101,35 +2857,41 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:const illegalIds = ['0', 'None', 'undefined', 'NaN', ' ', 'distinctId']for (const illegalId of illegalIds) {await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, illegalId)- .withEvent('$identify')- .withProperties({ $anon_distinct_id: anonymousId })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, illegalId)+ .withEvent('$identify')+ .withProperties({ $anon_distinct_id: anonymousId })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)}await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)// 1 original + 5 illegal IDs each created their own person (merges failed)expect(persons.length).toBe(1 + illegalIds.length)})// 'Nan' is a legal ID (only 'NaN' is illegal), so the merge should workawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, 'Nan')- .withEvent('$identify')- .withProperties({ $anon_distinct_id: anonymousId })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, 'Nan')+ .withEvent('$identify')+ .withProperties({ $anon_distinct_id: anonymousId })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)// No extra person created because 'Nan' merged with the anonymous personexpect(persons.length).toBe(1 + illegalIds.length)})@@ -3139,31 +2901,35 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('$create_alias with illegal distinct id does not merge persons',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {const legalId = 'user123'const illegalId = 'null'// Create a person for the legal IDawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, legalId).withEvent('custom event').withProperties({}).build(),- ])+ createKafkaMessages(+ [new EventBuilder(team, legalId).withEvent('custom event').withProperties({}).build()],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)// Try $create_alias with an illegal aliasawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, illegalId)- .withEvent('$create_alias')- .withProperties({ alias: legalId })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, illegalId)+ .withEvent('$create_alias')+ .withProperties({ alias: legalId })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)// Person with illegal ID got created but not mergedexpect(persons.length).toBe(2)})@@ -3178,44 +2944,50 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('$identify merges anonymous person into existing person preserving properties',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {// Create two persons: one anonymous, one with propertiesawait ingester.handleKafkaBatch(- createKafkaMessages([new EventBuilder(team, 'anonymous_id').withEvent('anon event').build()])+ createKafkaMessages([new EventBuilder(team, 'anonymous_id').withEvent('anon event').build()], token))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, 'new_distinct_id')- .withEvent('$identify')- .withProperties({ $set: { email: '[email protected]' } })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, 'new_distinct_id')+ .withEvent('$identify')+ .withProperties({ $set: { email: '[email protected]' } })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(2)})// $identify merges anonymous_id into new_distinct_idawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, 'new_distinct_id')- .withEvent('$identify')- .withProperties({ $anon_distinct_id: 'anonymous_id' })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, 'new_distinct_id')+ .withEvent('$identify')+ .withProperties({ $anon_distinct_id: 'anonymous_id' })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)- const distinctIds = await fetchDistinctIds(hub.postgres, persons[0])+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual(['anonymous_id', 'new_distinct_id'])expect(persons[0].properties).toEqual(expect.objectContaining({ email: '[email protected]' }))expect(persons[0].is_identified).toBe(true)@@ -3226,33 +2998,37 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('$identify where distinct_id equals $anon_distinct_id is a no-op',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {const anonymousId = 'anonymous_id'// Create a person for anonymous_idawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, anonymousId).withEvent('custom event').withProperties({}).build(),- ])+ createKafkaMessages(+ [new EventBuilder(team, anonymousId).withEvent('custom event').withProperties({}).build()],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)// Send $identify where distinct_id == $anon_distinct_idawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, anonymousId)- .withEvent('$identify')- .withProperties({ $anon_distinct_id: anonymousId })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, anonymousId)+ .withEvent('$identify')+ .withProperties({ $anon_distinct_id: anonymousId })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)- const distinctIds = await fetchDistinctIds(hub.postgres, persons[0])+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])expect(distinctIds.map((d) => d.distinct_id)).toEqual([anonymousId])// Person should NOT be marked as identified (self-identify is a no-op)@@ -3264,36 +3040,42 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('$identify merges multiple anonymous persons sequentially preserving properties',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {// Create anonymous person and identified person with propertiesawait ingester.handleKafkaBatch(- createKafkaMessages([new EventBuilder(team, 'anonymous_id').withEvent('anon event').build()])+ createKafkaMessages([new EventBuilder(team, 'anonymous_id').withEvent('anon event').build()], token))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, 'new_distinct_id')- .withEvent('$identify')- .withProperties({ $set: { email: '[email protected]' } })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, 'new_distinct_id')+ .withEvent('$identify')+ .withProperties({ $set: { email: '[email protected]' } })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)// First $identify: merge anonymous_id into new_distinct_idawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, 'new_distinct_id')- .withEvent('$identify')- .withProperties({ $anon_distinct_id: 'anonymous_id' })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, 'new_distinct_id')+ .withEvent('$identify')+ .withProperties({ $anon_distinct_id: 'anonymous_id' })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)expect(persons[0].properties).toEqual(expect.objectContaining({ email: '[email protected]' }))expect(persons[0].is_identified).toBe(true)@@ -3301,26 +3083,32 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// Create a second anonymous personawait ingester.handleKafkaBatch(- createKafkaMessages([new EventBuilder(team, 'anonymous_id_2').withEvent('anon event 2').build()])+ createKafkaMessages(+ [new EventBuilder(team, 'anonymous_id_2').withEvent('anon event 2').build()],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)// Second $identify: merge anonymous_id_2 into new_distinct_idawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, 'new_distinct_id')- .withEvent('$identify')- .withProperties({ $anon_distinct_id: 'anonymous_id_2' })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, 'new_distinct_id')+ .withEvent('$identify')+ .withProperties({ $anon_distinct_id: 'anonymous_id_2' })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)- const distinctIds = await fetchDistinctIds(hub.postgres, persons[0])+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual(['anonymous_id','anonymous_id_2',@@ -3335,67 +3123,73 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('$identify does not merge persons across teams',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {// Create a second teamconst team2Id = Math.floor((Date.now() % 1000000000) + Math.random() * 1000000)await createUserTeamAndOrganization(- hub.postgres,+ infra.postgres,team2Id,team2Id,new UUIDT().toString(),new UUIDT().toString(),new UUIDT().toString())- const team2 = (await hub.teamManager.getTeam(team2Id))!+ const team2 = (await infra.teamManager.getTeam(team2Id))!// Create a person for team2 with distinct_id '2'- const team1Token = currentToken- currentToken = team2.api_tokenawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team2, '2')- .withEvent('$identify')- .withProperties({ $set: { email: '[email protected]' } })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team2, '2')+ .withEvent('$identify')+ .withProperties({ $set: { email: '[email protected]' } })+ .build(),+ ],+ team2.api_token+ ))- await waitForKafkaMessages(_kafkaProducer)- currentToken = team1Token+ await waitForKafkaMessages(kafkaProducer)// Create persons for team1 with distinct_ids '1' and '2'await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, '1').withEvent('custom event').withProperties({}).build(),- new EventBuilder(team, '2').withEvent('custom event').withProperties({}).build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, '1').withEvent('custom event').withProperties({}).build(),+ new EventBuilder(team, '2').withEvent('custom event').withProperties({}).build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)// Merge '1' into '2' on team1await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, '2')- .withEvent('$identify')- .withProperties({ $anon_distinct_id: '1' })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, '2')+ .withEvent('$identify')+ .withProperties({ $anon_distinct_id: '1' })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)// Verify team1 merged correctlyawait waitForExpect(async () => {- const team1Persons = await fetchPostgresPersons(hub.postgres, team.id)+ const team1Persons = await fetchPostgresPersons(infra.postgres, team.id)expect(team1Persons.length).toBe(1)- const distinctIds = await fetchDistinctIds(hub.postgres, team1Persons[0])+ const distinctIds = await fetchDistinctIds(infra.postgres, team1Persons[0])expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual(['1', '2'])})// Verify team2's person is untouchedawait waitForExpect(async () => {- const team2Persons = await fetchPostgresPersons(hub.postgres, team2Id)+ const team2Persons = await fetchPostgresPersons(infra.postgres, team2Id)expect(team2Persons.length).toBe(1)expect(team2Persons[0].properties).toEqual(expect.objectContaining({ email: '[email protected]' }))- const distinctIds = await fetchDistinctIds(hub.postgres, team2Persons[0])+ const distinctIds = await fetchDistinctIds(infra.postgres, team2Persons[0])expect(distinctIds.map((d) => d.distinct_id)).toEqual(['2'])})}@@ -3404,7 +3198,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('we do not alias users if distinct id changes but we are already identified',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {// This test is in reference to// https://github.com/PostHog/posthog/issues/5527 , where we were// correctly identifying that an anonymous user before login should be@@ -3434,28 +3228,31 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:new EventBuilder(team, p2NewDistinctId).withEvent('event 4').build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events))- await waitForKafkaMessages(_kafkaProducer)+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(2)expect(persons.every((p) => p.is_identified)).toBe(true)})// Batch 2: try to alias back to initialDistinctId (should fail — both already identified)await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, initialDistinctId)- .withEvent('$identify')- .withProperties({ $anon_distinct_id: p2NewDistinctId })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, initialDistinctId)+ .withEvent('$identify')+ .withProperties({ $anon_distinct_id: p2NewDistinctId })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)// Still 2 separate persons — merge was rejected because both are identifiedexpect(persons.length).toBe(2)expect(persons.every((p) => p.is_identified)).toBe(true)@@ -3466,7 +3263,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('we do not alias already identified users with no anonymous event',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {// This test is in reference to// https://github.com/PostHog/posthog/issues/5527 , where we were// correctly identifying that an anonymous user before login should be@@ -3501,15 +3298,15 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(events))- await waitForKafkaMessages(_kafkaProducer)+ await ingester.handleKafkaBatch(createKafkaMessages(events, token))+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(2)expect(persons.map((p) => p.is_identified)).toEqual([true, true])- const allEvents = await fetchEvents(hub, team.id)+ const allEvents = await fetchEvents(clickhouse, team.id)const eventsByPersonId = new Map<string, string[]>()for (const event of allEvents) {const personId = event.person_id!@@ -3534,55 +3331,64 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('$create_alias merges anonymous person into identified person',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {const someAnonId = 'some_anon_id'const identifiedId = 'identified_id'const anonymousId = 'anonymous_id'// Create a truly identified person (via real $identify merge)await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, identifiedId)- .withEvent('$identify')- .withProperties({ $anon_distinct_id: someAnonId })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, identifiedId)+ .withEvent('$identify')+ .withProperties({ $anon_distinct_id: someAnonId })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)expect(persons[0].is_identified).toBe(true)})// Create an anonymous personawait ingester.handleKafkaBatch(- createKafkaMessages([new EventBuilder(team, anonymousId).withEvent('anonymous event').build()])+ createKafkaMessages(+ [new EventBuilder(team, anonymousId).withEvent('anonymous event').build()],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(2)})// $create_alias: alias person (anonymous) is not identified → merge allowedawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, identifiedId)- .withEvent('$create_alias')- .withProperties({ alias: anonymousId })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, identifiedId)+ .withEvent('$create_alias')+ .withProperties({ alias: anonymousId })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)- const distinctIds = await fetchDistinctIds(hub.postgres, persons[0])+ const distinctIds = await fetchDistinctIds(infra.postgres, persons[0])expect(distinctIds.map((d) => d.distinct_id).sort()).toEqual([someAnonId, anonymousId, identifiedId].sort())@@ -3594,46 +3400,55 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('$create_alias does not merge when alias person is already identified',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {const someAnonId = 'some_anon_id'const identifiedId = 'identified_id'const anonymousId = 'anonymous_id'// Create a truly identified person (via real $identify merge)await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, identifiedId)- .withEvent('$identify')- .withProperties({ $anon_distinct_id: someAnonId })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, identifiedId)+ .withEvent('$identify')+ .withProperties({ $anon_distinct_id: someAnonId })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)// Create an anonymous personawait ingester.handleKafkaBatch(- createKafkaMessages([new EventBuilder(team, anonymousId).withEvent('anonymous event').build()])+ createKafkaMessages(+ [new EventBuilder(team, anonymousId).withEvent('anonymous event').build()],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(2)})// $create_alias: alias person (identifiedId) IS identified → merge blockedawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, anonymousId)- .withEvent('$create_alias')- .withProperties({ alias: identifiedId })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, anonymousId)+ .withEvent('$create_alias')+ .withProperties({ alias: identifiedId })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)// Merge blocked: alias person (identifiedId) has is_identified=trueexpect(persons.length).toBe(2)})@@ -3643,64 +3458,76 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('person and group properties are set on events',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, kafkaProducer, token }) => {// Create person with propertiesawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, 'distinct_id1')- .withEvent('$whatever')- .withProperties({ $set: { pineapple: 'on', pizza: 1 } })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, 'distinct_id1')+ .withEvent('$whatever')+ .withProperties({ $set: { pineapple: 'on', pizza: 1 } })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)// Set up group typesawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, 'distinct_id1')- .withEvent('$groupidentify')- .withProperties({- $group_type: 'organization',- $group_key: 'org:5',- $group_set: { foo: 'bar' },- })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, 'distinct_id1')+ .withEvent('$groupidentify')+ .withProperties({+ $group_type: 'organization',+ $group_key: 'org:5',+ $group_set: { foo: 'bar' },+ })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, 'distinct_id1')- .withEvent('$groupidentify')- .withProperties({- $group_type: 'second',- $group_key: 'second_key',- $group_set: { pineapple: 'yummy' },- })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, 'distinct_id1')+ .withEvent('$groupidentify')+ .withProperties({+ $group_type: 'second',+ $group_key: 'second_key',+ $group_set: { pineapple: 'yummy' },+ })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)// Send a regular event with group references and $setawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, 'distinct_id1')- .withEvent('test event')- .withProperties({- $set: { new: 5 },- $group_0: 'org:5',- $group_1: 'second_key',- })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, 'distinct_id1')+ .withEvent('test event')+ .withProperties({+ $set: { new: 5 },+ $group_0: 'org:5',+ $group_1: 'second_key',+ })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)const testEvent = events.find((e) => e.event === 'test event')expect(testEvent).toBeDefined()expect(testEvent!.person_properties).toEqual(@@ -3715,80 +3542,93 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('$set wins over $set_once on the same key',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, 'distinct_id1')- .withEvent('some_event')- .withProperties({- $set: { a_prop: 'test-set' },- $set_once: { a_prop: 'test-set_once' },- })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, 'distinct_id1')+ .withEvent('some_event')+ .withProperties({+ $set: { a_prop: 'test-set' },+ $set_once: { a_prop: 'test-set_once' },+ })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toBe(1)expect(events[0].properties['$set']).toEqual({ a_prop: 'test-set' })expect(events[0].properties['$set_once']).toEqual({ a_prop: 'test-set_once' })- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)expect(persons[0].properties).toEqual(expect.objectContaining({ a_prop: 'test-set' }))})})- testWithTeamIngester('$unset removes person properties', {}, async (ingester, hub, team, _kafkaProducer) => {- // Create person with properties- await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, 'distinct_id1')- .withEvent('$identify')- .withProperties({ $set: { a: 1, b: 2, c: 3 } })- .build(),- ])- )- await waitForKafkaMessages(_kafkaProducer)+ testWithTeamIngester(+ '$unset removes person properties',+ {},+ async ({ ingester, infra, team, kafkaProducer, token }) => {+ // Create person with properties+ await ingester.handleKafkaBatch(+ createKafkaMessages(+ [+ new EventBuilder(team, 'distinct_id1')+ .withEvent('$identify')+ .withProperties({ $set: { a: 1, b: 2, c: 3 } })+ .build(),+ ],+ token+ )+ )+ await waitForKafkaMessages(kafkaProducer)- await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)- expect(persons.length).toBe(1)- expect(persons[0].properties).toEqual(expect.objectContaining({ a: 1, b: 2, c: 3 }))- })+ await waitForExpect(async () => {+ const persons = await fetchPostgresPersons(infra.postgres, team.id)+ expect(persons.length).toBe(1)+ expect(persons[0].properties).toEqual(expect.objectContaining({ a: 1, b: 2, c: 3 }))+ })- // $unset a and c- await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, 'distinct_id1')- .withEvent('some_event')- .withProperties({ $unset: ['a', 'c'] })- .build(),- ])- )- await waitForKafkaMessages(_kafkaProducer)+ // $unset a and c+ await ingester.handleKafkaBatch(+ createKafkaMessages(+ [+ new EventBuilder(team, 'distinct_id1')+ .withEvent('some_event')+ .withProperties({ $unset: ['a', 'c'] })+ .build(),+ ],+ token+ )+ )+ await waitForKafkaMessages(kafkaProducer)- await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)- const unsetEvent = events.find((e) => e.event === 'some_event')- expect(unsetEvent).toBeDefined()- expect(unsetEvent!.properties['$unset']).toEqual(['a', 'c'])-- const persons = await fetchPostgresPersons(hub.postgres, team.id)- expect(persons.length).toBe(1)- expect(persons[0].properties).toEqual(expect.objectContaining({ b: 2 }))- expect(persons[0].properties).not.toHaveProperty('a')- expect(persons[0].properties).not.toHaveProperty('c')- })- })+ await waitForExpect(async () => {+ const events = await fetchEvents(clickhouse, team.id)+ const unsetEvent = events.find((e) => e.event === 'some_event')+ expect(unsetEvent).toBeDefined()+ expect(unsetEvent!.properties['$unset']).toEqual(['a', 'c'])++ const persons = await fetchPostgresPersons(infra.postgres, team.id)+ expect(persons.length).toBe(1)+ expect(persons[0].properties).toEqual(expect.objectContaining({ b: 2 }))+ expect(persons[0].properties).not.toHaveProperty('a')+ expect(persons[0].properties).not.toHaveProperty('c')+ })+ }+ )testWithTeamIngester('$set and $set_once apply correctly across sequential events',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {// key encodes when the value is updated, e.g. s0 means only set call for the 0th event// s03o23 means via a set in events 0 and 3 plus via set_once on 2nd and 3rd eventconst set0 = { s0123o0123: 's0a', s02o13: 's0b', s013: 's0e' }@@ -3810,18 +3650,21 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:[set3, setOnce3],]) {await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('some_event')- .withProperties({ $set: set, $set_once: setOnce })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('some_event')+ .withProperties({ $set: set, $set_once: setOnce })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)}await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)// $set wins: last write for each key@@ -3844,7 +3687,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('Should not share cached person data between batches',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, kafkaProducer, token }) => {const distinctId = 'user-across-batches'// First batch: Create a person with initial properties@@ -3857,12 +3700,12 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(batch1Events))- await waitForKafkaMessages(_kafkaProducer)+ await ingester.handleKafkaBatch(createKafkaMessages(batch1Events, token))+ await waitForKafkaMessages(kafkaProducer)// Verify batch 1 wrote correctlyawait waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)expect(persons[0].properties).toMatchObject({batch1_prop: 'value1',@@ -3881,12 +3724,12 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(batch2Events))- await waitForKafkaMessages(_kafkaProducer)+ await ingester.handleKafkaBatch(createKafkaMessages(batch2Events, token))+ await waitForKafkaMessages(kafkaProducer)// Verify batch 2 wrote correctly and merged with existing propertiesawait waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)// Should have properties from both batches, with batch2 overwriting shared_propexpect(persons[0].properties).toMatchObject({@@ -3906,11 +3749,11 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:.build(),]- await ingester.handleKafkaBatch(createKafkaMessages(batch3Events))- await waitForKafkaMessages(_kafkaProducer)+ await ingester.handleKafkaBatch(createKafkaMessages(batch3Events, token))+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const persons = await fetchPostgresPersons(hub.postgres, team.id)+ const persons = await fetchPostgresPersons(infra.postgres, team.id)expect(persons.length).toBe(1)// Should have properties from all three batchesexpect(persons[0].properties).toMatchObject({@@ -3926,26 +3769,29 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('ASSERT_VERSION mode should correctly apply properties_to_set when updating person',{ pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, token }) => {const distinctId = new UUIDT().toString()const timestamp = DateTime.now().toMillis()// First event: Create a person with initial propertiesawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set: { initial_prop: 'initial_value' },- })- .withTimestamp(timestamp)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set: { initial_prop: 'initial_value' },+ })+ .withTimestamp(timestamp)+ .build(),+ ],+ token+ ))// Wait for person to be createdawait waitForExpect(async () => {- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()expect(person!.properties).toEqual(expect.objectContaining({@@ -3957,22 +3803,25 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// Second event: Update the person with new properties via $identify// This is where the bug manifests - properties_to_set is not applied in ASSERT_VERSION modeawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set: { email: '[email protected]', name: 'Test User' },- })- .withTimestamp(timestamp + 1)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set: { email: '[email protected]', name: 'Test User' },+ })+ .withTimestamp(timestamp + 1)+ .build(),+ ],+ token+ ))// Verify the properties were updated in the database// BUG: With ASSERT_VERSION mode, properties_to_set is not merged into properties// before writing to database, so only the original properties are writtenawait waitForExpect(async () => {- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()// This assertion will FAIL with the bug - email and name won't be setexpect(person!.properties).toEqual(@@ -3986,7 +3835,7 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// Also verify the event has the correct person properties attachedawait waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toEqual(2)// The second event should have accumulated propertiesexpect(events[1].person_properties).toEqual(@@ -4003,25 +3852,28 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('ASSERT_VERSION mode should correctly apply $set_once for new properties',{ pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, token }) => {const distinctId = new UUIDT().toString()const timestamp = DateTime.now().toMillis()// First event: Create a personawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set: { name: 'Test User' },- })- .withTimestamp(timestamp)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set: { name: 'Test User' },+ })+ .withTimestamp(timestamp)+ .build(),+ ],+ token+ ))await waitForExpect(async () => {- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()expect(person!.properties).toEqual(expect.objectContaining({@@ -4032,20 +3884,23 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// Second event: Use $set_once for a new propertyawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set_once: { first_seen: '2024-01-01' },- })- .withTimestamp(timestamp + 1)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set_once: { first_seen: '2024-01-01' },+ })+ .withTimestamp(timestamp + 1)+ .build(),+ ],+ token+ ))// Verify the $set_once property was addedawait waitForExpect(async () => {- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()expect(person!.properties).toEqual(expect.objectContaining({@@ -4060,25 +3915,28 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('ASSERT_VERSION mode should preserve $set_once semantics across multiple events',{ pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, token }) => {const distinctId = new UUIDT().toString()const timestamp = DateTime.now().toMillis()// First event: Create person with $set_once for prop1await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set_once: { prop1: 'first_value' },- })- .withTimestamp(timestamp)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set_once: { prop1: 'first_value' },+ })+ .withTimestamp(timestamp)+ .build(),+ ],+ token+ ))await waitForExpect(async () => {- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()expect(person!.properties).toEqual(expect.objectContaining({@@ -4089,20 +3947,23 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// Second event: Try to $set_once prop1 again (should NOT overwrite) and add prop2await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set_once: { prop1: 'second_value_should_be_ignored', prop2: 'new_property' },- })- .withTimestamp(timestamp + 1)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set_once: { prop1: 'second_value_should_be_ignored', prop2: 'new_property' },+ })+ .withTimestamp(timestamp + 1)+ .build(),+ ],+ token+ ))// Verify prop1 retains first value, prop2 is addedawait waitForExpect(async () => {- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()expect(person!.properties).toEqual(expect.objectContaining({@@ -4114,20 +3975,23 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// Third event: Another $set_once with prop1 (still should not change) and prop3await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set_once: { prop1: 'third_value_also_ignored', prop3: 'another_new' },- })- .withTimestamp(timestamp + 2)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set_once: { prop1: 'third_value_also_ignored', prop3: 'another_new' },+ })+ .withTimestamp(timestamp + 2)+ .build(),+ ],+ token+ ))// Final verificationawait waitForExpect(async () => {- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()expect(person!.properties).toEqual(expect.objectContaining({@@ -4143,25 +4007,32 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('ASSERT_VERSION mode should correctly apply $unset operations',{ pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, token }) => {const distinctId = new UUIDT().toString()const timestamp = DateTime.now().toMillis()// First event: Create a person with propertiesawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set: { name: 'Test User', email: '[email protected]', to_remove: 'will be removed' },- })- .withTimestamp(timestamp)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set: {+ name: 'Test User',+ email: '[email protected]',+ to_remove: 'will be removed',+ },+ })+ .withTimestamp(timestamp)+ .build(),+ ],+ token+ ))await waitForExpect(async () => {- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()expect(person!.properties).toEqual(expect.objectContaining({@@ -4174,20 +4045,23 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// Second event: Unset a propertyawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $unset: ['to_remove'],- })- .withTimestamp(timestamp + 1)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $unset: ['to_remove'],+ })+ .withTimestamp(timestamp + 1)+ .build(),+ ],+ token+ ))// Verify the property was removedawait waitForExpect(async () => {- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()expect(person!.properties).toEqual(expect.objectContaining({@@ -4203,26 +4077,29 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('ASSERT_VERSION mode should correctly apply properties after person merge',{ pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, token }) => {const anonDistinctId = new UUIDT().toString()const identifiedDistinctId = new UUIDT().toString()const timestamp = DateTime.now().toMillis()// First event: Create anonymous person with propertiesawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, anonDistinctId)- .withEvent('pageview')- .withProperties({- $set: { anon_prop: 'anon_value' },- })- .withTimestamp(timestamp)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, anonDistinctId)+ .withEvent('pageview')+ .withProperties({+ $set: { anon_prop: 'anon_value' },+ })+ .withTimestamp(timestamp)+ .build(),+ ],+ token+ ))await waitForExpect(async () => {- const person = await hub.personRepository.fetchPerson(team.id, anonDistinctId)+ const person = await infra.personRepository.fetchPerson(team.id, anonDistinctId)expect(person).toBeDefined()expect(person!.properties).toEqual(expect.objectContaining({@@ -4233,21 +4110,24 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// Second event: Identify with merge and set new propertiesawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, identifiedDistinctId)- .withEvent('$identify')- .withProperties({- $anon_distinct_id: anonDistinctId,- $set: { email: '[email protected]', name: 'Identified User' },- })- .withTimestamp(timestamp + 1)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, identifiedDistinctId)+ .withEvent('$identify')+ .withProperties({+ $anon_distinct_id: anonDistinctId,+ $set: { email: '[email protected]', name: 'Identified User' },+ })+ .withTimestamp(timestamp + 1)+ .build(),+ ],+ token+ ))// Verify merged person has all propertiesawait waitForExpect(async () => {- const person = await hub.personRepository.fetchPerson(team.id, identifiedDistinctId)+ const person = await infra.personRepository.fetchPerson(team.id, identifiedDistinctId)expect(person).toBeDefined()expect(person!.properties).toEqual(expect.objectContaining({@@ -4263,58 +4143,64 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('ASSERT_VERSION mode should correctly apply properties from multiple events in same batch',{ pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, token }) => {const distinctId = new UUIDT().toString()const timestamp = DateTime.now().toMillis()// First: Create personawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set: { initial: 'value' },- })- .withTimestamp(timestamp)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set: { initial: 'value' },+ })+ .withTimestamp(timestamp)+ .build(),+ ],+ token+ ))await waitForExpect(async () => {- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()})// Send multiple events in same batch that each set different propertiesawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set: { prop1: 'value1' },- })- .withTimestamp(timestamp + 1)- .build(),- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set: { prop2: 'value2' },- })- .withTimestamp(timestamp + 2)- .build(),- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set: { prop3: 'value3' },- })- .withTimestamp(timestamp + 3)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set: { prop1: 'value1' },+ })+ .withTimestamp(timestamp + 1)+ .build(),+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set: { prop2: 'value2' },+ })+ .withTimestamp(timestamp + 2)+ .build(),+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set: { prop3: 'value3' },+ })+ .withTimestamp(timestamp + 3)+ .build(),+ ],+ token+ ))// Verify all properties from the batch were appliedawait waitForExpect(async () => {- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()expect(person!.properties).toEqual(expect.objectContaining({@@ -4331,25 +4217,28 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('ASSERT_VERSION mode should handle combined $set and $unset in same event',{ pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, token }) => {const distinctId = new UUIDT().toString()const timestamp = DateTime.now().toMillis()// First event: Create a person with propertiesawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set: { keep_prop: 'keep', remove_prop: 'remove' },- })- .withTimestamp(timestamp)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set: { keep_prop: 'keep', remove_prop: 'remove' },+ })+ .withTimestamp(timestamp)+ .build(),+ ],+ token+ ))await waitForExpect(async () => {- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()expect(person!.properties).toEqual(expect.objectContaining({@@ -4361,21 +4250,24 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// Second event: Set new property AND unset existing property in same eventawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set: { new_prop: 'new_value' },- $unset: ['remove_prop'],- })- .withTimestamp(timestamp + 1)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set: { new_prop: 'new_value' },+ $unset: ['remove_prop'],+ })+ .withTimestamp(timestamp + 1)+ .build(),+ ],+ token+ ))// Verify the new property was added and the old one was removedawait waitForExpect(async () => {- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()expect(person!.properties).toEqual(expect.objectContaining({@@ -4391,25 +4283,28 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('ASSERT_VERSION mode should handle $unset overlaps within a batch',{ pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, token }) => {const distinctId = new UUIDT().toString()const timestamp = DateTime.now().toMillis()// First: Create person with multiple propertiesawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set: { prop1: 'value1', prop2: 'value2', prop3: 'value3', prop4: 'value4' },- })- .withTimestamp(timestamp)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set: { prop1: 'value1', prop2: 'value2', prop3: 'value3', prop4: 'value4' },+ })+ .withTimestamp(timestamp)+ .build(),+ ],+ token+ ))await waitForExpect(async () => {- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()expect(person!.properties).toEqual(expect.objectContaining({@@ -4423,38 +4318,41 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:// Send batch with overlapping $unset operationsawait ingester.handleKafkaBatch(- createKafkaMessages([- // First event unsets prop1 and prop2- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $unset: ['prop1', 'prop2'],- })- .withTimestamp(timestamp + 1)- .build(),- // Second event also tries to unset prop2 (overlap) and unsets prop3- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $unset: ['prop2', 'prop3'],- })- .withTimestamp(timestamp + 2)- .build(),- // Third event sets a new property and unsets prop2 again (already unset)- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set: { new_prop: 'new_value' },- $unset: ['prop2'],- })- .withTimestamp(timestamp + 3)- .build(),- ])+ createKafkaMessages(+ [+ // First event unsets prop1 and prop2+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $unset: ['prop1', 'prop2'],+ })+ .withTimestamp(timestamp + 1)+ .build(),+ // Second event also tries to unset prop2 (overlap) and unsets prop3+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $unset: ['prop2', 'prop3'],+ })+ .withTimestamp(timestamp + 2)+ .build(),+ // Third event sets a new property and unsets prop2 again (already unset)+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set: { new_prop: 'new_value' },+ $unset: ['prop2'],+ })+ .withTimestamp(timestamp + 3)+ .build(),+ ],+ token+ ))// Verify all unsets were applied correctly despite overlapsawait waitForExpect(async () => {- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()expect(person!.properties).toEqual(expect.objectContaining({@@ -4472,43 +4370,46 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('ASSERT_VERSION mode should preserve $set_once semantics within same batch',{ pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, token }) => {const distinctId = new UUIDT().toString()const timestamp = DateTime.now().toMillis()// Send all events in same batch - $set_once should only apply first valueawait ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set_once: { prop1: 'first_value', prop2: 'first_prop2' },- })- .withTimestamp(timestamp)- .build(),- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set_once: { prop1: 'second_value_ignored', prop3: 'first_prop3' },- })- .withTimestamp(timestamp + 1)- .build(),- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set_once: {- prop1: 'third_value_ignored',- prop2: 'second_prop2_ignored',- prop4: 'first_prop4',- },- })- .withTimestamp(timestamp + 2)- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set_once: { prop1: 'first_value', prop2: 'first_prop2' },+ })+ .withTimestamp(timestamp)+ .build(),+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set_once: { prop1: 'second_value_ignored', prop3: 'first_prop3' },+ })+ .withTimestamp(timestamp + 1)+ .build(),+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set_once: {+ prop1: 'third_value_ignored',+ prop2: 'second_prop2_ignored',+ prop4: 'first_prop4',+ },+ })+ .withTimestamp(timestamp + 2)+ .build(),+ ],+ token+ ))await waitForExpect(async () => {- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()expect(person!.properties).toEqual(expect.objectContaining({@@ -4525,44 +4426,47 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('ASSERT_VERSION mode should handle combined $set and $unset within same batch',{ pluginServerConfig: { PERSON_BATCH_WRITING_DB_WRITE_MODE: 'ASSERT_VERSION' } },- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, infra, team, token }) => {const distinctId = new UUIDT().toString()const timestamp = DateTime.now().toMillis()// All operations in same batch including person creationawait ingester.handleKafkaBatch(- createKafkaMessages([- // First event creates person with initial properties- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set: { prop1: 'value1', prop2: 'value2', prop3: 'value3' },- })- .withTimestamp(timestamp)- .build(),- // Second event sets new property and unsets prop1- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set: { prop4: 'value4' },- $unset: ['prop1'],- })- .withTimestamp(timestamp + 1)- .build(),- // Third event updates prop2 and unsets prop3- new EventBuilder(team, distinctId)- .withEvent('$identify')- .withProperties({- $set: { prop2: 'updated_value2' },- $unset: ['prop3'],- })- .withTimestamp(timestamp + 2)- .build(),- ])+ createKafkaMessages(+ [+ // First event creates person with initial properties+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set: { prop1: 'value1', prop2: 'value2', prop3: 'value3' },+ })+ .withTimestamp(timestamp)+ .build(),+ // Second event sets new property and unsets prop1+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set: { prop4: 'value4' },+ $unset: ['prop1'],+ })+ .withTimestamp(timestamp + 1)+ .build(),+ // Third event updates prop2 and unsets prop3+ new EventBuilder(team, distinctId)+ .withEvent('$identify')+ .withProperties({+ $set: { prop2: 'updated_value2' },+ $unset: ['prop3'],+ })+ .withTimestamp(timestamp + 2)+ .build(),+ ],+ token+ ))await waitForExpect(async () => {- const person = await hub.personRepository.fetchPerson(team.id, distinctId)+ const person = await infra.personRepository.fetchPerson(team.id, distinctId)expect(person).toBeDefined()expect(person!.properties).toEqual(expect.objectContaining({@@ -4579,20 +4483,23 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('should scrub IPs when team.anonymize_ips=true',{ teamOverrides: { anonymize_ips: true } },- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, kafkaProducer, token }) => {const distinctId = new UUIDT().toString()await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$pageview')- .withProperties({ $ip: '11.12.13.14' })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$pageview')+ .withProperties({ $ip: '11.12.13.14' })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toBe(1)expect(events[0].properties.$ip).toBeUndefined()})@@ -4602,20 +4509,23 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('should use $elements_chain string directly as elements_chain',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, kafkaProducer, token }) => {const distinctId = new UUIDT().toString()await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$autocapture')- .withProperties({ $elements_chain: 'button:nth-child="1"', a: 1 })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$autocapture')+ .withProperties({ $elements_chain: 'button:nth-child="1"', a: 1 })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toBe(1)expect(events[0].elements_chain).toBeDefined()expect(events[0].properties.$elements_chain).toBeUndefined()@@ -4627,23 +4537,26 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('should convert $elements array to elements_chain',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, kafkaProducer, token }) => {const distinctId = new UUIDT().toString()await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$autocapture')- .withProperties({- $elements: [{ tag_name: 'div', nth_child: 1, nth_of_type: 2, $el_text: 'text' }],- a: 1,- })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$autocapture')+ .withProperties({+ $elements: [{ tag_name: 'div', nth_child: 1, nth_of_type: 2, $el_text: 'text' }],+ a: 1,+ })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toBe(1)expect(events[0].elements_chain).toBeDefined()expect(events[0].properties.$elements).toBeUndefined()@@ -4655,23 +4568,26 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('should prefer $elements_chain over $elements when both are present',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, kafkaProducer, token }) => {const distinctId = new UUIDT().toString()await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$autocapture')- .withProperties({- $elements_chain: 'span:nth-child="1"',- $elements: [{ tag_name: 'div', nth_child: 1, nth_of_type: 2, $el_text: 'text' }],- })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$autocapture')+ .withProperties({+ $elements_chain: 'span:nth-child="1"',+ $elements: [{ tag_name: 'div', nth_child: 1, nth_of_type: 2, $el_text: 'text' }],+ })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toBe(1)// elements_chain is parsed back into element objects by parseRawClickHouseEvent// so we check the first element's tag_name to verify $elements_chain was used@@ -4685,23 +4601,28 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('should drop $$heatmap events when team.heatmaps_opt_in=false',{ teamOverrides: { heatmaps_opt_in: false } },- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, kafkaProducer, token }) => {const distinctId = new UUIDT().toString()await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$$heatmap')- .withProperties({- $heatmap_data: {- 'http://localhost:3000/': [{ x: 100, y: 200, target_fixed: false, type: 'click' }],- },- })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$$heatmap')+ .withProperties({+ $heatmap_data: {+ 'http://localhost:3000/': [+ { x: 100, y: 200, target_fixed: false, type: 'click' },+ ],+ },+ })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)- const events = await fetchEvents(hub, team.id)+ await waitForKafkaMessages(kafkaProducer)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toBe(0)})@@ -4709,43 +4630,46 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('should route $ai_generation events through AI subpipeline with full enrichment',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, kafkaProducer, token }) => {const distinctId = new UUIDT().toString()await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$ai_generation')- .withProperties({- $ai_model: 'gpt-4',- $ai_provider: 'openai',- $ai_input_tokens: 100,- $ai_output_tokens: 50,- $ai_trace_id: 12345,- $ai_parent_id: 67890,- $ai_model_parameters: {- temperature: 0.7,- stream: true,- max_tokens: 1024,- },- $ai_output_choices: JSON.stringify([- {- role: 'assistant',- message: {- tool_calls: [- { function: { name: 'get_weather' } },- { function: { name: 'search_docs' } },- ],- },+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$ai_generation')+ .withProperties({+ $ai_model: 'gpt-4',+ $ai_provider: 'openai',+ $ai_input_tokens: 100,+ $ai_output_tokens: 50,+ $ai_trace_id: 12345,+ $ai_parent_id: 67890,+ $ai_model_parameters: {+ temperature: 0.7,+ stream: true,+ max_tokens: 1024,},- ]),- })- .build(),- ])+ $ai_output_choices: JSON.stringify([+ {+ role: 'assistant',+ message: {+ tool_calls: [+ { function: { name: 'get_weather' } },+ { function: { name: 'search_docs' } },+ ],+ },+ },+ ]),+ })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toBe(1)const props = events[0].properties@@ -4778,24 +4702,27 @@ describe.each([{ PERSONS_PREFETCH_ENABLED: false }, { PERSONS_PREFETCH_ENABLED:testWithTeamIngester('should route $ai_trace events through AI subpipeline with trace normalization',{},- async (ingester, hub, team, _kafkaProducer) => {+ async ({ ingester, team, kafkaProducer, token }) => {const distinctId = new UUIDT().toString()await ingester.handleKafkaBatch(- createKafkaMessages([- new EventBuilder(team, distinctId)- .withEvent('$ai_trace')- .withProperties({- $ai_trace_id: 'trace-abc',- $ai_span_id: 99999,- $ai_session_id: true,- })- .build(),- ])+ createKafkaMessages(+ [+ new EventBuilder(team, distinctId)+ .withEvent('$ai_trace')+ .withProperties({+ $ai_trace_id: 'trace-abc',+ $ai_span_id: 99999,+ $ai_session_id: true,+ })+ .build(),+ ],+ token+ ))- await waitForKafkaMessages(_kafkaProducer)+ await waitForKafkaMessages(kafkaProducer)await waitForExpect(async () => {- const events = await fetchEvents(hub, team.id)+ const events = await fetchEvents(clickhouse, team.id)expect(events.length).toBe(1)const props = events[0].propertiesdiff --git a/nodejs/src/ingestion/ingestion-testing-consumer.test.ts b/nodejs/src/ingestion/ingestion-testing-consumer.test.tsindex cd85d436c026..45dae464c386 100644--- a/nodejs/src/ingestion/ingestion-testing-consumer.test.ts+++ b/nodejs/src/ingestion/ingestion-testing-consumer.test.ts@@ -260,25 +260,6 @@ describe('IngestionTestingConsumer', () => {})})- describe('client ingestion warnings', () => {- it('should process client ingestion warning events', async () => {- const events = [- createEvent({- event: '$$client_ingestion_warning',- properties: {- $$client_ingestion_warning_message: 'test warning',- },- }),- ]- await ingester.handleKafkaBatch(createKafkaMessages(events))-- const allMessages = mockProducerObserver.getProducedKafkaMessages()- // Client ingestion warnings produce to the ingestion_warnings topic- const warningMessages = allMessages.filter((m) => m.topic === 'clickhouse_ingestion_warnings_test')- expect(warningMessages).toHaveLength(1)- })- })-describe('heatmap subpipeline', () => {it('should produce heatmap events to the heatmaps topic', async () => {const events = [@@ -404,11 +385,6 @@ describe('IngestionTestingConsumer', () => {$ai_output: 'world',},}),- createEvent({- event: '$$client_ingestion_warning',- distinct_id: 'user-4',- properties: { $$client_ingestion_warning_message: 'warning' },- }),]await ingester.handleKafkaBatch(createKafkaMessages(events))@@ -422,10 +398,6 @@ describe('IngestionTestingConsumer', () => {const heatmapMessages = allMessages.filter((m) => m.topic === 'clickhouse_heatmap_events_test')expect(heatmapMessages).toHaveLength(1)- // Client ingestion warning → clickhouse_ingestion_warnings- const warningMessages = allMessages.filter((m) => m.topic === 'clickhouse_ingestion_warnings_test')- expect(warningMessages).toHaveLength(1)-// No person messages from any subpipelineconst personMessages = allMessages.filter((m) => m.topic === 'clickhouse_person_test' || m.topic === 'clickhouse_person_distinct_id2_test'diff --git a/nodejs/src/ingestion/outputs/ingestion-outputs.ts b/nodejs/src/ingestion/outputs/ingestion-outputs.tsindex b285fe313912..30f9978836ec 100644--- a/nodejs/src/ingestion/outputs/ingestion-outputs.ts+++ b/nodejs/src/ingestion/outputs/ingestion-outputs.ts@@ -65,3 +65,23 @@ export class IngestionOutputs<O extends string> {return failures}}++/**+ * Scope owner for an `IngestionOutputs` derived from already-running+ * infrastructure (typically a shared Kafka producer registry). `start()`+ * resolves the outputs via the `build` callback and verifies that every+ * output's topic is reachable; `stop()` is a no-op because the producer+ * registry's own component owns the connection lifetimes.+ */+export class IngestionOutputsComponent<O extends string> {+ constructor(private readonly build: () => IngestionOutputs<O>) {}++ async start(): Promise<{ value: IngestionOutputs<O>; stop: () => Promise<void> }> {+ const outputs = this.build()+ const failures = await outputs.checkTopics()+ if (failures.length > 0) {+ throw new Error(`Output topic verification failed for: ${failures.join(', ')}`)+ }+ return { value: outputs, stop: () => Promise.resolve() }+ }+}diff --git a/nodejs/src/ingestion/pipelines/batching-pipeline.test.ts b/nodejs/src/ingestion/pipelines/batching-pipeline.test.tsindex 828ee1be54b2..35d758a49da5 100644--- a/nodejs/src/ingestion/pipelines/batching-pipeline.test.ts+++ b/nodejs/src/ingestion/pipelines/batching-pipeline.test.ts@@ -255,10 +255,7 @@ describe('BatchingPipeline', () => {)),(builder) => builder,- (builder) =>- builder.pipe((input) =>- Promise.resolve(ok({ elements: input.elements, batchContext: input.batchContext }))- ),+ (builder) => builder.pipe((input) => Promise.resolve(ok(input))),{ concurrentBatches: Infinity })@@ -291,7 +288,7 @@ describe('BatchingPipeline', () => {(builder) =>builder.pipe((input) => {capturedAfter.push(input.batchContext)- return Promise.resolve(ok({ elements: input.elements, batchContext: input.batchContext }))+ return Promise.resolve(ok(input))}),{ concurrentBatches: Infinity })diff --git a/nodejs/src/ingestion/pipelines/batching-pipeline.ts b/nodejs/src/ingestion/pipelines/batching-pipeline.tsindex 3ece1b8fed0a..51faf0f72419 100644--- a/nodejs/src/ingestion/pipelines/batching-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/batching-pipeline.ts@@ -27,10 +27,16 @@ export interface AfterBatchInput<TOutput, COutput, CBatch, R extends string = nebatchId: number}-export interface AfterBatchOutput<TOutput, COutput, CBatch, R extends string = never> {- elements: BatchPipelineResultWithContext<TOutput, COutput, R>- batchContext: CBatch-}+/**+ * What an afterBatch pipeline produces. Structurally the same as+ * `AfterBatchInput` — extending it means a passthrough step (one that+ * returns its input untouched) satisfies the afterBatch contract without+ * needing an explicit Input→Output transformer in front. The runtime+ * downstream of `afterPipeline.process(...)` only reads `elements`, so+ * carrying `batchId` through is harmless.+ */+export interface AfterBatchOutput<TOutput, COutput, CBatch, R extends string = never>+ extends AfterBatchInput<TOutput, COutput, CBatch, R> {}export type BeforeBatchStep<TInput, CInput, CBatch> = (input: BeforeBatchInput<TInput, CInput>diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex 442871b3bbac..67c2d57b31de 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -32,7 +32,7 @@ import {getDefaultKafkaProducerEnvConfig,getDefaultKafkaWarpstreamProducerEnvConfig,} from '../ingestion/common/config'-import { EventFilterManager } from '../ingestion/common/event-filters'+import { EventFilterManagerComponent } from '../ingestion/common/event-filters'import { ProducerName } from '../ingestion/common/outputs'import { createProducerRegistry } from '../ingestion/common/outputs/registry'import {@@ -58,7 +58,7 @@ import { RedisOverflowRepository } from '../ingestion/utils/overflow-redirect/ovimport { HealthCheckResultOk, PluginServerService, RedisPool } from '../types'import { PostgresRouter } from '../utils/db/postgres'import { createRedisPoolFromConfig } from '../utils/db/redis'-import { EventIngestionRestrictionManager } from '../utils/event-ingestion-restrictions'+import { EventIngestionRestrictionManagerComponent } from '../utils/event-ingestion-restrictions'import { EventSchemaEnforcementManager } from '../utils/event-schema-enforcement-manager'import { GeoIPService } from '../utils/geoip'import { logger } from '../utils/logger'@@ -290,13 +290,15 @@ export class IngestionApiServer implements NodeServer {})}- const eventIngestionRestrictionManager = new EventIngestionRestrictionManager(this.redisPool, {- pipeline: 'analytics',- staticDropEventTokens: this.config.DROP_EVENTS_BY_TOKEN_DISTINCT_ID.split(',').filter(Boolean),- staticSkipPersonTokens: this.config.SKIP_PERSONS_PROCESSING_BY_TOKEN_DISTINCT_ID.split(',').filter(Boolean),- staticForceOverflowTokens:- this.config.INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID.split(',').filter(Boolean),- })+ const { value: eventIngestionRestrictionManager, stop: stopEventIngestionRestrictionManager } =+ await new EventIngestionRestrictionManagerComponent(this.redisPool, {+ pipeline: 'analytics',+ staticDropEventTokens: this.config.DROP_EVENTS_BY_TOKEN_DISTINCT_ID.split(',').filter(Boolean),+ staticSkipPersonTokens:+ this.config.SKIP_PERSONS_PROCESSING_BY_TOKEN_DISTINCT_ID.split(',').filter(Boolean),+ staticForceOverflowTokens:+ this.config.INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID.split(',').filter(Boolean),+ }).start()const personsStore: PersonsStore = new BatchWritingPersonsStore(personRepository, ingestionOutputs, {dbWriteMode: this.config.PERSON_BATCH_WRITING_DB_WRITE_MODE,@@ -347,11 +349,12 @@ export class IngestionApiServer implements NodeServer {},concurrentBatches: this.config.INGESTION_WORKER_CONCURRENT_BATCHES,}+ const eventFilterManagerStarted = await new EventFilterManagerComponent(this.postgres).start()const joinedPipelineDeps: JoinedIngestionPipelineDeps = {personsStore,groupStore,hogTransformer: this.hogTransformer,- eventFilterManager: new EventFilterManager(this.postgres),+ eventFilterManager: eventFilterManagerStarted.value,eventIngestionRestrictionManager,eventSchemaEnforcementManager: new EventSchemaEnforcementManager(this.postgres),promiseScheduler: this.promiseScheduler,@@ -374,6 +377,8 @@ export class IngestionApiServer implements NodeServer {onShutdown: async () => {await this.topHog.stop()await this.hogTransformer.stop()+ await eventFilterManagerStarted.stop()+ await stopEventIngestionRestrictionManager()},healthcheck: () => this.isHealthy(),}diff --git a/nodejs/src/servers/ingestion-general-server.ts b/nodejs/src/servers/ingestion-general-server.tsindex 704c20a3000f..35ab4adcdc5d 100644--- a/nodejs/src/servers/ingestion-general-server.ts+++ b/nodejs/src/servers/ingestion-general-server.ts@@ -16,6 +16,7 @@ import {} from '../config/kafka-topics'import { createCookielessRedisConnectionConfig, createIngestionRedisConnectionConfig } from '../config/redis-pools'import { createOutputsRegistry } from '../ingestion/analytics/outputs/registry'+import { createClientWarningsConsumer } from '../ingestion/clientwarnings'import {KafkaIngestionProducerEnvConfig,KafkaProducerEnvConfig,@@ -24,8 +25,9 @@ import {getDefaultKafkaProducerEnvConfig,getDefaultKafkaWarpstreamProducerEnvConfig,} from '../ingestion/common/config'-import { ProducerName } from '../ingestion/common/outputs'-import { createProducerRegistry } from '../ingestion/common/outputs/registry'+import { ingestionConsumerService } from '../ingestion/common/ingestion-consumer'+import { KafkaProducerRegistryComponent } from '../ingestion/common/outputs/registry'+import { extend, newScope } from '../ingestion/common/scopes'import {DatabaseConnectionConfig,IngestionConsumerConfig,@@ -39,17 +41,16 @@ import {import { CookielessManager } from '../ingestion/cookieless/cookieless-manager'import { IngestionConsumer, IngestionConsumerDeps } from '../ingestion/ingestion-consumer'import { IngestionTestingConsumer } from '../ingestion/ingestion-testing-consumer'-import { KafkaProducerRegistry } from '../ingestion/outputs/kafka-producer-registry'import { buildGroupRepository, buildPersonRepository, createPersonHogClient } from '../ingestion/personhog'import { KafkaProducerWrapper } from '../kafka/producer'import { PluginServerService, RedisPool } from '../types'import { ServerCommands } from '../utils/commands'-import { PostgresRouter } from '../utils/db/postgres'-import { createRedisPoolFromConfig } from '../utils/db/redis'+import { PostgresRouter, PostgresRouterComponent } from '../utils/db/postgres'+import { RedisPoolComponent, createRedisPoolFromConfig } from '../utils/db/redis'import { GeoIPService } from '../utils/geoip'import { logger } from '../utils/logger'import { PubSub } from '../utils/pubsub'-import { TeamManager } from '../utils/team-manager'+import { TeamManagerComponent } from '../utils/team-manager'import { GroupTypeManager } from '../worker/ingestion/group-type-manager'import { ClickhouseGroupRepository } from '../worker/ingestion/groups/repositories/clickhouse-group-repository'import { PostgresGroupRepository } from '../worker/ingestion/groups/repositories/postgres-group-repository'@@ -101,11 +102,11 @@ export class IngestionGeneralServer implements NodeServer {private config: IngestionGeneralServerConfigprivate postgres?: PostgresRouter- private ingestionProducerRegistry?: KafkaProducerRegistry<ProducerName>private redisPool?: RedisPoolprivate cookielessRedisPool?: RedisPoolprivate cookielessManager?: CookielessManagerprivate pubsub?: PubSub+ private stopSharedServices?: () => Promise<void>constructor(config: Partial<IngestionGeneralServerConfig> = {}) {this.config = {@@ -133,30 +134,53 @@ export class IngestionGeneralServer implements NodeServer {private async startServices(): Promise<void> {initializePrometheusLabels(this.config.INGESTION_PIPELINE, this.config.INGESTION_LANE)- // 1. Shared infrastructure+ // 1. Shared infrastructure — postgres + redis lifetimes are owned+ // by a server-level Scope so consumers can extend off it via+ // `Scope.extend` to get them as handles without taking+ // ownership.logger.info('ℹ️', 'Connecting to shared infrastructure...')- this.postgres = new PostgresRouter(this.config, this.config.PLUGIN_SERVER_MODE!)- logger.info('👍', 'Postgres Router ready')+ const sharedInfraScope = newScope('shared-infra', (builder) =>+ builder+ .add('postgres', new PostgresRouterComponent(this.config, this.config.PLUGIN_SERVER_MODE!))+ .add(+ 'redisPool',+ new RedisPoolComponent({+ connection: createIngestionRedisConnectionConfig(this.config),+ poolMinSize: this.config.REDIS_POOL_MIN_SIZE,+ poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,+ })+ )+ .add('producerRegistry', new KafkaProducerRegistryComponent(this.config.KAFKA_CLIENT_RACK, this.config))+ )- logger.info('🤔', 'Connecting to ingestion Redis...')- this.redisPool = createRedisPoolFromConfig({- connection: createIngestionRedisConnectionConfig(this.config),- poolMinSize: this.config.REDIS_POOL_MIN_SIZE,- poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,- })+ // `teamManager` is built inside the extension via its component so+ // it picks up `postgres` from the started infra scope's container+ // and is owned by that scope. The server extracts it from the+ // started container to pass on to CDP services etc.+ const sharedServicesScope = extend(sharedInfraScope, 'shared', (container, builder) =>+ builder.add(+ 'teamManager',+ // Retry transient team-load failures (e.g. a Postgres pooler scale-down returning+ // ECONNREFUSED). The team loader runs detached in the LazyLoader buffer, so an un-retried+ // transient failure can surface as an unhandled rejection and restart the worker.+ new TeamManagerComponent(container.postgres, {+ loaderRetry: { retryIntervalMs: 250, retryJitterMs: 250, maxElapsedMs: 5000 },+ })+ )+ )++ const sharedServices = await sharedServicesScope.start()+ this.postgres = sharedServices.container.postgres+ this.redisPool = sharedServices.container.redisPool+ const teamManager = sharedServices.container.teamManager+ this.stopSharedServices = sharedServices.stop+ logger.info('👍', 'Postgres Router ready')logger.info('👍', 'Ingestion Redis ready')this.pubsub = new PubSub(this.redisPool)await this.pubsub.start()- // Retry transient team-load failures (e.g. a Postgres pooler scale-down returning- // ECONNREFUSED). The team loader runs detached in the LazyLoader buffer, so an un-retried- // transient failure can surface as an unhandled rejection and restart the worker.- const teamManager = new TeamManager(this.postgres, {- loaderRetry: { retryIntervalMs: 250, retryJitterMs: 250, maxElapsedMs: 5000 },- })-// 2. Ingestion + CDP shared services (geoip, repos, encryption)const geoipService = new GeoIPService(this.config.MMDB_FILE_LOCATION)await geoipService.get()@@ -219,13 +243,12 @@ export class IngestionGeneralServer implements NodeServer {return consumer.service})} else {- // Build producer registry — producer creation blocks until the broker- // is reachable (rdkafka retries indefinitely), so the server will hang- // here if a broker is down and the pod never becomes healthy.- this.ingestionProducerRegistry = await createProducerRegistry(this.config.KAFKA_CLIENT_RACK).build(- this.config- )- const ingestionOutputs = createOutputsRegistry().build(this.ingestionProducerRegistry, this.config)+ // Producer registry is owned by `sharedInfraScope`; the+ // server reads it back from the started services. Outputs is+ // a typed view over it — built once here for analytics, and+ // separately by each consumer factory as needed.+ const ingestionProducerRegistry = sharedServices.container.producerRegistry+ const ingestionOutputs = createOutputsRegistry().build(ingestionProducerRegistry, this.config)const clickhouseGroupRepository = new ClickhouseGroupRepository(ingestionOutputs)const hogTransformerDeps: HogTransformerServiceDeps = {@@ -251,13 +274,27 @@ export class IngestionGeneralServer implements NodeServer {hogTransformer: createHogTransformerService(this.config, hogTransformerDeps),}+ const startClientWarnings = (override?: { topic: string; groupId: string }) => {+ serviceLoaders.push(async () => {+ const consumerConfig = override+ ? {+ ...this.config,+ INGESTION_CONSUMER_CONSUME_TOPIC: override.topic,+ INGESTION_CONSUMER_GROUP_ID: override.groupId,+ }+ : this.config+ const consumerScope = createClientWarningsConsumer(consumerConfig, sharedServicesScope)+ const { consumer, stop } = await consumerScope.start()+ return ingestionConsumerService(consumer, stop)+ })+ }+if (isCombinedMode) {// Local dev / hobby: run multiple consumers for all ingestion topics in one processconst consumersOptions = [{ topic: KAFKA_EVENTS_PLUGIN_INGESTION, group_id: 'clickhouse-ingestion' },{ topic: KAFKA_EVENTS_PLUGIN_INGESTION_HISTORICAL, group_id: 'clickhouse-ingestion-historical' },{ topic: KAFKA_EVENTS_PLUGIN_INGESTION_OVERFLOW, group_id: 'clickhouse-ingestion-overflow' },- { topic: 'client_iwarnings_ingestion', group_id: 'client_iwarnings_ingestion' },{ topic: 'heatmaps_ingestion', group_id: 'heatmaps_ingestion' },]@@ -271,6 +308,13 @@ export class IngestionGeneralServer implements NodeServer {return consumer.service})}++ startClientWarnings({+ topic: 'ingestion-clientwarnings-main-1',+ groupId: 'ingestion-clientwarnings-main',+ })+ } else if (this.config.INGESTION_PIPELINE === 'clientwarnings') {+ startClientWarnings()} else {// Production ingestion-v2: single consumer using config-provided topicserviceLoaders.push(async () => {@@ -295,12 +339,16 @@ export class IngestionGeneralServer implements NodeServer {private getCleanupResources(): CleanupResources {return {kafkaProducers: [],- redisPools: [this.redisPool, this.cookielessRedisPool].filter(Boolean) as RedisPool[],- postgres: this.postgres,+ // `redisPool` and `postgres` are owned by `sharedInfraScope` and+ // get torn down by `stopSharedServices()` below. Only+ // cookielessRedisPool stays here — it's not on the scope.+ redisPools: [this.cookielessRedisPool].filter(Boolean) as RedisPool[],pubsub: this.pubsub,additionalCleanup: async () => {- await this.ingestionProducerRegistry?.disconnectAll()this.cookielessManager?.shutdown()+ if (this.stopSharedServices) {+ await this.stopSharedServices()+ }},}}diff --git a/nodejs/src/session-recording/consumer.ts b/nodejs/src/session-recording/consumer.tsindex 18255f3b0119..3b946b3b913f 100644--- a/nodejs/src/session-recording/consumer.ts+++ b/nodejs/src/session-recording/consumer.ts@@ -33,7 +33,10 @@ import { TeamService } from '../session-replay/shared/teams/team-service'import { KeyStore, RecordingEncryptor } from '../session-replay/shared/types'import { HealthCheckResult, PluginServerService, RedisPool, ValueMatcher } from '../types'import { PostgresRouter } from '../utils/db/postgres'-import { EventIngestionRestrictionManager } from '../utils/event-ingestion-restrictions'+import {+ EventIngestionRestrictionManager,+ EventIngestionRestrictionManagerComponent,+} from '../utils/event-ingestion-restrictions'import { logger } from '../utils/logger'import { captureException } from '../utils/posthog'import { PromiseScheduler } from '../utils/promise-scheduler'@@ -76,13 +79,24 @@ export class SessionRecordingIngester {private readonly restrictionRedisPool: RedisPoolprivate readonly teamService: TeamServiceprivate readonly fileStorage: SessionBatchFileStorage- private readonly eventIngestionRestrictionManager: EventIngestionRestrictionManager- private readonly sessionReplayPipeline: BatchPipelineUnwrapper<+ private readonly eventIngestionRestrictionManagerComponent: EventIngestionRestrictionManagerComponent+ private eventIngestionRestrictionManager!: EventIngestionRestrictionManager+ private stopEventIngestionRestrictionManager?: () => Promise<void>+ private sessionReplayPipeline!: BatchPipelineUnwrapper<SessionReplayPipelineInput,SessionReplayPipelineOutput,{ message: Message },OverflowOutput>+ private readonly outputs: IngestionOutputs<+ | IngestionWarningsOutput+ | DlqOutput+ | OverflowOutput+ | TophogOutput+ | LogEntriesOutput+ | ReplayEventsOutput+ | SessionFeaturesOutput+ >private readonly topHog: TopHogprivate readonly keyStore: KeyStoreprivate readonly encryptor: RecordingEncryptor@@ -118,6 +132,7 @@ export class SessionRecordingIngester {this.redisPool = redisPoolthis.restrictionRedisPool = restrictionRedisPool+ this.outputs = outputslet s3Client: S3Client | null = nullif (@@ -150,9 +165,10 @@ export class SessionRecordingIngester {this.teamService = new TeamService(postgres)- this.eventIngestionRestrictionManager = new EventIngestionRestrictionManager(this.restrictionRedisPool, {- pipeline: 'session_recordings',- })+ this.eventIngestionRestrictionManagerComponent = new EventIngestionRestrictionManagerComponent(+ this.restrictionRedisPool,+ { pipeline: 'session_recordings' }+ )const retentionService = new RetentionService(this.redisPool, this.teamService)@@ -207,17 +223,6 @@ export class SessionRecordingIngester {keyStore: this.keyStore,encryptor: this.encryptor,})-- this.sessionReplayPipeline = createSessionReplayPipeline({- outputs,- eventIngestionRestrictionManager: this.eventIngestionRestrictionManager,- overflowEnabled: this.overflowEnabled(),- promiseScheduler: this.promiseScheduler,- teamService: this.teamService,- topHog: this.topHog,- sessionBatchManager: this.sessionBatchManager,- isDebugLoggingEnabled: this.isDebugLoggingEnabled,- })}public get service(): PluginServerService {@@ -280,6 +285,20 @@ export class SessionRecordingIngester {await this.keyStore.start()await this.encryptor.start()+ const started = await this.eventIngestionRestrictionManagerComponent.start()+ this.eventIngestionRestrictionManager = started.value+ this.stopEventIngestionRestrictionManager = started.stop++ this.sessionReplayPipeline = createSessionReplayPipeline({+ outputs: this.outputs,+ eventIngestionRestrictionManager: this.eventIngestionRestrictionManager,+ overflowEnabled: this.overflowEnabled(),+ promiseScheduler: this.promiseScheduler,+ teamService: this.teamService,+ topHog: this.topHog,+ sessionBatchManager: this.sessionBatchManager,+ isDebugLoggingEnabled: this.isDebugLoggingEnabled,+ })// Check that the storage backend is healthy before starting the consumer// This is especially important in local dev with minio@@ -337,6 +356,7 @@ export class SessionRecordingIngester {const promiseResults = await this.promiseScheduler.waitForAllSettled()this.keyStore.stop()+ await this.stopEventIngestionRestrictionManager?.()// Note: Kafka producers and Redis pools are owned by the server (IngestionSessionReplayServer),// not by the ingester. The server handles their lifecycle in getCleanupResources().diff --git a/nodejs/src/utils/db/postgres.ts b/nodejs/src/utils/db/postgres.tsindex 3fb860d0fae3..4adab5a9d913 100644--- a/nodejs/src/utils/db/postgres.ts+++ b/nodejs/src/utils/db/postgres.ts@@ -230,6 +230,27 @@ export class PostgresRouter {}}+/**+ * Scope entry for a `PostgresRouter`. `start` constructs the router+ * (which opens connection pools eagerly), `stop` ends every pool. Register+ * this in a `Scope` so the router's lifetime is tied to the scope that+ * owns it.+ */+export class PostgresRouterComponent {+ constructor(+ private readonly config: PostgresRouterConfig,+ private readonly appName?: string+ ) {}++ start(): Promise<{ value: PostgresRouter; stop: () => Promise<void> }> {+ const router = new PostgresRouter(this.config, this.appName)+ return Promise.resolve({+ value: router,+ stop: () => router.end(),+ })+ }+}+function postgresQuery<R extends QueryResultRow = any, I extends any[] = any[]>(// Un-exported, use PostgresRouter to run PG queriesclient: Client | Pool | PoolClient,diff --git a/nodejs/src/utils/db/redis.ts b/nodejs/src/utils/db/redis.tsindex b61ebb28e3fd..1f45171ad240 100644--- a/nodejs/src/utils/db/redis.ts+++ b/nodejs/src/utils/db/redis.ts@@ -49,6 +49,26 @@ export function createRedisPoolFromConfig(config: RedisPoolConfig): RedisPool {)}+/**+ * Scope entry for a `RedisPool`. `start` creates the pool (which connects+ * to Redis eagerly via `autostart`), `stop` drains the pool then clears+ * it so all connections are released.+ */+export class RedisPoolComponent {+ constructor(private readonly config: RedisPoolConfig) {}++ start(): Promise<{ value: RedisPool; stop: () => Promise<void> }> {+ const pool = createRedisPoolFromConfig(this.config)+ return Promise.resolve({+ value: pool,+ stop: async (): Promise<void> => {+ await pool.drain()+ await pool.clear()+ },+ })+ }+}+/*** Sanitizes a Redis URL for safe logging by extracting only the host portion.* This prevents leaking credentials that may be embedded in the URL.diff --git a/nodejs/src/utils/event-ingestion-restrictions/index.ts b/nodejs/src/utils/event-ingestion-restrictions/index.tsindex 1a083a4d2f6d..7a68d006fdca 100644--- a/nodejs/src/utils/event-ingestion-restrictions/index.ts+++ b/nodejs/src/utils/event-ingestion-restrictions/index.ts@@ -1,6 +1,6 @@// Public API-export { EventIngestionRestrictionManager } from './manager'-export type { IngestionPipeline } from './manager'+export { EventIngestionRestrictionManager, EventIngestionRestrictionManagerComponent } from './manager'+export type { EventIngestionRestrictionManagerOptions, IngestionPipeline } from './manager'export { REDIS_KEY_PREFIX, RedisRestrictionType } from './redis-schema'export { RestrictionFilters, RestrictionMap, RestrictionType } from './rules'export type { EventContext, RestrictionRule, RestrictionScope } from './rules'diff --git a/nodejs/src/utils/event-ingestion-restrictions/manager.test.ts b/nodejs/src/utils/event-ingestion-restrictions/manager.test.tsindex 07076afb1205..e43522316720 100644--- a/nodejs/src/utils/event-ingestion-restrictions/manager.test.ts+++ b/nodejs/src/utils/event-ingestion-restrictions/manager.test.ts@@ -2,10 +2,22 @@ import { Pool as GenericPool } from 'generic-pool'import { Redis } from 'ioredis'import { RedisPool } from '../../types'-import { EventIngestionRestrictionManager } from './manager'+import {+ EventIngestionRestrictionManager,+ EventIngestionRestrictionManagerComponent,+ EventIngestionRestrictionManagerOptions,+} from './manager'import { REDIS_KEY_PREFIX, RedisRestrictionType } from './redis-schema'import { RestrictionType } from './rules'+async function buildManager(+ redisPool: RedisPool,+ options?: EventIngestionRestrictionManagerOptions+): Promise<EventIngestionRestrictionManager> {+ const lifecycle = new EventIngestionRestrictionManagerComponent(redisPool, options)+ return (await lifecycle.start()).value+}+const createMockRedisPool = (): RedisPool => {const redisClient = {pipeline: jest.fn(),@@ -99,7 +111,7 @@ describe('EventIngestionRestrictionManager', () => {hub = { redisPool }- manager = new EventIngestionRestrictionManager(hub.redisPool, {+ manager = await buildManager(hub.redisPool, {staticDropEventTokens: [],staticSkipPersonTokens: [],staticForceOverflowTokens: [],@@ -112,13 +124,13 @@ describe('EventIngestionRestrictionManager', () => {})describe('constructor', () => {- it('initializes with default values if no options provided', () => {- const mgr = new EventIngestionRestrictionManager(hub.redisPool)+ it('initializes with default values if no options provided', async () => {+ const mgr = await buildManager(hub.redisPool)expect(mgr).toBeDefined()})- it('initializes with provided static config', () => {- const mgr = new EventIngestionRestrictionManager(hub.redisPool, {+ it('initializes with provided static config', async () => {+ const mgr = await buildManager(hub.redisPool, {staticDropEventTokens: ['token1'],staticSkipPersonTokens: ['token2'],staticForceOverflowTokens: ['token3'],@@ -300,7 +312,7 @@ describe('EventIngestionRestrictionManager', () => {})it('filters by session_recordings pipeline', async () => {- const sessionManager = new EventIngestionRestrictionManager(hub.redisPool, {+ const sessionManager = await buildManager(hub.redisPool, {pipeline: 'session_recordings',})@@ -342,7 +354,7 @@ describe('EventIngestionRestrictionManager', () => {describe('static config', () => {it('applies token-level static restriction', async () => {- const mgr = new EventIngestionRestrictionManager(hub.redisPool, {+ const mgr = await buildManager(hub.redisPool, {staticDropEventTokens: ['static-token'],})await mgr.forceRefresh()@@ -352,7 +364,7 @@ describe('EventIngestionRestrictionManager', () => {})it('applies distinct_id static restriction (legacy format)', async () => {- const mgr = new EventIngestionRestrictionManager(hub.redisPool, {+ const mgr = await buildManager(hub.redisPool, {staticDropEventTokens: ['static-token:user1'],})await mgr.forceRefresh()@@ -364,7 +376,7 @@ describe('EventIngestionRestrictionManager', () => {})it('applies distinct_id static restriction (explicit format)', async () => {- const mgr = new EventIngestionRestrictionManager(hub.redisPool, {+ const mgr = await buildManager(hub.redisPool, {staticDropEventTokens: ['static-token:distinct_id:user1'],})await mgr.forceRefresh()@@ -375,7 +387,7 @@ describe('EventIngestionRestrictionManager', () => {})it('combines static and dynamic restrictions', async () => {- const mgr = new EventIngestionRestrictionManager(hub.redisPool, {+ const mgr = await buildManager(hub.redisPool, {staticDropEventTokens: ['combo-token'],})diff --git a/nodejs/src/utils/event-ingestion-restrictions/manager.ts b/nodejs/src/utils/event-ingestion-restrictions/manager.tsindex ee24882d135a..a40c7e17f8ee 100644--- a/nodejs/src/utils/event-ingestion-restrictions/manager.ts+++ b/nodejs/src/utils/event-ingestion-restrictions/manager.ts@@ -7,10 +7,18 @@ import { logger } from '../logger'import { REDIS_KEY_PREFIX, RedisRestrictionArraySchema, RedisRestrictionType, toRestrictionRule } from './redis-schema'import { EventContext, RestrictionFilters, RestrictionMap, RestrictionRule, RestrictionType } from './rules'-export type IngestionPipeline = 'analytics' | 'session_recordings' | 'errortracking'+export type IngestionPipeline = 'analytics' | 'session_recordings' | 'errortracking' | 'clientwarnings'const EMPTY_RESTRICTIONS: ReadonlySet<RestrictionType> = new Set()+export interface EventIngestionRestrictionManagerOptions {+ pipeline?: IngestionPipeline+ staticDropEventTokens?: string[]+ staticSkipPersonTokens?: string[]+ staticForceOverflowTokens?: string[]+ staticRedirectToDlqTokens?: string[]+}+/** Events can be restricted for ingestion through static and dynamic configs.* This manager handles the loading/caching/refreshing of the dynamic configs@@ -26,6 +34,10 @@ const EMPTY_RESTRICTIONS: ReadonlySet<RestrictionType> = new Set()* - AND between filter types (distinct_ids AND session_ids AND event_names AND event_uuids)* - OR within each filter type (value in set)* - Empty filter = matches all (neutral in AND)+ *+ * The constructor does not prime the cache; call `prime()` (or wrap+ * construction in `EventIngestionRestrictionManagerComponent`) to await+ * the initial load.*/export class EventIngestionRestrictionManager {private redisPool: GenericPool<Redis>@@ -33,16 +45,7 @@ export class EventIngestionRestrictionManager {private staticRestrictionMap: RestrictionMap = new RestrictionMap()private dynamicConfigRefresher: BackgroundRefresher<RestrictionMap>- constructor(- redisPool: GenericPool<Redis>,- options: {- pipeline?: IngestionPipeline- staticDropEventTokens?: string[]- staticSkipPersonTokens?: string[]- staticForceOverflowTokens?: string[]- staticRedirectToDlqTokens?: string[]- } = {}- ) {+ constructor(redisPool: GenericPool<Redis>, options: EventIngestionRestrictionManagerOptions = {}) {const {pipeline = 'analytics',staticDropEventTokens = [],@@ -63,9 +66,12 @@ export class EventIngestionRestrictionManager {logger.debug('🔁', 'ingestion_event_restriction_manager - refreshing dynamic config in the background')return await this.buildRestrictionMap()})+ }- // Initialize the restriction manager (includes static restrictions)- void this.dynamicConfigRefresher.get().catch((error) => {+ async prime(): Promise<void> {+ // Failures are logged but don't surface — static restrictions still+ // apply, and `tryGet` will retry in the background on subsequent reads.+ await this.dynamicConfigRefresher.get().catch((error) => {logger.error('Failed to initialize event ingestion restriction config', { error })})}@@ -180,3 +186,22 @@ export class EventIngestionRestrictionManager {return rules}}++/**+ * Scope entry for `EventIngestionRestrictionManager`. `start()` constructs+ * the manager from the supplied options and awaits the initial cache+ * prime before handing it back. Stop is a no-op — the manager doesn't+ * hold lifetime-bound resources directly.+ */+export class EventIngestionRestrictionManagerComponent {+ constructor(+ private readonly redisPool: GenericPool<Redis>,+ private readonly options: EventIngestionRestrictionManagerOptions = {}+ ) {}++ async start(): Promise<{ value: EventIngestionRestrictionManager; stop: () => Promise<void> }> {+ const manager = new EventIngestionRestrictionManager(this.redisPool, this.options)+ await manager.prime()+ return { value: manager, stop: () => Promise.resolve() }+ }+}diff --git a/nodejs/src/utils/event-ingestion-restrictions/redis-schema.ts b/nodejs/src/utils/event-ingestion-restrictions/redis-schema.tsindex 356f899e74dc..1fea72558be2 100644--- a/nodejs/src/utils/event-ingestion-restrictions/redis-schema.ts+++ b/nodejs/src/utils/event-ingestion-restrictions/redis-schema.ts@@ -13,7 +13,9 @@ export enum RedisRestrictionType {export const REDIS_KEY_PREFIX = 'event_ingestion_restriction_dynamic_config'// Base schema for common fields-const pipelinesSchema = z.array(z.enum(['analytics', 'session_recordings', 'errortracking'])).optional()+const pipelinesSchema = z+ .array(z.enum(['analytics', 'session_recordings', 'errortracking', 'clientwarnings']))+ .optional()// Redis schema v0 (legacy) - single identifier per entry, no version fieldconst RedisRestrictionItemSchemaV0 = z.object({diff --git a/nodejs/src/utils/team-manager.ts b/nodejs/src/utils/team-manager.tsindex ffec494bf6ea..23290f126283 100644--- a/nodejs/src/utils/team-manager.ts+++ b/nodejs/src/utils/team-manager.ts@@ -14,6 +14,11 @@ export interface TeamManagerOptions {loaderRetry?: LoaderRetryOptions}+/**+ * Looks up Teams by id or token, backed by a Postgres-loaded lazy cache.+ * Pure business surface — no `start` / `stop`. Callers that need to manage+ * its lifetime as part of a `Lifecycle` use `TeamManagerComponent`.+ */export class TeamManager {private lazyLoader: LazyLoader<Team>@@ -162,6 +167,26 @@ export class TeamManager {resultRecord[row.api_token] = team})- return resultRecord as Record<string, Team | null>+ return resultRecord+ }+}++/**+ * Lifecycle owner for `TeamManager`. `start()` constructs a fresh+ * `TeamManager` and hands it back along with a no-op stop callback. The+ * resulting `TeamManager` has no `start`/`stop` of its own — its lifetime+ * is fully controlled through this Manager.+ */+export class TeamManagerComponent {+ constructor(+ private postgres: PostgresRouter,+ private options?: TeamManagerOptions+ ) {}++ start(): Promise<{ value: TeamManager; stop: () => Promise<void> }> {+ return Promise.resolve({+ value: new TeamManager(this.postgres, this.options),+ stop: () => Promise.resolve(),+ })}}diff --git a/nodejs/tests/helpers/ingestion-e2e.ts b/nodejs/tests/helpers/ingestion-e2e.tsnew file mode 100644index 000000000000..92ed641b16f4--- /dev/null+++ b/nodejs/tests/helpers/ingestion-e2e.ts@@ -0,0 +1,477 @@+import { DateTime } from 'luxon'+import { Message } from 'node-rdkafka'+import { v4 } from 'uuid'++import { IntegrationManagerService } from '../../src/cdp/services/managers/integration-manager.service'+import { EncryptedFields } from '../../src/cdp/utils/encryption-utils'+import { defaultConfig } from '../../src/config/config'+import { KAFKA_INGESTION_WARNINGS } from '../../src/config/kafka-topics'+import {+ createCookielessRedisConnectionConfig,+ createIngestionRedisConnectionConfig,+} from '../../src/config/redis-pools'+import { CookielessManager } from '../../src/ingestion/cookieless/cookieless-manager'+import { buildGroupRepository, buildPersonRepository, createPersonHogClient } from '../../src/ingestion/personhog'+import { KafkaProducerWrapper } from '../../src/kafka/producer'+import { PipelineEvent, PluginsServerConfig, ProjectId, RawClickHouseEvent, RedisPool, Team } from '../../src/types'+import { PostgresRouter } from '../../src/utils/db/postgres'+import { createRedisPoolFromConfig } from '../../src/utils/db/redis'+import { parseRawClickHouseEvent } from '../../src/utils/event'+import { GeoIPService } from '../../src/utils/geoip'+import { parseJSON } from '../../src/utils/json-parse'+import { PubSub } from '../../src/utils/pubsub'+import { TeamManager } from '../../src/utils/team-manager'+import { UUIDT } from '../../src/utils/utils'+import { GroupTypeManager } from '../../src/worker/ingestion/group-type-manager'+import { GroupRepository } from '../../src/worker/ingestion/groups/repositories/group-repository.interface'+import { PostgresGroupRepository } from '../../src/worker/ingestion/groups/repositories/postgres-group-repository'+import { PersonRepository } from '../../src/worker/ingestion/persons/repositories/person-repository'+import { PostgresPersonRepository } from '../../src/worker/ingestion/persons/repositories/postgres-person-repository'+import { Clickhouse } from './clickhouse'+import { waitForExpect } from './expectations'+import { createUserTeamAndOrganization } from './sql'++export const DEFAULT_TEAM: Team = {+ id: 2,+ project_id: 2 as ProjectId,+ organization_id: '2',+ uuid: v4(),+ name: '2',+ anonymize_ips: true,+ api_token: 'api_token',+ secret_api_token: null,+ session_recording_opt_in: true,+ person_processing_opt_out: null,+ heatmaps_opt_in: null,+ ingested_event: true,+ person_display_name_properties: null,+ test_account_filters: null,+ cookieless_server_hash_mode: null,+ timezone: 'UTC',+ available_features: [],+ drop_events_older_than_seconds: null,+ extra_settings: null,+}++export class EventBuilder {+ private event: Partial<PipelineEvent> = {}++ constructor(team: Team, distinctId: string = new UUIDT().toString()) {+ this.event = {+ event: 'custom event',+ properties: {},+ timestamp: new Date().toISOString(),+ now: new Date().toISOString(),+ ip: null,+ site_url: 'https://example.com',+ uuid: new UUIDT().toString(),+ }+ this.event.distinct_id = distinctId+ this.event.team_id = team.id+ }++ withEvent(event: string) {+ this.event.event = event+ return this+ }++ withProperties(properties: Record<string, any>) {+ this.event.properties = properties+ return this+ }++ withOverrides(overrides: Record<string, any>) {+ this.event = { ...this.event, ...overrides }+ return this+ }++ withTimestamp(timestamp: number) {+ const date = DateTime.fromMillis(timestamp)+ this.event.timestamp = date.toString()+ this.event.now = date.toString()+ return this+ }++ withNow(now: number) {+ const date = DateTime.fromMillis(now)+ this.event.now = date.toString()+ return this+ }++ withGroupProperties(groupType: string, groupKey: string, groupSet?: Record<string, any>) {+ this.event.properties = {+ ...this.event.properties,+ $group_type: groupType,+ $group_key: groupKey,+ ...(groupSet ? { $group_set: groupSet } : {}),+ }+ return this+ }++ build(): PipelineEvent {+ return this.event as PipelineEvent+ }+}++let offsetIncrementer = 0++export function createKafkaMessage(+ event: PipelineEvent,+ token: string,+ timestamp: number = DateTime.now().toMillis()+): Message {+ const captureEvent = {+ uuid: event.uuid,+ distinct_id: event.distinct_id,+ ip: event.ip,+ now: event.now,+ token,+ data: JSON.stringify(event),+ }++ const headers: { [key: string]: Buffer }[] = [+ { token: Buffer.from(token) },+ { distinct_id: Buffer.from(event.distinct_id!) },+ ]+ if (event.timestamp) {+ const timestampMs = DateTime.fromISO(event.timestamp).toMillis()+ headers.push({ timestamp: Buffer.from(timestampMs.toString()) })+ }+ if (event.now) {+ headers.push({ now: Buffer.from(event.now) })+ }++ return {+ key: `${token}:${event.distinct_id}`,+ value: Buffer.from(JSON.stringify(captureEvent)),+ size: 1,+ topic: 'test',+ offset: offsetIncrementer++,+ timestamp: timestamp + offsetIncrementer,+ partition: 1,+ headers,+ }+}++export function createKafkaMessages(events: PipelineEvent[], token: string): Message[] {+ return events.map((e) => createKafkaMessage(e, token))+}++export const waitForKafkaMessages = async (kafkaProducer: KafkaProducerWrapper) => {+ await kafkaProducer.flush()+}++/**+ * After `resetKafka()` recreates topics, ClickHouse's Kafka engine consumers need to+ * reconnect. With the default auto.offset.reset=latest, any messages produced before+ * reconnection are permanently missed. We repeatedly produce probe messages until+ * ClickHouse consumes one, which guarantees at least one lands after reconnection.+ */+export async function waitForClickHouseKafkaConsumer(clickhouse: Clickhouse): Promise<void> {+ const producer = await KafkaProducerWrapper.create(undefined)+ const probeTeamId = -1++ try {+ await waitForExpect(async () => {+ await producer.queueMessages({+ topic: KAFKA_INGESTION_WARNINGS,+ messages: [+ {+ value: JSON.stringify({+ team_id: probeTeamId,+ type: 'probe',+ source: 'test-warmup',+ details: '{}',+ timestamp: DateTime.utc().toFormat('yyyy-MM-dd HH:mm:ss'),+ }),+ },+ ],+ })+ await producer.flush()++ const result = await clickhouse.query<{ count: number }>(+ `SELECT count() as count FROM ingestion_warnings WHERE team_id = ${probeTeamId}`+ )+ expect(Number(result[0]?.count ?? 0)).toBeGreaterThan(0)+ }, 30_000)+ } finally {+ await producer.disconnect()+ }+}++export async function retryClickHouseOperation<T>(+ operation: () => Promise<T>,+ operationName: string,+ maxRetries: number = 3,+ throwOnFailure: boolean = true+): Promise<T | null> {+ let lastError: Error | null = null++ for (let attempt = 1; attempt <= maxRetries; attempt++) {+ try {+ return await operation()+ } catch (error: any) {+ lastError = error++ const isSocketError =+ error?.message?.includes('socket hang up') ||+ error?.message?.includes('ECONNRESET') ||+ error?.message?.includes('ETIMEDOUT')++ if (isSocketError && attempt < maxRetries) {+ const backoffMs = Math.min(1000 * Math.pow(2, attempt - 1), 10000)+ console.warn(+ `[DEBUG] ClickHouse ${operationName} failed (attempt ${attempt}/${maxRetries}), retrying in ${backoffMs}ms:`,+ error?.message+ )+ await new Promise((resolve) => setTimeout(resolve, backoffMs))+ continue+ }++ console.warn(+ `[DEBUG] ClickHouse ${operationName} failed (attempt ${attempt}/${maxRetries}):`,+ error?.message+ )+ break+ }+ }++ if (throwOnFailure && lastError) {+ throw lastError+ } else if (lastError) {+ console.warn(`[DEBUG] ClickHouse ${operationName} failed after all retries (non-fatal):`, lastError?.message)+ return null+ }++ return null+}++export async function fetchEvents(clickhouse: Clickhouse, teamId: number) {+ await retryClickHouseOperation(+ () => clickhouse.exec(`OPTIMIZE TABLE person_distinct_id_overrides FINAL`),+ 'OPTIMIZE TABLE person_distinct_id_overrides FINAL',+ 3,+ false+ )++ const queryResult = (await retryClickHouseOperation(+ () =>+ clickhouse.query(`+ SELECT *,+ if(notEmpty(overrides.person_id), overrides.person_id, e.person_id) as person_id+ FROM events e+ FINAL+ LEFT OUTER JOIN (+ SELECT+ distinct_id,+ argMax(person_id, version) as person_id+ FROM person_distinct_id_overrides+ FINAL+ WHERE team_id = ${teamId}+ GROUP BY distinct_id+ ) AS overrides USING distinct_id+ WHERE team_id = ${teamId}+ ORDER BY timestamp ASC+ `),+ 'fetchEvents query',+ 3,+ true+ )) as unknown as RawClickHouseEvent[]++ return queryResult.map(parseRawClickHouseEvent)+}++export async function fetchIngestionWarnings(clickhouse: Clickhouse, teamId: number) {+ const queryResult = (await retryClickHouseOperation(+ () =>+ clickhouse.query(`+ SELECT *+ FROM ingestion_warnings+ WHERE team_id = ${teamId}+ `),+ 'fetchIngestionWarnings query',+ 3,+ true+ )) as any[]++ return queryResult.map((warning: any) => ({ ...warning, details: parseJSON(warning.details) }))+}++export interface IngesterLike {+ start(): Promise<void>+ stop(): Promise<void>+}++/**+ * Set of primitives the test harness exposes to an ingester builder. Built+ * directly from primitive Manager/factory calls — no hub involved.+ */+export interface IngestionTestInfra {+ config: PluginsServerConfig+ postgres: PostgresRouter+ redisPool: RedisPool+ teamManager: TeamManager+ groupRepository: GroupRepository+ personRepository: PersonRepository+ cookielessManager: CookielessManager+ pubSub: PubSub+ geoipService: GeoIPService+ encryptedFields: EncryptedFields+ integrationManager: IntegrationManagerService+ groupTypeManager: GroupTypeManager+}++export interface TeamIngesterTestContext<T extends IngesterLike> {+ infra: IngestionTestInfra+ team: Team+ kafkaProducer: KafkaProducerWrapper+ ingester: T+ token: string+}++export interface TeamIngesterTestConfig {+ teamOverrides?: Partial<Team>+ pluginServerConfig?: Partial<PluginsServerConfig>+}++export type BuildIngester<T extends IngesterLike> = (+ infra: IngestionTestInfra,+ kafkaProducer: KafkaProducerWrapper+) => T++/**+ * Builds a `test` factory that spins up an isolated team + hub + consumer per+ * test. The caller supplies the `buildIngester` function that constructs the+ * consumer under test — different pipelines have different deps.+ */+export function createTestWithTeamIngester<T extends IngesterLike>(+ baseConfig: Partial<PluginsServerConfig>,+ buildIngester: BuildIngester<T>+) {+ return (+ name: string,+ config: TeamIngesterTestConfig = {},+ testFn: (ctx: TeamIngesterTestContext<T>) => Promise<void>+ ) => {+ test(name, async () => {+ const serverConfig: PluginsServerConfig = {+ ...defaultConfig,+ ...baseConfig,+ ...config.pluginServerConfig,+ }++ const postgres = new PostgresRouter(serverConfig, serverConfig.PLUGIN_SERVER_MODE ?? undefined)+ const redisPool = createRedisPoolFromConfig({+ connection: createIngestionRedisConnectionConfig(serverConfig),+ poolMinSize: serverConfig.REDIS_POOL_MIN_SIZE,+ poolMaxSize: serverConfig.REDIS_POOL_MAX_SIZE,+ })+ const cookielessRedisPool = createRedisPoolFromConfig({+ connection: createCookielessRedisConnectionConfig(serverConfig),+ poolMinSize: serverConfig.REDIS_POOL_MIN_SIZE,+ poolMaxSize: serverConfig.REDIS_POOL_MAX_SIZE,+ })++ const teamManager = new TeamManager(postgres)+ const pubSub = new PubSub(redisPool)+ await pubSub.start()++ const personhogClient = createPersonHogClient(serverConfig)+ const clientLabel = serverConfig.PLUGIN_SERVER_MODE ?? 'unknown'++ const postgresGroupRepository = new PostgresGroupRepository(postgres)+ const postgresPersonRepository = new PostgresPersonRepository(postgres, {+ calculatePropertiesSize: serverConfig.PERSON_UPDATE_CALCULATE_PROPERTIES_SIZE,+ })+ const personRepository = buildPersonRepository(+ personhogClient,+ postgresPersonRepository,+ serverConfig.PERSONHOG_PERSONS_ROLLOUT_PERCENTAGE,+ serverConfig.PERSONHOG_PERSONS_ROLLOUT_TEAM_IDS,+ clientLabel+ )+ const groupRepository = buildGroupRepository(+ personhogClient,+ postgresGroupRepository,+ serverConfig.PERSONHOG_GROUPS_ROLLOUT_PERCENTAGE,+ serverConfig.PERSONHOG_GROUPS_ROLLOUT_TEAM_IDS,+ clientLabel+ )+ const groupTypeManager = new GroupTypeManager(groupRepository, teamManager)+ const cookielessManager = new CookielessManager(serverConfig, cookielessRedisPool)+ const geoipService = new GeoIPService(serverConfig.MMDB_FILE_LOCATION)+ await geoipService.get()+ const encryptedFields = new EncryptedFields(serverConfig.ENCRYPTION_SALT_KEYS)+ const integrationManager = new IntegrationManagerService(pubSub, postgres, encryptedFields)++ const kafkaProducer = await KafkaProducerWrapper.create(serverConfig.KAFKA_CLIENT_RACK)++ const teamId = Math.floor((Date.now() % 1000000000) + Math.random() * 1000000)+ const userId = teamId+ const organizationId = new UUIDT().toString()++ const newTeam: Team = {+ ...DEFAULT_TEAM,+ id: teamId,+ project_id: teamId as ProjectId,+ organization_id: organizationId,+ uuid: v4(),+ name: teamId.toString(),+ ...config.teamOverrides,+ }+ const userUuid = new UUIDT().toString()+ const organizationMembershipId = new UUIDT().toString()++ await createUserTeamAndOrganization(+ postgres,+ newTeam.id,+ userId,+ userUuid,+ newTeam.organization_id,+ organizationMembershipId,+ config.teamOverrides+ )++ const fetchedTeam = await teamManager.getTeam(newTeam.id)+ if (!fetchedTeam) {+ throw new Error(`Failed to fetch team ${newTeam.id} from database`)+ }++ const infra: IngestionTestInfra = {+ config: serverConfig,+ postgres,+ redisPool,+ teamManager,+ groupRepository,+ personRepository,+ cookielessManager,+ pubSub,+ geoipService,+ encryptedFields,+ integrationManager,+ groupTypeManager,+ }++ const ingester = buildIngester(infra, kafkaProducer)+ // We don't actually use kafka so we skip instantiation for faster tests+ ;(ingester as unknown as { kafkaConsumer: unknown }).kafkaConsumer = {+ connect: jest.fn(),+ disconnect: jest.fn(),+ isHealthy: jest.fn(),+ }++ await ingester.start()+ try {+ await testFn({ infra, team: fetchedTeam, kafkaProducer, ingester, token: fetchedTeam.api_token })+ } finally {+ await ingester.stop()+ await kafkaProducer.disconnect()+ await pubSub.stop()+ await Promise.allSettled([redisPool.drain(), cookielessRedisPool.drain(), postgres.end()])+ await redisPool.clear()+ await cookielessRedisPool.clear()+ cookielessManager.shutdown()+ }+ })+ }+}diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rsindex accec17075ba..52a0de6ccbd1 100644--- a/rust/capture/src/config.rs+++ b/rust/capture/src/config.rs@@ -292,7 +292,7 @@ pub struct KafkaConfig {pub kafka_overflow_topic: String,#[envconfig(default = "events_plugin_ingestion_historical")]pub kafka_historical_topic: String,- #[envconfig(default = "events_plugin_ingestion")]+ #[envconfig(default = "ingestion-clientwarnings-main-1")]pub kafka_client_ingestion_warning_topic: String,#[envconfig(default = "error_tracking_events")]pub kafka_error_tracking_topic: String,