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.

25.3 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { urlToAction } from 'kea-router'
import posthog from 'posthog-js'

import api from 'lib/api'
import { getSeriesColor } from 'lib/colors'
import { dayjs } from 'lib/dayjs'
import { hogql } from 'lib/utils/hogql'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
import { AnyPropertyFilter, Breadcrumb } from '~/types'

import type { ProductIntentProperties } from '../../../../frontend/src/lib/utils/product-intents'
import { aiObservabilitySharedLogic } from '../aiObservabilitySharedLogic'
import type { ApplyUrlStatePayload } from '../aiObservabilitySharedLogic'
import { llmEvaluationsLogic, waitForEvaluationsSettled } from '../evaluations/llmEvaluationsLogic'
import { loadClusterMetrics } from './clusterMetricsLoader'
import type { ClusterScatterSeries } from './clusterScatter'
import {
    AI_OBSERVABILITY_CLUSTER_SCENE_TAG,
    AI_OBSERVABILITY_CLUSTER_URL_PATTERN,
    NOISE_CLUSTER_ID,
    OUTLIER_COLOR,
    TRACES_PER_PAGE,
} from './constants'
import { loadFilterMatchedItemIds } from './filteredItemIdsLoader'
import { loadTraceSummaries } from './traceSummaryLoader'
import {
    Cluster,
    ClusterItemInfo,
    ClusterMetrics,
    ClusteringLevel,
    TraceSummary,
    getTimestampBoundsFromRunId,
    parseClusterMetrics,
} from './types'

export interface ClusterDetailLogicProps {
    runId: string
    clusterId: number
}

export interface TraceWithSummary {
    traceId: string
    traceInfo: ClusterItemInfo
    summary?: TraceSummary
}

