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.

4.0 KB
Raw Blame
import { captureException } from '~/common/utils/posthog'
import { UUIDT } from '~/common/utils/utils'
import { PipelineResultType } from '~/ingestion/framework/results'
import { processAiEvent } from '~/ingestion/pipelines/ai/process-ai-event'
import { PluginEvent } from '~/plugin-scaffold'

import { createProcessAiEventStep } from './process-ai-event-step'

jest.mock('~/common/utils/posthog', () => ({
    captureException: jest.fn(),
}))

jest.mock('~/ingestion/pipelines/ai/process-ai-event', () => ({
    processAiEvent: jest.fn((event: PluginEvent) => ({
        ...event,
        properties: { ...event.properties, $ai_was_processed: true },
    })),
}))

const mockedProcessAiEvent = processAiEvent as jest.MockedFunction<typeof processAiEvent>
const mockedCaptureException = captureException as jest.MockedFunction<typeof captureException>

function createTestEvent(overrides: Partial<PluginEvent> = {}): PluginEvent {
    return {
        distinct_id: 'user-1',
        ip: null,
        site_url: 'http://localhost',
        team_id: 1,
        now: '2020-02-23T02:15:00Z',
        timestamp: '2020-02-23T02:15:00Z',
        event: '$pageview',
        uuid: new UUIDT().toString(),
        properties: {},
        ...overrides,
    }
}

describe('processAiEventStep', () => {
    beforeEach(() => {
        jest.clearAllMocks()
    })

    it.each([
        '$ai_generation',
        '$ai_embedding',
        '$ai_evaluation',
        '$ai_span',
        '$ai_trace',
        '$ai_metric',
        '$ai_feedback',
        '$ai_tag',
        '$ai_generation_summary',
        '$ai_trace_summary',
        '$ai_evaluation_report',
        // Any `$ai_*` name is an AI event, including ones this code has never seen.
        '$ai_custom_metric',
    ])('calls processAiEvent for %s event', async (eventName) => {
        const event = createTestEvent({ event: eventName, properties: { $ai_model: 'gpt-4' } })
        const step = createProcessAiEventStep()
        const input = { normalizedEvent: event }

        const result = await step(input)

        expect(result.type).toBe(PipelineResultType.OK)
        expect(mockedProcessAiEvent).toHaveBeenCalledWith(event)
        if (result.type === PipelineResultType.OK) {
            expect(result.value.normalizedEvent.properties?.$ai_was_processed).toBe(true)
        }
    })

    it.each(['$pageview', '$autocapture', 'custom_event', '$$heatmap', 'ai_generation', '$AI_generation'])(
        'sends %s event to DLQ',
        async (eventName) => {
            const event = createTestEvent({ event: eventName })
            const step = createProcessAiEventStep()
            const input = { normalizedEvent: event }

            const result = await step(input)

            expect(result.type).toBe(PipelineResultType.DLQ)
            expect(mockedProcessAiEvent).not.toHaveBeenCalled()
        }
    )

    it('passes through unchanged on processAiEvent error', async () => {
        const event = createTestEvent({ event: '$ai_generation' })
        mockedProcessAiEvent.mockImplementationOnce(() => {
            throw new Error('cost calculation failed')
        })

        const step = createProcessAiEventStep()
        const input = { normalizedEvent: event }

        const result = await step(input)

        expect(result.type).toBe(PipelineResultType.OK)
        expect(mockedCaptureException).toHaveBeenCalled()
        if (result.type === PipelineResultType.OK) {
            expect(result.value.normalizedEvent).toBe(event)
        }
    })

    it('preserves additional input fields', async () => {
        const event = createTestEvent({ event: '$ai_generation' })
        const step = createProcessAiEventStep<{ normalizedEvent: PluginEvent; extraField: string }>()
        const input = { normalizedEvent: event, extraField: 'preserved' }

        const result = await step(input)

        expect(result.type).toBe(PipelineResultType.OK)
        if (result.type === PipelineResultType.OK) {
            expect(result.value.extraField).toBe('preserved')
        }
    })
})