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.

36.5 KB
Raw Blame
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 { TopHogRegistry, countResult } from '~/ingestion/framework/extensions/tophog'
import { createOkContext } from '~/ingestion/framework/helpers'
import { PipelineResult, dlq, drop, isDropResult, isOkResult, ok, redirect } from '~/ingestion/framework/results'
import { ProcessingStep } from '~/ingestion/framework/steps'
import { PluginEvent } from '~/plugin-scaffold'
import { getMetricValues, resetMetrics } from '~/tests/helpers/metrics'
import { createTestTeam } from '~/tests/helpers/team'
import { RecordedTopHogMetric, createRecordingTopHog } from '~/tests/helpers/tophog'
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>
    let topHog: TopHogRegistry
    let topHogRecords: Map<string, RecordedTopHogMetric[]>

    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[], batchContext: Record<never, never>) => 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()

        const recording = createRecordingTopHog()
        topHog = recording.registry
        topHogRecords = recording.records

        config = {
            teamManager: mockTeamManager,
            topHog,
            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('fans out through the skeleton and hands the fanned-in value to subsequent team-aware steps', async () => {
        const log: string[] = []
        const merged: string[] = []

        interface EventPart {
            distinctId: string
            index: number
        }

        // user-0 fans out to three parts (one of which the sub-step drops);
        // user-1 fans out to nothing and completes via fanIn(input, []).
        function splitPartsFanOut(input: { event: PluginEvent }): EventPart[] {
            const count = input.event.distinct_id === 'user-0' ? 3 : 0
            return Array.from({ length: count }, (_, index) => ({ distinctId: input.event.distinct_id, index }))
        }

        function processPartStep(part: EventPart): Promise<PipelineResult<EventPart>> {
            if (part.index === 1) {
                return Promise.resolve(drop('skipped part'))
            }
            log.push(`part:${part.distinctId}:${part.index}`)
            return Promise.resolve(ok(part))
        }

        function collectPartsFanIn<T extends { event: PluginEvent }>(original: T, parts: EventPart[]): T {
            return {
                ...original,
                event: {
                    ...original.event,
                    properties: {
                        ...original.event.properties,
                        part_indexes: parts.map((part) => part.index).sort(),
                    },
                },
            }
        }

        const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
            .parseHeaders()
            .parseMessage()
            .resolveTeam()
            .pipe(teamLogStep(log, 'A'))
            .fanOut(splitPartsFanOut)
            .via((sub) => sub.concurrently((b) => b.pipe(processPartStep)))
            .fanIn(collectPartsFanIn)
            .pipe(function recordMergedStep(input) {
                merged.push(`${input.event.distinct_id}:${JSON.stringify(input.event.properties!.part_indexes)}`)
                return Promise.resolve(ok(input))
            })
            .build()

        const batches = await runPipeline(pipeline, [createMessage('user-0'), createMessage('user-1')])

        // The open sequential block (A) was committed before the fan-out stage.
        expect(log).toEqual(['A:user-0', 'A:user-1', 'part:user-0:0', 'part:user-0:2'])
        // Downstream team-aware steps see the fanned-in values: user-0 keeps
        // the surviving parts (the dropped one excluded), user-1 fans in empty.
        expect(merged.sort()).toEqual(['user-0:[0,2]', 'user-1:[]'])
        expect(okValues(batches)).toHaveLength(2)
    })

    it('routes warnings from fan-out sub-steps to the warnings output with the resolved team', async () => {
        interface EventPart {
            distinctId: string
        }

        function splitSingleFanOut(input: { event: PluginEvent }): EventPart[] {
            return [{ distinctId: input.event.distinct_id }]
        }

        function warnPartStep(part: EventPart): Promise<PipelineResult<EventPart>> {
            return Promise.resolve(
                ok(part, [], [{ type: 'client_ingestion_warning', details: { marker: 'sub-step' }, alwaysSend: true }])
            )
        }

        function keepOriginalFanIn<T>(original: T): T {
            return original
        }

        const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
            .parseHeaders()
            .parseMessage()
            .resolveTeam()
            .fanOut(splitSingleFanOut)
            .via((sub) => sub.concurrently((b) => b.pipe(warnPartStep)))
            .fanIn(keepOriginalFanIn)
            .build()

        await runPipeline(pipeline, [createMessage('user-0')])

        // The stage sits inside the team-aware warning scope: a warning raised
        // on a sub-element lands on the parent and routes with the resolved team.
        const warnings = warningsProduced()
        expect(warnings).toHaveLength(1)
        expect(warnings[0].team_id).toBe(42)
        expect(warnings[0].type).toBe('client_ingestion_warning')
        expect(parseJSON(warnings[0].details).marker).toBe('sub-step')
    })

    it('records resolveTeam topHog metrics around team resolution', async () => {
        const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
            .parseHeaders()
            .parseMessage()
            .resolveTeam({
                topHog: [
                    countResult('teams_resolved', (result, input) =>
                        isOkResult(result)
                            ? { outcome: `ok:${result.value.team.id}` }
                            : { outcome: `miss:${input.headers.distinct_id}` }
                    ),
                ],
            })
            .build()

        const batches = await runPipeline(pipeline, [
            createMessage('user-0'),
            createMessage('user-1', 'test_event', 'unknown-token'),
        ])

        expect((topHogRecords.get('teams_resolved') ?? []).map((r) => r.key)).toEqual([
            { outcome: 'ok:42' },
            { outcome: '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('records teams resolved through a team id sent as the token', async () => {
        resetMetrics()
        mockTeamManager.getTeamByToken.mockImplementation((token: string) =>
            Promise.resolve(token === team.api_token || token === String(team.id) ? team : null)
        )
        const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
            .parseHeaders()
            .parseMessage()
            .resolveTeam()
            .build()

        await runPipeline(pipeline, [createMessage('user-0'), createMessage('user-1', 'test_event', String(team.id))])

        expect((topHogRecords.get('token_resolved_as_team_id') ?? []).map((r) => r.key)).toEqual([
            { team_id: String(team.id) },
        ])
        expect(await getMetricValues('ingestion_token_resolved_as_team_id_total')).toEqual([{ labels: {}, value: 1 }])
    })

    it('records parse timing and message sizes for every parsed message', async () => {
        const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
            .parseHeaders()
            .parseMessage()
            .resolveTeam()
            .build()

        await runPipeline(pipeline, [createMessage('user-0')])

        const sizes = topHogRecords.get('message_size_by_token') ?? []
        expect(sizes).toHaveLength(1)
        expect(sizes[0].key).toEqual({ token: team.api_token })
        expect(sizes[0].value).toBeGreaterThan(0)
        expect(topHogRecords.get('parse_time_ms_by_token')).toHaveLength(1)
    })

    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()
        })

        it('rejects an unclosed fan-out stage at compile time', () => {
            const teamStage = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)
                .parseHeaders()
                .parseMessage()
                .resolveTeam()

            const opened = teamStage.fanOut(function splitFanOut(input) {
                return [input.team.id]
            })

            // @ts-expect-error fanIn is only available after via()
            const _noEarlyFanIn = opened.fanIn
            // @ts-expect-error an unclosed fan-out stage cannot be built
            const _noFanOutBuild = opened.build
            // @ts-expect-error an unclosed fan-out stage cannot register afterBatch hooks
            const _noFanOutAfterBatch = opened.afterBatch

            const routed = opened.via((sub) => sub)

            // @ts-expect-error only fanIn can close the stage
            const _noFanInBuild = routed.build
            // @ts-expect-error only fanIn can close the stage
            const _noFanInAfterBatch = routed.afterBatch

            expect(routed).toBeDefined()
        })
    })
})