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.

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

import { CdpOutputs } from '../../cdp-services'
import { CDP_EVENTS_DLQ_OUTPUT } from '../../outputs/outputs'
import { DeadLetterStep, HogFunctionInvocationGlobals, InvocationBuildFailure } from '../../types'
import { CdpDeadLetterService } from './cdp-dead-letter.service'

describe('CdpDeadLetterService', () => {
    let produce: jest.Mock
    let outputs: CdpOutputs
    let messagesByGlobals: Map<HogFunctionInvocationGlobals, Message>

    const message = (uuid: string, offset = 10): Message =>
        ({
            value: Buffer.from(JSON.stringify({ uuid })),
            key: Buffer.from(uuid),
            topic: 'clickhouse_events_json',
            partition: 3,
            offset,
            size: 0,
            headers: [{ token: Buffer.from('phc_abc') }],
        }) as unknown as Message

    const globalsFor = (teamId: number, uuid: string): HogFunctionInvocationGlobals =>
        ({ project: { id: teamId }, event: { uuid } }) as HogFunctionInvocationGlobals

    const defaultGlobals = globalsFor(2, 'event-1')

    const failure = (overrides: Partial<InvocationBuildFailure> = {}): InvocationBuildFailure => ({
        sourceId: 'fn-1',
        sourceKind: 'hog_function',
        step: 'inputs',
        error: 'Invalid arguments',
        ...overrides,
    })

    const batchOf = (size: number): Message[] =>
        Array.from({ length: size }, (_, offset) => message(`event-${offset}`, offset))

    const recordFailure = (service: CdpDeadLetterService, step: DeadLetterStep, source: Message): void => {
        if (step === 'parse' || step === 'lookup') {
            service.recordMessageFailure(source, { step, error: 'boom' })
            return
        }
        const globals = globalsFor(2, `event-${source.offset}`)
        messagesByGlobals.set(globals, source)
        if (step === 'process') {
            service.recordProcessFailure(globals, new Error('boom'), 'hog_function')
        } else {
            service.recordBuildFailures(globals, [failure({ step })])
        }
    }

    const createService = (enabled = true): CdpDeadLetterService =>
        new CdpDeadLetterService(
            { CDP_DLQ_ENABLED: enabled, CDP_DLQ_BATCH_FAIL_RATIO: 0.1 },
            {
                outputs,
                output: CDP_EVENTS_DLQ_OUTPUT,
                consumerGroup: 'cdp-processed-events-consumer',
                resolveMessage: (globals) => messagesByGlobals.get(globals),
            }
        )

    beforeEach(() => {
        produce = jest.fn().mockResolvedValue(undefined)
        outputs = { produce } as unknown as CdpOutputs
        messagesByGlobals = new Map()
        messagesByGlobals.set(defaultGlobals, message('event-1'))
    })

    it('parks the original bytes with the source position and the failed function', async () => {
        const service = createService()
        service.recordBuildFailures(defaultGlobals, [failure()])

        await service.produceForBatch([message('event-1')])

        expect(produce).toHaveBeenCalledTimes(1)
        expect(produce).toHaveBeenCalledWith(CDP_EVENTS_DLQ_OUTPUT, {
            value: Buffer.from(JSON.stringify({ uuid: 'event-1' })),
            key: Buffer.from('event-1'),
            headers: {
                token: 'phc_abc',
                dlq_step: 'inputs',
                dlq_reason: 'Invalid arguments',
                dlq_class: '',
                dlq_timestamp: expect.any(String),
                dlq_topic: 'clickhouse_events_json',
                dlq_partition: '3',
                dlq_offset: '10',
                dlq_consumer_group: 'cdp-processed-events-consumer',
                dlq_team_id: '2',
                dlq_hog_function_ids: 'fn-1',
                dlq_hog_flow_ids: '',
                dlq_kinds: 'hog_function',
            },
        })
    })

    it('parks only the failures we can fix, and says which class parked them', async () => {
        // The owner's classes would fill the queue with events no rebuild can change.
        const service = createService()
        service.recordBuildFailures(defaultGlobals, [
            failure({ sourceId: 'ours', errorClass: 'drift' }),
            failure({ sourceId: 'theirs', errorClass: 'data' }),
            failure({ sourceId: 'timed-out', errorClass: 'limit' }),
            failure({ sourceId: 'unstamped', errorClass: 'legacy' }),
        ])

        await service.produceForBatch([message('event-1')])

        expect(produce).toHaveBeenCalledTimes(1)
        expect(produce).toHaveBeenCalledWith(
            CDP_EVENTS_DLQ_OUTPUT,
            expect.objectContaining({
                headers: expect.objectContaining({ dlq_hog_function_ids: 'ours', dlq_class: 'drift' }),
            })
        )
    })

    it('parks nothing when every failure belongs to the owner', async () => {
        const service = createService()
        service.recordBuildFailures(defaultGlobals, [failure({ errorClass: 'data' }), failure({ errorClass: 'limit' })])

        await service.produceForBatch([message('event-1')])

        expect(produce).not.toHaveBeenCalled()
    })

    it('writes one record per event and step, naming every source that failed at that step', async () => {
        const service = createService()
        service.recordBuildFailures(defaultGlobals, [
            failure({ sourceId: 'fn-1' }),
            failure({ sourceId: 'fn-2' }),
            failure({ sourceId: 'flow-1', sourceKind: 'hog_flow' }),
            failure({ sourceId: 'fn-3', step: 'filter' }),
        ])

        await service.produceForBatch([message('event-1')])

        expect(produce).toHaveBeenCalledTimes(2)
        const byStep = Object.fromEntries(produce.mock.calls.map(([, m]) => [m.headers.dlq_step, m.headers]))
        expect(byStep.inputs).toMatchObject({ dlq_hog_function_ids: 'fn-1,fn-2', dlq_hog_flow_ids: 'flow-1' })
        expect(byStep.filter).toMatchObject({ dlq_hog_function_ids: 'fn-3', dlq_hog_flow_ids: '' })
    })

    it('parks a message that could not be parsed, naming no function', async () => {
        const service = createService()
        service.recordMessageFailure(message('event-1'), {
            step: 'parse',
            error: 'Unexpected end of JSON input',
        })

        await service.produceForBatch([])

        expect(produce).toHaveBeenCalledTimes(1)
        expect(produce.mock.calls[0][1].headers).toMatchObject({
            dlq_step: 'parse',
            dlq_reason: 'Unexpected end of JSON input',
            // No team and no functions: a replay rebuilds everything the team has, because nothing
            // was built the first time.
            dlq_team_id: '',
            dlq_hog_function_ids: '',
            dlq_hog_flow_ids: '',
        })
    })

    it('parks an event that threw outside the handled failures', async () => {
        const service = createService()
        service.recordProcessFailure(defaultGlobals, new Error('Cannot read properties of undefined'), 'hog_function')

        await service.produceForBatch([message('event-1')])

        expect(produce.mock.calls[0][1].headers).toMatchObject({
            dlq_step: 'process',
            dlq_team_id: '2',
            dlq_hog_function_ids: '',
        })
    })

    it.each<{ name: string; steps: DeadLetterStep[]; counts: string }>([
        { name: 'throws unexpectedly', steps: ['process', 'process', 'process'], counts: '3 process, 0 lookup' },
        { name: 'fails its lookups', steps: ['lookup', 'lookup', 'lookup'], counts: '0 process, 3 lookup' },
        { name: 'throws or fails its lookups', steps: ['process', 'lookup', 'lookup'], counts: '1 process, 2 lookup' },
    ])('fails the batch instead of parking it when most of it $name', async ({ steps, counts }) => {
        const service = createService()
        const messages = batchOf(4)
        steps.forEach((step, index) => recordFailure(service, step, messages[index]))

        await expect(service.produceForBatch(messages)).rejects.toThrow(
            `Refusing to dead-letter 3 of 4 messages (${counts})`
        )
        expect(produce).not.toHaveBeenCalled()
    })

    it.each<{ name: string; step: DeadLetterStep; failing: number; batchSize: number }>([
        // A ratio says nothing about one message. Breaking here would stall the partition on the
        // very event this path exists to park.
        { name: 'a lone unexpected failure in a batch of one', step: 'process', failing: 1, batchSize: 1 },
        // Three meets the floor, but three of forty is under the ratio.
        { name: 'three lookup failures in a batch of forty', step: 'lookup', failing: 3, batchSize: 40 },
    ])('parks $name rather than breaking', async ({ step, failing, batchSize }) => {
        const service = createService()
        const messages = batchOf(batchSize)
        messages.slice(0, failing).forEach((source) => recordFailure(service, step, source))

        await service.produceForBatch(messages)

        expect(produce).toHaveBeenCalledTimes(failing)
    })

    it('counts events, not failures, when two pipelines both throw on the same event', async () => {
        // The function and flow pipelines each record against one event, so counting entries let
        // two bad events reach the floor of three and stall a partition early.
        const service = createService()
        const messages = [message('event-1', 10), message('event-2', 11)]
        const second = globalsFor(2, 'event-2')
        messagesByGlobals.set(second, messages[1])
        for (const globals of [defaultGlobals, second]) {
            service.recordProcessFailure(globals, new Error('from the function pipeline'), 'hog_function')
            service.recordProcessFailure(globals, new Error('from the flow pipeline'), 'hog_function')
        }

        await service.produceForBatch(messages)

        expect(produce).toHaveBeenCalledTimes(2)
    })

    it('reports that a disabled queue retained nothing, so a caller can let the error through', () => {
        const service = createService(false)

        expect(service.recordProcessFailure(defaultGlobals, new Error('boom'), 'hog_function')).toBe(false)
    })

    it.each<{ name: string; steps: DeadLetterStep[] }>([
        // One broken builtin legitimately breaks every function in a batch. Those records are
        // exactly what the replay needs, so the ratio must not apply to them.
        { name: 'filter and input failures', steps: ['filter', 'inputs', 'inputs'] },
        { name: 'parse failures', steps: ['parse', 'parse', 'parse'] },
    ])('still parks a whole batch of $name', async ({ steps }) => {
        // Sized to clear the breaker on every axis: three events is the floor, and three of four
        // messages is past the ratio. Counting these would fail the batch here.
        const service = createService()
        const messages = batchOf(4)
        steps.forEach((step, index) => recordFailure(service, step, messages[index]))

        await service.produceForBatch(messages)

        expect(produce).toHaveBeenCalledTimes(3)
    })

    it('gives each team its own record when two events collide on the same client-supplied ID', async () => {
        // Event IDs come from the client, so two teams can send the same one on a topic that
        // carries every team. Nothing here keys on the ID, so there is nothing to collide.
        const service = createService()
        const teamA = globalsFor(2, 'shared')
        const teamB = globalsFor(3, 'shared')
        const messageA = message('a', 10)
        const messageB = message('b', 11)
        messagesByGlobals.set(teamA, messageA)
        messagesByGlobals.set(teamB, messageB)

        service.recordBuildFailures(teamA, [failure({ sourceId: 'fn-a' })])
        service.recordBuildFailures(teamB, [failure({ sourceId: 'fn-b' })])
        await service.produceForBatch([messageA, messageB])

        expect(produce).toHaveBeenCalledTimes(2)
        const byTeam = Object.fromEntries(produce.mock.calls.map(([, m]) => [m.headers.dlq_team_id, m]))
        expect(byTeam['2'].value).toEqual(messageA.value)
        expect(byTeam['2'].headers.dlq_hog_function_ids).toBe('fn-a')
        expect(byTeam['3'].value).toEqual(messageB.value)
        expect(byTeam['3'].headers.dlq_hog_function_ids).toBe('fn-b')
    })

    it('produces nothing while the queue is disabled', async () => {
        const service = createService(false)
        service.recordBuildFailures(defaultGlobals, [failure()])

        await service.produceForBatch([message('event-1')])

        expect(produce).not.toHaveBeenCalled()
    })

    it('fails the batch when a record cannot be produced', async () => {
        produce.mockRejectedValue(new Error('broker unavailable'))
        const service = createService()
        service.recordBuildFailures(defaultGlobals, [failure()])

        await expect(service.produceForBatch([message('event-1')])).rejects.toThrow('broker unavailable')
    })

    it('fails the batch when a failure has no source message left to park', async () => {
        // Nothing to write means nothing to replay, so advancing past the event loses it.
        const service = createService()
        const untracked = globalsFor(2, 'event-untracked')
        service.recordBuildFailures(untracked, [failure()])

        await expect(service.produceForBatch([message('event-untracked')])).rejects.toThrow('No source message')
        expect(produce).not.toHaveBeenCalled()
    })

    it('parks every failure it accepted, across steps, events and sources', async () => {
        // The one invariant that matters: nothing recorded may quietly fail to reach the topic.
        // Counts the records rather than inspecting them, so a new step cannot slip through.
        const service = createService()
        const second = globalsFor(7, 'event-2')
        const messages = [message('event-1', 10), message('event-2', 11), message('event-3', 12)]
        messagesByGlobals.set(second, messages[1])

        service.recordBuildFailures(defaultGlobals, [failure({ sourceId: 'fn-1' }), failure({ sourceId: 'fn-2' })])
        service.recordBuildFailures(defaultGlobals, [failure({ sourceId: 'flow-1', sourceKind: 'hog_flow' })])
        service.recordBuildFailures(second, [failure({ step: 'filter', sourceId: 'fn-3' })])
        service.recordProcessFailure(second, new Error('boom'), 'hog_function')
        service.recordMessageFailure(messages[2], { step: 'parse', error: 'not json' })

        await service.produceForBatch(messages)

        // event-1 inputs, event-2 filter, event-2 process, event-3 parse.
        expect(produce).toHaveBeenCalledTimes(4)
        const steps = produce.mock.calls.map((call) => call[1].headers.dlq_step).sort()
        expect(steps).toEqual(['filter', 'inputs', 'parse', 'process'])
        const named = produce.mock.calls
            .flatMap((call) => [call[1].headers.dlq_hog_function_ids, call[1].headers.dlq_hog_flow_ids])
            .filter(Boolean)
            .flatMap((ids: string) => ids.split(','))
            .sort()
        expect(named).toEqual(['flow-1', 'fn-1', 'fn-2', 'fn-3'])
    })

    it('clears recorded failures so the next batch does not repark them', async () => {
        const service = createService()
        service.recordBuildFailures(defaultGlobals, [failure()])
        await service.produceForBatch([message('event-1')])

        await service.produceForBatch([message('event-1')])

        expect(produce).toHaveBeenCalledTimes(1)
    })
})