Skip to content

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

feat(ingestion): add common ingestion pipeline builder prototype (#70800)

Paweł Ledwońcd9f48461dd9
diff --git a/nodejs/src/ingestion/common/common-ingestion-pipeline.test.ts b/nodejs/src/ingestion/common/common-ingestion-pipeline.test.ts
new file mode 100644
index 000000000000..56afa303f047
--- /dev/null
+++ b/nodejs/src/ingestion/common/common-ingestion-pipeline.test.ts
@@ -0,0 +1,740 @@
+import { Message } from 'node-rdkafka'
+
+import { KafkaProducerWrapper } from '~/common/kafka/producer'
+import { DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT } from '~/common/outputs'
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
+import { parseJSON } from '~/common/utils/json-parse'
+import { PromiseScheduler } from '~/common/utils/promise-scheduler'
+import { TeamManager } from '~/common/utils/team-manager'
+import { UUIDT } from '~/common/utils/utils'
+import { ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'
+import { createOkContext } from '~/ingestion/framework/helpers'
+import { dlq, drop, isDropResult, isOkResult, ok, redirect } from '~/ingestion/framework/results'
+import { ProcessingStep } from '~/ingestion/framework/steps'
+import { PluginEvent } from '~/plugin-scaffold'
+import { createTestTeam } from '~/tests/helpers/team'
+import { EventHeaders, IncomingEvent, Team } from '~/types'
+
+import { CommonIngestionPipelineConfig, newCommonIngestionPipeline } from './common-ingestion-pipeline'
+
+jest.mock('~/common/utils/logger', () => ({
+ logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },
+}))
+
+const DLQ_TOPIC = 'events_dlq_test'
+const WARNINGS_TOPIC = 'ingestion_warnings_test'
+const REDIRECT_TOPIC = 'redirect_test'
+const TEST_REDIRECT_OUTPUT = 'test_redirect' as const
+type TestRedirectOutput = typeof TEST_REDIRECT_OUTPUT
+
+type MessageOnly = { message: Message }
+
+interface Deferred {
+ promise: Promise<void>
+ resolve: () => void
+}
+
+function deferred(): Deferred {
+ let resolve!: () => void
+ const promise = new Promise<void>((r) => {
+ resolve = r
+ })
+ return { promise, resolve }
+}
+
+/**
+ * Let in-flight promise chains run until they park on a gate or a fake timer,
+ * without firing any fake timers. Each round crosses a real setImmediate
+ * (excluded from faking below), which drains the entire microtask queue —
+ * bare Promise.resolve() rounds only advance chains one continuation at a
+ * time, which is not enough to reach a park point before asserting.
+ */
+async function settle(rounds: number = 10): Promise<void> {
+ for (let i = 0; i < rounds; i++) {
+ await new Promise((resolve) => setImmediate(resolve))
+ }
+}
+
+describe('CommonIngestionPipelineBuilder', () => {
+ let mockKafkaProducer: jest.Mocked<KafkaProducerWrapper>
+ let mockTeamManager: jest.Mocked<TeamManager>
+ let promiseScheduler: PromiseScheduler
+ let config: CommonIngestionPipelineConfig<TestRedirectOutput>
+
+ const team = createTestTeam({ id: 42, api_token: 'token-42' })
+
+ const createMessage = (distinctId: string, eventName = 'test_event', token = team.api_token): Message => {
+ const eventData = {
+ event: eventName,
+ distinct_id: distinctId,
+ uuid: new UUIDT().toString(),
+ timestamp: '2024-01-01T00:00:00Z',
+ properties: {},
+ }
+ return {
+ value: Buffer.from(JSON.stringify({ token, data: JSON.stringify(eventData), ...eventData })),
+ headers: [{ token: Buffer.from(token) }, { distinct_id: Buffer.from(distinctId) }],
+ topic: 'events_ingestion',
+ partition: 0,
+ offset: 0,
+ size: 0,
+ key: Buffer.from(distinctId),
+ } as Message
+ }
+
+ // Drains the pipeline the way real drivers do, and enforces the builder's
+ // contract along the way: side effects are handled inside the pipeline,
+ // so no batch result may ever surface any to the driver.
+ const runPipeline = async (
+ pipeline: {
+ feed: (batch: any[]) => Promise<{ ok: boolean }>
+ next: () => Promise<{ elements: any[]; sideEffects?: Promise<unknown>[] } | null>
+ },
+ messages: Message[]
+ ): Promise<{ elements: any[]; sideEffects?: Promise<unknown>[] }[]> => {
+ const batch = messages.map((message) => createOkContext({ message }, { message }))
+ const feedResult = await pipeline.feed(batch)
+ expect(feedResult.ok).toBe(true)
+
+ const batches = []
+ let result = await pipeline.next()
+ while (result !== null) {
+ expect(result.sideEffects ?? []).toEqual([])
+ batches.push(result)
+ result = await pipeline.next()
+ }
+ await promiseScheduler.waitForAll()
+ return batches
+ }
+
+ const okValues = (batches: { elements: any[] }[]): any[] =>
+ batches
+ .flatMap((batch) => batch.elements)
+ .filter((element) => isOkResult(element.result))
+ .map((element) => element.result.value)
+
+ const producedTo = (topic: string): any[] =>
+ mockKafkaProducer.produce.mock.calls.map((call) => call[0]).filter((arg: any) => arg.topic === topic)
+
+ const warningsProduced = (): any[] =>
+ mockKafkaProducer.queueMessages.mock.calls
+ .map((call) => call[0])
+ .filter((arg: any) => arg.topic === WARNINGS_TOPIC)
+ .flatMap((arg: any) => arg.messages.map((m: { value: Buffer }) => parseJSON(m.value.toString())))
+
+ function preTeamLogStep<T extends { headers: EventHeaders }>(log: string[], name: string): ProcessingStep<T, T> {
+ return function preTeamLogStep(input) {
+ log.push(`${name}:${input.headers.distinct_id}`)
+ return Promise.resolve(ok(input))
+ }
+ }
+
+ function preTeamLogChunkStep<T extends { headers: EventHeaders }>(
+ log: string[],
+ name: string
+ ): ChunkProcessingStep<T, T> {
+ return function preTeamLogChunkStep(values) {
+ log.push(`${name}:[${values.map((value) => value.headers.distinct_id).join(',')}]`)
+ return Promise.resolve(values.map((value) => ok(value)))
+ }
+ }
+
+ function teamLogStep<T extends { event: PluginEvent }>(log: string[], name: string): ProcessingStep<T, T> {
+ return function teamLogStep(input) {
+ log.push(`${name}:${input.event.distinct_id}`)
+ return Promise.resolve(ok(input))
+ }
+ }
+
+ function teamLogChunkStep<T extends { event: PluginEvent }>(
+ log: string[],
+ name: string
+ ): ChunkProcessingStep<T, T> {
+ return function teamLogChunkStep(values) {
+ log.push(`${name}:[${values.map((value) => value.event.distinct_id).join(',')}]`)
+ return Promise.resolve(values.map((value) => ok(value)))
+ }
+ }
+
+ beforeEach(() => {
+ // Fake every duration-bearing API so nothing in the suite depends on
+ // wall-clock time; keep setImmediate real — settle() relies on it to
+ // fully drain the event loop before mid-flight assertions.
+ jest.useFakeTimers({ doNotFake: ['setImmediate'] })
+
+ mockKafkaProducer = {
+ produce: jest.fn().mockResolvedValue(undefined),
+ queueMessages: jest.fn().mockResolvedValue(undefined),
+ flush: jest.fn().mockResolvedValue(undefined),
+ } as unknown as jest.Mocked<KafkaProducerWrapper>
+
+ mockTeamManager = {
+ getTeamByToken: jest
+ .fn()
+ .mockImplementation((token: string) => Promise.resolve(token === team.api_token ? team : null)),
+ } as unknown as jest.Mocked<TeamManager>
+
+ promiseScheduler = new PromiseScheduler()
+
+ config = {
+ teamManager: mockTeamManager,
+ outputs: new IngestionOutputs({
+ [DLQ_OUTPUT]: new SingleIngestionOutput(DLQ_OUTPUT, DLQ_TOPIC, mockKafkaProducer, 'test'),
+ [INGESTION_WARNINGS_OUTPUT]: new SingleIngestionOutput(
+ INGESTION_WARNINGS_OUTPUT,
+ WARNINGS_TOPIC,
+ mockKafkaProducer,
+ 'test'
+ ),
+ [TEST_REDIRECT_OUTPUT]: new SingleIngestionOutput(
+ TEST_REDIRECT_OUTPUT,
+ REDIRECT_TOPIC,
+ mockKafkaProducer,
+ 'test'
+ ),
+ }),
+ promiseScheduler,
+ }
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ it('parses events, resolves the team, and returns results in feed order', async () => {
+ const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
+ .parseHeaders()
+ .parseMessage()
+ .resolveTeam()
+ .pipe(function tagStep(input) {
+ return Promise.resolve(ok({ distinctId: input.event.distinct_id, teamId: input.team.id }))
+ })
+ .build()
+
+ const batches = await runPipeline(pipeline, [createMessage('user-0'), createMessage('user-1')])
+
+ expect(batches).toHaveLength(1)
+ expect(okValues(batches)).toEqual([
+ { distinctId: 'user-0', teamId: 42 },
+ { distinctId: 'user-1', teamId: 42 },
+ ])
+ })
+
+ it('runs consecutive pre-team pipe steps element by element in one sequential block', async () => {
+ const log: string[] = []
+ const gate = deferred()
+ const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
+ .parseHeaders()
+ .pipe(async function gatedStepA(input: { message: Message; headers: EventHeaders }) {
+ if (input.headers.distinct_id === 'user-0') {
+ await gate.promise
+ }
+ log.push(`A:${input.headers.distinct_id}`)
+ return ok(input)
+ })
+ .pipe(preTeamLogStep(log, 'B'))
+ .parseMessage()
+ .resolveTeam()
+ .build()
+
+ const run = runPipeline(pipeline, [createMessage('user-0'), createMessage('user-1')])
+ await settle()
+
+ // user-0 is held inside the block's first step; a sequential block must
+ // not let user-1 start, so nothing may have been logged yet.
+ expect(log).toEqual([])
+
+ gate.resolve()
+ await run
+
+ expect(log).toEqual(['A:user-0', 'B:user-0', 'A:user-1', 'B:user-1'])
+ })
+
+ it('pipeChunk closes the pre-team sequential block and receives the whole chunk at once', async () => {
+ const log: string[] = []
+ const gate = deferred()
+ const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
+ .parseHeaders()
+ .pipe(async function gatedStepA(input: { message: Message; headers: EventHeaders }) {
+ if (input.headers.distinct_id === 'user-2') {
+ await gate.promise
+ }
+ log.push(`A:${input.headers.distinct_id}`)
+ return ok(input)
+ })
+ .pipeChunk(preTeamLogChunkStep(log, 'C'))
+ .pipe(preTeamLogStep(log, 'D'))
+ .parseMessage()
+ .resolveTeam()
+ .build()
+
+ const run = runPipeline(pipeline, [createMessage('user-0'), createMessage('user-1'), createMessage('user-2')])
+ await settle()
+
+ // The last element is held inside the block; the chunk step is a
+ // barrier, so neither C nor anything after it may have run yet.
+ expect(log).toEqual(['A:user-0', 'A:user-1'])
+
+ gate.resolve()
+ await run
+
+ expect(log).toEqual([
+ 'A:user-0',
+ 'A:user-1',
+ 'A:user-2',
+ 'C:[user-0,user-1,user-2]',
+ 'D:user-0',
+ 'D:user-1',
+ 'D:user-2',
+ ])
+ })
+
+ it('coalesces and chunk-splits team-aware steps the same way as pre-team steps', async () => {
+ const log: string[] = []
+ const gate = deferred()
+ const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
+ .parseHeaders()
+ .parseMessage()
+ .resolveTeam()
+ .pipe(async function gatedStepX(input) {
+ if (input.event.distinct_id === 'user-0') {
+ await gate.promise
+ }
+ log.push(`X:${input.event.distinct_id}`)
+ return ok(input)
+ })
+ .pipeChunk(teamLogChunkStep(log, 'Y'))
+ .pipe(teamLogStep(log, 'Z'))
+ .build()
+
+ const run = runPipeline(pipeline, [createMessage('user-0'), createMessage('user-1')])
+ await settle()
+
+ // user-0 is held inside the team block's first step; user-1 must not
+ // overtake it and the chunk step must not fire.
+ expect(log).toEqual([])
+
+ gate.resolve()
+ await run
+
+ expect(log).toEqual(['X:user-0', 'X:user-1', 'Y:[user-0,user-1]', 'Z:user-0', 'Z:user-1'])
+ })
+
+ it('drops events whose token cannot be resolved and keeps processing the rest', async () => {
+ const log: string[] = []
+ const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
+ .parseHeaders()
+ .parseMessage()
+ .resolveTeam()
+ .pipe(teamLogStep(log, 'X'))
+ .build()
+
+ const batches = await runPipeline(pipeline, [
+ createMessage('user-0'),
+ createMessage('user-1', 'test_event', 'unknown-token'),
+ ])
+
+ expect(log).toEqual(['X:user-0'])
+ const elements = batches.flatMap((batch) => batch.elements)
+ expect(elements).toHaveLength(2)
+ expect(isOkResult(elements[0].result)).toBe(true)
+ expect(isDropResult(elements[1].result)).toBe(true)
+ expect(producedTo(DLQ_TOPIC)).toHaveLength(0)
+ })
+
+ it('produces DLQ results from steps to the DLQ output', async () => {
+ const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
+ .parseHeaders()
+ .parseMessage()
+ .resolveTeam()
+ .pipe(function poisonStep(input) {
+ if (input.event.event === 'poison') {
+ return Promise.resolve(dlq('poison_event'))
+ }
+ return Promise.resolve(ok(input))
+ })
+ .build()
+
+ const batches = await runPipeline(pipeline, [createMessage('user-0'), createMessage('user-1', 'poison')])
+
+ expect(producedTo(DLQ_TOPIC)).toHaveLength(1)
+ expect(okValues(batches)).toHaveLength(1)
+ })
+
+ it('produces redirect results to the configured redirect output', async () => {
+ const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly, TestRedirectOutput>(config)
+ .parseHeaders()
+ .parseMessage()
+ .resolveTeam()
+ .pipe(function redirectStep(input) {
+ if (input.event.event === 'redirect_me') {
+ return Promise.resolve(redirect('overflowing', TEST_REDIRECT_OUTPUT))
+ }
+ return Promise.resolve(ok(input))
+ })
+ .build()
+
+ const batches = await runPipeline(pipeline, [createMessage('user-0'), createMessage('user-1', 'redirect_me')])
+
+ expect(producedTo(REDIRECT_TOPIC)).toHaveLength(1)
+ expect(okValues(batches)).toHaveLength(1)
+ })
+
+ it('routes warnings from pre-team and team-aware steps to the warnings output with the resolved team', async () => {
+ const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
+ .parseHeaders()
+ .pipe(function preTeamWarningStep(input) {
+ if (input.headers.distinct_id === 'user-0') {
+ return Promise.resolve(
+ ok(
+ input,
+ [],
+ [{ type: 'client_ingestion_warning', details: { marker: 'pre-team' }, alwaysSend: true }]
+ )
+ )
+ }
+ return Promise.resolve(ok(input))
+ })
+ .parseMessage()
+ .resolveTeam()
+ .pipe(function teamWarningStep(input) {
+ if (input.event.distinct_id === 'user-1') {
+ return Promise.resolve(
+ ok(
+ input,
+ [],
+ [{ type: 'client_ingestion_warning', details: { marker: 'team' }, alwaysSend: true }]
+ )
+ )
+ }
+ if (input.event.distinct_id === 'user-2') {
+ return Promise.resolve(
+ drop(
+ 'dropped_with_warning',
+ [],
+ [{ type: 'client_ingestion_warning', details: { marker: 'dropped' }, alwaysSend: true }]
+ )
+ )
+ }
+ return Promise.resolve(ok(input))
+ })
+ .build()
+
+ await runPipeline(pipeline, [createMessage('user-0'), createMessage('user-1'), createMessage('user-2')])
+
+ const warnings = warningsProduced()
+ expect(warnings).toHaveLength(3)
+ for (const warning of warnings) {
+ expect(warning.team_id).toBe(42)
+ expect(warning.type).toBe('client_ingestion_warning')
+ }
+ const markers = warnings.map((warning) => parseJSON(warning.details).marker)
+ expect(markers.sort()).toEqual(['dropped', 'pre-team', 'team'])
+ })
+
+ it('schedules step and batch hook side effects on the promise scheduler instead of returning them', async () => {
+ const scheduleSpy = jest.spyOn(promiseScheduler, 'schedule')
+ const beforeEffect = Promise.resolve('before')
+ const stepEffect = Promise.resolve('step')
+ const afterEffect = Promise.resolve('after')
+
+ const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
+ .beforeBatch<Record<never, object>>((builder) =>
+ builder.pipe(function beforeHook(input) {
+ return Promise.resolve(ok(input, [beforeEffect]))
+ })
+ )
+ .parseHeaders()
+ .parseMessage()
+ .resolveTeam()
+ .pipe(function effectStep(input) {
+ return Promise.resolve(ok(input, [stepEffect]))
+ })
+ .afterBatch((builder) =>
+ builder.pipe(function afterHook(input) {
+ return Promise.resolve(ok(input, [afterEffect]))
+ })
+ )
+ .build()
+
+ // runPipeline asserts every batch result surfaces zero side effects.
+ await runPipeline(pipeline, [createMessage('user-0')])
+
+ const scheduled = scheduleSpy.mock.calls.map((call) => call[0])
+ expect(scheduled).toEqual(expect.arrayContaining([beforeEffect, stepEffect, afterEffect]))
+ })
+
+ it('awaits side effects inline when awaitSideEffects is set', async () => {
+ const scheduleSpy = jest.spyOn(promiseScheduler, 'schedule')
+ let effectCompleted = false
+ const effect = (async () => {
+ await new Promise<void>((resolve) => setTimeout(resolve, 50))
+ effectCompleted = true
+ })()
+
+ const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>({ ...config, awaitSideEffects: true })
+ .parseHeaders()
+ .parseMessage()
+ .resolveTeam()
+ .pipe(function effectStep(input) {
+ return Promise.resolve(ok(input, [effect]))
+ })
+ .build()
+
+ let drained = false
+ const run = runPipeline(pipeline, [createMessage('user-0')]).then((batches) => {
+ drained = true
+ return batches
+ })
+ await settle()
+
+ // The side effect is parked on a fake timer; awaiting inline means
+ // the pipeline cannot finish draining until the timer fires.
+ expect(drained).toBe(false)
+ expect(effectCompleted).toBe(false)
+
+ await jest.runAllTimersAsync()
+ await run
+
+ expect(effectCompleted).toBe(true)
+ expect(scheduleSpy).not.toHaveBeenCalled()
+ })
+
+ it('exposes beforeBatch context to steps and runs afterBatch once per batch with all results', async () => {
+ const seenTags: string[] = []
+ const afterBatchCalls: { count: number; tag: string }[] = []
+
+ const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
+ .beforeBatch<{ batchTag: string }>((builder) =>
+ builder.pipe(function attachBatchTag(input) {
+ return Promise.resolve(
+ ok({
+ elements: input.elements,
+ batchContext: { ...input.batchContext, batchTag: `tag-${input.batchContext.batchId}` },
+ })
+ )
+ })
+ )
+ .parseHeaders()
+ .pipe(function readBatchTag(input) {
+ seenTags.push(input.batchTag)
+ return Promise.resolve(ok(input))
+ })
+ .parseMessage()
+ .resolveTeam()
+ .afterBatch((builder) =>
+ builder.pipe(function recordFlush(input) {
+ afterBatchCalls.push({ count: input.elements.length, tag: input.batchContext.batchTag })
+ return Promise.resolve(ok(input))
+ })
+ )
+ .build()
+
+ await runPipeline(pipeline, [createMessage('user-0'), createMessage('user-1')])
+ await runPipeline(pipeline, [createMessage('user-2')])
+
+ expect(seenTags).toEqual(['tag-0', 'tag-0', 'tag-1'])
+ expect(afterBatchCalls).toEqual([
+ { count: 2, tag: 'tag-0' },
+ { count: 1, tag: 'tag-1' },
+ ])
+ })
+
+ it('runs groups concurrently with sequential multi-step subpipelines within each group', async () => {
+ const log: string[] = []
+ let releaseFirstA!: () => void
+ const firstAGate = new Promise<void>((resolve) => (releaseFirstA = resolve))
+
+ const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
+ .parseHeaders()
+ .parseMessage()
+ .resolveTeam()
+ .concurrentlyPerGroup(
+ (value) => value.event.distinct_id,
+ (group) =>
+ group.sequentially((element) =>
+ element
+ .pipe(async function stepOne(input) {
+ // Group a's first event waits for group b to make progress:
+ // if groups ran sequentially instead of concurrently, this
+ // would deadlock and the test would fail by timeout.
+ if (input.event.distinct_id === 'user-a' && input.event.event === 'e0') {
+ await firstAGate
+ }
+ log.push(`one:${input.event.distinct_id}:${input.event.event}`)
+ return ok(input)
+ })
+ .pipe(function stepTwo(input) {
+ if (input.event.distinct_id === 'user-b') {
+ releaseFirstA()
+ }
+ log.push(`two:${input.event.distinct_id}:${input.event.event}`)
+ return Promise.resolve(ok(input))
+ })
+ )
+ )
+ .gather()
+ .pipeChunk(function afterGatherStep(values) {
+ log.push(`gathered:${values.length}`)
+ return Promise.resolve(values.map((value) => ok(value)))
+ })
+ .build()
+
+ const batches = await runPipeline(pipeline, [
+ createMessage('user-a', 'e0'),
+ createMessage('user-a', 'e1'),
+ createMessage('user-b', 'e2'),
+ createMessage('user-b', 'e3'),
+ ])
+
+ expect(okValues(batches)).toHaveLength(4)
+ // Within each group, every element runs through both steps before the next element.
+ expect(log.filter((line) => line.includes(':user-a:'))).toEqual([
+ 'one:user-a:e0',
+ 'two:user-a:e0',
+ 'one:user-a:e1',
+ 'two:user-a:e1',
+ ])
+ expect(log.filter((line) => line.includes(':user-b:'))).toEqual([
+ 'one:user-b:e2',
+ 'two:user-b:e2',
+ 'one:user-b:e3',
+ 'two:user-b:e3',
+ ])
+ // Group b completed its first element while group a was still gated.
+ expect(log.indexOf('two:user-b:e2')).toBeLessThan(log.indexOf('one:user-a:e0'))
+ expect(log[log.length - 1]).toBe('gathered:4')
+ })
+
+ it('applies compose subpipelines with their own sequential and chunk stages', async () => {
+ const log: string[] = []
+ const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
+ .parseHeaders()
+ .parseMessage()
+ .resolveTeam()
+ .pipe(teamLogStep(log, 'A'))
+ .compose((builder) =>
+ builder
+ .sequentially((element) => element.pipe(teamLogStep(log, 'X')).pipe(teamLogStep(log, 'Y')))
+ .pipeChunk(teamLogChunkStep(log, 'C'))
+ )
+ .pipe(teamLogStep(log, 'D'))
+ .build()
+
+ await runPipeline(pipeline, [createMessage('user-0'), createMessage('user-1')])
+
+ expect(log).toEqual([
+ 'A:user-0',
+ 'A:user-1',
+ 'X:user-0',
+ 'Y:user-0',
+ 'X:user-1',
+ 'Y:user-1',
+ 'C:[user-0,user-1]',
+ 'D:user-0',
+ 'D:user-1',
+ ])
+ })
+
+ it('applies the resolveTeam wrap decorator around team resolution', async () => {
+ const wrapObserved: string[] = []
+ const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
+ .parseHeaders()
+ .parseMessage()
+ .resolveTeam({
+ wrap: (step) => async (input) => {
+ const result = await step(input)
+ wrapObserved.push(
+ isOkResult(result) ? `ok:${result.value.team.id}` : `miss:${input.headers.distinct_id}`
+ )
+ return result
+ },
+ })
+ .build()
+
+ const batches = await runPipeline(pipeline, [
+ createMessage('user-0'),
+ createMessage('user-1', 'test_event', 'unknown-token'),
+ ])
+
+ expect(wrapObserved).toEqual(['ok:42', 'miss:user-1'])
+ const elements = batches.flatMap((batch) => batch.elements)
+ expect(isOkResult(elements[0].result)).toBe(true)
+ expect(isDropResult(elements[1].result)).toBe(true)
+ })
+
+ it('passes retry options through to chunk steps', async () => {
+ let attempts = 0
+ const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
+ .parseHeaders()
+ .parseMessage()
+ .resolveTeam()
+ .pipeChunk(
+ function flakyChunkStep(values) {
+ attempts++
+ if (attempts === 1) {
+ const transient = new Error('transient failure') as Error & { isRetriable: boolean }
+ transient.isRetriable = true
+ throw transient
+ }
+ return Promise.resolve(values.map((value) => ok(value)))
+ },
+ { retry: { tries: 2, sleepMs: 100, name: 'flaky_chunk' } }
+ )
+ .build()
+
+ const run = runPipeline(pipeline, [createMessage('user-0')])
+ await settle()
+
+ // The first attempt failed and the retry is parked on the fake
+ // backoff timer — the second attempt must not run before it fires.
+ expect(attempts).toBe(1)
+
+ await jest.runAllTimersAsync()
+ const batches = await run
+
+ expect(attempts).toBe(2)
+ expect(okValues(batches)).toHaveLength(1)
+ })
+
+ describe('compile-time type safety', () => {
+ // These assertions run at typecheck time, not at test time: each
+ // misuse sits under @ts-expect-error, so if a builder refactor loosens
+ // the stage constraints and a misuse starts compiling, tsc fails with
+ // an unused-directive error.
+ it('rejects stage misuse at compile time', () => {
+ const teamDependentStep = (input: { message: Message; headers: EventHeaders; team: Team }) =>
+ Promise.resolve(ok(input))
+ const bodyDependentStep = (input: { message: Message; headers: EventHeaders; event: IncomingEvent }) =>
+ Promise.resolve(ok(input))
+
+ const preTeam = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config).parseHeaders()
+
+ // @ts-expect-error team-dependent steps must not typecheck before .resolveTeam()
+ preTeam.pipe(teamDependentStep)
+
+ // @ts-expect-error body-dependent steps must not typecheck before .parseMessage()
+ preTeam.pipe(bodyDependentStep)
+
+ // @ts-expect-error .resolveTeam() requires the parsed body from .parseMessage()
+ preTeam.resolveTeam()
+
+ const teamStage = preTeam.parseMessage().resolveTeam()
+
+ // @ts-expect-error redirect outputs not declared in ROut must not typecheck
+ teamStage.pipe(function undeclaredRedirectStep(_input: MessageOnly) {
+ return Promise.resolve(redirect('nope', 'undeclared_output'))
+ })
+
+ const narrowed = teamStage.pipe(function narrowStep(input) {
+ return Promise.resolve(ok({ teamId: input.team.id }))
+ })
+
+ // @ts-expect-error steps must accept the previous step's output type
+ narrowed.pipe(teamDependentStep)
+
+ expect(narrowed).toBeDefined()
+ })
+ })
+})
diff --git a/nodejs/src/ingestion/common/common-ingestion-pipeline.ts b/nodejs/src/ingestion/common/common-ingestion-pipeline.ts
new file mode 100644
index 000000000000..5beee425d728
--- /dev/null
+++ b/nodejs/src/ingestion/common/common-ingestion-pipeline.ts
@@ -0,0 +1,475 @@
+import { Message } from 'node-rdkafka'
+
+import { DlqOutput, IngestionWarningsOutput } from '~/common/outputs'
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+import { PromiseScheduler } from '~/common/utils/promise-scheduler'
+import { TeamManager } from '~/common/utils/team-manager'
+import { ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'
+import {
+ AfterBatchInput,
+ AfterBatchOutput,
+ BatchingContext,
+ BatchingPipeline,
+ BeforeBatchInput,
+ BeforeBatchOutput,
+} from '~/ingestion/framework/batching-pipeline'
+import { newBatchingPipeline } from '~/ingestion/framework/builders'
+import { ChunkPipelineBuilder, GroupProcessingBuilder } from '~/ingestion/framework/builders/chunk-pipeline-builders'
+import { PipelineBuilder, StartPipelineBuilder } from '~/ingestion/framework/builders/pipeline-builders'
+import { GroupingFunction } from '~/ingestion/framework/concurrently-grouping-chunk-pipeline'
+import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'
+import { ok } from '~/ingestion/framework/results'
+import { RetryOptions } from '~/ingestion/framework/retry'
+import { ProcessingStep } from '~/ingestion/framework/steps'
+import { PluginEvent } from '~/plugin-scaffold'
+import { EventHeaders, IncomingEvent, Team } from '~/types'
+
+import { createParseHeadersStep, createParseKafkaMessageStep, createResolveTeamStep } from './steps/event-preprocessing'
+import { addTeamToContext } from './subpipelines/helpers'
+
+/**
+ * Common ingestion pipeline builder.
+ *
+ * Every Kafka-fed ingestion pipeline (analytics, AI, error tracking, heatmaps,
+ * client warnings, session replay) shares the same skeleton; only the steps in
+ * the middle vary. This builder owns the skeleton and reads as a flat recipe —
+ * the phase markers carry the structure:
+ *
+ * ```text
+ * beforeBatch hooks .beforeBatch(cb) (optional)
+ * messageAware
+ * parse headers .parseHeaders()
+ * header-only steps .pipe / .pipeChunk
+ * parse body .parseMessage()
+ * body steps .pipe
+ * resolve team, lift team into context .resolveTeam()
+ * team-aware processing .pipe / .pipeChunk / .gather /
+ * .concurrentlyPerGroup / .compose
+ * handleIngestionWarnings (automatic)
+ * handleResults (automatic)
+ * handleSideEffects (automatic)
+ * afterBatch hooks .afterBatch(cb) (optional)
+ * ```
+ *
+ * Consecutive `.pipe()` calls coalesce into one sequential per-element block;
+ * any chunk-level call (`.pipeChunk`, `.gather`, `.concurrentlyPerGroup`,
+ * `.compose`, a phase marker that is chunk-level) closes the block. Block
+ * boundaries therefore fall out of where the chunk operations sit, which is
+ * how the hand-written pipelines were already shaped.
+ *
+ * `.resolveTeam()` resolves the team, lifts it into the element context, and
+ * opens the team-aware scope: every step after it runs inside
+ * `handleIngestionWarnings`, so warnings (and warnings on dropped elements)
+ * route to the resolved team. The warning handler only covers that scope:
+ * warnings attached to non-OK results before `.resolveTeam()` are silently
+ * dropped (there is no team to route them to), so pre-team steps must attach
+ * warnings to OK results only. The stages are enforced by the type system —
+ * body steps don't typecheck before `.parseMessage()`, team-dependent steps
+ * not before `.resolveTeam()`. Redirect kinds are fixed up front via the
+ * `ROut` type parameter — the configured outputs must cover every redirect any
+ * step can produce.
+ */
+export interface CommonIngestionPipelineConfig<ROut extends string = never> {
+ teamManager: TeamManager
+ outputs: IngestionOutputs<IngestionWarningsOutput | DlqOutput | ROut>
+ promiseScheduler: PromiseScheduler
+ /** Maximum number of batches accepted concurrently. Defaults to the framework default. */
+ concurrentBatches?: number
+ /**
+ * Await side effects inline instead of scheduling them on the promise
+ * scheduler. Applies to element results and to the beforeBatch/afterBatch
+ * hooks alike — the built pipeline always handles its own side effects, so
+ * drivers never see them on `BatchResult.sideEffects`. Defaults to false.
+ */
+ awaitSideEffects?: boolean
+}
+
+/** Element type entering the per-batch sub-pipeline: input enriched by the beforeBatch hooks. */
+type BatchElement<TInput, CBatch> = TInput & CBatch
+
+/** Element context inside the per-batch sub-pipeline. */
+type BatchContext<TContext> = TContext & BatchingContext
+
+/** Element context after `.resolveTeam()`, once the team is lifted into it. */
+type TeamAwareContext<TContext> = BatchContext<TContext> & { team: Team }
+
+/** Output of `.resolveTeam()`: the parsed event with the resolved team attached. */
+type TeamResolved<T> = Omit<T & { event: IncomingEvent }, 'event'> & { event: PluginEvent; team: Team }
+
+export type BeforeBatchCallback<TInput, TContext, CBatch> = (
+ builder: StartPipelineBuilder<BeforeBatchInput<TInput, TContext>, Record<string, never>>
+) => PipelineBuilder<
+ BeforeBatchInput<TInput, TContext>,
+ BeforeBatchOutput<TInput, TContext, CBatch>,
+ Record<string, never>
+>
+
+export type AfterBatchCallback<TOutput, TContext, CBatch, ROut extends string> = (
+ builder: StartPipelineBuilder<AfterBatchInput<TOutput, BatchContext<TContext>, CBatch, ROut>, Record<string, never>>
+) => PipelineBuilder<
+ AfterBatchInput<TOutput, BatchContext<TContext>, CBatch, ROut>,
+ AfterBatchOutput<TOutput, BatchContext<TContext>, CBatch, ROut>,
+ Record<string, never>
+>
+
+/**
+ * A phase's accumulated content: a transform over the phase's chunk builder,
+ * from the phase's start element type `TStart` to the current element type,
+ * under the element context `C`. Each call extends the previous transform,
+ * so the skeleton is composed exactly once, at `.build()`.
+ */
+type ChainTransform<TStart, TCurrent, C, ROut extends string> = (
+ builder: ChunkPipelineBuilder<TStart, TStart, C, C>
+) => ChunkPipelineBuilder<TStart, TCurrent, C, C, ROut>
+
+/** The messageAware block before `.resolveTeam()`: runs under the batch context. */
+type SubpipelineTransform<TInput, TContext, CBatch, TOut, ROut extends string> = ChainTransform<
+ BatchElement<TInput, CBatch>,
+ TOut,
+ BatchContext<TContext>,
+ ROut
+>
+
+/**
+ * Coalesces consecutive per-element steps into one sequential block. `extend`
+ * appends a step to the open block (or opens one); `build` closes it into the
+ * committed chunk-level transform. The block's start type stays existential —
+ * it lives only in the closures — so stages don't carry it as a type parameter.
+ *
+ * Both builder phases share this mechanism and differ only in instantiation:
+ * the pre-team phase runs under the batch context, the team-aware phase under
+ * the team-lifted context (see the aliases below).
+ */
+interface Chain<TStart, C, ROut extends string, TCurrent> {
+ build(): ChainTransform<TStart, TCurrent, C, ROut>
+ extend<U, R2 extends ROut>(
+ step: ProcessingStep<TCurrent, U, R2>,
+ options?: { retry?: RetryOptions }
+ ): Chain<TStart, C, ROut, U>
+}
+
+function pendingChain<TStart, C, ROut extends string, TBlock, TCurrent>(
+ committed: ChainTransform<TStart, TBlock, C, ROut>,
+ pending: (start: StartPipelineBuilder<TBlock, C>) => PipelineBuilder<TBlock, TCurrent, C, ROut>
+): Chain<TStart, C, ROut, TCurrent> {
+ return {
+ build: () => (builder) => committed(builder).sequentially(pending),
+ extend: (step, options) => pendingChain(committed, (start) => pending(start).pipe(step, options)),
+ }
+}
+
+function committedChain<TStart, C, ROut extends string, TCurrent>(
+ committed: ChainTransform<TStart, TCurrent, C, ROut>
+): Chain<TStart, C, ROut, TCurrent> {
+ return {
+ build: () => committed,
+ extend: (step, options) => pendingChain(committed, (start) => start.pipe(step, options)),
+ }
+}
+
+/** Chain over the pre-team phase. */
+type PreTeamChain<TInput, TContext, ROut extends string, CBatch, TCurrent> = Chain<
+ BatchElement<TInput, CBatch>,
+ BatchContext<TContext>,
+ ROut,
+ TCurrent
+>
+
+/** Chain over the team-aware phase. */
+type TeamChain<TPost, TContext, ROut extends string, TCurrent> = Chain<
+ TPost,
+ TeamAwareContext<TContext>,
+ ROut,
+ TCurrent
+>
+
+export function newCommonIngestionPipeline<
+ TInput extends { message: Message },
+ TContext extends { message: Message },
+ ROut extends string = never,
+>(config: CommonIngestionPipelineConfig<ROut>): CommonIngestionPipelineBuilder<TInput, TContext, ROut> {
+ return new CommonIngestionPipelineBuilder(config)
+}
+
+export class CommonIngestionPipelineBuilder<
+ TInput extends { message: Message },
+ TContext extends { message: Message },
+ ROut extends string,
+> {
+ constructor(private readonly config: CommonIngestionPipelineConfig<ROut>) {}
+
+ /** Attach batch context (e.g. batch-scoped stores) before each batch is processed. */
+ beforeBatch<CBatch>(
+ callback: BeforeBatchCallback<TInput, TContext, CBatch>
+ ): CommonBatchHooksStage<TInput, TContext, ROut, CBatch> {
+ return new CommonBatchHooksStage(this.config, callback)
+ }
+
+ /** Skip batch context and go straight to header parsing. */
+ parseHeaders(): CommonPreTeamStage<
+ TInput,
+ TContext,
+ ROut,
+ Record<never, object>,
+ BatchElement<TInput, Record<never, object>> & { headers: EventHeaders }
+ > {
+ return this.beforeBatch<Record<never, object>>((builder) =>
+ builder.pipe(function passThroughBeforeBatch(input) {
+ return Promise.resolve(ok(input))
+ })
+ ).parseHeaders()
+ }
+}
+
+export class CommonBatchHooksStage<
+ TInput extends { message: Message },
+ TContext extends { message: Message },
+ ROut extends string,
+ CBatch,
+> {
+ constructor(
+ private readonly config: CommonIngestionPipelineConfig<ROut>,
+ private readonly beforeBatchCallback: BeforeBatchCallback<TInput, TContext, CBatch>
+ ) {}
+
+ /** Parse Kafka headers; after this, header-shaped steps can be piped. */
+ parseHeaders(): CommonPreTeamStage<
+ TInput,
+ TContext,
+ ROut,
+ CBatch,
+ BatchElement<TInput, CBatch> & { headers: EventHeaders }
+ > {
+ return new CommonPreTeamStage(
+ this.config,
+ this.beforeBatchCallback,
+ pendingChain<
+ BatchElement<TInput, CBatch>,
+ BatchContext<TContext>,
+ ROut,
+ BatchElement<TInput, CBatch>,
+ BatchElement<TInput, CBatch> & { headers: EventHeaders }
+ >(
+ (builder) => builder,
+ (start) => start.pipe(createParseHeadersStep())
+ )
+ )
+ }
+}
+
+export class CommonPreTeamStage<
+ TInput extends { message: Message },
+ TContext extends { message: Message },
+ ROut extends string,
+ CBatch,
+ TCurrent extends { message: Message; headers: EventHeaders },
+> {
+ constructor(
+ private readonly config: CommonIngestionPipelineConfig<ROut>,
+ private readonly beforeBatchCallback: BeforeBatchCallback<TInput, TContext, CBatch>,
+ private readonly chain: PreTeamChain<TInput, TContext, ROut, CBatch, TCurrent>
+ ) {}
+
+ /** Per-element step; consecutive pipes run in one sequential block. */
+ pipe<U extends { message: Message; headers: EventHeaders }, R2 extends ROut>(
+ step: ProcessingStep<TCurrent, U, R2>,
+ options?: { retry?: RetryOptions }
+ ): CommonPreTeamStage<TInput, TContext, ROut, CBatch, U> {
+ return new CommonPreTeamStage(this.config, this.beforeBatchCallback, this.chain.extend(step, options))
+ }
+
+ /** Chunk-level step (e.g. rate-limit-to-overflow); closes the open sequential block. */
+ pipeChunk<U extends { message: Message; headers: EventHeaders }, R2 extends ROut>(
+ step: ChunkProcessingStep<TCurrent, U, R2>,
+ options?: { retry?: RetryOptions }
+ ): CommonPreTeamStage<TInput, TContext, ROut, CBatch, U> {
+ const committed = this.chain.build()
+ return new CommonPreTeamStage(
+ this.config,
+ this.beforeBatchCallback,
+ committedChain((builder) => committed(builder).pipeChunk(step, options))
+ )
+ }
+
+ /** Parse the message body; after this, body-dependent steps can be piped. */
+ parseMessage(): CommonPreTeamStage<TInput, TContext, ROut, CBatch, TCurrent & { event: IncomingEvent }> {
+ return this.pipe(createParseKafkaMessageStep())
+ }
+
+ /**
+ * Resolve the team from the token, lift it into the element context, and
+ * open the team-aware scope: every step piped after this runs inside
+ * `handleIngestionWarnings`, with warnings routed to the resolved team.
+ *
+ * `options.wrap` decorates the team-resolution step while preserving its
+ * types — e.g. a topHog metrics wrapper.
+ */
+ resolveTeam(
+ this: CommonPreTeamStage<TInput, TContext, ROut, CBatch, TCurrent & { event: IncomingEvent }>,
+ options?: {
+ wrap?: (
+ step: ProcessingStep<TCurrent & { event: IncomingEvent }, TeamResolved<TCurrent>>
+ ) => ProcessingStep<TCurrent & { event: IncomingEvent }, TeamResolved<TCurrent>, ROut>
+ }
+ ): CommonTeamStage<TInput, TContext, ROut, CBatch, TeamResolved<TCurrent>, TeamResolved<TCurrent>> {
+ const step = createResolveTeamStep<TCurrent & { event: IncomingEvent }>(this.config.teamManager)
+ const resolved = this.chain.extend(options?.wrap ? options.wrap(step) : step)
+ return new CommonTeamStage(
+ this.config,
+ this.beforeBatchCallback,
+ resolved.build(),
+ committedChain((builder) => builder)
+ )
+ }
+}
+
+export class CommonTeamStage<
+ TInput extends { message: Message },
+ TContext extends { message: Message },
+ ROut extends string,
+ CBatch,
+ TPost extends { team: Team },
+ TCurrent,
+> {
+ constructor(
+ private readonly config: CommonIngestionPipelineConfig<ROut>,
+ private readonly beforeBatchCallback: BeforeBatchCallback<TInput, TContext, CBatch>,
+ private readonly preTeamTransform: SubpipelineTransform<TInput, TContext, CBatch, TPost, ROut>,
+ private readonly chain: TeamChain<TPost, TContext, ROut, TCurrent>
+ ) {}
+
+ /** Per-element step; consecutive pipes run in one sequential block. */
+ pipe<U, R2 extends ROut>(
+ step: ProcessingStep<TCurrent, U, R2>,
+ options?: { retry?: RetryOptions }
+ ): CommonTeamStage<TInput, TContext, ROut, CBatch, TPost, U> {
+ return new CommonTeamStage(
+ this.config,
+ this.beforeBatchCallback,
+ this.preTeamTransform,
+ this.chain.extend(step, options)
+ )
+ }
+
+ /** Chunk-level step; closes the open sequential block. */
+ pipeChunk<U, R2 extends ROut>(
+ step: ChunkProcessingStep<TCurrent, U, R2>,
+ options?: { retry?: RetryOptions }
+ ): CommonTeamStage<TInput, TContext, ROut, CBatch, TPost, U> {
+ const committed = this.chain.build()
+ return new CommonTeamStage(
+ this.config,
+ this.beforeBatchCallback,
+ this.preTeamTransform,
+ committedChain((builder) => committed(builder).pipeChunk(step, options))
+ )
+ }
+
+ /** Re-collect concurrent groups or streamed elements into one chunk. */
+ gather(): CommonTeamStage<TInput, TContext, ROut, CBatch, TPost, TCurrent> {
+ const committed = this.chain.build()
+ return new CommonTeamStage(
+ this.config,
+ this.beforeBatchCallback,
+ this.preTeamTransform,
+ committedChain((builder) => committed(builder).gather())
+ )
+ }
+
+ /**
+ * Group elements by key and process the groups concurrently; the callback
+ * configures how items within a group are processed (mirrors the framework
+ * method — within-group ordering stays visible at the call site).
+ */
+ concurrentlyPerGroup<TKey, U>(
+ groupingFn: GroupingFunction<TCurrent, TKey>,
+ callback: (
+ group: GroupProcessingBuilder<TPost, TCurrent, TeamAwareContext<TContext>, TeamAwareContext<TContext>, ROut>
+ ) => ChunkPipelineBuilder<TPost, U, TeamAwareContext<TContext>, TeamAwareContext<TContext>, ROut>,
+ options?: { maxConcurrency?: number }
+ ): CommonTeamStage<TInput, TContext, ROut, CBatch, TPost, U> {
+ const committed = this.chain.build()
+ return new CommonTeamStage(
+ this.config,
+ this.beforeBatchCallback,
+ this.preTeamTransform,
+ committedChain((builder) => committed(builder).concurrentlyPerGroup(groupingFn, callback, options))
+ )
+ }
+
+ /** Escape hatch: apply a subpipeline function (a transform over the chunk builder). */
+ compose<U>(
+ fn: (
+ builder: ChunkPipelineBuilder<TPost, TCurrent, TeamAwareContext<TContext>, TeamAwareContext<TContext>, ROut>
+ ) => ChunkPipelineBuilder<TPost, U, TeamAwareContext<TContext>, TeamAwareContext<TContext>, ROut>
+ ): CommonTeamStage<TInput, TContext, ROut, CBatch, TPost, U> {
+ const committed = this.chain.build()
+ return new CommonTeamStage(
+ this.config,
+ this.beforeBatchCallback,
+ this.preTeamTransform,
+ committedChain((builder) => fn(committed(builder)))
+ )
+ }
+
+ /** Flush steps that run once per batch after every element has a result. */
+ afterBatch(
+ callback: AfterBatchCallback<TCurrent, TContext, CBatch, ROut>
+ ): CommonBuildStage<TInput, TContext, ROut, CBatch, TCurrent> {
+ return new CommonBuildStage(this.config, this.beforeBatchCallback, this.completeTransform(), callback)
+ }
+
+ build(): BatchingPipeline<TInput, TCurrent, TContext, CBatch, BatchContext<TContext>, ROut> {
+ return new CommonBuildStage(this.config, this.beforeBatchCallback, this.completeTransform()).build()
+ }
+
+ private completeTransform(): SubpipelineTransform<TInput, TContext, CBatch, TCurrent, ROut> {
+ const { outputs } = this.config
+ const preTeam = this.preTeamTransform
+ const inner = this.chain.build()
+ return (builder) =>
+ preTeam(builder).filterMap(addTeamToContext, (b) =>
+ b.teamAware((teamAware) => inner(teamAware)).handleIngestionWarnings(outputs)
+ )
+ }
+}
+
+export class CommonBuildStage<
+ TInput extends { message: Message },
+ TContext extends { message: Message },
+ ROut extends string,
+ CBatch,
+ TFinal,
+> {
+ constructor(
+ private readonly config: CommonIngestionPipelineConfig<ROut>,
+ private readonly beforeBatchCallback: BeforeBatchCallback<TInput, TContext, CBatch>,
+ private readonly transform: SubpipelineTransform<TInput, TContext, CBatch, TFinal, ROut>,
+ private readonly afterBatchCallback?: AfterBatchCallback<TFinal, TContext, CBatch, ROut>
+ ) {}
+
+ build(): BatchingPipeline<TInput, TFinal, TContext, CBatch, BatchContext<TContext>, ROut> {
+ const { outputs, promiseScheduler, concurrentBatches, awaitSideEffects } = this.config
+ const pipelineConfig: PipelineConfig<ROut> = { outputs, promiseScheduler }
+ const sideEffectOptions = { await: awaitSideEffects ?? false }
+ const afterBatchCallback: AfterBatchCallback<TFinal, TContext, CBatch, ROut> =
+ this.afterBatchCallback ??
+ ((builder) =>
+ builder.pipe(function passThroughAfterBatch(input) {
+ return Promise.resolve(ok(input))
+ }))
+
+ // The hooks handle their own side effects, so nothing rides out on
+ // `BatchResult.sideEffects` and drivers only ever drain results.
+ return newBatchingPipeline<TInput, TFinal, TContext, CBatch, TContext, ROut>(
+ (builder) => this.beforeBatchCallback(builder).handleSideEffects(promiseScheduler, sideEffectOptions),
+ (batch) =>
+ batch
+ .messageAware((b) => this.transform(b))
+ .handleResults(pipelineConfig)
+ .handleSideEffects(promiseScheduler, sideEffectOptions),
+ (builder) => afterBatchCallback(builder).handleSideEffects(promiseScheduler, sideEffectOptions),
+ concurrentBatches === undefined ? undefined : { concurrentBatches }
+ )
+ }
+}
diff --git a/nodejs/src/ingestion/common/ingestion-consumer.ts b/nodejs/src/ingestion/common/ingestion-consumer.ts
index 70bc9e0886b8..1a20aa731726 100644
--- a/nodejs/src/ingestion/common/ingestion-consumer.ts
+++ b/nodejs/src/ingestion/common/ingestion-consumer.ts
@@ -31,9 +31,10 @@ export type PipelineFactory<S extends Record<string, object>> = (
/**
* 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.
+ * The pipeline schedules its side effects there; the common consumer
+ * pulls it from the container to await them after each batch. 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 }
@@ -150,11 +151,10 @@ class KafkaBatchHandler {
throw new Error(`Pipeline rejected batch: ${feedResult.reason}`)
}
+ // The pipeline handles its own side effects (scheduling them on the
+ // promise scheduler), so draining results is all that's left to do.
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()
}
diff --git a/nodejs/src/ingestion/common/steps/event-preprocessing/validate-event-schema.test.ts b/nodejs/src/ingestion/common/steps/event-preprocessing/validate-event-schema.test.ts
index 0fb3da868fd8..093258e853a3 100644
--- a/nodejs/src/ingestion/common/steps/event-preprocessing/validate-event-schema.test.ts
+++ b/nodejs/src/ingestion/common/steps/event-preprocessing/validate-event-schema.test.ts
@@ -343,9 +343,25 @@ describe('createValidateEventSchemaStep', () => {
} as unknown as Team,
})
+ it('should pass events that violate an enforced schema when enforcement is disabled', async () => {
+ const schemas: EventSchemaEnforcement[] = [
+ {
+ event_name: 'test_event',
+ required_properties: new Map([['required_prop', ['String']]]),
+ },
+ ]
+ const mockManager = createMockSchemaManager(schemas)
+ const step = createValidateEventSchemaStep(mockManager, false)
+ const input = createInput('test_event', {})
+
+ const result = await step(input)
+
+ expect(result).toEqual(ok(input))
+ })
+
it('should pass events when team has no enforced schemas', async () => {
const mockManager = createMockSchemaManager([])
- const step = createValidateEventSchemaStep(mockManager)
+ const step = createValidateEventSchemaStep(mockManager, true)
const input = createInput('test_event', { prop: 'value' })
const result = await step(input)
@@ -361,7 +377,7 @@ describe('createValidateEventSchemaStep', () => {
},
]
const mockManager = createMockSchemaManager(schemas)
- const step = createValidateEventSchemaStep(mockManager)
+ const step = createValidateEventSchemaStep(mockManager, true)
const input = createInput('test_event', {})
const result = await step(input)
@@ -377,7 +393,7 @@ describe('createValidateEventSchemaStep', () => {
},
]
const mockManager = createMockSchemaManager(schemas)
- const step = createValidateEventSchemaStep(mockManager)
+ const step = createValidateEventSchemaStep(mockManager, true)
const input = createInput('test_event', { required_prop: 'hello' })
const result = await step(input)
@@ -393,7 +409,7 @@ describe('createValidateEventSchemaStep', () => {
},
]
const mockManager = createMockSchemaManager(schemas)
- const step = createValidateEventSchemaStep(mockManager)
+ const step = createValidateEventSchemaStep(mockManager, true)
const input = createInput('test_event', {})
const result = await step(input)
@@ -432,7 +448,7 @@ describe('createValidateEventSchemaStep', () => {
},
]
const mockManager = createMockSchemaManager(schemas)
- const step = createValidateEventSchemaStep(mockManager)
+ const step = createValidateEventSchemaStep(mockManager, true)
const input = createInput('test_event', { numeric_prop: 'not-a-number' })
const result = await step(input)
@@ -474,7 +490,7 @@ describe('createValidateEventSchemaStep', () => {
},
]
const mockManager = createMockSchemaManager(schemas)
- const step = createValidateEventSchemaStep(mockManager)
+ const step = createValidateEventSchemaStep(mockManager, true)
const input = createInput('test_event', { field2: 'not-numeric' })
const result = await step(input)
@@ -493,7 +509,7 @@ describe('createValidateEventSchemaStep', () => {
},
]
const mockManager = createMockSchemaManager(schemas)
- const step = createValidateEventSchemaStep(mockManager)
+ const step = createValidateEventSchemaStep(mockManager, true)
const input = createInput('test_event', { prop: { nested: 'object' } })
const result = await step(input)
diff --git a/nodejs/src/ingestion/common/steps/event-preprocessing/validate-event-schema.ts b/nodejs/src/ingestion/common/steps/event-preprocessing/validate-event-schema.ts
index 33e603fbbe34..3b923f4e1bbc 100644
--- a/nodejs/src/ingestion/common/steps/event-preprocessing/validate-event-schema.ts
+++ b/nodejs/src/ingestion/common/steps/event-preprocessing/validate-event-schema.ts
@@ -106,13 +106,21 @@ export function validateEventAgainstSchema(
/**
* Creates a processing step that validates events against enforced schemas.
* Events that fail validation are dropped and an ingestion warning is emitted.
+ * When `enabled` is false the step passes every event through untouched, so
+ * pipelines can pipe it unconditionally.
*
* @param schemaManager - Manager for fetching enforced schemas (uses caching internally)
+ * @param enabled - Schema enforcement opt-in; when false the step is a no-op
*/
export function createValidateEventSchemaStep<T extends { event: PipelineEvent; team: Team }>(
- schemaManager: EventSchemaEnforcementManager
+ schemaManager: EventSchemaEnforcementManager,
+ enabled: boolean
): ProcessingStep<T, T> {
return async function validateEventSchemaStep(input) {
+ if (!enabled) {
+ return ok(input)
+ }
+
const { event, team } = input
const enforcedSchemas = await schemaManager.getSchemas(team.id)
diff --git a/nodejs/src/ingestion/framework/builders/pipeline-builders.ts b/nodejs/src/ingestion/framework/builders/pipeline-builders.ts
index c312094fa585..0130265fb0e2 100644
--- a/nodejs/src/ingestion/framework/builders/pipeline-builders.ts
+++ b/nodejs/src/ingestion/framework/builders/pipeline-builders.ts
@@ -1,6 +1,11 @@
import { BranchDecisionFn, BranchingPipeline } from '~/ingestion/framework/branching-pipeline'
import { Pipeline } from '~/ingestion/framework/pipeline.interface'
import { RetryOptions, withStepRetry } from '~/ingestion/framework/retry'
+import {
+ PromiseSchedulerInterface,
+ SideEffectHandlingConfig,
+ SideEffectHandlingProcessor,
+} from '~/ingestion/framework/side-effect-handling-pipeline'
import { StartPipeline } from '~/ingestion/framework/start-pipeline'
import { StepPipeline } from '~/ingestion/framework/step-pipeline'
import { ProcessingStep } from '~/ingestion/framework/steps'
@@ -54,6 +59,18 @@ export class PipelineBuilder<TInput, TOutput, C, R extends string = never> {
return new PipelineBuilder(finalBuilder.build())
}
+ /**
+ * Schedule (or await) the side effects carried by this pipeline's results
+ * and clear them, so downstream consumers never have to drain them.
+ * Mirrors `ChunkPipelineBuilder.handleSideEffects`.
+ */
+ handleSideEffects(
+ promiseScheduler: PromiseSchedulerInterface,
+ options: SideEffectHandlingConfig
+ ): PipelineBuilder<TInput, TOutput, C, R> {
+ return new PipelineBuilder(new SideEffectHandlingProcessor(this.pipeline, promiseScheduler, options))
+ }
+
build(): Pipeline<TInput, TOutput, C, R> {
return this.pipeline
}
diff --git a/nodejs/src/ingestion/framework/side-effect-handling-pipeline.ts b/nodejs/src/ingestion/framework/side-effect-handling-pipeline.ts
index 041b4db0789a..ef5dcbf3dbc2 100644
--- a/nodejs/src/ingestion/framework/side-effect-handling-pipeline.ts
+++ b/nodejs/src/ingestion/framework/side-effect-handling-pipeline.ts
@@ -1,5 +1,6 @@
import { ChunkPipeline, ChunkPipelineResultWithContext, OkResultWithContext } from './chunk-pipeline.interface'
import { sideEffectResultCounter } from './metrics'
+import { Pipeline, PipelineResultWithContext } from './pipeline.interface'
export interface PromiseSchedulerInterface {
schedule<T>(promise: Promise<T>): Promise<T>
@@ -63,3 +64,44 @@ export class SideEffectHandlingPipeline<TInput, TOutput, CInput, COutput = CInpu
}))
}
}
+
+/**
+ * Single-item counterpart of {@link SideEffectHandlingPipeline}: wraps a
+ * {@link Pipeline} and schedules (or awaits) the side effects its results
+ * carry, then clears them. Lets simple pipelines — like the batching
+ * before/afterBatch hooks — handle their own side effects instead of leaving
+ * them for the driver to drain.
+ */
+export class SideEffectHandlingProcessor<TInput, TOutput, C, R extends string = never>
+ implements Pipeline<TInput, TOutput, C, R>
+{
+ constructor(
+ private subPipeline: Pipeline<TInput, TOutput, C, R>,
+ private promiseScheduler: PromiseSchedulerInterface,
+ private config: SideEffectHandlingConfig = { await: false }
+ ) {}
+
+ async process(input: OkResultWithContext<TInput, C>): Promise<PipelineResultWithContext<TOutput, C, R>> {
+ const resultWithContext = await this.subPipeline.process(input)
+ const sideEffects = resultWithContext.context.sideEffects
+
+ if (sideEffects.length > 0) {
+ if (this.config.await) {
+ const settledResults = await Promise.allSettled(sideEffects)
+ settledResults.forEach((result) => {
+ sideEffectResultCounter.labels(result.status === 'fulfilled' ? 'ok' : 'error').inc()
+ })
+ } else {
+ sideEffects.forEach((promise) => void this.promiseScheduler.schedule(promise))
+ }
+ }
+
+ return {
+ result: resultWithContext.result,
+ context: {
+ ...resultWithContext.context,
+ sideEffects: [],
+ },
+ }
+ }
+}
diff --git a/nodejs/src/ingestion/framework/side-effect-handling-processor.test.ts b/nodejs/src/ingestion/framework/side-effect-handling-processor.test.ts
new file mode 100644
index 000000000000..67932ea004c2
--- /dev/null
+++ b/nodejs/src/ingestion/framework/side-effect-handling-processor.test.ts
@@ -0,0 +1,57 @@
+import { Pipeline } from './pipeline.interface'
+import { ok } from './results'
+import { PromiseSchedulerInterface, SideEffectHandlingProcessor } from './side-effect-handling-pipeline'
+
+describe('SideEffectHandlingProcessor', () => {
+ let mockPromiseScheduler: jest.Mocked<PromiseSchedulerInterface>
+
+ const createSubPipeline = (
+ sideEffects: Promise<unknown>[]
+ ): Pipeline<{ value: number }, { value: number }, Record<never, never>> => ({
+ process: (input) =>
+ Promise.resolve({
+ result: ok(input.result.value),
+ context: { ...input.context, sideEffects },
+ }),
+ })
+
+ const processInput = { result: ok({ value: 1 }), context: { sideEffects: [], warnings: [] } }
+
+ beforeEach(() => {
+ mockPromiseScheduler = {
+ schedule: jest.fn().mockImplementation((promise) => promise),
+ }
+ })
+
+ it('should schedule side effects and clear them from the result', async () => {
+ const sideEffect = Promise.resolve('side effect')
+ const processor = new SideEffectHandlingProcessor(createSubPipeline([sideEffect]), mockPromiseScheduler, {
+ await: false,
+ })
+
+ const result = await processor.process(processInput)
+
+ expect(mockPromiseScheduler.schedule).toHaveBeenCalledWith(sideEffect)
+ expect(result.context.sideEffects).toEqual([])
+ expect(result.result).toEqual(ok({ value: 1 }))
+ })
+
+ it('should await side effects inline when configured', async () => {
+ let sideEffectResolved = false
+ const sideEffect = new Promise<void>((resolve) => {
+ setTimeout(() => {
+ sideEffectResolved = true
+ resolve()
+ }, 10)
+ })
+ const processor = new SideEffectHandlingProcessor(createSubPipeline([sideEffect]), mockPromiseScheduler, {
+ await: true,
+ })
+
+ const result = await processor.process(processInput)
+
+ expect(sideEffectResolved).toBe(true)
+ expect(mockPromiseScheduler.schedule).not.toHaveBeenCalled()
+ expect(result.context.sideEffects).toEqual([])
+ })
+})
diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.ts
index 46e8f17e0a47..4503fc9fd82f 100644
--- a/nodejs/src/ingestion/ingestion-consumer.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.ts
@@ -438,12 +438,10 @@ export class IngestionConsumer {
throw new Error(`Pipeline rejected batch: ${feedResult.reason}`)
}
- // Drain the pipeline, scheduling batch-level side effects
+ // The pipeline handles its own side effects (scheduling them on the
+ // promise scheduler), so draining results is all that's left to do.
let result = await this.joinedPipeline.next()
while (result !== null) {
- for (const sideEffect of result.sideEffects ?? []) {
- void this.promiseScheduler.schedule(sideEffect)
- }
result = await this.joinedPipeline.next()
}
}
diff --git a/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts b/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts
index 56be3e8bc9b9..5d1ed7879f72 100644
--- a/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts
@@ -83,9 +83,8 @@ describe('AiIngestionPipeline', () => {
await pipeline.feed(batch)
let result = await pipeline.next()
while (result !== null) {
- for (const sideEffect of result.sideEffects ?? []) {
- void promiseScheduler.schedule(sideEffect)
- }
+ // The pipeline handles its own side effects; none may leak to drivers.
+ expect(result.sideEffects ?? []).toEqual([])
result = await pipeline.next()
}
await promiseScheduler.waitForAll()
diff --git a/nodejs/src/ingestion/pipelines/ai/pipeline.ts b/nodejs/src/ingestion/pipelines/ai/pipeline.ts
index 3804c490104f..e967d3476a7d 100644
--- a/nodejs/src/ingestion/pipelines/ai/pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/ai/pipeline.ts
@@ -9,12 +9,12 @@ import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion
import { EventSchemaEnforcementManager } from '~/common/utils/event-schema-enforcement-manager'
import { PromiseScheduler } from '~/common/utils/promise-scheduler'
import { TeamManager } from '~/common/utils/team-manager'
+import { newCommonIngestionPipeline } from '~/ingestion/common/common-ingestion-pipeline'
import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'
import { EventFilterManager } from '~/ingestion/common/event-filters'
import { OverflowRedirectService } from '~/ingestion/common/overflow-redirect/overflow-redirect-service'
import { createAllowEventsStep } from '~/ingestion/common/steps/allow-events'
import {
- EventFiltersBatchContext,
createApplyEventFiltersStep,
createEventFiltersBatchAppMetricsBeforeBatchStep,
createFlushEventFiltersBatchAppMetricsStep,
@@ -25,9 +25,6 @@ import {
createApplyPersonProcessingRestrictionsStep,
createOnlyCookielessRateLimitToOverflowStep,
createOverflowLaneTTLRefreshStep,
- createParseHeadersStep,
- createParseKafkaMessageStep,
- createResolveTeamStep,
createSkipCookielessRateLimitToOverflowStep,
createValidateAiEventTokensStep,
createValidateEventMetadataStep,
@@ -37,7 +34,7 @@ import {
} from '~/ingestion/common/steps/event-preprocessing'
import { createCreateEventStep } from '~/ingestion/common/steps/event-processing/create-event-step'
import { createDropOldEventsStep } from '~/ingestion/common/steps/event-processing/drop-old-events-step'
-import { EmitEventStepOutput, createEmitEventStep } from '~/ingestion/common/steps/event-processing/emit-event-step'
+import { createEmitEventStep } from '~/ingestion/common/steps/event-processing/emit-event-step'
import { createFetchPersonChunkStep } from '~/ingestion/common/steps/event-processing/fetch-person-chunk-step'
import { createFlushHogTransformerStep } from '~/ingestion/common/steps/event-processing/flush-hog-transformer-step'
import { createHogTransformEventStep } from '~/ingestion/common/steps/event-processing/hog-transform-event-step'
@@ -50,11 +47,8 @@ import { createSplitAiEventsStep } from '~/ingestion/common/steps/event-processi
import { createStripPersonUpdatePropertiesStep } from '~/ingestion/common/steps/event-processing/strip-person-update-properties-step'
import { createRecordIngestionLagStep } from '~/ingestion/common/steps/record-ingestion-lag'
import { AI_EVENT_TYPES } from '~/ingestion/common/subpipelines/ai-event-types'
-import { addTeamToContext } from '~/ingestion/common/subpipelines/helpers'
import { IngestionOverflowMode } from '~/ingestion/config'
-import { newBatchingPipeline } from '~/ingestion/framework/builders'
import { TopHogWrapper, sum, sumOk, sumResult } from '~/ingestion/framework/extensions/tophog'
-import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'
import { isDropResult } from '~/ingestion/framework/results'
import { AiEventOutput, EVENTS_OUTPUT, EventOutput } from './outputs'
@@ -131,177 +125,124 @@ export function createAiIngestionPipeline<
topHog,
} = config
- const pipelineConfig: PipelineConfig<OverflowOutput> = {
- outputs,
- promiseScheduler,
- }
-
- return newBatchingPipeline<
- TInput,
- EmitEventStepOutput,
- TContext,
- EventFiltersBatchContext,
- TContext,
- OverflowOutput
- >(
- (beforeBatch) => beforeBatch.pipe(createEventFiltersBatchAppMetricsBeforeBatchStep(outputs)),
- (batch) =>
- batch
- .messageAware((b) =>
- b
- // Header-only steps: parse headers, allow only AI events, apply token restrictions.
- .sequentially((b) =>
- b
- .pipe(createParseHeadersStep())
- .pipe(createAllowEventsStep([...AI_EVENT_TYPES]))
- .pipe(
- createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {
- overflowMode,
- preservePartitionLocality,
- })
- )
- )
- // Rate-limit non-cookieless events to overflow before parsing the body.
- // Cookieless events pass through and are handled post-cookieless below.
- .pipeChunk(
- createSkipCookielessRateLimitToOverflowStep(
- preservePartitionLocality,
- overflowRedirectService
- )
- )
- // Body parse, team resolution, and AI token validation.
- .sequentially((b) =>
- b
- .pipe(createParseKafkaMessageStep())
- .pipe(createResolveTeamStep(teamManager))
- .pipe(createValidateHistoricalMigrationStep())
- .pipe(createValidateAiEventTokensStep())
- )
- .filterMap(addTeamToContext, (b) =>
- b
- .teamAware((b) =>
- b
- .sequentially((b) => {
- const validated = b
- .pipe(createValidateEventMetadataStep())
- .pipe(createValidateEventPropertiesStep())
- // Schema enforcement is opt-in (same as analytics); only
- // applied when enabled so AI events match that path.
- const schemaChecked = eventSchemaEnforcementEnabled
- ? validated.pipe(
- createValidateEventSchemaStep(eventSchemaEnforcementManager)
- )
- : validated
- return schemaChecked
- .pipe(
- createApplyPersonProcessingRestrictionsStep(
- eventIngestionRestrictionManager
- )
- )
- .pipe(createDropOldEventsStep())
- .pipe(createApplyEventFiltersStep(eventFilterManager))
- })
- // Cookieless processing rewrites distinct_id; person fetch keys on the
- // final distinct_id, so it must run after this batch step.
- .gather()
- .pipeChunk(createApplyCookielessProcessingStep(cookielessManager))
- .pipeChunk(
- createOnlyCookielessRateLimitToOverflowStep(
- preservePartitionLocality,
- overflowRedirectService
- )
- )
- .pipeChunk(createOverflowLaneTTLRefreshStep(overflowLaneTTLRefreshService))
- // Read-only batch person fetch (no person writes).
- .pipeChunk(createFetchPersonChunkStep(personRepository))
- // Prefetch hog functions for the batch's teams so the transformer
- // honors Hog watcher's disabled-function state (mirrors analytics).
- .pipeChunk(
- createPrefetchHogFunctionsStep(hogTransformer, cdpHogWatcherSampleRate)
- )
- // Per-event chain. Retry is applied per step: only the steps
- // that do transient-failure-prone I/O (hog transform, group-type
- // fetch, emit) retry, matching the analytics per-distinct-id path.
- .sequentially((b) =>
- b
- .pipe(createNormalizeProcessPersonFlagStep())
- .pipe(
- topHog(createHogTransformEventStep(hogTransformer), [
- sumOk(
- 'transformations_run',
- (output) => ({ team_id: String(output.team.id) }),
- (output) => output.transformationsRun
- ),
- sumOk(
- 'transformations_run_per_partition',
- (output, input) => ({
- team_id: String(output.team.id),
- partition: String(input.message.partition),
- }),
- (output) => output.transformationsRun
- ),
- sumResult(
- 'events_dropped_by_transformation',
- (_result, input) => ({
- team_id: String(input.team.id),
- }),
- (result) => (isDropResult(result) ? 1 : 0)
- ),
- sumResult(
- 'events_dropped_by_transformation_per_partition',
- (_result, input) => ({
- team_id: String(input.team.id),
- partition: String(input.message.partition),
- }),
- (result) => (isDropResult(result) ? 1 : 0)
- ),
- ]),
- { retry: { tries: 5, sleepMs: 100, name: 'hog_transform_event' } }
- )
- .pipe(createNormalizeEventStep())
- .pipe(createProcessAiEventStep())
- // Read-only: drop person-update props so they don't
- // leak into person_properties (person is never written).
- .pipe(createStripPersonUpdatePropertiesStep())
- .pipe(createPrepareEventStep())
- // Read-only group-type resolution (no new group types created).
- .pipe(createReadOnlyProcessGroupsStep(groupTypeManager), {
- retry: { tries: 5, sleepMs: 100, name: 'readonly_process_groups' },
- })
- .pipe(createCreateEventStep(EVENTS_OUTPUT))
- // Double-write to events + ai_events outputs.
- .pipe(createSplitAiEventsStep())
- .pipe(
- topHog(createEmitEventStep({ outputs }), [
- sum(
- 'emitted_events',
- (input) => ({ team_id: String(input.teamId) }),
- (input) => input.eventsToEmit.length
- ),
- sum(
- 'emitted_events_per_partition',
- (input) => ({
- team_id: String(input.teamId),
- partition: String(input.message.partition),
- }),
- (input) => input.eventsToEmit.length
- ),
- ]),
- { retry: { tries: 5, sleepMs: 100, name: 'emit_event' } }
- )
- .pipe(createRecordIngestionLagStep())
- )
- )
- .handleIngestionWarnings(outputs)
- )
- )
- .handleResults(pipelineConfig)
- .handleSideEffects(promiseScheduler, { await: false }),
- (afterBatch) =>
- afterBatch
- .pipe(createFlushEventFiltersBatchAppMetricsStep())
- // Drain hog transformer invocation results once per batch.
- .pipe(createFlushHogTransformerStep(hogTransformer)),
- { concurrentBatches }
+ return (
+ newCommonIngestionPipeline<TInput, TContext, OverflowOutput>({
+ teamManager,
+ outputs,
+ promiseScheduler,
+ concurrentBatches,
+ })
+ .beforeBatch((b) => b.pipe(createEventFiltersBatchAppMetricsBeforeBatchStep(outputs)))
+ // Header-only steps: allow only AI events, apply token restrictions.
+ .parseHeaders()
+ .pipe(createAllowEventsStep([...AI_EVENT_TYPES]))
+ .pipe(
+ createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {
+ overflowMode,
+ preservePartitionLocality,
+ })
+ )
+ // Rate-limit non-cookieless events to overflow before parsing the body.
+ // Cookieless events pass through and are handled post-cookieless below.
+ .pipeChunk(createSkipCookielessRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService))
+ .parseMessage()
+ .resolveTeam()
+ .pipe(createValidateHistoricalMigrationStep())
+ .pipe(createValidateAiEventTokensStep())
+ .pipe(createValidateEventMetadataStep())
+ .pipe(createValidateEventPropertiesStep())
+ // Schema enforcement is opt-in (same as analytics); the step passes
+ // events through when disabled.
+ .pipe(createValidateEventSchemaStep(eventSchemaEnforcementManager, eventSchemaEnforcementEnabled))
+ .pipe(createApplyPersonProcessingRestrictionsStep(eventIngestionRestrictionManager))
+ .pipe(createDropOldEventsStep())
+ .pipe(createApplyEventFiltersStep(eventFilterManager))
+ // Cookieless processing rewrites distinct_id; person fetch keys on the
+ // final distinct_id, so it must run after this batch step.
+ .gather()
+ .pipeChunk(createApplyCookielessProcessingStep(cookielessManager))
+ .pipeChunk(createOnlyCookielessRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService))
+ .pipeChunk(createOverflowLaneTTLRefreshStep(overflowLaneTTLRefreshService))
+ // Read-only batch person fetch (no person writes).
+ .pipeChunk(createFetchPersonChunkStep(personRepository))
+ // Prefetch hog functions for the batch's teams so the transformer
+ // honors Hog watcher's disabled-function state (mirrors analytics).
+ .pipeChunk(createPrefetchHogFunctionsStep(hogTransformer, cdpHogWatcherSampleRate))
+ // Per-event chain. Retry is applied per step: only the steps
+ // that do transient-failure-prone I/O (hog transform, group-type
+ // fetch, emit) retry, matching the analytics per-distinct-id path.
+ .pipe(createNormalizeProcessPersonFlagStep())
+ .pipe(
+ topHog(createHogTransformEventStep(hogTransformer), [
+ sumOk(
+ 'transformations_run',
+ (output) => ({ team_id: String(output.team.id) }),
+ (output) => output.transformationsRun
+ ),
+ sumOk(
+ 'transformations_run_per_partition',
+ (output, input) => ({
+ team_id: String(output.team.id),
+ partition: String(input.message.partition),
+ }),
+ (output) => output.transformationsRun
+ ),
+ sumResult(
+ 'events_dropped_by_transformation',
+ (_result, input) => ({
+ team_id: String(input.team.id),
+ }),
+ (result) => (isDropResult(result) ? 1 : 0)
+ ),
+ sumResult(
+ 'events_dropped_by_transformation_per_partition',
+ (_result, input) => ({
+ team_id: String(input.team.id),
+ partition: String(input.message.partition),
+ }),
+ (result) => (isDropResult(result) ? 1 : 0)
+ ),
+ ]),
+ { retry: { tries: 5, sleepMs: 100, name: 'hog_transform_event' } }
+ )
+ .pipe(createNormalizeEventStep())
+ .pipe(createProcessAiEventStep())
+ // Read-only: drop person-update props so they don't
+ // leak into person_properties (person is never written).
+ .pipe(createStripPersonUpdatePropertiesStep())
+ .pipe(createPrepareEventStep())
+ // Read-only group-type resolution (no new group types created).
+ .pipe(createReadOnlyProcessGroupsStep(groupTypeManager), {
+ retry: { tries: 5, sleepMs: 100, name: 'readonly_process_groups' },
+ })
+ .pipe(createCreateEventStep(EVENTS_OUTPUT))
+ // Double-write to events + ai_events outputs.
+ .pipe(createSplitAiEventsStep())
+ .pipe(
+ topHog(createEmitEventStep({ outputs }), [
+ sum(
+ 'emitted_events',
+ (input) => ({ team_id: String(input.teamId) }),
+ (input) => input.eventsToEmit.length
+ ),
+ sum(
+ 'emitted_events_per_partition',
+ (input) => ({
+ team_id: String(input.teamId),
+ partition: String(input.message.partition),
+ }),
+ (input) => input.eventsToEmit.length
+ ),
+ ]),
+ { retry: { tries: 5, sleepMs: 100, name: 'emit_event' } }
+ )
+ .pipe(createRecordIngestionLagStep())
+ .afterBatch((b) =>
+ b
+ .pipe(createFlushEventFiltersBatchAppMetricsStep())
+ // Drain hog transformer invocation results once per batch.
+ .pipe(createFlushHogTransformerStep(hogTransformer))
+ )
+ .build()
)
}
diff --git a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
index 0ad258d4736e..25649d0e3a6c 100644
--- a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
@@ -8,6 +8,7 @@ import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion
import { EventSchemaEnforcementManager } from '~/common/utils/event-schema-enforcement-manager'
import { PromiseScheduler } from '~/common/utils/promise-scheduler'
import { TeamManager } from '~/common/utils/team-manager'
+import { newCommonIngestionPipeline } from '~/ingestion/common/common-ingestion-pipeline'
import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'
import { EventFilterManager } from '~/ingestion/common/event-filters'
import { FeatureFlagCalledDedupService } from '~/ingestion/common/feature-flag-called-dedup/feature-flag-called-dedup-service'
@@ -16,39 +17,24 @@ import { OverflowRedirectService } from '~/ingestion/common/overflow-redirect/ov
import { PersonsStore } from '~/ingestion/common/persons/persons-store'
import { createDenyEventsStep } from '~/ingestion/common/steps/deny-events'
import {
- EventFiltersBatchContext,
createEventFiltersBatchAppMetricsBeforeBatchStep,
createFlushEventFiltersBatchAppMetricsStep,
} from '~/ingestion/common/steps/event-filters-steps'
import {
createApplyEventRestrictionsStep,
createEnrichSurveyPersonPropertiesStep,
- createParseHeadersStep,
- createParseKafkaMessageStep,
- createResolveTeamStep,
createSkipCookielessRateLimitToOverflowStep,
createValidateAiEventTokensStep,
createValidateHistoricalMigrationStep,
} from '~/ingestion/common/steps/event-preprocessing'
-import { EmitEventStepOutput } from '~/ingestion/common/steps/event-processing/emit-event-step'
import { EventPipelineRunnerOptions } from '~/ingestion/common/steps/event-processing/event-pipeline-options'
import { createFlushBatchStoresStep } from '~/ingestion/common/steps/event-processing/flush-batch-stores-step'
import { createFlushHogTransformerStep } from '~/ingestion/common/steps/event-processing/flush-hog-transformer-step'
-import {
- GroupStoreBatchContext,
- createGroupStoreBeforeBatchStep,
-} from '~/ingestion/common/steps/group-store-batch-step'
-import {
- PersonsStoreBatchContext,
- createPersonsStoreBeforeBatchStep,
-} from '~/ingestion/common/steps/persons-store-batch-step'
+import { createGroupStoreBeforeBatchStep } from '~/ingestion/common/steps/group-store-batch-step'
+import { createPersonsStoreBeforeBatchStep } from '~/ingestion/common/steps/persons-store-batch-step'
import { AiEventSubpipelineFactory } from '~/ingestion/common/subpipelines/ai-subpipeline.contract'
import { IngestionOverflowMode } from '~/ingestion/config'
-import { newBatchingPipeline } from '~/ingestion/framework/builders'
import { TopHogRegistry, createTopHogWrapper } from '~/ingestion/framework/extensions/tophog'
-import { OkResultWithContext } from '~/ingestion/framework/pipeline.interface'
-import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'
-import { Team } from '~/types'
import {
AiEventOutput,
@@ -117,8 +103,6 @@ export interface JoinedIngestionPipelineDeps {
topHog: TopHogRegistry
}
-type IngestionBatchContext = EventFiltersBatchContext & PersonsStoreBatchContext & GroupStoreBatchContext
-
export interface JoinedIngestionPipelineInput {
message: Message
}
@@ -127,18 +111,6 @@ export interface JoinedIngestionPipelineContext {
message: Message
}
-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,
- },
- }
-}
-
function getTokenAndDistinctId(input: PerDistinctIdPipelineInput): string {
const token = input.headers.token ?? ''
const distinctId = input.event.distinct_id ?? ''
@@ -181,11 +153,6 @@ export function createJoinedIngestionPipeline<
const topHogWrapper = createTopHogWrapper(topHog)
- const pipelineConfig: PipelineConfig<OverflowOutput | AsyncOutput> = {
- outputs,
- promiseScheduler,
- }
-
const postTeamConfig: PostTeamPreprocessingSubpipelineConfig = {
eventFilterManager,
eventIngestionRestrictionManager,
@@ -214,83 +181,57 @@ export function createJoinedIngestionPipeline<
topHog: topHogWrapper,
}
- return newBatchingPipeline<
- TInput,
- EmitEventStepOutput,
- TContext,
- IngestionBatchContext,
- TContext,
- OverflowOutput | AsyncOutput
- >(
- (beforeBatch) =>
- beforeBatch
- .pipe(createEventFiltersBatchAppMetricsBeforeBatchStep(outputs))
- .pipe(createPersonsStoreBeforeBatchStep(personsStore))
- .pipe(createGroupStoreBeforeBatchStep(groupStore)),
- (batch) =>
- batch
- .messageAware((b) =>
- b
- // 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(createDenyEventsStep(['$exception', '$$client_ingestion_warning', '$$heatmap']))
- .pipe(
- createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {
- overflowMode,
- preservePartitionLocality,
- })
- )
- )
- // Rate-limit non-cookieless events to overflow before parsing the body.
- // Cookieless events (headers.distinct_id === sentinel) pass through and are
- // handled by the matching only-cookieless step in post-team, which keys on
- // the hashed distinct_id assigned by the cookieless step.
- .pipeChunk(
- createSkipCookielessRateLimitToOverflowStep(
- preservePartitionLocality,
- overflowRedirectService
- )
- )
- // Body parse and team resolution. Anything that needs the parsed event lives here.
- .sequentially((b) =>
- b
- .pipe(createParseKafkaMessageStep())
- .pipe(createResolveTeamStep(teamManager))
- .pipe(createValidateHistoricalMigrationStep())
- .pipe(createValidateAiEventTokensStep())
- .pipe(createEnrichSurveyPersonPropertiesStep())
- )
- .filterMap(addTeamToContext, (b) =>
- b
- .teamAware((b) =>
- createPostTeamPreprocessingSubpipeline(b, postTeamConfig)
- // Group by token:distinctId and process each group concurrently.
- // Events within each group are processed sequentially.
- .concurrentlyPerGroup(getTokenAndDistinctId, (group) =>
- group.sequentially((event) =>
- createPerDistinctIdPipeline(event, perEventConfig)
- )
- )
- )
- .handleIngestionWarnings(outputs)
- )
- )
- .handleResults(pipelineConfig)
- .handleSideEffects(promiseScheduler, { await: false }),
- (afterBatch) =>
- afterBatch
- .pipe(createFlushBatchStoresStep({ personsStore, groupStore, outputs }))
- .pipe(createFlushEventFiltersBatchAppMetricsStep())
- .pipe(createFlushHogTransformerStep(hogTransformer)),
- // Batch stores are singleton persistent caches, but each batch receives a
- // batch-bound view so entries can be reference-counted and released after
- // that batch's flush lifecycle completes. The Rust consumer's per-worker
- // Semaphore caps in-flight batches at the same value
- // (INGESTION_WORKER_CONCURRENT_BATCHES); divergence shows up as HTTP 503s
- // in `ingestion_api_batch_capacity_rejections_total`.
- { concurrentBatches }
+ return (
+ newCommonIngestionPipeline<TInput, TContext, OverflowOutput | AsyncOutput>({
+ teamManager,
+ outputs,
+ promiseScheduler,
+ // Batch stores are singleton persistent caches, but each batch receives a
+ // batch-bound view so entries can be reference-counted and released after
+ // that batch's flush lifecycle completes. The Rust consumer's per-worker
+ // Semaphore caps in-flight batches at the same value
+ // (INGESTION_WORKER_CONCURRENT_BATCHES); divergence shows up as HTTP 503s
+ // in `ingestion_api_batch_capacity_rejections_total`.
+ concurrentBatches,
+ })
+ .beforeBatch((beforeBatch) =>
+ beforeBatch
+ .pipe(createEventFiltersBatchAppMetricsBeforeBatchStep(outputs))
+ .pipe(createPersonsStoreBeforeBatchStep(personsStore))
+ .pipe(createGroupStoreBeforeBatchStep(groupStore))
+ )
+ // Header-only steps: token-level deny list and restrictions. Cheap; runs
+ // per-event before we touch the body.
+ .parseHeaders()
+ .pipe(createDenyEventsStep(['$exception', '$$client_ingestion_warning', '$$heatmap']))
+ .pipe(
+ createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {
+ overflowMode,
+ preservePartitionLocality,
+ })
+ )
+ // Rate-limit non-cookieless events to overflow before parsing the body.
+ // Cookieless events (headers.distinct_id === sentinel) pass through and are
+ // handled by the matching only-cookieless step in post-team, which keys on
+ // the hashed distinct_id assigned by the cookieless step.
+ .pipeChunk(createSkipCookielessRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService))
+ .parseMessage()
+ .resolveTeam()
+ .pipe(createValidateHistoricalMigrationStep())
+ .pipe(createValidateAiEventTokensStep())
+ .pipe(createEnrichSurveyPersonPropertiesStep())
+ .compose((b) => createPostTeamPreprocessingSubpipeline(b, postTeamConfig))
+ // Group by token:distinctId and process each group concurrently.
+ // Events within each group are processed sequentially.
+ .concurrentlyPerGroup(getTokenAndDistinctId, (group) =>
+ group.sequentially((event) => createPerDistinctIdPipeline(event, perEventConfig))
+ )
+ .afterBatch((afterBatch) =>
+ afterBatch
+ .pipe(createFlushBatchStoresStep({ personsStore, groupStore, outputs }))
+ .pipe(createFlushEventFiltersBatchAppMetricsStep())
+ .pipe(createFlushHogTransformerStep(hogTransformer))
+ )
+ .build()
)
}
diff --git a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
index ec61c99f79fe..d7d545900dd4 100644
--- a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
@@ -59,8 +59,13 @@ export interface PostTeamPreprocessingSubpipelineConfig {
cdpHogWatcherSampleRate: number
}
-export function createPostTeamPreprocessingSubpipeline<TInput extends PostTeamPreprocessingSubpipelineInput, TContext>(
- builder: ChunkPipelineBuilder<TInput, TInput, TContext, TContext>,
+export function createPostTeamPreprocessingSubpipeline<
+ TStart,
+ TInput extends PostTeamPreprocessingSubpipelineInput,
+ TContext,
+ R extends string = never,
+>(
+ builder: ChunkPipelineBuilder<TStart, TInput, TContext, TContext, R>,
config: PostTeamPreprocessingSubpipelineConfig
) {
const {
@@ -84,18 +89,16 @@ export function createPostTeamPreprocessingSubpipeline<TInput extends PostTeamPr
return (
builder
// These validation steps are synchronous, so we can process events sequentially.
- .sequentially((b) => {
- const validated = b.pipe(createValidateEventMetadataStep()).pipe(createValidateEventPropertiesStep())
-
- const schemaChecked = eventSchemaEnforcementEnabled
- ? validated.pipe(createValidateEventSchemaStep(eventSchemaEnforcementManager))
- : validated
-
- return schemaChecked
+ .sequentially((b) =>
+ b
+ .pipe(createValidateEventMetadataStep())
+ .pipe(createValidateEventPropertiesStep())
+ // Schema enforcement is opt-in; the step passes events through when disabled.
+ .pipe(createValidateEventSchemaStep(eventSchemaEnforcementManager, eventSchemaEnforcementEnabled))
.pipe(createApplyPersonProcessingRestrictionsStep(eventIngestionRestrictionManager))
.pipe(createDropOldEventsStep())
.pipe(createApplyEventFiltersStep(eventFilterManager))
- })
+ )
// We want to call cookieless with the whole batch at once.
// IMPORTANT: Cookieless processing changes distinct IDs (cookieless events
// are captured with $posthog_cookieless distinct ID and rewritten here).
diff --git a/nodejs/src/ingestion/pipelines/clientwarnings/pipeline.test.ts b/nodejs/src/ingestion/pipelines/clientwarnings/pipeline.test.ts
new file mode 100644
index 000000000000..97396bcc3339
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/clientwarnings/pipeline.test.ts
@@ -0,0 +1,150 @@
+import { Message } from 'node-rdkafka'
+
+import { KafkaProducerWrapper } from '~/common/kafka/producer'
+import { APP_METRICS_OUTPUT, DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT } from '~/common/outputs'
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
+import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'
+import { parseJSON } from '~/common/utils/json-parse'
+import { PromiseScheduler } from '~/common/utils/promise-scheduler'
+import { TeamManager } from '~/common/utils/team-manager'
+import { UUIDT } from '~/common/utils/utils'
+import { EventFilterManager } from '~/ingestion/common/event-filters'
+import { createOkContext } from '~/ingestion/framework/helpers'
+import { createTestTeam } from '~/tests/helpers/team'
+
+import { ClientWarningsPipelineConfig, createClientWarningsPipeline } from './pipeline'
+
+jest.mock('~/common/utils/logger', () => ({
+ logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },
+}))
+
+const WARNINGS_TOPIC = 'clickhouse_ingestion_warnings_test'
+const DLQ_TOPIC = 'events_plugin_ingestion_dlq_test'
+
+describe('ClientWarningsPipeline', () => {
+ let mockKafkaProducer: jest.Mocked<KafkaProducerWrapper>
+ let mockTeamManager: jest.Mocked<TeamManager>
+ let mockEventIngestionRestrictionManager: jest.Mocked<EventIngestionRestrictionManager>
+ let mockEventFilterManager: jest.Mocked<EventFilterManager>
+ let promiseScheduler: PromiseScheduler
+ let config: ClientWarningsPipelineConfig
+
+ const team = createTestTeam({ id: 123, api_token: 'token-123' })
+
+ const createMessage = (event: string, warningMessage = 'something broke'): Message => {
+ const distinctId = 'user-1'
+ const eventData = {
+ event,
+ distinct_id: distinctId,
+ uuid: new UUIDT().toString(),
+ timestamp: '2024-01-01T00:00:00Z',
+ properties: { $$client_ingestion_warning_message: warningMessage },
+ }
+ return {
+ value: Buffer.from(
+ JSON.stringify({ token: team.api_token, data: JSON.stringify(eventData), ...eventData })
+ ),
+ headers: [
+ { token: Buffer.from(team.api_token) },
+ { distinct_id: Buffer.from(distinctId) },
+ // Capture sets the event-name header; the allow-list reads it before the body is parsed.
+ { event: Buffer.from(event) },
+ ],
+ topic: 'client_iwarnings_ingestion',
+ partition: 0,
+ offset: 0,
+ size: 0,
+ key: Buffer.from(distinctId),
+ } as Message
+ }
+
+ const runPipeline = async (messages: Message[]): Promise<void> => {
+ const pipeline = createClientWarningsPipeline<{ message: Message }, { message: Message }>(config)
+ const batch = messages.map((message) => createOkContext({ message }, { message }))
+ await pipeline.feed(batch)
+ let result = await pipeline.next()
+ while (result !== null) {
+ // The pipeline handles its own side effects; none may leak to drivers.
+ expect(result.sideEffects ?? []).toEqual([])
+ result = await pipeline.next()
+ }
+ await promiseScheduler.waitForAll()
+ }
+
+ const warningsProduced = (): any[] =>
+ mockKafkaProducer.queueMessages.mock.calls
+ .map((call) => call[0])
+ .filter((arg: any) => arg.topic === WARNINGS_TOPIC)
+ .flatMap((arg: any) => arg.messages.map((m: { value: Buffer }) => parseJSON(m.value.toString())))
+
+ const dlqProduced = (): any[] =>
+ mockKafkaProducer.produce.mock.calls.map((call) => call[0]).filter((arg: any) => arg.topic === DLQ_TOPIC)
+
+ beforeEach(() => {
+ mockKafkaProducer = {
+ produce: jest.fn().mockResolvedValue(undefined),
+ queueMessages: jest.fn().mockResolvedValue(undefined),
+ flush: jest.fn().mockResolvedValue(undefined),
+ } as unknown as jest.Mocked<KafkaProducerWrapper>
+
+ mockTeamManager = {
+ getTeamByToken: jest.fn().mockResolvedValue(team),
+ getTeam: jest.fn().mockResolvedValue(team),
+ } as unknown as jest.Mocked<TeamManager>
+
+ mockEventIngestionRestrictionManager = {
+ getAppliedRestrictions: jest.fn().mockReturnValue(new Set()),
+ forceRefresh: jest.fn(),
+ } as unknown as jest.Mocked<EventIngestionRestrictionManager>
+
+ mockEventFilterManager = {
+ getFilter: jest.fn().mockReturnValue(undefined),
+ } as unknown as jest.Mocked<EventFilterManager>
+
+ promiseScheduler = new PromiseScheduler()
+
+ config = {
+ outputs: new IngestionOutputs({
+ [INGESTION_WARNINGS_OUTPUT]: new SingleIngestionOutput(
+ INGESTION_WARNINGS_OUTPUT,
+ WARNINGS_TOPIC,
+ mockKafkaProducer,
+ 'test'
+ ),
+ [DLQ_OUTPUT]: new SingleIngestionOutput(DLQ_OUTPUT, DLQ_TOPIC, mockKafkaProducer, 'test'),
+ [APP_METRICS_OUTPUT]: new SingleIngestionOutput(
+ APP_METRICS_OUTPUT,
+ 'clickhouse_app_metrics2_test',
+ mockKafkaProducer,
+ 'test'
+ ),
+ }),
+ teamManager: mockTeamManager,
+ eventIngestionRestrictionManager: mockEventIngestionRestrictionManager,
+ eventFilterManager: mockEventFilterManager,
+ promiseScheduler,
+ }
+ })
+
+ it('emits a client_ingestion_warning for $$client_ingestion_warning events', async () => {
+ await runPipeline([createMessage('$$client_ingestion_warning', 'localStorage full')])
+
+ const warnings = warningsProduced()
+ expect(warnings).toHaveLength(1)
+ expect(warnings[0].team_id).toBe(team.id)
+ expect(warnings[0].type).toBe('client_ingestion_warning')
+ expect(parseJSON(warnings[0].details).message).toBe('localStorage full')
+ expect(dlqProduced()).toHaveLength(0)
+ })
+
+ it.each(['$pageview', '$identify', 'custom_event'])(
+ 'DLQs %s events instead of emitting warnings',
+ async (event) => {
+ await runPipeline([createMessage(event)])
+
+ expect(dlqProduced()).toHaveLength(1)
+ expect(warningsProduced()).toHaveLength(0)
+ }
+ )
+})
diff --git a/nodejs/src/ingestion/pipelines/clientwarnings/pipeline.ts b/nodejs/src/ingestion/pipelines/clientwarnings/pipeline.ts
index 2ae6376b4818..da4987879ee4 100644
--- a/nodejs/src/ingestion/pipelines/clientwarnings/pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/clientwarnings/pipeline.ts
@@ -5,30 +5,23 @@ import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'
import { PromiseScheduler } from '~/common/utils/promise-scheduler'
import { TeamManager } from '~/common/utils/team-manager'
+import { newCommonIngestionPipeline } from '~/ingestion/common/common-ingestion-pipeline'
import { EventFilterManager } from '~/ingestion/common/event-filters'
import { createAllowEventsStep } from '~/ingestion/common/steps/allow-events'
import {
- EventFiltersBatchContext,
createApplyEventFiltersStep,
createEventFiltersBatchAppMetricsBeforeBatchStep,
createFlushEventFiltersBatchAppMetricsStep,
} from '~/ingestion/common/steps/event-filters-steps'
import {
- createParseHeadersStep,
- createParseKafkaMessageStep,
- createResolveTeamStep,
createValidateEventMetadataStep,
createValidateEventPropertiesStep,
createValidateHistoricalMigrationStep,
} from '~/ingestion/common/steps/event-preprocessing'
import { createApplyBasicEventRestrictionsStep } from '~/ingestion/common/steps/event-preprocessing/apply-event-restrictions'
import { createDropOldEventsStep } from '~/ingestion/common/steps/event-processing/drop-old-events-step'
-import { EmitEventStepOutput } from '~/ingestion/common/steps/event-processing/emit-event-step'
import { createHandleClientIngestionWarningStep } from '~/ingestion/common/steps/event-processing/handle-client-ingestion-warning-step'
import { createRecordIngestionLagStep } from '~/ingestion/common/steps/record-ingestion-lag'
-import { addTeamToContext } from '~/ingestion/common/subpipelines/helpers'
-import { newBatchingPipeline } from '~/ingestion/framework/builders'
-import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'
export interface ClientWarningsPipelineConfig {
outputs: IngestionOutputs<IngestionWarningsOutput | DlqOutput | AppMetricsOutput>
@@ -55,45 +48,25 @@ export function createClientWarningsPipeline<
>(config: ClientWarningsPipelineConfig) {
const { outputs, teamManager, eventIngestionRestrictionManager, eventFilterManager, promiseScheduler } = config
- const pipelineConfig: PipelineConfig = {
+ return newCommonIngestionPipeline<TInput, TContext>({
+ teamManager,
outputs,
promiseScheduler,
- }
-
- return newBatchingPipeline<TInput, EmitEventStepOutput, 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(outputs))
- .pipe(createRecordIngestionLagStep())
- )
- )
- .handleIngestionWarnings(outputs)
- )
- )
- .handleResults(pipelineConfig)
- .handleSideEffects(promiseScheduler, { await: false }),
- (afterBatch) => afterBatch.pipe(createFlushEventFiltersBatchAppMetricsStep()),
- { concurrentBatches: 1 }
- )
+ concurrentBatches: 1,
+ })
+ .beforeBatch((b) => b.pipe(createEventFiltersBatchAppMetricsBeforeBatchStep(outputs)))
+ .parseHeaders()
+ .pipe(createAllowEventsStep(['$$client_ingestion_warning']))
+ .pipe(createApplyBasicEventRestrictionsStep(eventIngestionRestrictionManager))
+ .parseMessage()
+ .resolveTeam()
+ .pipe(createValidateHistoricalMigrationStep())
+ .pipe(createValidateEventMetadataStep())
+ .pipe(createValidateEventPropertiesStep())
+ .pipe(createApplyEventFiltersStep(eventFilterManager))
+ .pipe(createDropOldEventsStep())
+ .pipe(createHandleClientIngestionWarningStep(outputs))
+ .pipe(createRecordIngestionLagStep())
+ .afterBatch((b) => b.pipe(createFlushEventFiltersBatchAppMetricsStep()))
+ .build()
}
diff --git a/nodejs/src/ingestion/pipelines/errortracking/attach-message-bytes-step.ts b/nodejs/src/ingestion/pipelines/errortracking/attach-message-bytes-step.ts
new file mode 100644
index 000000000000..ed3e306fcf4b
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/errortracking/attach-message-bytes-step.ts
@@ -0,0 +1,17 @@
+import { Message } from 'node-rdkafka'
+
+import { ok } from '~/ingestion/framework/results'
+import { ProcessingStep } from '~/ingestion/framework/steps'
+
+/**
+ * Carries the Kafka message byte size on the value, so downstream chunk steps
+ * (Cymbal batch chunking) can budget by payload size.
+ */
+export function createAttachMessageBytesStep<T extends { message: Message }>(): ProcessingStep<
+ T,
+ T & { messageBytes: number }
+> {
+ return function attachMessageBytesStep(input) {
+ return Promise.resolve(ok({ ...input, messageBytes: input.message.value?.length ?? 0 }))
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts
index f9389c6ce946..251e97654629 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts
@@ -6,7 +6,6 @@ import { Counter, Gauge } from 'prom-client'
import { ReadOnlyGroupTypeManager } from '~/common/groups/readonly-group-type-manager'
import { HogTransformationResult } from '~/common/hog-transformations/hog-transformer.interface'
import { KafkaConsumerInterface, createKafkaConsumer } from '~/common/kafka/consumer'
-import { OverflowOutput } from '~/common/outputs'
import { PersonReadRepository } from '~/common/persons/repositories/person-repository'
import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'
import { AppMetricsAggregator } from '~/common/services/app-metrics-aggregator'
@@ -26,7 +25,6 @@ import { OverflowLaneOverflowRedirect } from '~/ingestion/common/overflow-redire
import { OverflowRedirectService } from '~/ingestion/common/overflow-redirect/overflow-redirect-service'
import { RedisOverflowRepository } from '~/ingestion/common/overflow-redirect/overflow-redis-repository'
import { IngestionLane, IngestionOverflowMode } from '~/ingestion/config'
-import { ChunkPipelineUnwrapper } from '~/ingestion/framework/chunk-pipeline-unwrapper'
import { TopHog } from '~/ingestion/framework/tophog'
import { PluginEvent } from '~/plugin-scaffold'
import { HealthCheckResult, PluginServerService } from '~/types'
@@ -34,7 +32,7 @@ import { HealthCheckResult, PluginServerService } from '~/types'
import { CymbalClient } from './cymbal'
import {
ErrorTrackingOutputs,
- ErrorTrackingPipelineOutput,
+ ErrorTrackingPipeline,
PostCymbalRateLimiterInput,
createErrorTrackingPipeline,
runErrorTrackingPipeline,
@@ -126,12 +124,7 @@ const latestOffsetTimestampGauge = new Gauge({
export class ErrorTrackingConsumer {
protected name = 'error-tracking-consumer'
protected kafkaConsumer: KafkaConsumerInterface
- protected pipeline!: ChunkPipelineUnwrapper<
- { message: Message },
- ErrorTrackingPipelineOutput,
- { message: Message },
- OverflowOutput
- >
+ protected pipeline!: ErrorTrackingPipeline
protected cymbalClient: CymbalClient
protected promiseScheduler: PromiseScheduler
private eventIngestionRestrictionManagerComponent: EventIngestionRestrictionManagerComponent
diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts
index e920b3c1de23..f102f7add216 100644
--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts
@@ -16,6 +16,7 @@ import { ErrorTrackingSettings, ErrorTrackingSettingsManager } from '~/common/ut
import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'
import { PromiseScheduler } from '~/common/utils/promise-scheduler'
import { TeamManager } from '~/common/utils/team-manager'
+import { CommonTeamStage, newCommonIngestionPipeline } from '~/ingestion/common/common-ingestion-pipeline'
import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'
import { OverflowRedirectService } from '~/ingestion/common/overflow-redirect/overflow-redirect-service'
import {
@@ -23,9 +24,6 @@ import {
createApplyEventRestrictionsStep,
createOnlyCookielessRateLimitToOverflowStep,
createOverflowLaneTTLRefreshStep,
- createParseHeadersStep,
- createParseKafkaMessageStep,
- createResolveTeamStep,
createSkipCookielessRateLimitToOverflowStep,
} from '~/ingestion/common/steps/event-preprocessing'
import { createCreateEventStep } from '~/ingestion/common/steps/event-processing/create-event-step'
@@ -35,15 +33,13 @@ import { createHogTransformEventStep } from '~/ingestion/common/steps/event-proc
import { createReadOnlyProcessGroupsStep } from '~/ingestion/common/steps/event-processing/readonly-process-groups-step'
import { createRecordIngestionLagStep } from '~/ingestion/common/steps/record-ingestion-lag'
import { IngestionOverflowMode } from '~/ingestion/config'
-import { newChunkPipelineBuilder } from '~/ingestion/framework/builders'
-import { ChunkPipelineBuilder } from '~/ingestion/framework/builders/chunk-pipeline-builders'
-import { ChunkPipelineUnwrapper } from '~/ingestion/framework/chunk-pipeline-unwrapper'
+import { BatchingContext, BatchingPipeline } from '~/ingestion/framework/batching-pipeline'
import { TopHogRegistry, count, countOk, createTopHogWrapper } from '~/ingestion/framework/extensions/tophog'
-import { createBatch, createUnwrapper } from '~/ingestion/framework/helpers'
-import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'
-import { ok } from '~/ingestion/framework/results'
+import { createBatch } from '~/ingestion/framework/helpers'
import { PluginEvent } from '~/plugin-scaffold'
+import { Team } from '~/types'
+import { createAttachMessageBytesStep } from './attach-message-bytes-step'
import { createCymbalProcessingStep } from './cymbal-processing-step'
import { CymbalClient } from './cymbal/client'
import { ErrorTrackingHogTransformer } from './error-tracking-consumer'
@@ -62,6 +58,15 @@ export interface ErrorTrackingPipelineInput {
*/
export type ErrorTrackingPipelineOutput = EmitEventStepOutput
+export type ErrorTrackingPipeline = BatchingPipeline<
+ ErrorTrackingPipelineInput,
+ ErrorTrackingPipelineOutput,
+ { message: Message },
+ Record<never, object>,
+ { message: Message } & BatchingContext,
+ OverflowOutput
+>
+
export type ErrorTrackingOutputs = IngestionOutputs<
EventOutput | IngestionWarningsOutput | DlqOutput | OverflowOutput | TophogOutput | AppMetricsOutput
>
@@ -116,15 +121,22 @@ export interface PostCymbalRateLimiterInput {
}
/**
- * Apply each rate limiter spec as its own post-Cymbal batch step. The chain's TOutput
+ * Apply each rate limiter spec as its own post-Cymbal chunk step. The chain's TCurrent
* is wider than the spec's input type, but `KeyedRateLimiterStepOptions<T>` is
* contravariant in T, so a narrower spec assigns into the wider chain context.
*/
-function applyKeyedRateLimiters<TInput, TOutput, CInput, COutput, R extends string>(
- builder: ChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R>,
- specs: KeyedRateLimiterStepOptions<TOutput>[]
-): ChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R> {
- return specs.reduce((b, spec) => b.pipeChunk(createKeyedRateLimiterStep(spec)), builder)
+function applyKeyedRateLimiters<
+ TInput extends { message: Message },
+ TContext extends { message: Message },
+ ROut extends string,
+ CBatch,
+ TPost extends { team: Team },
+ TCurrent,
+>(
+ stage: CommonTeamStage<TInput, TContext, ROut, CBatch, TPost, TCurrent>,
+ specs: KeyedRateLimiterStepOptions<TCurrent>[]
+): CommonTeamStage<TInput, TContext, ROut, CBatch, TPost, TCurrent> {
+ return specs.reduce((s, spec) => s.pipeChunk(createKeyedRateLimiterStep(spec)), stage)
}
/**
@@ -153,14 +165,7 @@ function applyKeyedRateLimiters<TInput, TOutput, CInput, COutput, R extends stri
* for symbolication and fingerprinting. This reduces payload size and avoids
* wasted enrichment work if Cymbal suppresses the event.
*/
-export function createErrorTrackingPipeline(
- config: ErrorTrackingPipelineConfig
-): ChunkPipelineUnwrapper<
- ErrorTrackingPipelineInput,
- ErrorTrackingPipelineOutput,
- { message: Message },
- OverflowOutput
-> {
+export function createErrorTrackingPipeline(config: ErrorTrackingPipelineConfig): ErrorTrackingPipeline {
const {
outputs,
promiseScheduler,
@@ -182,137 +187,95 @@ export function createErrorTrackingPipeline(
const topHogWrapper = createTopHogWrapper(topHog)
- const pipelineConfig: PipelineConfig<OverflowOutput> = {
+ const preCymbal = newCommonIngestionPipeline<ErrorTrackingPipelineInput, { message: Message }, OverflowOutput>({
+ teamManager,
outputs,
promiseScheduler,
- }
-
- const pipeline = newChunkPipelineBuilder<ErrorTrackingPipelineInput, { message: Message }>()
- .messageAware((b) =>
- b
- // 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, {
- overflowMode,
- preservePartitionLocality,
- })
- )
- )
- // Rate-limit non-cookieless events to overflow before parsing the body.
- // Cookieless events (headers.distinct_id === sentinel) pass through and are
- // handled post-cookieless by createOnlyCookielessRateLimitToOverflowStep, which
- // keys on the hashed distinct_id assigned by the cookieless step.
- .pipeChunk(
- createSkipCookielessRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService)
- )
- // Body parse and team resolution. Anything that needs the parsed event lives here.
- .sequentially((b) =>
- b
- .pipe(createParseKafkaMessageStep())
- .pipe(
- topHogWrapper(createResolveTeamStep(teamManager), [
- countOk('resolved_teams', (output) => ({
- team_id: String(output.team.id),
- })),
- ])
- )
- // Attach per-team error-tracking settings. No-op when the manager isn't wired
- // (rate limiter disabled) — keeps the type chain consistent regardless.
- .pipe(createLoadErrorTrackingSettingsStep(errorTrackingSettingsManager))
- )
- // Map team to context for handleIngestionWarnings, and carry
- // the Kafka message byte size through for Cymbal batch chunking.
- .filterMap(
- (element) => ({
- result: ok({
- ...element.result.value,
- messageBytes: element.context.message.value?.length ?? 0,
- }),
- context: {
- ...element.context,
- team: { id: element.result.value.team.id },
- },
- }),
- (b) =>
- b
- .teamAware((b) => {
- // Cookieless processing: rewrites event.distinct_id for cookieless
- // events. Must run as a batch and before any step that depends on
- // the final distinct ID.
- const afterCookieless = b
- .gather()
- .pipeChunk(createApplyCookielessProcessingStep(cookielessManager))
- // Rate-limit only cookieless events to overflow now that they
- // have a real hashed distinct_id. Non-cookieless events were
- // rate-limited pre-parse above.
- .pipeChunk(
- createOnlyCookielessRateLimitToOverflowStep(
- preservePartitionLocality,
- overflowRedirectService
- )
- )
- const preCymbal = afterCookieless
- // Refresh TTLs for overflow lane events (keeps Redis flags alive)
- .pipeChunk(createOverflowLaneTTLRefreshStep(overflowLaneTTLRefreshService))
- const afterCymbal = preCymbal
- // Process through Cymbal as a batch (before enrichment - Cymbal only
- // needs raw exception data, not person/geoip/group data).
- // Retry on transient failures (5xx, timeout, network errors).
- // 3 retries keeps the worst-case batch time (3 × 45s timeout =
- // 135s) well within the 180s liveness interval, and reduces
- // amplification pressure on Cymbal during degradation.
- .pipeChunk(createCymbalProcessingStep(cymbalClient), {
- retry: { tries: 3, sleepMs: 100, name: 'cymbal_processing' },
- })
- // Post-Cymbal team-global rate-limit chain. Drops events the team
- // has explicitly capped. Empty / undefined → no-op.
- const afterRateLimit = applyKeyedRateLimiters(afterCymbal, postCymbalRateLimiters ?? [])
- return (
- afterRateLimit
- // Enrich, prepare, create, and emit events
- // Batch fetch person (read-only, no updates)
- .pipeChunk(createFetchPersonChunkStep(personRepository))
- .sequentially((b) =>
- b
- // Run Hog transformations (including GeoIP if team has it enabled)
- .pipe(createHogTransformEventStep(hogTransformer))
- // Prepare event for emission
- .pipe(createErrorTrackingPrepareEventStep())
- // Map group types to indexes (read-only, no new group types created)
- .pipe(createReadOnlyProcessGroupsStep(groupTypeManager))
- .pipe(createCreateEventStep(EVENTS_OUTPUT))
- .pipe(
- topHogWrapper(
- createEmitEventStep({
- outputs,
- }),
- [
- count('emitted_events', (input) => ({
- team_id: String(input.teamId),
- })),
- count('emitted_events_per_distinct_id', (input) => ({
- team_id: String(input.teamId),
- distinct_id:
- input.eventsToEmit[0]?.event.distinct_id ?? '',
- })),
- ]
- )
- )
- .pipe(createRecordIngestionLagStep())
- )
- )
- })
- .handleIngestionWarnings(outputs)
- )
+ concurrentBatches: 1,
+ })
+ // Header-only steps: parse Kafka headers and apply token-level restrictions.
+ // Cheap; runs per-event before we touch the body.
+ .parseHeaders()
+ .pipe(
+ createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {
+ overflowMode,
+ preservePartitionLocality,
+ })
)
- .handleResults(pipelineConfig)
- .handleSideEffects(promiseScheduler, { await: false })
+ // Rate-limit non-cookieless events to overflow before parsing the body.
+ // Cookieless events (headers.distinct_id === sentinel) pass through and are
+ // handled post-cookieless by createOnlyCookielessRateLimitToOverflowStep, which
+ // keys on the hashed distinct_id assigned by the cookieless step.
+ .pipeChunk(createSkipCookielessRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService))
+ .parseMessage()
+ .resolveTeam({
+ wrap: (step) =>
+ topHogWrapper(step, [
+ countOk('resolved_teams', (output) => ({
+ team_id: String(output.team.id),
+ })),
+ ]),
+ })
+ // Attach per-team error-tracking settings. No-op when the manager isn't wired
+ // (rate limiter disabled) — keeps the type chain consistent regardless.
+ .pipe(createLoadErrorTrackingSettingsStep(errorTrackingSettingsManager))
+ // Carry the Kafka message byte size through for Cymbal batch chunking.
+ .pipe(createAttachMessageBytesStep())
+ // Cookieless processing: rewrites event.distinct_id for cookieless
+ // events. Must run as a batch and before any step that depends on
+ // the final distinct ID.
.gather()
- .build()
+ .pipeChunk(createApplyCookielessProcessingStep(cookielessManager))
+ // Rate-limit only cookieless events to overflow now that they
+ // have a real hashed distinct_id. Non-cookieless events were
+ // rate-limited pre-parse above.
+ .pipeChunk(createOnlyCookielessRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService))
+ // Refresh TTLs for overflow lane events (keeps Redis flags alive)
+ .pipeChunk(createOverflowLaneTTLRefreshStep(overflowLaneTTLRefreshService))
- return createUnwrapper(pipeline)
+ const afterCymbal = preCymbal
+ // Process through Cymbal as a batch (before enrichment - Cymbal only
+ // needs raw exception data, not person/geoip/group data).
+ // Retry on transient failures (5xx, timeout, network errors).
+ // 3 retries keeps the worst-case batch time (3 × 45s timeout =
+ // 135s) well within the 180s liveness interval, and reduces
+ // amplification pressure on Cymbal during degradation.
+ .pipeChunk(createCymbalProcessingStep(cymbalClient), {
+ retry: { tries: 3, sleepMs: 100, name: 'cymbal_processing' },
+ })
+
+ // Post-Cymbal team-global rate-limit chain. Drops events the team
+ // has explicitly capped. Empty / undefined → no-op.
+ return (
+ applyKeyedRateLimiters(afterCymbal, postCymbalRateLimiters ?? [])
+ // Batch fetch person (read-only, no updates)
+ .pipeChunk(createFetchPersonChunkStep(personRepository))
+ // Run Hog transformations (including GeoIP if team has it enabled)
+ .pipe(createHogTransformEventStep(hogTransformer))
+ // Prepare event for emission
+ .pipe(createErrorTrackingPrepareEventStep())
+ // Map group types to indexes (read-only, no new group types created)
+ .pipe(createReadOnlyProcessGroupsStep(groupTypeManager))
+ .pipe(createCreateEventStep(EVENTS_OUTPUT))
+ .pipe(
+ topHogWrapper(
+ createEmitEventStep({
+ outputs,
+ }),
+ [
+ count('emitted_events', (input) => ({
+ team_id: String(input.teamId),
+ })),
+ count('emitted_events_per_distinct_id', (input) => ({
+ team_id: String(input.teamId),
+ distinct_id: input.eventsToEmit[0]?.event.distinct_id ?? '',
+ })),
+ ]
+ )
+ )
+ .pipe(createRecordIngestionLagStep())
+ .build()
+ )
}
/**
@@ -320,22 +283,23 @@ export function createErrorTrackingPipeline(
*
* Events are emitted to the output topic as a side effect. Failures are
* handled by the result handling pipeline (DLQ, drop, redirect).
+ *
+ * All side effects — element results and batch hooks alike — are handled
+ * inside the pipeline (scheduled on the promise scheduler, which the consumer
+ * drains before committing offsets), so this driver only drains results.
*/
-export async function runErrorTrackingPipeline(
- pipeline: ChunkPipelineUnwrapper<
- ErrorTrackingPipelineInput,
- ErrorTrackingPipelineOutput,
- { message: Message },
- OverflowOutput
- >,
- messages: Message[]
-): Promise<void> {
+export async function runErrorTrackingPipeline(pipeline: ErrorTrackingPipeline, messages: Message[]): Promise<void> {
if (messages.length === 0) {
return
}
const batch = createBatch(messages.map((message) => ({ message })))
- pipeline.feed(batch)
+ // The consumer drains each batch fully before feeding the next and the hooks
+ // always succeed, so a rejected feed can only be a framework invariant violation.
+ const feedResult = await pipeline.feed(batch)
+ if (!feedResult.ok) {
+ throw new Error(`error tracking pipeline rejected feed: ${feedResult.kind} (${feedResult.reason})`)
+ }
while ((await pipeline.next()) !== null) {
// Drain all results
diff --git a/nodejs/src/ingestion/pipelines/heatmaps/pipeline.test.ts b/nodejs/src/ingestion/pipelines/heatmaps/pipeline.test.ts
index 8bfa07fe91fd..aac469396db6 100644
--- a/nodejs/src/ingestion/pipelines/heatmaps/pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/heatmaps/pipeline.test.ts
@@ -79,9 +79,8 @@ describe('HeatmapsPipeline', () => {
await pipeline.feed(batch)
let result = await pipeline.next()
while (result !== null) {
- for (const sideEffect of result.sideEffects ?? []) {
- void promiseScheduler.schedule(sideEffect)
- }
+ // The pipeline handles its own side effects; none may leak to drivers.
+ expect(result.sideEffects ?? []).toEqual([])
result = await pipeline.next()
}
await promiseScheduler.waitForAll()
diff --git a/nodejs/src/ingestion/pipelines/heatmaps/pipeline.ts b/nodejs/src/ingestion/pipelines/heatmaps/pipeline.ts
index 883d0cb7f0db..ffa5ad6fb254 100644
--- a/nodejs/src/ingestion/pipelines/heatmaps/pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/heatmaps/pipeline.ts
@@ -5,33 +5,26 @@ import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'
import { PromiseScheduler } from '~/common/utils/promise-scheduler'
import { TeamManager } from '~/common/utils/team-manager'
+import { newCommonIngestionPipeline } from '~/ingestion/common/common-ingestion-pipeline'
import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'
import { EventFilterManager } from '~/ingestion/common/event-filters'
import { createAllowEventsStep } from '~/ingestion/common/steps/allow-events'
import {
- EventFiltersBatchContext,
createApplyEventFiltersStep,
createEventFiltersBatchAppMetricsBeforeBatchStep,
createFlushEventFiltersBatchAppMetricsStep,
} from '~/ingestion/common/steps/event-filters-steps'
import {
createApplyCookielessProcessingStep,
- createParseHeadersStep,
- createParseKafkaMessageStep,
- createResolveTeamStep,
createValidateEventMetadataStep,
createValidateEventPropertiesStep,
createValidateHistoricalMigrationStep,
} from '~/ingestion/common/steps/event-preprocessing'
import { createApplyBasicEventRestrictionsStep } from '~/ingestion/common/steps/event-preprocessing/apply-event-restrictions'
import { createDropOldEventsStep } from '~/ingestion/common/steps/event-processing/drop-old-events-step'
-import { EmitEventStepOutput } from '~/ingestion/common/steps/event-processing/emit-event-step'
import { createNormalizeEventStep } from '~/ingestion/common/steps/event-processing/normalize-event-step'
import { createPrepareEventStep } from '~/ingestion/common/steps/event-processing/prepare-event-step'
import { createRecordIngestionLagStep } from '~/ingestion/common/steps/record-ingestion-lag'
-import { addTeamToContext } from '~/ingestion/common/subpipelines/helpers'
-import { newBatchingPipeline } from '~/ingestion/framework/builders'
-import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'
import { createCheckHeatmapOptInStep } from './check-heatmap-opt-in-step'
import { createDisablePersonProcessingStep } from './disable-person-processing-step'
@@ -70,58 +63,36 @@ export function createHeatmapsPipeline<TInput extends HeatmapsPipelineInput, TCo
promiseScheduler,
} = config
- const pipelineConfig: PipelineConfig = {
- outputs,
- promiseScheduler,
- }
-
- return newBatchingPipeline<TInput, EmitEventStepOutput, TContext, EventFiltersBatchContext, TContext>(
- (beforeBatch) => beforeBatch.pipe(createEventFiltersBatchAppMetricsBeforeBatchStep(outputs)),
- (batch) =>
- batch
- .messageAware((b) =>
- b
- .sequentially((b) =>
- b
- .pipe(createParseHeadersStep())
- .pipe(createAllowEventsStep(['$$heatmap']))
- .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())
- )
- // Cookieless events arrive with a sentinel distinct id; rewrite it to the
- // deterministic server-side hash (and derive the session) before extraction,
- // which keys heatmaps on distinct id and session id.
- .gather()
- .pipeChunk(createApplyCookielessProcessingStep(cookielessManager))
- .sequentially((b) =>
- b
- .pipe(createCheckHeatmapOptInStep())
- .pipe(createDisablePersonProcessingStep())
- .pipe(createNormalizeEventStep())
- .pipe(createPrepareEventStep())
- .pipe(createExtractHeatmapDataStep(outputs))
- .pipe(createRecordIngestionLagStep())
- )
- )
- .handleIngestionWarnings(outputs)
- )
- )
- .handleResults(pipelineConfig)
- .handleSideEffects(promiseScheduler, { await: false }),
- (afterBatch) => afterBatch.pipe(createFlushEventFiltersBatchAppMetricsStep()),
- { concurrentBatches: 1 }
+ return (
+ newCommonIngestionPipeline<TInput, TContext>({
+ teamManager,
+ outputs,
+ promiseScheduler,
+ concurrentBatches: 1,
+ })
+ .beforeBatch((b) => b.pipe(createEventFiltersBatchAppMetricsBeforeBatchStep(outputs)))
+ .parseHeaders()
+ .pipe(createAllowEventsStep(['$$heatmap']))
+ .pipe(createApplyBasicEventRestrictionsStep(eventIngestionRestrictionManager))
+ .parseMessage()
+ .resolveTeam()
+ .pipe(createValidateHistoricalMigrationStep())
+ .pipe(createValidateEventMetadataStep())
+ .pipe(createValidateEventPropertiesStep())
+ .pipe(createApplyEventFiltersStep(eventFilterManager))
+ .pipe(createDropOldEventsStep())
+ // Cookieless events arrive with a sentinel distinct id; rewrite it to the
+ // deterministic server-side hash (and derive the session) before extraction,
+ // which keys heatmaps on distinct id and session id.
+ .gather()
+ .pipeChunk(createApplyCookielessProcessingStep(cookielessManager))
+ .pipe(createCheckHeatmapOptInStep())
+ .pipe(createDisablePersonProcessingStep())
+ .pipe(createNormalizeEventStep())
+ .pipe(createPrepareEventStep())
+ .pipe(createExtractHeatmapDataStep(outputs))
+ .pipe(createRecordIngestionLagStep())
+ .afterBatch((b) => b.pipe(createFlushEventFiltersBatchAppMetricsStep()))
+ .build()
)
}
diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.ts
index 2f91dd9de66a..944ef27ed019 100644
--- a/nodejs/src/servers/ingestion-api-server.ts
+++ b/nodejs/src/servers/ingestion-api-server.ts
@@ -502,11 +502,11 @@ export class IngestionApiServer implements NodeServer {
batchesInFlight.inc()
inFlight = true
+ // The pipeline handles its own side effects (scheduling them on
+ // the promise scheduler), so draining results is all that's left
+ // to do.
let result = await this.joinedPipeline.next()
while (result !== null) {
- for (const sideEffect of result.sideEffects ?? []) {
- void this.promiseScheduler.schedule(sideEffect)
- }
result = await this.joinedPipeline.next()
}