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.

24.9 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import posthog from 'posthog-js'

import { inApiCase } from 'lib/components/ViewTraceButton/traceUrl'
import { sessionPlayerModalLogic } from 'scenes/session-recordings/player/modal/sessionPlayerModalLogic'

import { logsViewerModalLogic } from 'products/logs/frontend/components/LogsViewer/LogsViewerModal/logsViewerModalLogic'

import { traceViewLogic } from './components/TraceView/traceViewLogic'
import type { ErrorScope } from './errorCorrelation'
import {
    EMPTY_TRACE_IDENTITY,
    resolveSpanSessionId,
    resolveTraceIdentity,
    resolveTraceSessionId,
    type TraceIdentity,
} from './traceIdentity'
import { tracingConfigLogic } from './tracingConfigLogic'
import { tracingCorrelationConfigLogic } from './tracingCorrelationConfigLogic'
import { PREFETCH_SPANS, tracingDataLogic } from './tracingDataLogic'
import { TRACING_SCENE_VIEWER_ID, tracingFiltersLogic } from './tracingFiltersLogic'
import type { OverlayWindow } from './tracingFiltersLogic'
import type { Span, SpanInspectorTab, TraceViewMode } from './types'

export interface TracingViewerLogicProps {
    id: string
}

// Pinned: autocapture and the span keys both match on the drawer's data-attr.
export const TRACE_DRAWER_DATA_ATTR = 'tracing-trace-drawer'

export function traceViewId(viewerId: string): string {
    return `tracing-viewer-${viewerId}`
}