export interface ClusterData {
    cluster: Cluster
    runTimestamp: string
    windowStart: string
    windowEnd: string
    clusteringLevel: ClusteringLevel
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface clusterDetailLogicValues {
    propertyFilters: AnyPropertyFilter[] // aiObservabilitySharedLogic
    shouldFilterTestAccounts: boolean // aiObservabilitySharedLogic
    detectorEvaluationIds: string[] // llmEvaluationsLogic
    breadcrumbs: Breadcrumb[]
    cluster: Cluster | null
    clusterData: ClusterData | null
    clusterDataLoading: boolean
    clusterMetrics: ClusterMetrics | null
    clusterMetricsLoading: boolean
    clusteringLevel: ClusteringLevel
    currentPage: number
    filteredItemIds: Set<string> | null
    filteredItemIdsLoading: boolean
    hasActiveFilters: boolean
    isOutlierCluster: boolean
    paginatedTraceIds: string[]
    paginatedTracesWithSummaries: TraceWithSummary[]
    runTimestamp: string
    scatterPlotSeries: ClusterScatterSeries[]
    sortedTraceIds: string[]
    totalPages: number
    totalTraces: number
    traceSummaries: Record<string, TraceSummary>
    traceSummariesLoading: boolean
    unfilteredTotalTraces: number
    windowEnd: string
    windowStart: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface clusterDetailLogicActions {
    applyUrlState: (state: ApplyUrlStatePayload) => ApplyUrlStatePayload // aiObservabilitySharedLogic
    setPropertyFilters: (propertyFilters: AnyPropertyFilter[]) => {
        propertyFilters: AnyPropertyFilter[]
    } // aiObservabilitySharedLogic
    setShouldFilterTestAccounts: (shouldFilterTestAccounts: boolean) => {
        shouldFilterTestAccounts: boolean
    } // aiObservabilitySharedLogic
    addProductIntent: (properties: ProductIntentProperties) => ProductIntentProperties // teamLogic
    loadClusterData: () => any
    loadClusterDataFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadClusterDataSuccess: (
        clusterData: {
            cluster: Cluster
            clusteringLevel: ClusteringLevel
            runTimestamp: string
            windowEnd: string
            windowStart: string
        } | null,
        payload?: any
    ) => {
        clusterData: {
            cluster: Cluster
            clusteringLevel: ClusteringLevel
            runTimestamp: string
            windowEnd: string
            windowStart: string
        } | null
        payload?: any
    }
    loadClusterMetricsForCluster: () => {
        value: true
    }
    loadFilteredItemIds: () => {
        value: true
    }
    loadFilteredItemIdsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadFilteredItemIdsSuccess: (
        filteredItemIds: Set<string> | null,
        payload?: {
            value: true
        }
    ) => {
        filteredItemIds: Set<string> | null
        payload?: {
            value: true
        }
    }
    loadMoreTraces: () => {
        value: true
    }
    setClusterMetrics: (metrics: ClusterMetrics | null) => {
        metrics: ClusterMetrics | null
    }
    setClusterMetricsLoading: (loading: boolean) => {
        loading: boolean
    }
    setPage: (page: number) => {
        page: number
    }
    setTraceSummaries: (summaries: Record<string, TraceSummary>) => {
        summaries: Record<string, TraceSummary>
    }
    setTraceSummariesLoading: (loading: boolean) => {
        loading: boolean
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface clusterDetailLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        cluster: (clusterData: ClusterData | null) => Cluster | null
        runTimestamp: (clusterData: ClusterData | null) => string
        windowStart: (clusterData: ClusterData | null) => string
        windowEnd: (clusterData: ClusterData | null) => string
        clusteringLevel: (clusterData: ClusterData | null) => ClusteringLevel
        isOutlierCluster: (cluster: Cluster | null) => boolean
        scatterPlotSeries: (
            cluster: Cluster | null,
            isOutlierCluster: boolean,
            filteredItemIds: Set<string> | null
        ) => ClusterScatterSeries[]
        sortedTraceIds: (cluster: Cluster | null, filteredItemIds: Set<string> | null) => string[]
        totalTraces: (sortedTraceIds: string[]) => number
        unfilteredTotalTraces: (cluster: Cluster | null) => number
        hasActiveFilters: (propertyFilters: AnyPropertyFilter[], shouldFilterTestAccounts: boolean) => boolean
        totalPages: (totalTraces: number) => number
        paginatedTraceIds: (sortedTraceIds: string[], currentPage: number) => string[]
        paginatedTracesWithSummaries: (
            paginatedTraceIds: string[],
            cluster: Cluster | null,
            traceSummaries: Record<string, TraceSummary>
        ) => TraceWithSummary[]
        breadcrumbs: (cluster: Cluster | null, runId: string) => Breadcrumb[]
    }
}

export type clusterDetailLogicType = MakeLogicType<
    clusterDetailLogicValues,
    clusterDetailLogicActions,
    ClusterDetailLogicProps,
    clusterDetailLogicMeta
>

export const clusterDetailLogic = kea<clusterDetailLogicType>([
    path(['products', 'ai_observability', 'frontend', 'clusters', 'clusterDetailLogic']),
    props({} as ClusterDetailLogicProps),
    key((props) => `${props.runId}:${props.clusterId}`),
    connect(() => ({
        values: [
            aiObservabilitySharedLogic,
            ['propertyFilters', 'shouldFilterTestAccounts'],
            llmEvaluationsLogic,
            ['detectorEvaluationIds'],
        ],
        actions: [
            teamLogic,
            ['addProductIntent'],
            aiObservabilitySharedLogic,
            ['setPropertyFilters', 'setShouldFilterTestAccounts', 'applyUrlState'],
        ],
    })),

    actions({
        setPage: (page: number) => ({ page }),
        loadMoreTraces: true,
        setTraceSummaries: (summaries: Record<string, TraceSummary>) => ({ summaries }),
        setTraceSummariesLoading: (loading: boolean) => ({ loading }),
        setClusterMetrics: (metrics: ClusterMetrics | null) => ({ metrics }),
        setClusterMetricsLoading: (loading: boolean) => ({ loading }),
        loadClusterMetricsForCluster: true,
        // Declared explicitly so kea-typegen generates a no-arg signature for the
        // loader action below — without this, the `(_, breakpoint)` loader signature
        // forces every call site to pass a placeholder argument.
        loadFilteredItemIds: true,
    }),

    reducers({
        currentPage: [
            1,
            {
                setPage: (_, { page }) => page,
            },
        ],
        traceSummaries: [
            {} as Record<string, TraceSummary>,
            {
                setTraceSummaries: (state, { summaries }) => ({ ...state, ...summaries }),
            },
        ],
        traceSummariesLoading: [
            false,
            {
                setTraceSummariesLoading: (_, { loading }) => loading,
            },
        ],
        clusterMetrics: [
            null as ClusterMetrics | null,
            {
                setClusterMetrics: (_, { metrics }) => metrics,
            },
        ],
        clusterMetricsLoading: [
            false,
            {
                setClusterMetricsLoading: (_, { loading }) => loading,
            },
        ],
    }),

    loaders(({ props, values }) => ({
        // Subset of cluster item IDs that match the user's active property filters
        // (cohorts, person properties, etc.). Null when no filters are active —
        // selectors treat null as "show everything", which avoids forcing every
        // unfiltered cluster view to round-trip a query on mount.
        filteredItemIds: [
            null as Set<string> | null,
            {
                loadFilteredItemIds: async (_, breakpoint) => {
                    // Debounce to coalesce overlapping filter changes (e.g. quick toggles
                    // of the test-accounts switch or successive cohort selections) into a
                    // single round-trip.
                    await breakpoint(150)

                    const cluster = values.cluster
                    const windowStart = values.windowStart
                    const windowEnd = values.windowEnd

                    if (!cluster || !windowStart || !windowEnd) {
                        return null
                    }

                    const matched = await loadFilterMatchedItemIds({
                        itemIds: Object.keys(cluster.traces),
                        level: values.clusteringLevel,
                        windowStart,
                        windowEnd,
                        propertyFilters: values.propertyFilters || [],
                        filterTestAccounts: values.shouldFilterTestAccounts,
                        scene: AI_OBSERVABILITY_CLUSTER_SCENE_TAG,
                    })
                    breakpoint()
                    return matched
                },
            },
        ],

        clusterData: [
            null as ClusterData | null,
            {
                loadClusterData: async () => {
                    const { dayStart, dayEnd } = getTimestampBoundsFromRunId(props.runId)

                    // Query all three cluster event types so a single URL works regardless of level
                    const response = await api.queryHogQL(
                        hogql`
                            SELECT
                                properties.$ai_clustering_run_id as run_id,
                                properties.$ai_window_start as window_start,
                                properties.$ai_window_end as window_end,
                                properties.$ai_clusters as clusters,
                                timestamp,
                                properties.$ai_clustering_level as clustering_level
                            FROM events
                            WHERE event IN ('$ai_trace_clusters', '$ai_generation_clusters', '$ai_evaluation_clusters')
                                AND timestamp >= ${dayStart}
                                AND timestamp <= ${dayEnd}
                                AND properties.$ai_clustering_run_id = ${props.runId}
                            LIMIT 1
                        `,
                        { productKey: 'llm_analytics', scene: 'AIObservabilityCluster' },
                        // Run IDs and bounds are in UTC, so compare timestamps in UTC
                        { queryParams: { modifiers: { convertToProjectTimezone: false } } }
                    )

                    if (!response.results?.length) {
                        return null
                    }

                    const row = response.results[0] as string[]

                    let clustersData: Cluster[] = []
                    try {
                        const rawClusters: Array<Record<string, unknown>> = JSON.parse(row[3] || '[]')
                        // Normalize snake_case metrics dict to camelCase ClusterMetrics — matches
                        // clustersLogic so the detail page's cluster object has the same shape as
                        // the list page's cluster cards.
                        clustersData = rawClusters.map((raw) => {
                            const { metrics: rawMetrics, ...rest } = raw as {
                                metrics?: unknown
                            } & Record<string, unknown>
                            const parsed = parseClusterMetrics(rawMetrics)
                            return {
                                ...(rest as unknown as Cluster),
                                ...(parsed ? { metrics: parsed } : {}),
                            }
                        })
                    } catch {
                        console.error('Failed to parse clusters data')
                        return null
                    }

                    const cluster = clustersData.find((c) => c.cluster_id === props.clusterId)
                    if (!cluster) {
                        return null
                    }

                    // Default to 'trace' for backwards compatibility
                    const clusteringLevel = (row[5] as ClusteringLevel) || 'trace'

                    return {
                        cluster,
                        runTimestamp: row[4],
                        windowStart: row[1],
                        windowEnd: row[2],
                        clusteringLevel,
                    }
                },
            },
        ],
    })),

    selectors({
        cluster: [
            (s) => [s.clusterData],
            (clusterData: ClusterData | null): Cluster | null => clusterData?.cluster || null,
        ],

        runTimestamp: [
            (s) => [s.clusterData],
            (clusterData: ClusterData | null): string => clusterData?.runTimestamp || '',
        ],

        windowStart: [
            (s) => [s.clusterData],
            (clusterData: ClusterData | null): string => clusterData?.windowStart || '',
        ],

        windowEnd: [(s) => [s.clusterData], (clusterData: ClusterData | null): string => clusterData?.windowEnd || ''],

        clusteringLevel: [
            (s) => [s.clusterData],
            (clusterData: ClusterData | null): ClusteringLevel => clusterData?.clusteringLevel || 'trace',
        ],

        isOutlierCluster: [
            (s) => [s.cluster],
            (cluster: Cluster | null): boolean => cluster?.cluster_id === NOISE_CLUSTER_ID,
        ],

        scatterPlotSeries: [
            (s) => [s.cluster, s.isOutlierCluster, s.filteredItemIds],
            (
                cluster: Cluster | null,
                isOutlier: boolean,
                filteredItemIds: Set<string> | null
            ): ClusterScatterSeries[] => {
                if (!cluster) {
                    return []
                }

                // Same membership rule as sortedTraceIds, so the plot and the list show the same items
                const entries = Object.entries(cluster.traces)
                const visibleEntries = filteredItemIds ? entries.filter(([id]) => filteredItemIds.has(id)) : entries
                const color = isOutlier ? OUTLIER_COLOR : getSeriesColor(cluster.cluster_id)

                const result: ClusterScatterSeries[] = [
                    {
                        key: 'items',
                        label: cluster.title,
                        color,
                        pointRadius: 5,
                        shape: isOutlier ? 'cross' : 'circle',
                        points: visibleEntries.map(([itemKey, traceInfo]) => ({
                            x: traceInfo.x,
                            y: traceInfo.y,
                            meta: {
                                traceId: traceInfo.trace_id || itemKey,
                                generationId: traceInfo.generation_id,
                                timestamp: traceInfo.timestamp,
                            },
                        })),
                    },
                ]

                // Add centroid marker for non-outlier clusters
                if (!isOutlier && visibleEntries.length > 0) {
                    result.push({
                        key: 'centroid',
                        label: 'Centroid',
                        color,
                        pointRadius: 10,
                        shape: 'circle',
                        points: [{ x: cluster.centroid_x, y: cluster.centroid_y, meta: { isCentroid: true } }],
                    })
                }

                return result
            },
        ],

        sortedTraceIds: [
            (s) => [s.cluster, s.filteredItemIds],
            (cluster: Cluster | null, filteredItemIds: Set<string> | null): string[] => {
                if (!cluster) {
                    return []
                }
                const entries = Object.entries(cluster.traces)
                const filtered = filteredItemIds ? entries.filter(([id]) => filteredItemIds.has(id)) : entries
                return filtered
                    .sort(([, a], [, b]) => (a as ClusterItemInfo).rank - (b as ClusterItemInfo).rank)
                    .map(([traceId]) => traceId)
            },
        ],

        totalTraces: [(s) => [s.sortedTraceIds], (sortedTraceIds: string[]): number => sortedTraceIds.length],

        unfilteredTotalTraces: [
            (s) => [s.cluster],
            (cluster: Cluster | null): number => (cluster ? Object.keys(cluster.traces).length : 0),
        ],

        hasActiveFilters: [
            (s) => [s.propertyFilters, s.shouldFilterTestAccounts],
            (propertyFilters: AnyPropertyFilter[], shouldFilterTestAccounts: boolean): boolean =>
                (propertyFilters?.length ?? 0) > 0 || shouldFilterTestAccounts,
        ],

        totalPages: [(s) => [s.totalTraces], (totalTraces: number): number => Math.ceil(totalTraces / TRACES_PER_PAGE)],

        paginatedTraceIds: [
            (s) => [s.sortedTraceIds, s.currentPage],
            (sortedTraceIds: string[], currentPage: number): string[] => {
                const start = (currentPage - 1) * TRACES_PER_PAGE
                const end = start + TRACES_PER_PAGE
                return sortedTraceIds.slice(start, end)
            },
        ],

        paginatedTracesWithSummaries: [
            (s) => [s.paginatedTraceIds, s.cluster, s.traceSummaries],
            (
                paginatedTraceIds: string[],
                cluster: Cluster | null,
                summaries: Record<string, TraceSummary>
            ): TraceWithSummary[] => {
                if (!cluster) {
                    return []
                }
                return paginatedTraceIds.map((traceId: string) => ({
                    traceId,
                    traceInfo: cluster.traces[traceId],
                    summary: summaries[traceId],
                }))
            },
        ],

        breadcrumbs: [
            (s, p) => [s.cluster, p.runId],
            (cluster: Cluster | null, runId: string): Breadcrumb[] => [
                {
                    key: 'AIObservabilityClusters',
                    name: 'Clusters',
                    path: urls.aiObservabilityClusters(),
                    iconType: 'llm_clusters',
                },
                {
                    key: 'AIObservabilityClustersRun',
                    name: dayjs(runId.split('_')[1] || runId).isValid()
                        ? dayjs(runId.split('_')[1] || runId).format('MMM D, YYYY')
                        : 'Run',
                    path: urls.aiObservabilityClusters(runId),
                    iconType: 'llm_clusters',
                },
                {
                    key: 'AIObservabilityCluster',
                    name: cluster?.title || 'Cluster',
                    iconType: 'llm_clusters',
                },
            ],
        ],
    }),

    listeners(({ actions, values, props }) => ({
        loadClusterDataSuccess: () => {
            actions.setPage(1)
            actions.loadClusterMetricsForCluster()
            actions.loadFilteredItemIds()

            void actions.addProductIntent({
                product_type: ProductKey.LLM_CLUSTERS,
                intent_context: ProductIntentContext.LLM_CLUSTER_EXPLORED,
            })
        },

        // Filter-change listeners only kick the loader; resetting the page and reloading
        // summaries waits for the loader's success path so we don't burn a round-trip on
        // summaries for items the user is about to filter out. Both `setPropertyFilters`
        // and `applyUrlState` are needed: the first covers UI clicks (where actionToUrl
        // updates the URL but doesn't re-fire applyUrlState), the second covers deep
        // links and browser back/forward where applyUrlState is the only dispatch.
        setPropertyFilters: () => actions.loadFilteredItemIds(),
        setShouldFilterTestAccounts: () => actions.loadFilteredItemIds(),
        applyUrlState: () => actions.loadFilteredItemIds(),

        loadFilteredItemIdsSuccess: () => {
            // Resetting to page 1 fans out to the setPage listener, which loads summaries
            // for the now-correct first-page IDs. Doing it here keeps a single source of
            // truth for paging-reset-and-resummarize across both initial load and filter
            // changes.
            actions.setPage(1)
        },

        loadClusterMetricsForCluster: async () => {
            const { cluster, windowStart, windowEnd, clusteringLevel } = values
            if (!cluster || !windowStart || !windowEnd) {
                return
            }

            // Evaluation clusters ship with metrics baked into the event — use them
            // directly rather than re-computing via the HogQL items query. Matches
            // clustersLogic's short-circuit.
            if (clusteringLevel === 'evaluation') {
                actions.setClusterMetrics(cluster.metrics || null)
                return
            }

            actions.setClusterMetricsLoading(true)
            try {
                const metricsMap = await loadClusterMetrics([cluster], windowStart, windowEnd, clusteringLevel)
                actions.setClusterMetrics(metricsMap[cluster.cluster_id] || null)
            } catch (error) {
                console.error('Failed to load cluster metrics:', error)
            } finally {
                actions.setClusterMetricsLoading(false)
            }
        },

        setPage: async ({ page }) => {
            posthog.capture('llma clusters page changed', {
                page,
                cluster_id: props.clusterId,
                run_id: props.runId,
            })
            // Load trace summaries for the current page
            const traceIds = values.paginatedTraceIds
            const { windowStart, windowEnd, clusteringLevel } = values

            if (!windowStart || !windowEnd) {
                return
            }

            actions.setTraceSummariesLoading(true)

            try {
                // Only evaluation-level clustering derives a verdict, so only that level
                // needs to wait for llmEvaluationsLogic's evaluations to settle first —
                // otherwise a clustering response that resolves first would read
                // detectorEvaluationIds as [] and bake a wrong verdict into a cached summary
                // that never gets refetched (loadTraceSummaries only fetches missing ids).
                if (clusteringLevel === 'evaluation') {
                    await waitForEvaluationsSettled()
                }
                const summaries = await loadTraceSummaries(
                    traceIds,
                    values.traceSummaries,
                    windowStart,
                    windowEnd,
                    clusteringLevel,
                    values.detectorEvaluationIds
                )
                actions.setTraceSummaries(summaries)
            } catch (error) {
                console.error('Failed to load trace summaries:', error)
            } finally {
                actions.setTraceSummariesLoading(false)
            }
        },
    })),

    afterMount(({ actions }) => {
        actions.loadClusterData()
    }),

    urlToAction(({ actions, props }) => ({
        [AI_OBSERVABILITY_CLUSTER_URL_PATTERN]: ({ runId, clusterId }: { runId?: string; clusterId?: string }) => {
            const decodedRunId = runId ? decodeURIComponent(runId) : ''
            const parsedClusterId = clusterId ? parseInt(clusterId, 10) : 0

            if (decodedRunId !== props.runId || parsedClusterId !== props.clusterId) {
                // Props don't match URL, component should remount with new props
                actions.loadClusterData()
            }
        },
    })),
])