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.

7.1 KB
Raw Blame
import { Message } from 'node-rdkafka'
import { register } from 'prom-client'

import { IMAGE_FETCH_BATCH_JOIN_TIMEOUT_MS, ImageFetchBatchJoiner } from './image-fetch-batch-joiner'

function message(partition: number): Message {
    return {
        topic: 'session_replay_image_fetch',
        partition,
        offset: 1,
        value: Buffer.from(`partition-${partition}`),
        size: 11,
    }
}

function deferred(): { promise: Promise<void>; resolve: () => void; reject: (error: unknown) => void } {
    let resolve!: () => void
    let reject!: (error: unknown) => void
    const promise = new Promise<void>((done, fail) => {
        resolve = done
        reject = fail
    })
    return { promise, resolve, reject }
}

describe('ImageFetchBatchJoiner', () => {
    beforeEach(() => {
        jest.useFakeTimers()
        register.resetMetrics()
    })
    afterEach(() => jest.useRealTimers())

    it.each([1, 2, 16])('joins batches from %i consumers before processing', async (consumerCount) => {
        const pass = deferred()
        const processBatch = jest.fn(() => pass.promise)
        const joiner = new ImageFetchBatchJoiner(consumerCount, processBatch)

        const messages = Array.from({ length: consumerCount }, (_, partition) => message(partition))
        const pending = messages.slice(0, -1).map((item) => joiner.handleBatch([item]))
        expect(processBatch).not.toHaveBeenCalled()
        pending.push(joiner.handleBatch([messages[consumerCount - 1]]))

        const batches = await Promise.all(pending)
        expect(processBatch).toHaveBeenCalledTimes(1)
        expect(processBatch).toHaveBeenCalledWith(messages)
        expect(batches.every((batch) => batch?.backgroundTask === batches[0]?.backgroundTask)).toBe(true)
        const completed = jest.fn()
        const completion = Promise.all(batches.map((batch) => batch?.backgroundTask ?? Promise.resolve())).then(
            completed
        )
        await jest.advanceTimersByTimeAsync(0)
        expect(completed).not.toHaveBeenCalled()
        pass.resolve()
        await completion
    })

    it.each([2, 16])(
        'processes a partial batch with a target of %i when the join window ends',
        async (consumerCount) => {
            const processBatch = jest.fn(() => Promise.resolve())
            const joiner = new ImageFetchBatchJoiner(consumerCount, processBatch)

            const pending = joiner.handleBatch([message(0)])
            await jest.advanceTimersByTimeAsync(IMAGE_FETCH_BATCH_JOIN_TIMEOUT_MS - 1)
            expect(processBatch).not.toHaveBeenCalled()
            await jest.advanceTimersByTimeAsync(1)

            await (
                await pending
            )?.backgroundTask
            expect(processBatch).toHaveBeenCalledWith([message(0)])
        }
    )

    it('rejects active and pending consumers when processing fails', async () => {
        const error = new Error('fetch pass failed')
        const pass = deferred()
        const joiner = new ImageFetchBatchJoiner(2, () => pass.promise)

        const first = joiner.handleBatch([message(0)])
        await jest.advanceTimersByTimeAsync(IMAGE_FETCH_BATCH_JOIN_TIMEOUT_MS)
        const firstCompletion = (await first)?.backgroundTask
        const second = joiner.handleBatch([message(1)])
        const active = register.getSingleMetric('ml_image_fetch_stage_active')!
        expect((await active.get()).values).toEqual(
            expect.arrayContaining([
                expect.objectContaining({ labels: { stage: 'consumer_join' }, value: 1 }),
                expect.objectContaining({ labels: { stage: 'consumer_process' }, value: 1 }),
            ])
        )
        const rejected = Promise.all([expect(firstCompletion).rejects.toBe(error), expect(second).rejects.toBe(error)])
        pass.reject(error)
        await rejected
        await expect(joiner.handleBatch([message(2)])).rejects.toBe(error)
        expect((await active.get()).values).toEqual(
            expect.arrayContaining([
                expect.objectContaining({ labels: { stage: 'consumer_join' }, value: 0 }),
                expect.objectContaining({ labels: { stage: 'consumer_process' }, value: 0 }),
            ])
        )
    })

    it('does not hold a later partial batch behind active processing', async () => {
        const firstPass = deferred()
        const secondPass = deferred()
        const processBatch = jest
            .fn()
            .mockImplementationOnce(() => firstPass.promise)
            .mockImplementationOnce(() => secondPass.promise)
        const joiner = new ImageFetchBatchJoiner(2, processBatch)

        const first = joiner.handleBatch([message(0)])
        await jest.advanceTimersByTimeAsync(IMAGE_FETCH_BATCH_JOIN_TIMEOUT_MS)
        const second = joiner.handleBatch([message(1)])
        await jest.advanceTimersByTimeAsync(IMAGE_FETCH_BATCH_JOIN_TIMEOUT_MS)
        expect(processBatch).toHaveBeenCalledTimes(2)

        secondPass.resolve()
        await (
            await second
        )?.backgroundTask
        firstPass.resolve()
        await (
            await first
        )?.backgroundTask
        expect(processBatch).toHaveBeenLastCalledWith([message(1)])
    })

    it('keeps a fast consumer out of the same group twice while overlapping processing', async () => {
        const firstPass = deferred()
        const secondPass = deferred()
        const processBatch = jest
            .fn()
            .mockImplementationOnce(() => firstPass.promise)
            .mockImplementationOnce(() => secondPass.promise)
        const joiner = new ImageFetchBatchJoiner(2, processBatch)
        const secondFromFastConsumer = jest.fn(() => joiner.handleBatch([message(0)]))

        const firstFast = joiner.handleBatch([message(0)])
        const secondFast = firstFast.then(secondFromFastConsumer)
        await jest.advanceTimersByTimeAsync(0)
        expect(secondFromFastConsumer).not.toHaveBeenCalled()

        const firstSlow = joiner.handleBatch([message(1)])
        await firstSlow
        await jest.advanceTimersByTimeAsync(0)
        expect(secondFromFastConsumer).toHaveBeenCalledTimes(1)
        expect(processBatch).toHaveBeenCalledTimes(1)

        const secondSlow = joiner.handleBatch([message(1)])
        const secondBatches = await Promise.all([secondFast, secondSlow])
        expect(processBatch.mock.calls).toEqual([[[message(0), message(1)]], [[message(0), message(1)]]])
        const active = register.getSingleMetric('ml_image_fetch_stage_active')!
        expect((await active.get()).values).toEqual(
            expect.arrayContaining([expect.objectContaining({ labels: { stage: 'consumer_process' }, value: 4 })])
        )

        secondPass.resolve()
        await Promise.all(secondBatches.map((batch) => batch?.backgroundTask ?? Promise.resolve()))
        expect((await active.get()).values).toEqual(
            expect.arrayContaining([expect.objectContaining({ labels: { stage: 'consumer_process' }, value: 2 })])
        )
        firstPass.resolve()
        await (
            await firstFast
        )?.backgroundTask
        expect((await active.get()).values).toEqual(
            expect.arrayContaining([expect.objectContaining({ labels: { stage: 'consumer_process' }, value: 0 })])
        )
    })
})