// Mirrors the prefetch check in the `openTrace` listener: a batch with the trace's root span,
// under the cap, is already the trace's complete span set, so a fetch for it would be skipped.
// Also used by `selectedTraceLoadFailed` to tell a stale failure (from an earlier, differently
// shaped prefetch) apart from one that still describes what's about to be fetched.
function isCompletePrefetch(spans: Span[], traceId: string): boolean {
    const prefetchedSpans = spans.filter((s) => s.trace_id === traceId)
    return prefetchedSpans.some((s) => s.is_root_span) && prefetchedSpans.length < PREFETCH_SPANS
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tracingViewerLogicValues {
    traceViewMode: TraceViewMode // tracingConfigLogic
    configuredDistinctIdKeys: string[] | undefined // tracingCorrelationConfigLogic
    configuredSessionIdKeys: string[] | undefined // tracingCorrelationConfigLogic
    correlationLinksEnabled: boolean // tracingCorrelationConfigLogic
    sessionErrorBadgesEnabled: boolean // tracingCorrelationConfigLogic
    spans: Span[] // tracingDataLogic
    traceLoadContext: {
        traceId: string
        ts?: string | null
    } | null // tracingDataLogic
    traceSpans: Span[] // tracingDataLogic
    traceSpansHasMore: boolean // tracingDataLogic
    traceSpansLoadFailed: boolean // tracingDataLogic
    traceSpansLoading: boolean // tracingDataLogic
    traceSpansLoadingMore: boolean // tracingDataLogic
    hasDeferredFilterRefresh: boolean // tracingFiltersLogic
    canLoadMoreTraceSpans: boolean
    compareFlameServiceName: string | null
    compareFlameSpanName: string | null
    errorsScope: ErrorScope | null
    inspectorOpen: boolean
    inspectorTab: SpanInspectorTab
    isFullscreen: boolean
    isLoadingFullTrace: boolean
    isTraceOpen: boolean
    openTraceSpans: Span[]
    selectedSpanId: string | null
    selectedTraceId: string | null
    selectedTraceLoadFailed: boolean
    selectedTraceTs: string | null
    traceIdentity: TraceIdentity
    traceSessionId: string | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tracingViewerLogicActions {
    closeLogsViewerModal: () => {
        value: true
    } // logsViewerModalLogic
    openLogsViewerModal: (
        options?:
            | import('products/logs/frontend/components/LogsViewer/LogsViewerModal/logsViewerModalLogic').OpenLogsViewerModalOptions
            | undefined
    ) => {
        fullScreen: boolean
        id: string
        initialFilters: Partial<
            import('products/logs/frontend/components/LogsViewer/config/types').LogsViewerFilters
        > | null
        openedFrom:
            | null
            | import('products/logs/frontend/components/LogsViewer/LogsViewerModal/logsViewerModalLogic').LogsViewerModalOrigin
        personId: string | null
        pinnedFilters: null | import('~/types').UniversalFiltersGroup
        sessionId: string | null
    } // logsViewerModalLogic
    closeSessionPlayer: () => {
        value: true
    } // sessionPlayerModalLogic
    openSessionPlayer: (
        sessionRecording: Pick<import('~/types').SessionRecordingType, 'id' | 'matching_events'>,
        initialTimestamp?: number | null | undefined,
        modalContext?:
            | import('scenes/session-recordings/player/modal/sessionPlayerModalLogic').SessionPlayerModalContext
            | undefined
    ) => {
        initialTimestamp: number | null
        modalContext: import('scenes/session-recordings/player/modal/sessionPlayerModalLogic').SessionPlayerModalContext
        sessionRecording: Pick<import('~/types').SessionRecordingType, 'id' | 'matching_events'>
    } // sessionPlayerModalLogic
    disableSpanKeys: () => {
        value: true
    } // traceViewLogic
    enableSpanKeys: (
        containerSelector: string,
        surface: import('./components/TraceView/traceViewLogic').TraceViewSurface
    ) => {
        containerSelector: string
        surface: import('./components/TraceView/traceViewLogic').TraceViewSurface
    } // traceViewLogic
    selectViewSpan: (spanId: string | null) => {
        spanId: string | null
    } // traceViewLogic
    setInspectorTab: (
        tab: SpanInspectorTab,
        surface?: import('./components/TraceView/traceViewLogic').TraceViewSurface | undefined
    ) => {
        surface: null | import('./components/TraceView/traceViewLogic').TraceViewSurface
        tab: SpanInspectorTab
    } // traceViewLogic
    showTrace: (
        pinnedSpanId: string | null,
        tab: SpanInspectorTab | null
    ) => {
        pinnedSpanId: string | null
        tab: SpanInspectorTab | null
    } // traceViewLogic
    fetchAggregation: (
        options?:
            | {
                  fullRange?: boolean
                  groupByEndpoint?: boolean
              }
            | null
            | undefined
    ) => {
        fullRange?: boolean
        groupByEndpoint?: boolean
    } | null // tracingDataLogic
    fetchSpanTree: (params: { serviceName: string; spanName: string }) => {
        serviceName: string
        spanName: string
    } // tracingDataLogic
    loadTraceSpans: (args_0: { traceId: string; ts?: string | null }) => {
        traceId: string
        ts?: string | null
    } // tracingDataLogic
    refreshDeferredFilters: () => {
        value: true
    } // tracingFiltersLogic
    updateComparisonWindows: (
        current: OverlayWindow,
        previous: OverlayWindow
    ) => {
        current: OverlayWindow
        previous: OverlayWindow
    } // tracingFiltersLogic
    closeCompareFlame: () => {
        value: true
    }
    closeTrace: () => {
        value: true
    }
    openCompareFlame: (
        spanName: string,
        serviceName: string
    ) => {
        serviceName: string
        spanName: string
    }
    openTrace: (
        traceId: string,
        options?: {
            errorsScope?: ErrorScope | null
            spanId?: string | null
            tab?: SpanInspectorTab | null
            ts?: string | null
        }
    ) => {
        errorsScope: ErrorScope | null
        spanId: string | null
        tab: SpanInspectorTab | null
        traceId: string
        ts: string | null
    }
    selectInspectorTab: (tab: SpanInspectorTab) => {
        tab: SpanInspectorTab
    }
    selectSpan: (spanId: string | null) => {
        spanId: string | null
    }
    toggleFullscreen: () => {
        value: true
    }
    toggleInspector: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tracingViewerLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        isTraceOpen: (selectedTraceId: string | null) => boolean
        openTraceSpans: (selectedTraceId: string | null, spans: Span[], traceSpans: Span[]) => Span[]
        isLoadingFullTrace: (traceSpansLoading: boolean, traceSpansLoadingMore: boolean) => boolean
        canLoadMoreTraceSpans: (
            traceSpansHasMore: boolean,
            traceSpans: Span[],
            selectedTraceId: string | null
        ) => boolean
        selectedTraceLoadFailed: (
            traceSpansLoadFailed: boolean,
            traceLoadContext: {
                traceId: string
                ts?: string | null
            } | null,
            selectedTraceId: string | null,
            spans: Span[]
        ) => boolean
        traceIdentity: (
            openTraceSpans: Span[],
            canLoadMoreTraceSpans: boolean,
            traceSpansLoading: boolean,
            configuredDistinctIdKeys: string[] | undefined,
            configuredSessionIdKeys: string[] | undefined,
            correlationLinksEnabled: boolean
        ) => TraceIdentity
        traceSessionId: (
            openTraceSpans: Span[],
            spans: Span[],
            selectedSpanId: string | null,
            configuredSessionIdKeys: string[] | undefined,
            sessionErrorBadgesEnabled: boolean
        ) => string | null
    }
}

export type tracingViewerLogicType = MakeLogicType<
    tracingViewerLogicValues,
    tracingViewerLogicActions,
    TracingViewerLogicProps,
    tracingViewerLogicMeta
>

// Per-instance viewer UI state: the trace drawer and the compare-flame modal. URL-free by
// design — the /tracing scene logic reads and writes this instance's state to sync the URL;
// an embedded viewer just never wires it up. Mirrors the logsViewerLogic boundary.
export const tracingViewerLogic = kea<tracingViewerLogicType>([
    props({ id: TRACING_SCENE_VIEWER_ID } as TracingViewerLogicProps),
    key((props) => props.id),
    path((key) => ['products', 'tracing', 'frontend', 'tracingViewerLogic', key]),

    connect(({ id }: TracingViewerLogicProps) => ({
        values: [
            tracingDataLogic({ id }),
            [
                'spans',
                'traceSpans',
                'traceSpansLoading',
                'traceSpansLoadingMore',
                'traceSpansHasMore',
                'traceSpansLoadFailed',
                'traceLoadContext',
            ],
            tracingFiltersLogic({ id }),
            ['hasDeferredFilterRefresh'],
            tracingCorrelationConfigLogic,
            [
                'configuredDistinctIdKeys',
                'configuredSessionIdKeys',
                'correlationLinksEnabled',
                'sessionErrorBadgesEnabled',
            ],
            tracingConfigLogic,
            ['traceViewMode'],
        ],
        actions: [
            tracingDataLogic({ id }),
            ['loadTraceSpans', 'fetchSpanTree', 'fetchAggregation'],
            tracingFiltersLogic({ id }),
            ['updateComparisonWindows', 'refreshDeferredFilters'],
            traceViewLogic({ id: traceViewId(id) }),
            ['showTrace', 'selectSpan as selectViewSpan', 'setInspectorTab', 'enableSpanKeys', 'disableSpanKeys'],
            logsViewerModalLogic,
            ['openLogsViewerModal', 'closeLogsViewerModal'],
            sessionPlayerModalLogic,
            ['openSessionPlayer', 'closeSessionPlayer'],
        ],
    })),

    actions({
        openTrace: (
            traceId: string,
            options?: {
                spanId?: string | null
                ts?: string | null
                tab?: SpanInspectorTab | null
                errorsScope?: ErrorScope | null
            }
        ) => ({
            traceId: inApiCase(traceId),
            spanId: options?.spanId ? inApiCase(options.spanId) : null,
            ts: options?.ts ?? null,
            tab: options?.tab ?? null,
            errorsScope: options?.errorsScope ?? null,
        }),
        selectInspectorTab: (tab: SpanInspectorTab) => ({ tab }),
        selectSpan: (spanId: string | null) => ({ spanId: spanId ? inApiCase(spanId) : null }),
        closeTrace: true,
        toggleInspector: true,
        toggleFullscreen: true,
        openCompareFlame: (spanName: string, serviceName: string) => ({ spanName, serviceName }),
        closeCompareFlame: true,
    }),

    reducers({
        selectedTraceId: [
            null as string | null,
            {
                openTrace: (_, { traceId }) => traceId,
                closeTrace: () => null,
            },
        ],
        selectedSpanId: [
            null as string | null,
            {
                openTrace: (_, { spanId }) => spanId,
                selectSpan: (_, { spanId }) => spanId,
                closeTrace: () => null,
            },
        ],
        // Timestamp hint for the open trace — echoed into copy-links so cold loads can bound the
        // ClickHouse lookup (the spans table is time-keyed; OTel ids embed no timestamp).
        selectedTraceTs: [
            null as string | null,
            {
                openTrace: (_, { ts }) => ts,
                closeTrace: () => null,
            },
        ],
        // Which inspector tab the drawer shows. It lives here rather than in the drawer so a
        // caller can open a trace straight onto a tab, which the span list's error badge does.
        // Deliberately not a URL param, unlike the trace and span the drawer opens on. A shared
        // link carries which trace to read, and the reader picks their own tab from there, so a
        // reload lands on Attributes by design. Opening another trace while the drawer is up
        // keeps the tab, so a person reading the Logs tab row by row stays on it.
        // The scope the Errors tab opens on, when the caller named one.
        errorsScope: [
            null as ErrorScope | null,
            {
                openTrace: (_, { errorsScope }) => errorsScope,
                closeTrace: () => null,
            },
        ],
        inspectorTab: [
            'attributes' as SpanInspectorTab,
            {
                openTrace: (state, { tab }) => tab ?? state,
                closeTrace: () => 'attributes',
                selectInspectorTab: (_, { tab }) => tab,
                setInspectorTab: (_, { tab }) => tab,
            },
        ],
        inspectorOpen: [
            true,
            { persist: true },
            {
                toggleInspector: (open) => !open,
            },
        ],
        isFullscreen: [
            false,
            { persist: true },
            {
                toggleFullscreen: (fullscreen) => !fullscreen,
            },
        ],
        compareFlameSpanName: [
            null as string | null,
            {
                openCompareFlame: (_, { spanName }) => spanName,
                closeCompareFlame: () => null,
            },
        ],
        compareFlameServiceName: [
            null as string | null,
            {
                openCompareFlame: (_, { serviceName }) => serviceName,
                closeCompareFlame: () => null,
            },
        ],
    }),

    selectors({
        isTraceOpen: [
            (s) => [s.selectedTraceId],
            (selectedTraceId: string | null): boolean => selectedTraceId !== null,
        ],
        openTraceSpans: [
            (s) => [s.selectedTraceId, s.spans, s.traceSpans],
            (selectedTraceId: string | null, spans: Span[], traceSpans: Span[]): Span[] => {
                if (!selectedTraceId) {
                    return []
                }
                const filteredTraceSpans = traceSpans.filter((s) => s.trace_id === selectedTraceId)
                if (filteredTraceSpans.length > 0) {
                    return filteredTraceSpans
                }
                return spans.filter((s) => s.trace_id === selectedTraceId)
            },
        ],
        // The drawer's full-trace overlay should only show on the initial fetch — paging in more
        // spans (loadMoreTraceSpans) keeps the waterfall visible with its own bottom spinner.
        isLoadingFullTrace: [
            (s) => [s.traceSpansLoading, s.traceSpansLoadingMore],
            (traceSpansLoading: boolean, traceSpansLoadingMore: boolean): boolean =>
                traceSpansLoading && !traceSpansLoadingMore,
        ],
        // Only offer "load more" when the full-fetched spans for the open trace are what's displayed
        // — never for the small prefetch fallback, which is already the trace's complete span set.
        canLoadMoreTraceSpans: [
            (s) => [s.traceSpansHasMore, s.traceSpans, s.selectedTraceId],
            (traceSpansHasMore: boolean, traceSpans: Span[], selectedTraceId: string | null): boolean =>
                traceSpansHasMore &&
                !!selectedTraceId &&
                traceSpans.some((span: Span) => span.trace_id === selectedTraceId),
        ],
        // openTrace skips the fetch for a complete prefetch, so the raw flag can belong to a previous
        // attempt at this same trace (one a later, now-complete prefetch has since superseded).
        selectedTraceLoadFailed: [
            (s) => [s.traceSpansLoadFailed, s.traceLoadContext, s.selectedTraceId, s.spans],
            (
                traceSpansLoadFailed: boolean,
                traceLoadContext: { traceId: string; ts?: string | null } | null,
                selectedTraceId: string | null,
                spans: Span[]
            ): boolean =>
                traceSpansLoadFailed &&
                traceLoadContext?.traceId === selectedTraceId &&
                !!selectedTraceId &&
                !isCompletePrefetch(spans, selectedTraceId),
        ],
        // The person and session the open trace belongs to.
        traceIdentity: [
            (s) => [
                s.openTraceSpans,
                s.canLoadMoreTraceSpans,
                s.traceSpansLoading,
                s.configuredDistinctIdKeys,
                s.configuredSessionIdKeys,
                s.correlationLinksEnabled,
            ],
            (
                openTraceSpans: Span[],
                canLoadMoreTraceSpans: boolean,
                traceSpansLoading: boolean,
                configuredDistinctIdKeys: string[] | undefined,
                configuredSessionIdKeys: string[] | undefined,
                correlationLinksEnabled: boolean
            ): TraceIdentity => {
                // The flag guard runs before the scan, which reads every attribute of every span.
                if (!correlationLinksEnabled) {
                    return EMPTY_TRACE_IDENTITY
                }
                // Nothing while more spans can arrive, because a second, conflicting identity may
                // sit on a page that has not loaded, and the prefetch fallback shown during the
                // first fetch may itself be truncated.
                if (canLoadMoreTraceSpans || traceSpansLoading) {
                    return EMPTY_TRACE_IDENTITY
                }
                return resolveTraceIdentity(openTraceSpans, configuredDistinctIdKeys, configuredSessionIdKeys)
            },
        ],
        // The open trace's session for the Errors tab, which needs no person. It follows the badge
        // flag rather than the person and replay one, so the tab works for a team that has only the
        // badges. The gate also keeps the span scan off a team that has neither.
        //
        // It reads every span loaded so far, rather than waiting for a complete trace the way
        // `traceIdentity` does. A large trace pages in as the user scrolls the waterfall, and
        // waiting would leave the tab loading indefinitely. The badge that opens this tab already
        // resolves from one row, so the stricter rule would also make the two disagree. A later
        // page that carries a second session withdraws the answer rather than keeping a wrong one.
        traceSessionId: [
            (s) => [
                s.openTraceSpans,
                s.spans,
                s.selectedSpanId,
                s.configuredSessionIdKeys,
                s.sessionErrorBadgesEnabled,
            ],
            (
                openTraceSpans: Span[],
                spans: Span[],
                selectedSpanId: string | null,
                configuredSessionIdKeys: string[] | undefined,
                sessionErrorBadgesEnabled: boolean
            ): string | null => {
                if (!sessionErrorBadgesEnabled) {
                    return null
                }
                // The anchored span first, because a badge click opens the drawer on the row the
                // user pressed. Reading the whole trace instead would answer null for a trace that
                // touches two sessions, so a row that just showed a count would open a tab saying
                // the trace has no session.
                //
                // The full-trace fetch returns the earliest page of a large trace, which can omit
                // the anchored span. The row the user pressed is still in the list, so fall back to
                // it rather than resolving from a page that may carry another session.
                const findAnchored = (candidates: Span[]): Span | null =>
                    selectedSpanId ? (candidates.find((span) => span.span_id === selectedSpanId) ?? null) : null
                const anchored = findAnchored(openTraceSpans) ?? findAnchored(spans)
                const anchoredSessionId = anchored ? resolveSpanSessionId(anchored, configuredSessionIdKeys) : null
                return anchoredSessionId ?? resolveTraceSessionId(openTraceSpans, configuredSessionIdKeys)
            },
        ],
    }),

    listeners(({ actions, values, props }) => ({
        closeTrace: () => {
            actions.disableSpanKeys()
            // The attribute buttons in the drawer defer their query so the list doesn't reload
            // behind it — run it now that the drawer is closing.
            if (values.hasDeferredFilterRefresh) {
                actions.refreshDeferredFilters()
            }
        },
        openTrace: ({ traceId, ts, spanId }) => {
            actions.showTrace(spanId, values.inspectorTab)
            actions.enableSpanKeys(`[data-attr="${TRACE_DRAWER_DATA_ATTR}"]`, 'drawer')
            // pinned: analytics event and property names. The view persists across traces, so the view change event
            // alone cannot count how many traces people read as a call tree.
            posthog.capture('tracing trace opened', { view: values.traceViewMode })
            // Fetch the trace by id when the prefetch can be incomplete. A batch with no root span is a
            // cold link (no spans loaded) or an orphan trace, whose prefetch holds only the spans that
            // matched the list. A full prefetch batch (>= PREFETCH_SPANS) may be truncated.
            if (!isCompletePrefetch(values.spans, traceId)) {
                actions.loadTraceSpans({ traceId, ts })
            }
        },
        // The URL and the span tree each select spans, so each side passes on only a real change.
        selectSpan: ({ spanId }) => {
            if (spanId !== traceViewLogic({ id: traceViewId(props.id) }).values.selectedSpanId) {
                actions.selectViewSpan(spanId)
            }
        },
        selectViewSpan: ({ spanId }) => {
            if (spanId !== values.selectedSpanId) {
                actions.selectSpan(spanId)
            }
        },
        // These modals open over the drawer, so its keys must not step spans while one has focus.
        openLogsViewerModal: () => {
            actions.disableSpanKeys()
        },
        openSessionPlayer: () => {
            actions.disableSpanKeys()
        },
        closeLogsViewerModal: () => {
            if (values.isTraceOpen) {
                actions.enableSpanKeys(`[data-attr="${TRACE_DRAWER_DATA_ATTR}"]`, 'drawer')
            }
        },
        closeSessionPlayer: () => {
            if (values.isTraceOpen) {
                actions.enableSpanKeys(`[data-attr="${TRACE_DRAWER_DATA_ATTR}"]`, 'drawer')
            }
        },
        selectInspectorTab: ({ tab }) => {
            actions.setInspectorTab(tab)
        },
        openCompareFlame: ({ spanName, serviceName }) => {
            // The span and service names are the customer's own telemetry, so the event leaves them out.
            // pinned: analytics event name, so renaming it breaks the insights built on it
            posthog.capture('tracing compare flame opened')
            actions.fetchSpanTree({ spanName, serviceName })
        },
        updateComparisonWindows: () => {
            // The aggregation refetch on an overlay drag lives in tracingDataLogic; here we only
            // refresh the compare-flame modal (viewer UI) so it doesn't display stale windows.
            if (values.compareFlameSpanName && values.compareFlameServiceName) {
                actions.fetchSpanTree({
                    spanName: values.compareFlameSpanName,
                    serviceName: values.compareFlameServiceName,
                })
            }
        },
    })),
])