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.

13.4 KB
Raw Blame
import { MakeLogicType, actions, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { formatDate } from 'lib/utils/datetime'

import { AlertState, DetectorConfig, DetectorType } from '~/queries/schema/schema-general'

import type { AlertCheck, AlertType } from '../types'

export const CHART_CHECKS_LIMIT = 50
export const TABLE_CHECKS_PAGE_SIZE = 25

export interface ChecksHistoryParams {
    limit: number
    offset: number
}

export const DEFAULT_CHECKS_HISTORY_PARAMS: ChecksHistoryParams = {
    limit: TABLE_CHECKS_PAGE_SIZE,
    offset: 0,
}

export interface AlertHistoryChartPoint {
    value: number
    label: string
    /**
     * Whether the check was in a firing state at the time it ran — source of truth for historical firings.
     * Use this instead of re-applying the alert's current thresholds, which may have changed since the check.
     */
    firedAtTime?: boolean
    /**
     * Whether the check would fire under the alert's current configuration. `undefined` lets the chart infer it
     * from the thresholds; `null` marks a check it cannot classify.
     */
    wouldFireUnderCurrentConfiguration?: boolean | null
}

export interface AlertLogicProps {
    alertId?: AlertType['id'] | null
}

function initialChecksHistoryParams(): ChecksHistoryParams {
    return {
        limit: CHART_CHECKS_LIMIT,
        offset: 0,
    }
}

/** Whether the AI detector produced the check. Older AI checks predate `detector_type` but carry a verdict. */
function isModelCheck(check: AlertCheck): boolean {
    return (
        check.triggered_metadata?.detector_type === DetectorType.LLM ||
        typeof check.triggered_metadata?.verdict_is_anomaly === 'boolean'
    )
}

/**
 * The AI detector has no score, so its history plots the metric value. Older AI checks still
 * carry a stored score, and it is not plotted either.
 */
function plotsAnomalyScores(detectorConfig: DetectorConfig | null | undefined): boolean {
    return !!detectorConfig && detectorConfig.type !== DetectorType.LLM
}

/**
 * How a saved check reads under the alert's current detector. An AI check has no score to compare,
 * so the check's own state is its classification under the AI detector. Under any other detector an
 * AI check is unclassifiable. `undefined` leaves a statistical check to the chart's own threshold comparison.
 */
export function checkWouldFireUnderCurrentConfiguration(
    check: AlertCheck,
    detectorConfig: DetectorConfig | null | undefined
): boolean | null | undefined {
    if (detectorConfig?.type === DetectorType.LLM) {
        return isModelCheck(check) ? check.state === AlertState.FIRING : null
    }
    return isModelCheck(check) ? null : undefined
}

export function getAlertHistoryScoreName(usesAnomalyScores: boolean): 'Anomaly score' | 'Value' {
    return usesAnomalyScores ? 'Anomaly score' : 'Value'
}

function getCheckPlotValue(check: AlertCheck, isAnomalyDetection: boolean): number | null {
    if (isAnomalyDetection) {
        const scores = check.anomaly_scores
        const lastScore = scores?.length ? scores[scores.length - 1] : null
        if (lastScore != null && !Number.isNaN(lastScore)) {
            return lastScore
        }
    }
    const v = check.calculated_value
    return v != null && !Number.isNaN(v) ? v : null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface alertLogicValues {
    alert: AlertType | null
    alertHistoryChartSeries: AlertHistoryChartPoint[]
    alertHistoryChartSeriesName: 'Anomaly score' | 'Value'
    alertHistoryChecksSortedDesc: AlertCheck[]
    alertHistoryHasHistory: boolean
    alertHistoryIsAnomalyDetection: boolean
    alertHistoryTableEntryCount: number
    alertHistoryTablePageCount: number
    alertHistoryUsesAnomalyScores: boolean
    alertHistoryView: 'chart' | 'table'
    alertLoading: boolean
    checksHistoryParams: ChecksHistoryParams
    checksHistoryTablePage: number
    expandedInvestigationChecks: Record<string, boolean>
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface alertLogicActions {
    alertHistoryTablePageBackward: () => {
        value: true
    }
    alertHistoryTablePageForward: () => {
        value: true
    }
    loadAlert: () => any
    loadAlertFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadAlertSuccess: (
        alert: AlertType | null,
        payload?: any
    ) => {
        alert: AlertType | null
        payload?: any
    }
    selectAlertHistoryView: (view: 'chart' | 'table') => {
        view: 'chart' | 'table'
    }
    setAlertHistoryView: (view: 'chart' | 'table') => {
        view: 'chart' | 'table'
    }
    setChecksHistoryParams: (
        limit: number,
        offset: number
    ) => {
        limit: number
        offset: number
    }
    setChecksHistoryTablePage: (page: number) => {
        page: number
    }
    toggleInvestigationSummary: (checkId: string) => {
        checkId: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface alertLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        alertHistoryIsAnomalyDetection: (alert: AlertType | null) => boolean
        alertHistoryChecksSortedDesc: (alert: AlertType | null) => AlertCheck[]
        alertHistoryChartSeries: (alert: AlertType | null) => AlertHistoryChartPoint[]
        alertHistoryUsesAnomalyScores: (alert: AlertType | null) => boolean
        alertHistoryChartSeriesName: (alertHistoryUsesAnomalyScores: boolean) => 'Anomaly score' | 'Value'
        alertHistoryHasHistory: (alert: AlertType | null) => boolean
        alertHistoryTablePageCount: (alert: AlertType | null) => number
        alertHistoryTableEntryCount: (alert: AlertType | null) => number
    }
}

export type alertLogicType = MakeLogicType<alertLogicValues, alertLogicActions, AlertLogicProps, alertLogicMeta>

export const alertLogic = kea<alertLogicType>([
    path(['lib', 'components', 'Alerts', 'alertLogic']),
    props({
        alertId: null,
    } as AlertLogicProps),
    key(({ alertId }) => alertId ?? 'new'),

    actions({
        toggleInvestigationSummary: (checkId: string) => ({ checkId }),
        setChecksHistoryParams: (limit: number, offset: number) => ({ limit, offset }),
        // Low-level reducer setter — updates `alertHistoryView` only. Prefer `selectAlertHistoryView`
        // from UI code so pagination + checks fetch are reset in the same flow.
        setAlertHistoryView: (view: 'chart' | 'table') => ({ view }),
        setChecksHistoryTablePage: (page: number) => ({ page }),
        // User-facing action: switches view AND re-issues the right checks fetch for the new view.
        selectAlertHistoryView: (view: 'chart' | 'table') => ({ view }),
        alertHistoryTablePageForward: true,
        alertHistoryTablePageBackward: true,
    }),

    reducers(() => ({
        expandedInvestigationChecks: [
            {} as Record<string, boolean>,
            {
                toggleInvestigationSummary: (state, { checkId }) => ({ ...state, [checkId]: !state[checkId] }),
            },
        ],
        checksHistoryParams: [
            initialChecksHistoryParams(),
            {
                setChecksHistoryParams: (_, { limit, offset }) => ({ limit, offset }),
            },
        ],
        alertHistoryView: [
            'chart' as 'chart' | 'table',
            {
                setAlertHistoryView: (_, { view }) => view,
            },
        ],
        checksHistoryTablePage: [
            1,
            {
                setChecksHistoryTablePage: (_, { page }) => page,
            },
        ],
    })),

    // Loaders must run before `selectors` so `selectors.alert` exists when history selectors are built.
    loaders(({ props, values }) => ({
        alert: [
            null as AlertType | null,
            {
                loadAlert: async () => {
                    if (!props.alertId) {
                        return null
                    }

                    const { limit, offset } = values.checksHistoryParams
                    return await api.alerts.get(props.alertId, { checksLimit: limit, checksOffset: offset })
                },
            },
        ],
    })),

    // Selector deps must be functions from `logic.selectors` / propSelectors — not raw state values.
    selectors(() => ({
        alertHistoryIsAnomalyDetection: [(s) => [s.alert], (alert: AlertType | null) => !!alert?.detector_config],
        alertHistoryChecksSortedDesc: [
            (s) => [s.alert],
            (alert: AlertType | null): AlertCheck[] => {
                const checks = alert?.checks ?? []
                return [...checks].sort((a, b) => dayjs(b.created_at).valueOf() - dayjs(a.created_at).valueOf())
            },
        ],
        alertHistoryChartSeries: [
            (s) => [s.alert],
            (alert: AlertType | null): AlertHistoryChartPoint[] => {
                if (!alert) {
                    return []
                }
                const isAnomaly = plotsAnomalyScores(alert.detector_config)
                const sortedAsc = [...(alert.checks ?? [])].sort(
                    (a, b) => dayjs(a.created_at).valueOf() - dayjs(b.created_at).valueOf()
                )
                const points: AlertHistoryChartPoint[] = []
                for (const check of sortedAsc) {
                    const value = getCheckPlotValue(check, isAnomaly)
                    if (value === null) {
                        continue
                    }
                    const wouldFire = checkWouldFireUnderCurrentConfiguration(check, alert.detector_config)
                    points.push({
                        value,
                        label: formatDate(dayjs(check.created_at), 'MMM D, HH:mm'),
                        firedAtTime: check.state === AlertState.FIRING,
                        ...(wouldFire !== undefined ? { wouldFireUnderCurrentConfiguration: wouldFire } : {}),
                    })
                }
                return points
            },
        ],
        alertHistoryUsesAnomalyScores: [
            (s) => [s.alert],
            (alert: AlertType | null): boolean => {
                if (!plotsAnomalyScores(alert?.detector_config)) {
                    return false
                }
                const checks = alert?.checks ?? []
                return checks.some((c: AlertCheck) => {
                    const scores = c.anomaly_scores
                    const last = scores?.length ? scores[scores.length - 1] : null
                    return last != null && !Number.isNaN(last)
                })
            },
        ],
        alertHistoryChartSeriesName: [
            (s) => [s.alertHistoryUsesAnomalyScores],
            (usesAnomalyScores: boolean): 'Anomaly score' | 'Value' => getAlertHistoryScoreName(usesAnomalyScores),
        ],
        alertHistoryHasHistory: [
            (s) => [s.alert],
            (alert: AlertType | null): boolean => {
                const total = alert?.checks_total
                if (total !== undefined && total > 0) {
                    return true
                }
                return (alert?.checks?.length ?? 0) > 0
            },
        ],
        alertHistoryTablePageCount: [
            (s) => [s.alert],
            (alert: AlertType | null): number => {
                const checksTotal = alert?.checks_total
                const resolvedTotal = checksTotal ?? 0
                return Math.max(1, Math.ceil(resolvedTotal / TABLE_CHECKS_PAGE_SIZE) || 1)
            },
        ],
        alertHistoryTableEntryCount: [
            (s) => [s.alert],
            (alert: AlertType | null): number => {
                const resolvedTotal = alert?.checks_total ?? 0
                const checksLen = alert?.checks?.length ?? 0
                return resolvedTotal > 0 ? resolvedTotal : checksLen
            },
        ],
    })),

    listeners(({ actions, values }) => ({
        selectAlertHistoryView: ({ view }) => {
            actions.setAlertHistoryView(view)
            if (view === 'table') {
                actions.setChecksHistoryTablePage(1)
                actions.setChecksHistoryParams(TABLE_CHECKS_PAGE_SIZE, 0)
            } else {
                actions.setChecksHistoryParams(CHART_CHECKS_LIMIT, 0)
            }
            actions.loadAlert()
        },
        alertHistoryTablePageForward: () => {
            const tablePage = values.checksHistoryTablePage
            if (tablePage >= values.alertHistoryTablePageCount) {
                return
            }
            const next = tablePage + 1
            actions.setChecksHistoryTablePage(next)
            actions.setChecksHistoryParams(TABLE_CHECKS_PAGE_SIZE, (next - 1) * TABLE_CHECKS_PAGE_SIZE)
            actions.loadAlert()
        },
        alertHistoryTablePageBackward: () => {
            const tablePage = values.checksHistoryTablePage
            if (tablePage <= 1) {
                return
            }
            const next = tablePage - 1
            actions.setChecksHistoryTablePage(next)
            actions.setChecksHistoryParams(TABLE_CHECKS_PAGE_SIZE, (next - 1) * TABLE_CHECKS_PAGE_SIZE)
            actions.loadAlert()
        },
    })),

    events(({ actions, props }) => ({
        afterMount() {
            if (props.alertId) {
                actions.selectAlertHistoryView('chart')
            } else {
                actions.loadAlert()
            }
        },
    })),
])