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.

56.9 KB
Raw Blame
import { Message } from 'node-rdkafka'

import { createTestMessage } from '~/tests/helpers/kafka-message'
import { createMockPipeline } from '~/tests/helpers/mock-pipeline'

import {
    ConcurrentlyGroupingChunkPipeline,
    processGroupChunkSequentially,
} from './concurrently-grouping-chunk-pipeline'
import { createContext, createNewChunkPipeline, createNewPipeline, createOkContext } from './helpers'
import { PipelineResultWithContext } from './pipeline.interface'
import { dlq, drop, ok } from './results'

// xoshiro128** PRNG (Vigna & Blackman, 2018) - fast 128-bit state generator
function xoshiro128ss(a: number, b: number, c: number, d: number): () => number {
    return function () {
        const t = b << 9
        let r = b * 5
        r = ((r << 7) | (r >>> 25)) * 9
        c ^= a
        d ^= b
        b ^= c
        a ^= d
        c ^= t
        d = (d << 11) | (d >>> 21)
        return (r >>> 0) / 4294967296
    }
}

describe('ConcurrentlyGroupingChunkPipeline', () => {
    let message1: Message
    let message2: Message
    let message3: Message
    let message4: Message
    let context1: { message: Message }
    let context2: { message: Message }
    let context3: { message: Message }
    let context4: { message: Message }

    beforeEach(() => {
        jest.useFakeTimers()

        message1 = createTestMessage({ offset: 1, key: Buffer.from('key1'), value: Buffer.from('value1') })
        message2 = createTestMessage({ offset: 2, key: Buffer.from('key2'), value: Buffer.from('value2') })
        message3 = createTestMessage({ offset: 3, key: Buffer.from('key3'), value: Buffer.from('value3') })
        message4 = createTestMessage({ offset: 4, key: Buffer.from('key4'), value: Buffer.from('value4') })

        context1 = { message: message1 }
        context2 = { message: message2 }
        context3 = { message: message3 }
        context4 = { message: message4 }
    })

    afterEach(() => {
        jest.useRealTimers()
    })

    describe('constructor', () => {
        it('should create instance with grouping function, processor, and previous pipeline', () => {
            const processor = createNewPipeline<{ value: string; group: string }>().pipe((input) =>
                Promise.resolve(ok({ ...input, processed: true }))
            )
            const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()

            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline
            )

            expect(pipeline).toBeInstanceOf(ConcurrentlyGroupingChunkPipeline)
        })
    })

    describe('feed', () => {
        it('should delegate to previous pipeline', () => {
            const processor = createNewPipeline<{ value: string; group: string }>().pipe((input) =>
                Promise.resolve(ok(input))
            )
            const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
            const spy = jest.spyOn(previousPipeline, 'feed')

            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline
            )
            const testBatch = [createOkContext({ value: 'test', group: 'A' }, context1)]

            pipeline.feed(testBatch)

            expect(spy).toHaveBeenCalledWith(testBatch)
        })
    })

    describe('next', () => {
        it('should return null when no results available', async () => {
            const processor = createNewPipeline<{ value: string; group: string }>().pipe((input) =>
                Promise.resolve(ok(input))
            )
            const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()

            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline
            )

            const result = await pipeline.next()
            expect(result).toBeNull()
        })

        it('should rethrow processor errors', async () => {
            const processor = createNewPipeline<{ value: string; group: string }>().pipe((_input) => {
                return Promise.reject(new Error('Processor error'))
            })

            const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
            const testBatch = [createOkContext({ value: 'test', group: 'A' }, context1)]
            previousPipeline.feed(testBatch)

            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline
            )

            await expect(pipeline.next()).rejects.toThrow('Processor error')
        })
    })

    describe('grouping and sequential processing', () => {
        it('should group items by key and process each group', async () => {
            const processor = createNewPipeline<{ value: string; group: string }>().pipe((input) =>
                Promise.resolve(ok({ ...input, processed: true }))
            )
            const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()

            const testBatch = [
                createOkContext({ value: 'a1', group: 'A' }, context1),
                createOkContext({ value: 'b1', group: 'B' }, context2),
                createOkContext({ value: 'a2', group: 'A' }, context3),
            ]
            previousPipeline.feed(testBatch)

            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline
            )

            const results: PipelineResultWithContext<any, any>[] = []
            let result = await pipeline.next()
            while (result !== null) {
                results.push(...result)
                result = await pipeline.next()
            }

            expect(results).toHaveLength(3)
            expect(results.every((r) => r.result.type === 0 && (r.result as any).value.processed)).toBe(true)
        })

        it('should process items within each group sequentially', async () => {
            const processingOrder: string[] = []
            const processor = createNewPipeline<{ value: string; group: string }>().pipe(async (input) => {
                processingOrder.push(`start-${input.value}`)
                await new Promise((resolve) => setTimeout(resolve, 10))
                processingOrder.push(`end-${input.value}`)
                return ok({ ...input, processed: true })
            })
            const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()

            const testBatch = [
                createOkContext({ value: 'a1', group: 'A' }, context1),
                createOkContext({ value: 'a2', group: 'A' }, context2),
            ]
            previousPipeline.feed(testBatch)

            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline
            )

            const resultsPromise = (async () => {
                let result = await pipeline.next()
                while (result !== null) {
                    result = await pipeline.next()
                }
            })()

            await jest.advanceTimersByTimeAsync(100)
            await resultsPromise

            // Within group A, items should be processed sequentially (a1 completes before a2 starts)
            expect(processingOrder).toEqual(['start-a1', 'end-a1', 'start-a2', 'end-a2'])
        })

        it('should return results as groups complete (order not guaranteed)', async () => {
            // Fixed seeds for deterministic test runs
            const random = xoshiro128ss(0x9e3779b9, 0x243f6a88, 0xb7e15162, 0x6c078965)

            const groupCount = 50
            const totalElements = 500
            const groupNextIndex = new Map<string, number>()

            // Generate elements by randomly picking a group and assigning sequential indices
            const events: { group: string; groupIndex: number }[] = []
            for (let i = 0; i < totalElements; i++) {
                const group = `group-${Math.floor(random() * groupCount)}`
                const groupIndex = groupNextIndex.get(group) ?? 0
                events.push({ group, groupIndex })
                groupNextIndex.set(group, groupIndex + 1)
            }

            const processor = createNewPipeline<{ group: string; groupIndex: number }>().pipe((input) =>
                Promise.resolve(ok({ ...input, processed: true }))
            )
            const previousPipeline = createNewChunkPipeline<{ group: string; groupIndex: number }>().build()

            const testBatch = events.map((e) => createOkContext(e, context1))
            previousPipeline.feed(testBatch)

            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline
            )

            // Collect results and track per-group ordering
            const groupResults = new Map<string, number[]>()
            let result = await pipeline.next()
            while (result !== null) {
                for (const r of result) {
                    const { group, groupIndex } = (r.result as any).value
                    if (!groupResults.has(group)) {
                        groupResults.set(group, [])
                    }
                    groupResults.get(group)!.push(groupIndex)
                }
                result = await pipeline.next()
            }

            // Assert all groups with elements were returned
            expect(groupResults.size).toBe(groupNextIndex.size)

            // Assert each group has correct ordering and all elements
            for (const [group, indices] of groupResults) {
                const expectedCount = groupNextIndex.get(group)!

                // Check indices are in ascending order (sequential processing within group)
                for (let i = 1; i < indices.length; i++) {
                    expect(indices[i]).toBeGreaterThan(indices[i - 1])
                }

                // Check all indices are present (0 to expectedCount-1)
                expect(indices).toHaveLength(expectedCount)
                expect(indices).toEqual([...Array(expectedCount).keys()])
            }
        })
    })

    describe('concurrent group processing', () => {
        it('should process different groups concurrently', async () => {
            const groupCount = 1000
            const resolvers: (() => void)[] = []
            const startedPromises: Promise<void>[] = []
            for (let i = 0; i < groupCount; i++) {
                startedPromises.push(new Promise<void>((resolve) => resolvers.push(resolve)))
            }

            const processor = createNewPipeline<{ index: number; group: string }>().pipe(async (input) => {
                // Signal that this group has started
                resolvers[input.index]()
                // Wait for all groups to start - if processing were sequential, this would deadlock
                await Promise.all(startedPromises)
                return ok({ ...input, processed: true })
            })
            const previousPipeline = createNewChunkPipeline<{ index: number; group: string }>().build()

            const testBatch = []
            for (let i = 0; i < groupCount; i++) {
                testBatch.push(createOkContext({ index: i, group: `group-${i}` }, context1))
            }
            previousPipeline.feed(testBatch)

            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline
            )

            const results: PipelineResultWithContext<any, any>[] = []
            let result = await pipeline.next()
            while (result !== null) {
                results.push(...result)
                result = await pipeline.next()
            }

            expect(results).toHaveLength(groupCount)
            const indices = results.map((r) => (r.result as any).value.index).sort((a, b) => a - b)
            expect(indices).toEqual([...Array(groupCount).keys()])
        })

        it('should not block other groups when one group is slow', async () => {
            const normalGroupCount = 100
            const elementsPerGroup = 100
            const slowGroupDelay = 10000

            const processor = createNewPipeline<{ index: number; group: string }>().pipe(async (input) => {
                if (input.group === 'slow') {
                    await new Promise((resolve) => setTimeout(resolve, slowGroupDelay))
                }
                return ok({ ...input, processed: true })
            })
            const previousPipeline = createNewChunkPipeline<{ index: number; group: string }>().build()

            const testBatch = []
            let index = 0
            for (let g = 0; g < normalGroupCount; g++) {
                for (let e = 0; e < elementsPerGroup; e++) {
                    testBatch.push(createOkContext({ index: index++, group: `group-${g}` }, context1))
                }
            }
            testBatch.push(createOkContext({ index: index++, group: 'slow' }, context1))
            previousPipeline.feed(testBatch)

            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline
            )

            // Consume results until we have all normal groups
            const results: PipelineResultWithContext<any, any>[] = []
            while (results.length < normalGroupCount * elementsPerGroup) {
                const result = await pipeline.next()
                if (result !== null) {
                    results.push(...result)
                }
            }

            // All normal groups should be processed, slow group should not be included yet
            expect(results).toHaveLength(normalGroupCount * elementsPerGroup)
            expect(results.every((r) => (r.result as any).value.group !== 'slow')).toBe(true)

            // Advance time for the slow group to complete
            await jest.advanceTimersByTimeAsync(slowGroupDelay)
            const slowResult = await pipeline.next()

            // Now we should have the slow group result
            expect(slowResult).toHaveLength(1)
            expect((slowResult![0].result as any).value.group).toBe('slow')
        })
    })

    describe('bounded concurrency', () => {
        it('caps how many groups (not items) process at once when maxConcurrency is set', async () => {
            // Real timers so a full drain naturally lets each item's delay elapse; peak concurrency
            // is observed across the whole run.
            jest.useRealTimers()

            const groupCount = 6
            const itemsPerGroup = 3
            const maxConcurrency = 2
            // Track concurrent groups: a group is active from its first item's start to its last item's
            // end. Items within a group run sequentially under one slot, so items-in-flight would peak
            // higher than groups-in-flight if the cap counted items.
            const activeItemsByGroup = new Map<string, number>()
            let peakGroups = 0
            let peakItems = 0

            const processor = createNewPipeline<{ index: number; group: string }>().pipe(async (input) => {
                activeItemsByGroup.set(input.group, (activeItemsByGroup.get(input.group) ?? 0) + 1)
                peakGroups = Math.max(peakGroups, activeItemsByGroup.size)
                peakItems = Math.max(
                    peakItems,
                    [...activeItemsByGroup.values()].reduce((a, b) => a + b, 0)
                )
                await new Promise((resolve) => setTimeout(resolve, 5))
                const remaining = (activeItemsByGroup.get(input.group) ?? 1) - 1
                if (remaining === 0) {
                    activeItemsByGroup.delete(input.group)
                } else {
                    activeItemsByGroup.set(input.group, remaining)
                }
                return ok({ ...input, processed: true })
            })
            const previousPipeline = createNewChunkPipeline<{ index: number; group: string }>().build()

            const testBatch = []
            let index = 0
            for (let g = 0; g < groupCount; g++) {
                for (let i = 0; i < itemsPerGroup; i++) {
                    testBatch.push(createOkContext({ index: index++, group: `group-${g}` }, context1))
                }
            }
            previousPipeline.feed(testBatch)

            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline,
                maxConcurrency
            )

            const results: PipelineResultWithContext<any, any>[] = []
            let result = await pipeline.next()
            while (result !== null) {
                results.push(...result)
                result = await pipeline.next()
            }

            expect(results).toHaveLength(groupCount * itemsPerGroup)
            // The cap is on groups: at most `maxConcurrency` groups run at once...
            expect(peakGroups).toBe(maxConcurrency)
            // ...and a group's items run sequentially under its single slot, so items-in-flight never
            // exceeds the group cap either (one active item per active group).
            expect(peakItems).toBe(maxConcurrency)
        })

        it('preserves per-key ordering when a group parks for a permit and more same-key items arrive', async () => {
            // The key is claimed in activeProcessing synchronously when a group is started, so a
            // same-key item fed while that group is still parked waiting for a permit must queue
            // behind it rather than spawn a second concurrent runner. Two slow occupants (Y, Z) hold
            // both permits so A genuinely parks; if the claim regressed to happen only once the permit
            // is granted, a1 and a2 would run concurrently and A's peak concurrency would be 2.
            const processingOrder: string[] = []
            const activeByGroup = new Map<string, number>()
            const peakByGroup = new Map<string, number>()
            const processor = createNewPipeline<{ value: string; group: string }>().pipe(async (input) => {
                const active = (activeByGroup.get(input.group) ?? 0) + 1
                activeByGroup.set(input.group, active)
                peakByGroup.set(input.group, Math.max(peakByGroup.get(input.group) ?? 0, active))
                processingOrder.push(`start-${input.value}`)
                await new Promise((resolve) => setTimeout(resolve, input.group === 'A' ? 10 : 100))
                processingOrder.push(`end-${input.value}`)
                activeByGroup.set(input.group, (activeByGroup.get(input.group) ?? 1) - 1)
                return ok({ ...input, processed: true })
            })
            const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline,
                2
            )

            // Two slow groups fill both permits. Fed before the drain parks so they start on the
            // first next(); later same-key feeds go through the pipeline to wake the parked drain.
            previousPipeline.feed([
                createOkContext({ value: 'y1', group: 'Y' }, context1),
                createOkContext({ value: 'z1', group: 'Z' }, context2),
            ])

            const drained: PipelineResultWithContext<any, any>[] = []
            const run = (async () => {
                let result = await pipeline.next()
                while (result !== null) {
                    drained.push(...result)
                    result = await pipeline.next()
                }
            })()

            await jest.advanceTimersByTimeAsync(0)
            expect(processingOrder).toEqual(['start-y1', 'start-z1'])

            // A's first item parks (no permit free) and claims key A. Fed through the pipeline so the
            // wake-up reaches the parked drain.
            pipeline.feed([createOkContext({ value: 'a1', group: 'A' }, context3)])
            await jest.advanceTimersByTimeAsync(0)
            expect(processingOrder).toEqual(['start-y1', 'start-z1'])

            // A's second item, fed while A is still parked, must queue — not start a second A runner.
            pipeline.feed([createOkContext({ value: 'a2', group: 'A' }, context4)])
            await jest.advanceTimersByTimeAsync(0)
            expect(processingOrder).toEqual(['start-y1', 'start-z1'])

            // Free both permits and let everything drain.
            await jest.advanceTimersByTimeAsync(1000)
            await run

            expect(drained).toHaveLength(4)
            // A never ran two items at once, and a1 fully preceded a2.
            expect(peakByGroup.get('A')).toBe(1)
            expect(processingOrder.filter((s) => s.endsWith('a1') || s.endsWith('a2'))).toEqual([
                'start-a1',
                'end-a1',
                'start-a2',
                'end-a2',
            ])
        })
    })

    describe('non-success results', () => {
        it('should preserve non-success results without processing', async () => {
            let processorCallCount = 0
            const processor = createNewPipeline<{ value: string; group: string }>().pipe((input) => {
                processorCallCount++
                return Promise.resolve(ok(input))
            })
            const dropResult = drop<{ value: string; group: string }>('test drop')
            const dlqResult = dlq<{ value: string; group: string }>('test dlq', new Error('test error'))

            const testBatch = [createContext(dropResult, context1), createContext(dlqResult, context2)]
            const previousPipeline = createMockPipeline<{ value: string; group: string }>(testBatch)

            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline
            )

            const results: PipelineResultWithContext<any, any>[] = []
            let result = await pipeline.next()
            while (result !== null) {
                results.push(...result)
                result = await pipeline.next()
            }

            expect(processorCallCount).toBe(0)
            expect(results).toHaveLength(2)
            expect(results.map((r) => r.result)).toEqual(expect.arrayContaining([dropResult, dlqResult]))
        })

        it('should handle mixed success and non-success results', async () => {
            let processorCallCount = 0
            const processor = createNewPipeline<{ value: string; group: string }>().pipe((input) => {
                processorCallCount++
                return Promise.resolve(ok({ ...input, processed: true }))
            })
            const dropResult = drop<{ value: string; group: string }>('test drop')

            const testBatch = [
                createOkContext({ value: 'a1', group: 'A' }, context1),
                createContext(dropResult, context2),
                createOkContext({ value: 'a2', group: 'A' }, context3),
            ]
            const previousPipeline = createMockPipeline<{ value: string; group: string }>(testBatch)

            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline
            )

            const results: PipelineResultWithContext<any, any>[] = []
            let result = await pipeline.next()
            while (result !== null) {
                results.push(...result)
                result = await pipeline.next()
            }

            expect(processorCallCount).toBe(2)
            expect(results).toHaveLength(3)
            const okResults = results.filter((r) => r.result.type === 0)
            expect(okResults).toHaveLength(2)
            expect(okResults.every((r) => (r.result as any).value.processed)).toBe(true)
        })
    })

    describe('concurrentlyPerGroup builder DSL', () => {
        it('should work with the concurrentlyPerGroup builder method', async () => {
            const pipeline = createNewChunkPipeline<{ value: string; group: string }>()
                .concurrentlyPerGroup(
                    (input) => input.group,
                    (group) =>
                        group.sequentially((builder) =>
                            builder.pipe((input) => Promise.resolve(ok({ ...input, processed: true })))
                        )
                )
                .build()

            const testBatch = [
                createOkContext({ value: 'a1', group: 'A' }, context1),
                createOkContext({ value: 'b1', group: 'B' }, context2),
                createOkContext({ value: 'a2', group: 'A' }, context3),
            ]
            pipeline.feed(testBatch)

            const results: PipelineResultWithContext<any, any>[] = []
            let result = await pipeline.next()
            while (result !== null) {
                results.push(...result)
                result = await pipeline.next()
            }

            expect(results).toHaveLength(3)
            expect(results.every((r) => r.result.type === 0 && (r.result as any).value.processed)).toBe(true)
        })

        it('should compose chained group chunk steps in order', async () => {
            const pipeline = createNewChunkPipeline<{ value: string; group: string }>()
                .concurrentlyPerGroup(
                    (input) => input.group,
                    (group) =>
                        group
                            .pipeChunk((values: { value: string; group: string }[]) =>
                                Promise.resolve(
                                    values.map((value) =>
                                        value.value === 'a1'
                                            ? drop<{ value: string; group: string; first: boolean }>(
                                                  'dropped by first step'
                                              )
                                            : ok({ ...value, first: true })
                                    )
                                )
                            )
                            .pipeChunk((values: { value: string; group: string; first: boolean }[]) =>
                                Promise.resolve(values.map((value) => ok({ ...value, second: true })))
                            )
                            .sequentially((builder) => builder.pipe((input) => Promise.resolve(ok(input))))
                )
                .build()

            pipeline.feed([
                createOkContext({ value: 'a1', group: 'A' }, context1),
                createOkContext({ value: 'a2', group: 'A' }, context2),
            ])

            const results: PipelineResultWithContext<any, any>[] = []
            let result = await pipeline.next()
            while (result !== null) {
                results.push(...result)
                result = await pipeline.next()
            }

            expect(results).toHaveLength(2)
            const dropped = results.find((r) => r.context.message === message1)!
            const processed = results.find((r) => r.context.message === message2)!
            expect(dropped.result.type).toBe(2) // DROP
            expect(processed.result).toMatchObject({ value: { value: 'a2', first: true, second: true } })
        })

        it('should chain with gather to collect all results', async () => {
            const pipeline = createNewChunkPipeline<{ value: string; group: string }>()
                .concurrentlyPerGroup(
                    (input) => input.group,
                    (group) =>
                        group.sequentially((builder) =>
                            builder.pipe((input) => Promise.resolve(ok({ ...input, processed: true })))
                        )
                )
                .gather()
                .build()

            const testBatch = [
                createOkContext({ value: 'a1', group: 'A' }, context1),
                createOkContext({ value: 'b1', group: 'B' }, context2),
                createOkContext({ value: 'a2', group: 'A' }, context3),
            ]
            pipeline.feed(testBatch)

            const result = await pipeline.next()

            expect(result).not.toBeNull()
            expect(result).toHaveLength(3)
        })
    })

    describe('ordering across next() calls', () => {
        it('should maintain ordering when new items arrive for a group that is still processing', async () => {
            const processingOrder: string[] = []
            const processor = createNewPipeline<{ value: string; group: string }>().pipe(async (input) => {
                processingOrder.push(`start-${input.value}`)
                await new Promise((resolve) => setTimeout(resolve, 50))
                processingOrder.push(`end-${input.value}`)
                return ok({ ...input, processed: true })
            })
            const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline
            )

            // Feed first batch with items for group A
            previousPipeline.feed([
                createOkContext({ value: 'a1', group: 'A' }, context1),
                createOkContext({ value: 'a2', group: 'A' }, context2),
            ])
            expect(processingOrder).toEqual([])

            // Start processing
            const nextPromise = pipeline.next()
            expect(processingOrder).toEqual([])

            // Advance past microtasks - a1 should start processing
            await jest.advanceTimersByTimeAsync(0)
            expect(processingOrder).toEqual(['start-a1'])

            // Feed more items for group A while a1 is still processing. Fed through the
            // pipeline (not previousPipeline directly) so the wake-up reaches the parked next().
            pipeline.feed([createOkContext({ value: 'a3', group: 'A' }, context3)])
            expect(processingOrder).toEqual(['start-a1'])

            // Advance to complete a1 (50ms), a2 should start
            await jest.advanceTimersByTimeAsync(50)
            expect(processingOrder).toEqual(['start-a1', 'end-a1', 'start-a2'])

            // Advance to complete a2 - the group's batch ends and the queued a3
            // starts (per-key ordering: a3 runs after a1, a2)
            await jest.advanceTimersByTimeAsync(50)
            expect(processingOrder).toEqual(['start-a1', 'end-a1', 'start-a2', 'end-a2', 'start-a3'])

            // Await first next() - gets results for a1 and a2
            const results: any[] = []
            const result1 = await nextPromise
            if (result1) {
                results.push(...result1)
            }
            expect(results).toHaveLength(2)

            // a3 is already in flight; the second next() collects it
            const nextPromise2 = pipeline.next()
            await jest.advanceTimersByTimeAsync(0)
            expect(processingOrder).toEqual(['start-a1', 'end-a1', 'start-a2', 'end-a2', 'start-a3'])

            // Advance to complete a3
            await jest.advanceTimersByTimeAsync(50)
            expect(processingOrder).toEqual(['start-a1', 'end-a1', 'start-a2', 'end-a2', 'start-a3', 'end-a3'])

            const result2 = await nextPromise2
            if (result2) {
                results.push(...result2)
            }
            expect(results).toHaveLength(3)
        })

        it('should not block other groups from starting when one group has queued items', async () => {
            const processingOrder: string[] = []
            const processor = createNewPipeline<{ value: string; group: string }>().pipe(async (input) => {
                processingOrder.push(`start-${input.value}`)
                // B is slow (1000ms), others are fast (50ms)
                const delay = input.group === 'B' ? 1000 : 50
                await new Promise((resolve) => setTimeout(resolve, delay))
                processingOrder.push(`end-${input.value}`)
                return ok({ ...input, processed: true })
            })
            const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline
            )

            // Feed one element each for groups A and B (B is slow)
            previousPipeline.feed([
                createOkContext({ value: 'a1', group: 'A' }, context1),
                createOkContext({ value: 'b1', group: 'B' }, context2),
            ])
            expect(processingOrder).toEqual([])

            // Start processing - both start concurrently
            const nextPromise = pipeline.next()
            await jest.advanceTimersByTimeAsync(0)
            expect(processingOrder).toEqual(['start-a1', 'start-b1'])

            // Advance 50ms - A completes, B still processing
            await jest.advanceTimersByTimeAsync(50)
            expect(processingOrder).toEqual(['start-a1', 'start-b1', 'end-a1'])

            // Feed one element each for groups B and C
            // b2 will be queued (B is still processing b1), c1 should start immediately
            previousPipeline.feed([
                createOkContext({ value: 'b2', group: 'B' }, context3),
                createOkContext({ value: 'c1', group: 'C' }, context4),
            ])
            expect(processingOrder).toEqual(['start-a1', 'start-b1', 'end-a1'])

            // Await first next() - returns A's result
            const results: any[] = []
            const result1 = await nextPromise
            if (result1) {
                results.push(...result1)
            }
            expect(results).toHaveLength(1)
            expect((results[0].result as any).value.value).toBe('a1')

            // Call next() to route second batch - c1 starts even though b2 is queued
            const nextPromise2 = pipeline.next()
            await jest.advanceTimersByTimeAsync(0)
            expect(processingOrder).toEqual(['start-a1', 'start-b1', 'end-a1', 'start-c1'])

            // Advance 50ms - C completes, B still processing b1
            await jest.advanceTimersByTimeAsync(50)
            expect(processingOrder).toEqual(['start-a1', 'start-b1', 'end-a1', 'start-c1', 'end-c1'])

            // Await second next() - returns C's result
            const result2 = await nextPromise2
            if (result2) {
                results.push(...result2)
            }
            expect(results).toHaveLength(2)
            expect((results[1].result as any).value.value).toBe('c1')

            // Advance remaining time for B to complete b1 (1000 - 50 - 50 = 900ms).
            // The parked next() eagerly starts the queued b2 when b1's group ends.
            const nextPromise3 = pipeline.next()
            await jest.advanceTimersByTimeAsync(900)
            expect(processingOrder).toEqual([
                'start-a1',
                'start-b1',
                'end-a1',
                'start-c1',
                'end-c1',
                'end-b1',
                'start-b2',
            ])

            // Await third next() - returns b1's result
            const result3 = await nextPromise3
            if (result3) {
                results.push(...result3)
            }
            expect(results).toHaveLength(3)

            // b2 is already in flight; the fourth next() collects it
            const nextPromise4 = pipeline.next()
            await jest.advanceTimersByTimeAsync(0)
            expect(processingOrder).toEqual([
                'start-a1',
                'start-b1',
                'end-a1',
                'start-c1',
                'end-c1',
                'end-b1',
                'start-b2',
            ])

            // Advance 1000ms for b2 to complete
            await jest.advanceTimersByTimeAsync(1000)
            expect(processingOrder).toEqual([
                'start-a1',
                'start-b1',
                'end-a1',
                'start-c1',
                'end-c1',
                'end-b1',
                'start-b2',
                'end-b2',
            ])

            const result4 = await nextPromise4
            if (result4) {
                results.push(...result4)
            }
            expect(results).toHaveLength(4)
        })
    })

    describe('complex grouping scenarios', () => {
        it('should handle multiple items per group with sequential processing', async () => {
            const processingOrder: string[] = []
            const pipeline = createNewChunkPipeline<{ value: string; group: string }>()
                .concurrentlyPerGroup(
                    (input) => input.group,
                    (group) =>
                        group.sequentially((builder) =>
                            builder.pipe(async (input) => {
                                processingOrder.push(`start-${input.value}`)
                                await new Promise((resolve) => setTimeout(resolve, 10))
                                processingOrder.push(`end-${input.value}`)
                                return ok({ ...input, processed: true })
                            })
                        )
                )
                .gather()
                .build()

            const testBatch = [
                createOkContext({ value: 'a1', group: 'A' }, context1),
                createOkContext({ value: 'a2', group: 'A' }, context2),
                createOkContext({ value: 'b1', group: 'B' }, context3),
                createOkContext({ value: 'b2', group: 'B' }, context4),
            ]
            pipeline.feed(testBatch)

            const resultPromise = pipeline.next()
            await jest.advanceTimersByTimeAsync(100)
            await resultPromise

            // Verify sequential processing within groups
            const a1Start = processingOrder.indexOf('start-a1')
            const a1End = processingOrder.indexOf('end-a1')
            const a2Start = processingOrder.indexOf('start-a2')

            const b1Start = processingOrder.indexOf('start-b1')
            const b1End = processingOrder.indexOf('end-b1')
            const b2Start = processingOrder.indexOf('start-b2')

            // Within group A: a1 ends before a2 starts
            expect(a1End).toBeLessThan(a2Start)

            // Within group B: b1 ends before b2 starts
            expect(b1End).toBeLessThan(b2Start)

            // Groups are concurrent: both start before either fully completes all items
            expect(a1Start).toBeLessThan(b1End + 1 || b2Start)
            expect(b1Start).toBeLessThan(a1End + 1 || a2Start)
        })

        it('should handle empty batches gracefully', async () => {
            const pipeline = createNewChunkPipeline<{ value: string; group: string }>()
                .concurrentlyPerGroup(
                    (input) => input.group,
                    (group) =>
                        group.sequentially((builder) =>
                            builder.pipe((input) => Promise.resolve(ok({ ...input, processed: true })))
                        )
                )
                .build()

            pipeline.feed([])

            const result = await pipeline.next()
            expect(result).toBeNull()
        })

        it('should handle single item groups', async () => {
            const pipeline = createNewChunkPipeline<{ value: string; group: string }>()
                .concurrentlyPerGroup(
                    (input) => input.group,
                    (group) =>
                        group.sequentially((builder) =>
                            builder.pipe((input) => Promise.resolve(ok({ ...input, processed: true })))
                        )
                )
                .gather()
                .build()

            const testBatch = [
                createOkContext({ value: 'a1', group: 'A' }, context1),
                createOkContext({ value: 'b1', group: 'B' }, context2),
                createOkContext({ value: 'c1', group: 'C' }, context3),
            ]
            pipeline.feed(testBatch)

            const result = await pipeline.next()

            expect(result).not.toBeNull()
            expect(result).toHaveLength(3)
        })
    })

    describe('feeds interleaving with in-flight group processing', () => {
        it('wakes a parked drain when a group fed after it parked completes', async () => {
            const processor = createNewPipeline<{ value: string; group: string }>().pipe(async (input) => {
                // A is slow enough to keep the drain parked; B finishes quickly.
                const delay = input.group === 'A' ? 1000 : 10
                await new Promise((resolve) => setTimeout(resolve, delay))
                return ok({ ...input, processed: true })
            })
            const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline
            )

            previousPipeline.feed([createOkContext({ value: 'a1', group: 'A' }, context1)])
            const nextPromise = pipeline.next()
            await jest.advanceTimersByTimeAsync(0) // A starts, the drain parks on it

            // Feed a brand-new group B while the drain is parked on A.
            pipeline.feed([createOkContext({ value: 'b1', group: 'B' }, context2)])
            await jest.advanceTimersByTimeAsync(10)

            // B started only after the drain parked, yet its completion wakes it.
            const result = await nextPromise
            expect(result).toHaveLength(1)
            expect((result![0].result as any).value.value).toBe('b1')
        })

        it('starts groups from several feeds while a slow group keeps the drain parked', async () => {
            const processor = createNewPipeline<{ value: string; group: string }>().pipe(async (input) => {
                const delay = input.group === 'A' ? 1000 : 10
                await new Promise((resolve) => setTimeout(resolve, delay))
                return ok({ ...input, processed: true })
            })
            const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline
            )

            previousPipeline.feed([createOkContext({ value: 'a1', group: 'A' }, context1)])

            const drained: any[] = []
            const run = (async () => {
                let result = await pipeline.next()
                while (result !== null) {
                    drained.push(...result)
                    // Stop once both fast groups are collected — A blocks for 1000ms.
                    if (drained.length >= 2) {
                        break
                    }
                    result = await pipeline.next()
                }
            })()

            await jest.advanceTimersByTimeAsync(0) // A starts, the drain parks
            pipeline.feed([createOkContext({ value: 'b1', group: 'B' }, context2)])
            await jest.advanceTimersByTimeAsync(0) // B starts
            pipeline.feed([createOkContext({ value: 'c1', group: 'C' }, context3)])
            await jest.advanceTimersByTimeAsync(10) // B and C complete
            await run

            // Both groups, each from a separate feed landed mid-park, were processed.
            expect(drained.map((r) => r.result.value.value).sort()).toEqual(['b1', 'c1'])
        })
    })

    describe('failure surfacing with concurrent groups', () => {
        it('returns a completed group before surfacing a later failure in an in-flight group', async () => {
            const processor = createNewPipeline<{ value: string; group: string }>().pipe(async (input) => {
                if (input.group === 'B') {
                    await new Promise((resolve) => setTimeout(resolve, 10))
                    throw new Error('group B failed')
                }
                await new Promise((resolve) => setTimeout(resolve, 5))
                return ok({ ...input, processed: true })
            })
            const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline
            )

            previousPipeline.feed([
                createOkContext({ value: 'a1', group: 'A' }, context1),
                createOkContext({ value: 'b1', group: 'B' }, context2),
            ])

            // A completes at t=5 while B is still in flight, so the first drain
            // returns A's result rather than waiting on B.
            const first = pipeline.next()
            await jest.advanceTimersByTimeAsync(5)
            const result = await first
            expect(result).toHaveLength(1)
            expect((result![0].result as any).value.value).toBe('a1')

            // The second drain parks on the in-flight B; B's failure at t=10 wakes
            // it and the failure surfaces. Attach the rejection handler before
            // advancing time so the rejection that lands mid-advance is observed.
            const second = pipeline.next()
            const failure = expect(second).rejects.toThrow('group B failed')
            await jest.advanceTimersByTimeAsync(5)
            await failure
        })

        it('drains all completed group results before surfacing a failure', async () => {
            const processor = createNewPipeline<{ value: string; group: string }>().pipe(async (input) => {
                await new Promise((resolve) => setTimeout(resolve, 5))
                if (input.group === 'C') {
                    throw new Error('group C failed')
                }
                return ok({ ...input, processed: true })
            })
            const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline
            )

            previousPipeline.feed([
                createOkContext({ value: 'a1', group: 'A' }, context1),
                createOkContext({ value: 'b1', group: 'B' }, context2),
                createOkContext({ value: 'c1', group: 'C' }, context3),
            ])

            const drained: any[] = []
            let thrown: Error | undefined
            const run = (async () => {
                try {
                    let result = await pipeline.next()
                    while (result !== null) {
                        drained.push(...result)
                        result = await pipeline.next()
                    }
                } catch (error) {
                    thrown = error as Error
                }
            })()

            await jest.advanceTimersByTimeAsync(5)
            await run

            // Both successful groups come out before the failure ends the stream.
            expect(drained.map((r) => r.result.value.value).sort()).toEqual(['a1', 'b1'])
            expect(thrown?.message).toBe('group C failed')
        })

        it('keeps rejecting after a processor error', async () => {
            const processor = createNewPipeline<{ value: string; group: string }>().pipe(() =>
                Promise.reject(new Error('processor boom'))
            )
            const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()
            previousPipeline.feed([createOkContext({ value: 'a1', group: 'A' }, context1)])
            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline
            )

            await expect(pipeline.next()).rejects.toThrow('processor boom')
            await expect(pipeline.next()).rejects.toThrow('processor boom')
        })

        it('poisons permanently after a source error', async () => {
            const processor = createNewPipeline<{ value: string; group: string }>().pipe((input) =>
                Promise.resolve(ok(input))
            )
            const previousPipeline = {
                feed: jest.fn(),
                next: jest.fn().mockRejectedValueOnce(new Error('source boom')).mockResolvedValue(null),
            }
            const pipeline = new ConcurrentlyGroupingChunkPipeline(
                (input: { value: string; group: string }) => input.group,
                processGroupChunkSequentially(processor),
                previousPipeline
            )

            await expect(pipeline.next()).rejects.toThrow('source boom')
            await expect(pipeline.next()).rejects.toThrow('source boom')
        })
    })

    describe('group chunk step', () => {
        it("runs once per group chunk with that group's values in order", async () => {
            const scans: string[][] = []
            const pipeline = createNewChunkPipeline<{ value: string; group: string }>()
                .concurrentlyPerGroup(
                    (input) => input.group,
                    (group) =>
                        group
                            .pipeChunk((values: { value: string; group: string }[]) => {
                                scans.push(values.map((value) => value.value))
                                return Promise.resolve(values.map((value) => ok(value)))
                            })
                            .sequentially((builder) => builder.pipe((input) => Promise.resolve(ok(input))))
                )
                .build()

            pipeline.feed([
                createOkContext({ value: 'a1', group: 'A' }, context1),
                createOkContext({ value: 'b1', group: 'B' }, context2),
                createOkContext({ value: 'a2', group: 'A' }, context3),
            ])

            let result = await pipeline.next()
            while (result !== null) {
                result = await pipeline.next()
            }

            expect(scans).toHaveLength(2)
            expect(scans).toContainEqual(['a1', 'a2'])
            expect(scans).toContainEqual(['b1'])
        })

        it('makes returned values visible to the processor', async () => {
            const seenTags: (string | undefined)[] = []
            const pipeline = createNewChunkPipeline<{ value: string; group: string; groupTag?: string }>()
                .concurrentlyPerGroup(
                    (input) => input.group,
                    (group) =>
                        group
                            .pipeChunk((values: { value: string; group: string; groupTag?: string }[]) =>
                                Promise.resolve(values.map((value) => ok({ ...value, groupTag: `A:${values.length}` })))
                            )
                            .sequentially((builder) =>
                                builder.pipe((input) => {
                                    seenTags.push(input.groupTag)
                                    return Promise.resolve(ok(input))
                                })
                            )
                )
                .build()

            pipeline.feed([
                createOkContext({ value: 'a1', group: 'A' }, context1),
                createOkContext({ value: 'a2', group: 'A' }, context2),
            ])

            let result = await pipeline.next()
            while (result !== null) {
                result = await pipeline.next()
            }

            expect(seenTags).toEqual(['A:2', 'A:2'])
        })

        it('passes step-failed values through without invoking the processor', async () => {
            const processed: string[] = []
            const pipeline = createNewChunkPipeline<{ value: string; group: string }>()
                .concurrentlyPerGroup(
                    (input) => input.group,
                    (group) =>
                        group
                            .pipeChunk((values: { value: string; group: string }[]) =>
                                Promise.resolve(
                                    values.map((value) =>
                                        value.value === 'a1'
                                            ? dlq<{ value: string; group: string }>('rejected by group step')
                                            : ok(value)
                                    )
                                )
                            )
                            .sequentially((builder) =>
                                builder.pipe((input) => {
                                    processed.push(input.value)
                                    return Promise.resolve(ok(input))
                                })
                            )
                )
                .build()

            pipeline.feed([
                createOkContext({ value: 'a1', group: 'A' }, context1),
                createOkContext({ value: 'a2', group: 'A' }, context2),
            ])

            const results: PipelineResultWithContext<any, any>[] = []
            let result = await pipeline.next()
            while (result !== null) {
                results.push(...result)
                result = await pipeline.next()
            }

            expect(processed).toEqual(['a2'])
            expect(results).toHaveLength(2)
            const dlqd = results.find((r) => r.context.message === message1)!
            expect(dlqd.result.type).toBe(1) // DLQ
        })

        it('applies the step to chunks queued while the group was active separately', async () => {
            const scans: string[][] = []
            const pipeline = createNewChunkPipeline<{ value: string; group: string }>()
                .concurrentlyPerGroup(
                    (input) => input.group,
                    (group) =>
                        group
                            .pipeChunk((values: { value: string; group: string }[]) => {
                                scans.push(values.map((value) => value.value))
                                return Promise.resolve(values.map((value) => ok(value)))
                            })
                            .sequentially((builder) =>
                                builder.pipe(async (input) => {
                                    await new Promise((resolve) => setTimeout(resolve, 50))
                                    return ok(input)
                                })
                            )
                )
                .build()

            pipeline.feed([
                createOkContext({ value: 'a1', group: 'A' }, context1),
                createOkContext({ value: 'a2', group: 'A' }, context2),
            ])

            const nextPromise = pipeline.next()
            await jest.advanceTimersByTimeAsync(0)
            expect(scans).toEqual([['a1', 'a2']])

            // a3 arrives while the group is mid-chunk: it must not join the
            // in-flight step application, and gets its own when its chunk starts.
            pipeline.feed([createOkContext({ value: 'a3', group: 'A' }, context3)])
            await jest.advanceTimersByTimeAsync(100)
            await nextPromise

            const nextPromise2 = pipeline.next()
            await jest.advanceTimersByTimeAsync(50)
            await nextPromise2

            expect(scans).toEqual([['a1', 'a2'], ['a3']])
        })

        it('poisons the pipeline when the step throws', async () => {
            const pipeline = createNewChunkPipeline<{ value: string; group: string }>()
                .concurrentlyPerGroup(
                    (input) => input.group,
                    (group) =>
                        group
                            .pipeChunk((): Promise<never> => {
                                throw new Error('group step boom')
                            })
                            .sequentially((builder) => builder.pipe((input) => Promise.resolve(ok(input))))
                )
                .build()

            pipeline.feed([createOkContext({ value: 'a1', group: 'A' }, context1)])

            await expect(pipeline.next()).rejects.toThrow('group step boom')
            await expect(pipeline.next()).rejects.toThrow('group step boom')
        })
    })
})