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.

20.6 KB
Raw Blame
import {
    LogicWrapper,
    MakeLogicType,
    actions,
    afterMount,
    kea,
    key,
    listeners,
    path,
    props,
    reducers,
    selectors,
} from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'

import { urls } from 'scenes/urls'

import * as api from '../generated/api'
import type {
    ExperimentReceiptApi,
    OfflineExperimentReadApi,
    OfflineItemPageApi,
    OfflineResultCellApi,
    OfflineResultCellsApi,
    OfflineScorerSummaryApi,
    OfflineScorerVersionReadApi,
    OfflineSummaryPageApi,
} from '../generated/api.schemas'
import { loadOfflineRequest } from './loadOfflineRequest'
import {
    OFFLINE_ITEM_COLUMN_WIDTH,
    OFFLINE_SCORER_BATCH_SIZE,
    OFFLINE_SCORER_COLUMN_WIDTH,
} from './offlineItemMatrixConstants'
import { offlineCompletionError, offlineReadError } from './offlineResultPresentation'

export interface OfflineExperimentLogicProps {
    teamId: number
    experimentId: string
}

export interface OfflineCellBatch {
    state: 'loading' | 'loaded' | 'error'
    response?: OfflineResultCellsApi
    error?: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface offlineExperimentLogicValues {
    cellBatches: Record<number, OfflineCellBatch>
    cellEpoch: number
    cellsByItemAndVersion: Record<string, OfflineResultCellApi>
    completed: ExperimentReceiptApi | null
    completedLoading: boolean
    completionError: string | null
    completionOpen: boolean
    experiment: OfflineExperimentReadApi | null
    experimentError: string | null
    experimentLoading: boolean
    focusedScorerVersionId: string | null
    inspector: {
        itemId: string
        resultId?: string
        scorerVersionId?: string
    } | null
    itemCursor: string | null
    itemCursors: string[]
    items: OfflineItemPageApi | null
    itemsError: string | null
    itemsLoading: boolean
    requestedBatches: number[]
    scorers: OfflineScorerVersionReadApi[]
    summaries: OfflineScorerSummaryApi[]
    summariesError: string | null
    summaryCount: number | null
    summaryCountLoading: boolean
    viewport: {
        scrollLeft: number
        width: number
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface offlineExperimentLogicActions {
    addSummaryPage: (page: OfflineSummaryPageApi) => {
        page: OfflineSummaryPageApi
    }
    closeItem: () => {
        value: true
    }
    completeOfflineExperiment: (_: void) => void
    completeOfflineExperimentFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    completeOfflineExperimentSuccess: (
        completed: ExperimentReceiptApi,
        payload?: void
    ) => {
        completed: ExperimentReceiptApi
        payload?: void
    }
    failedCellBatch: (
        index: number,
        error: string
    ) => {
        error: string
        index: number
    }
    hideCompletion: () => {
        value: true
    }
    hydrateInspector: (search: Record<string, unknown>) => {
        search: Record<string, unknown>
    }
    loadCellBatch: (
        index: number,
        epoch: number,
        itemIds: string[],
        versionIds: string[]
    ) => {
        epoch: number
        index: number
        itemIds: string[]
        versionIds: string[]
    }
    loadOfflineExperiment: (_: void) => void
    loadOfflineExperimentFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadOfflineExperimentSuccess: (
        experiment: OfflineExperimentReadApi,
        payload?: void
    ) => {
        experiment: OfflineExperimentReadApi
        payload?: void
    }
    loadOfflineItems: (_: void) => void
    loadOfflineItemsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadOfflineItemsSuccess: (
        items: OfflineItemPageApi,
        payload?: void
    ) => {
        items: OfflineItemPageApi
        payload?: void
    }
    loadOfflineSummaries: (_: void) => void
    loadOfflineSummariesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadOfflineSummariesSuccess: (
        summaryCount: number,
        payload?: void
    ) => {
        summaryCount: number
        payload?: void
    }
    loadedCellBatch: (
        index: number,
        response: OfflineResultCellsApi
    ) => {
        index: number
        response: OfflineResultCellsApi
    }
    nextItems: (cursor: string) => {
        cursor: string
    }
    openItem: (
        itemId: string,
        resultId?: string,
        scorerVersionId?: string
    ) => {
        itemId: string
        resultId: string | undefined
        scorerVersionId: string | undefined
    }
    previousItems: () => {
        value: true
    }
    pumpCells: () => {
        value: true
    }
    refresh: () => {
        value: true
    }
    retryCellBatch: (index: number) => {
        index: number
    }
    setViewport: (
        scrollLeft: number,
        width: number
    ) => {
        scrollLeft: number
        width: number
    }
    showCompletion: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface offlineExperimentLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        cellsByItemAndVersion: (cellBatches: Record<number, OfflineCellBatch>) => Record<string, OfflineResultCellApi>
        itemCursor: (itemCursors: string[]) => string | null
        scorers: (summaries: OfflineScorerSummaryApi[]) => OfflineScorerVersionReadApi[]
        requestedBatches: (
            viewport: {
                scrollLeft: number
                width: number
            },
            scorers: OfflineScorerVersionReadApi[]
        ) => number[]
    }
}

export type offlineExperimentLogicType = MakeLogicType<
    offlineExperimentLogicValues,
    offlineExperimentLogicActions,
    OfflineExperimentLogicProps,
    offlineExperimentLogicMeta
>

export const offlineExperimentLogic: LogicWrapper<offlineExperimentLogicType> = kea<offlineExperimentLogicType>([
    props({} as OfflineExperimentLogicProps),
    key(({ teamId, experimentId }) => `${teamId}:${experimentId}`),
    path((key) => ['products', 'ai_observability', 'offlineExperimentLogic', key]),
    actions({
        refresh: true,
        addSummaryPage: (page: OfflineSummaryPageApi) => ({ page }),
        nextItems: (cursor: string) => ({ cursor }),
        previousItems: true,
        setViewport: (scrollLeft: number, width: number) => ({ scrollLeft, width }),
        pumpCells: true,
        loadCellBatch: (index: number, epoch: number, itemIds: string[], versionIds: string[]) => ({
            index,
            epoch,
            itemIds,
            versionIds,
        }),
        loadedCellBatch: (index: number, response: OfflineResultCellsApi) => ({ index, response }),
        failedCellBatch: (index: number, error: string) => ({ index, error }),
        retryCellBatch: (index: number) => ({ index }),
        openItem: (itemId: string, resultId?: string, scorerVersionId?: string) => ({
            itemId,
            resultId,
            scorerVersionId,
        }),
        closeItem: true,
        hydrateInspector: (search: Record<string, unknown>) => ({ search }),
        showCompletion: true,
        hideCompletion: true,
    }),
    loaders(({ actions, props, values }) => ({
        experiment: [
            null as OfflineExperimentReadApi | null,
            {
                loadOfflineExperiment: (_: void, breakpoint) => {
                    return loadOfflineRequest(
                        () => api.aiObservabilityOfflineExperimentsRetrieve(String(props.teamId), props.experimentId),
                        breakpoint
                    )
                },
            },
        ],
        summaryCount: [
            null as number | null,
            {
                loadOfflineSummaries: async (_: void, breakpoint) => {
                    let cursor: string | undefined
                    let count = 0
                    do {
                        try {
                            const page = await api.aiObservabilityOfflineExperimentsScorerSummariesList(
                                String(props.teamId),
                                props.experimentId,
                                { limit: 100, cursor }
                            )
                            breakpoint()
                            actions.addSummaryPage(page)
                            count = page.count
                            cursor = page.next_cursor || undefined
                        } catch (error) {
                            breakpoint()
                            throw error
                        }
                    } while (cursor)
                    return count
                },
            },
        ],
        items: [
            null as OfflineItemPageApi | null,
            {
                loadOfflineItems: (_: void, breakpoint) => {
                    return loadOfflineRequest(
                        () =>
                            api.aiObservabilityOfflineExperimentsItemsList(String(props.teamId), props.experimentId, {
                                limit: 50,
                                cursor: values.itemCursor || undefined,
                            }),
                        breakpoint
                    )
                },
            },
        ],
        completed: [
            null as ExperimentReceiptApi | null,
            {
                completeOfflineExperiment: (_: void, breakpoint) => {
                    return loadOfflineRequest(
                        () =>
                            api.aiObservabilityOfflineExperimentsCompleteCreate(
                                String(props.teamId),
                                props.experimentId,
                                { body: '{}' }
                            ),
                        breakpoint
                    )
                },
            },
        ],
    })),
    reducers({
        summaries: [
            [] as OfflineScorerSummaryApi[],
            {
                loadOfflineSummaries: () => [],
                addSummaryPage: (state, { page }) => [...state, ...page.results],
            },
        ],
        itemCursors: [
            [] as string[],
            {
                nextItems: (state, { cursor }) => [...state, cursor],
                previousItems: (state) => state.slice(0, -1),
                refresh: () => [],
            },
        ],
        cellEpoch: [0, { loadOfflineItems: (state) => state + 1 }],
        cellBatches: [
            {} as Record<number, OfflineCellBatch>,
            {
                loadOfflineItems: () => ({}),
                loadCellBatch: (state, { index }) => ({ ...state, [index]: { state: 'loading' as const } }),
                loadedCellBatch: (state, { index, response }) => ({
                    ...state,
                    [index]: { state: 'loaded' as const, response },
                }),
                failedCellBatch: (state, { index, error }) => ({
                    ...state,
                    [index]: { state: 'error' as const, error },
                }),
                retryCellBatch: (state, { index }) => {
                    const next = { ...state }
                    delete next[index]
                    return next
                },
            },
        ],
        viewport: [
            { scrollLeft: 0, width: 1000 },
            {
                setViewport: (_, viewport) => viewport,
                // Clearing the summaries removes the score columns, so the browser resets the table scroll to 0.
                loadOfflineSummaries: (state) => ({ ...state, scrollLeft: 0 }),
            },
        ],
        inspector: [
            null as { itemId: string; resultId?: string; scorerVersionId?: string } | null,
            {
                openItem: (_, value) => value,
                closeItem: () => null,
                hydrateInspector: (_, { search }) =>
                    typeof search.item_id === 'string'
                        ? {
                              itemId: search.item_id,
                              resultId: typeof search.result_id === 'string' ? search.result_id : undefined,
                              scorerVersionId:
                                  typeof search.scorer_version_id === 'string' ? search.scorer_version_id : undefined,
                          }
                        : null,
            },
        ],
        focusedScorerVersionId: [
            null as string | null,
            {
                openItem: (state, { scorerVersionId }) => scorerVersionId || state,
                hydrateInspector: (_, { search }) =>
                    typeof search.scorer_version_id === 'string' ? search.scorer_version_id : null,
            },
        ],
        completionOpen: [
            false,
            { showCompletion: () => true, hideCompletion: () => false, completeOfflineExperimentSuccess: () => false },
        ],
        experimentError: [
            null as string | null,
            {
                loadOfflineExperiment: () => null,
                loadOfflineExperimentFailure: (_, { errorObject }) =>
                    offlineReadError(errorObject, 'Could not load this experiment. Try again.'),
            },
        ],
        summariesError: [
            null as string | null,
            {
                loadOfflineSummaries: () => null,
                loadOfflineSummariesFailure: (_, { errorObject }) =>
                    offlineReadError(errorObject, 'Could not load all scorer summaries. Try again.'),
            },
        ],
        itemsError: [
            null as string | null,
            {
                loadOfflineItems: () => null,
                loadOfflineItemsFailure: (_, { errorObject }) =>
                    offlineReadError(errorObject, 'Could not load items. Try again.'),
            },
        ],
        completionError: [
            null as string | null,
            {
                completeOfflineExperiment: () => null,
                completeOfflineExperimentFailure: (_, { errorObject }) => offlineCompletionError(errorObject),
            },
        ],
    }),
    selectors({
        cellsByItemAndVersion: [
            (s) => [s.cellBatches],
            (batches: Record<number, OfflineCellBatch>): Record<string, OfflineResultCellApi> =>
                Object.fromEntries(
                    Object.values(batches).flatMap((batch) =>
                        (batch.response?.results || []).map((result) => [
                            `${result.item_id}:${result.scorer_version_id}`,
                            result,
                        ])
                    )
                ),
        ],
        itemCursor: [(s) => [s.itemCursors], (cursors: string[]): string | null => cursors[cursors.length - 1] || null],
        scorers: [
            (s) => [s.summaries],
            (summaries: OfflineScorerSummaryApi[]): OfflineScorerVersionReadApi[] =>
                summaries.map((summary) => summary.scorer),
        ],
        requestedBatches: [
            (s) => [s.viewport, s.scorers],
            (
                viewport: {
                    scrollLeft: number
                    width: number
                },
                scorers: OfflineScorerVersionReadApi[]
            ): number[] => {
                const start = Math.max(
                    0,
                    Math.floor(
                        Math.max(0, viewport.scrollLeft - OFFLINE_ITEM_COLUMN_WIDTH) /
                            OFFLINE_SCORER_COLUMN_WIDTH /
                            OFFLINE_SCORER_BATCH_SIZE
                    ) - 1
                )
                const end = Math.min(
                    Math.ceil(scorers.length / OFFLINE_SCORER_BATCH_SIZE) - 1,
                    Math.floor(
                        (viewport.scrollLeft + viewport.width) / OFFLINE_SCORER_COLUMN_WIDTH / OFFLINE_SCORER_BATCH_SIZE
                    ) + 1
                )
                return Array.from({ length: Math.max(0, end - start + 1) }, (_, index) => start + index)
            },
        ],
    }),
    listeners((logic) => {
        const { actions, values, props, cache } = logic
        return {
            refresh: () => {
                actions.loadOfflineExperiment()
                actions.loadOfflineSummaries()
                actions.loadOfflineItems()
            },
            nextItems: () => actions.loadOfflineItems(),
            previousItems: () => actions.loadOfflineItems(),
            loadOfflineItemsSuccess: () => actions.pumpCells(),
            addSummaryPage: () => actions.pumpCells(),
            setViewport: () => actions.pumpCells(),
            retryCellBatch: () => actions.pumpCells(),
            pumpCells: () => {
                if (values.itemsLoading || !values.items?.results.length) {
                    return
                }
                const active = Object.values(values.cellBatches).filter((batch) => batch.state === 'loading').length
                for (const index of values.requestedBatches
                    .filter((index) => !values.cellBatches[index])
                    .slice(0, Math.max(0, 2 - active))) {
                    actions.loadCellBatch(
                        index,
                        values.cellEpoch,
                        values.items.results.map((item) => item.id),
                        values.scorers
                            .slice(
                                index * OFFLINE_SCORER_BATCH_SIZE,
                                index * OFFLINE_SCORER_BATCH_SIZE + OFFLINE_SCORER_BATCH_SIZE
                            )
                            .map((scorer) => scorer.id)
                    )
                }
            },
            loadCellBatch: async ({ index, epoch, itemIds, versionIds }) => {
                const mountToken = cache.mountToken
                try {
                    const response = await api.aiObservabilityOfflineExperimentsResultCellsRetrieve(
                        String(props.teamId),
                        props.experimentId,
                        {
                            item_ids: [...itemIds].sort().join(','),
                            scorer_version_ids: [...versionIds].sort().join(','),
                        }
                    )
                    if (
                        offlineExperimentLogic.isMounted(props) &&
                        cache.mountToken === mountToken &&
                        values.cellEpoch === epoch
                    ) {
                        actions.loadedCellBatch(index, response)
                    }
                } catch (error) {
                    if (
                        offlineExperimentLogic.isMounted(props) &&
                        cache.mountToken === mountToken &&
                        values.cellEpoch === epoch
                    ) {
                        actions.failedCellBatch(
                            index,
                            offlineReadError(error, 'Could not load these scores. Retry this column batch.')
                        )
                    }
                } finally {
                    if (offlineExperimentLogic.isMounted(props) && cache.mountToken === mountToken) {
                        actions.pumpCells()
                    }
                }
            },
            completeOfflineExperimentSuccess: () => actions.refresh(),
            completeOfflineExperimentFailure: () => actions.loadOfflineExperiment(),
        }
    }),
    actionToUrl(({ props, values }) => ({
        openItem: () => [
            urls.aiObservabilityOfflineEvaluationExperiment(props.experimentId),
            {
                ...router.values.searchParams,
                item_id: values.inspector?.itemId,
                result_id: values.inspector?.resultId,
                scorer_version_id: values.inspector?.scorerVersionId || values.focusedScorerVersionId,
            },
        ],
        closeItem: () => [
            urls.aiObservabilityOfflineEvaluationExperiment(props.experimentId),
            { ...router.values.searchParams, item_id: undefined, result_id: undefined },
        ],
    })),
    urlToAction(({ actions, props }) => ({
        [urls.aiObservabilityOfflineEvaluationExperiment(':experimentId', false)]: ({ experimentId }, search) => {
            if (experimentId === props.experimentId) {
                actions.hydrateInspector(search)
            }
        },
    })),
    afterMount(({ actions, cache }) => {
        cache.mountToken = Symbol()
        actions.hydrateInspector(router.values.searchParams)
        actions.refresh()
    }),
])