: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tracing): show the span tree in the trace dialog (#116935)
Jon McCallumbf68631be7af
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex fe1d17a30656..d561bf143a2c 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -112,6 +112,7 @@ const ERROR_FILTER_ALLOW_LIST_BY_LOGIC_PATH: Record<string, string> = {loadFullReport: 'scenes.project-homepage.today.todayReportLogic',loadPage: 'scenes.project-homepage.today.todayReportLogic',loadReportDiff: 'scenes.inbox.logics.inboxReportDetailLogic',+ loadTraceSpans: 'products.tracing.frontend.components.TraceDialog.traceDialogLogic', // The dialog shows its own retry}// A keyed logic's path ends with its key, so match the owner path as a prefix.diff --git a/products/tracing/frontend/TraceWaterfallView.tsx b/products/tracing/frontend/TraceWaterfallView.tsxindex 34d35956406b..c563b8416e12 100644--- a/products/tracing/frontend/TraceWaterfallView.tsx+++ b/products/tracing/frontend/TraceWaterfallView.tsx@@ -10,6 +10,16 @@ import { SizeProps } from 'lib/components/AutoSizer/AutoSizer'import { Tooltip } from 'lib/lemon-ui/Tooltip'import { cn } from 'lib/utils/css-classes'+import {+ buildSpanTree,+ collectCollapsibleSpanIds,+ connectorLinesOf,+ countDescendants,+ flattenTree,+ getTimelineTicks,+ parseTimestampUs,+ type SpanNode,+} from './spanTree'import type { Span } from './types'interface TraceWaterfallViewProps {@@ -24,147 +34,6 @@ interface TraceWaterfallViewProps {onLoadMore?: () => void}-interface SpanNode {- span: Span- children: SpanNode[]- depth: number- isLastChild: boolean- connectorLines: boolean[]- /** A placeholder for a parent span that is not in the trace. Its children are the spans that point to it. */- isMissingParent?: boolean-}--const MISSING_PARENT_LABEL = '<parent span missing>'--function missingParentNode(parentSpanId: string, child: Span): SpanNode {- return {- span: {- uuid: `missing-parent-${parentSpanId}`,- trace_id: child.trace_id,- span_id: parentSpanId,- parent_span_id: '',- name: MISSING_PARENT_LABEL,- kind: 0,- service_name: '',- status_code: 0,- timestamp: child.timestamp,- end_time: child.timestamp,- duration_nano: 0,- is_root_span: false,- matched_filter: true,- attributes: {},- resource_attributes: {},- },- children: [],- depth: 0,- isLastChild: false,- connectorLines: [],- isMissingParent: true,- }-}--// A root span has the all-zero OTel parent id, which the API returns as hex ("0000000000000000"), not "".-function parentSpanIdOf(span: Span): string | null {- if (span.is_root_span || !span.parent_span_id || /^0+$/.test(span.parent_span_id)) {- return null- }- return span.parent_span_id-}--function buildSpanTree(spans: Span[]): SpanNode[] {- const byId = new Map<string, SpanNode>()- const missingParents = new Map<string, SpanNode>()- const roots: SpanNode[] = []-- for (const span of spans) {- byId.set(span.span_id, { span, children: [], depth: 0, isLastChild: false, connectorLines: [] })- }-- for (const node of byId.values()) {- const parentSpanId = parentSpanIdOf(node.span)- if (parentSpanId && byId.has(parentSpanId)) {- const parent = byId.get(parentSpanId)!- parent.children.push(node)- } else if (parentSpanId) {- let placeholder = missingParents.get(parentSpanId)- if (!placeholder) {- placeholder = missingParentNode(parentSpanId, node.span)- missingParents.set(parentSpanId, placeholder)- roots.push(placeholder)- }- placeholder.children.push(node)- // The placeholder sorts with the other roots by its earliest child.- if (parseTimestampUs(node.span.timestamp) < parseTimestampUs(placeholder.span.timestamp)) {- placeholder.span.timestamp = node.span.timestamp- placeholder.span.end_time = node.span.timestamp- }- } else {- roots.push(node)- }- }-- function setDepths(nodes: SpanNode[], depth: number, parentConnectors: boolean[]): void {- for (let i = 0; i < nodes.length; i++) {- const node = nodes[i]- node.depth = depth- node.isLastChild = i === nodes.length - 1- node.connectorLines = [...parentConnectors]- node.children.sort((a, b) => new Date(a.span.timestamp).getTime() - new Date(b.span.timestamp).getTime())- setDepths(node.children, depth + 1, [...parentConnectors, !node.isLastChild])- }- }- setDepths(roots, 0, [])-- return roots-}--function sortChildren(nodes: SpanNode[]): SpanNode[] {- return [...nodes].sort((a, b) => parseTimestampUs(a.span.timestamp) - parseTimestampUs(b.span.timestamp))-}--function countDescendants(node: SpanNode): number {- let total = 0- for (const child of node.children) {- total += 1 + countDescendants(child)- }- return total-}--/** Depth-first flatten for rendering, skipping the subtree of any collapsed span. */-function flattenTree(nodes: SpanNode[], collapsedSpanIds: Set<string>): SpanNode[] {- const result: SpanNode[] = []- function walk(node: SpanNode): void {- result.push(node)- if (collapsedSpanIds.has(node.span.span_id)) {- return- }- for (const child of sortChildren(node.children)) {- walk(child)- }- }- for (const root of sortChildren(nodes)) {- walk(root)- }- return result-}--/** span_ids of every node that has children — the set of spans that can be collapsed. */-function collectCollapsibleSpanIds(nodes: SpanNode[]): Set<string> {- const ids = new Set<string>()- function walk(node: SpanNode): void {- if (node.children.length > 0) {- ids.add(node.span.span_id)- }- for (const child of node.children) {- walk(child)- }- }- for (const root of nodes) {- walk(root)- }- return ids-}-export function formatDuration(durationNano: number): string {const us = durationNano / 1_000if (us < 100) {@@ -177,32 +46,6 @@ export function formatDuration(durationNano: number): string {return `${(ms / 1000).toFixed(2)}s`}-/**- * Parse an ISO 8601 timestamp string to microseconds since epoch.- * `Date.getTime()` only gives millisecond resolution, losing sub-ms- * precision from timestamps like "2024-01-15T10:30:00.123456Z".- */-function parseTimestampUs(iso: string): number {- const ms = new Date(iso).getTime()- // Extract fractional seconds beyond milliseconds- const dot = iso.indexOf('.')- if (dot === -1) {- return ms * 1_000- }- // Find the end of fractional digits (before 'Z')- const fracEnd = iso.search(/[Z+-](\d\d:\d\d)?$/i)- if (fracEnd === -1) {- return ms * 1_000- }- const fracStr = iso.slice(dot + 1, fracEnd)- // Pad or truncate to 6 digits (microseconds)- const padded = fracStr.padEnd(6, '0').slice(0, 6)- const totalUs = parseInt(padded, 10)- // ms already includes the first 3 fractional digits, so add the remaining sub-ms part- const subMsUs = totalUs % 1_000- return ms * 1_000 + subMsUs-}-export function buildServiceColorMap(spans: Span[]): Map<string, number> {const services = [...new Set(spans.map((s) => s.service_name))].sort()const map = new Map<string, number>()@@ -210,23 +53,6 @@ export function buildServiceColorMap(spans: Span[]): Map<string, number> {return map}-/** Generate evenly spaced tick marks for the timeline (in microseconds) */-function getTimelineTicks(durationUs: number): number[] {- if (durationUs <= 0) {- return []- }- const targetTickCount = 5- const rawInterval = durationUs / targetTickCount- const magnitude = Math.pow(10, Math.floor(Math.log10(rawInterval)))- const niceIntervals = [1, 2, 5, 10]- const interval = niceIntervals.find((n) => n * magnitude >= rawInterval)! * magnitude- const ticks: number[] = []- for (let t = interval; t < durationUs; t += interval) {- ticks.push(t)- }- return ticks-}-const INDENT_PX = 16const DEFAULT_LABEL_COLUMN_WIDTH = 280const MIN_LABEL_COLUMN_WIDTH = 120@@ -277,11 +103,12 @@ function TreeIndent({ node }: { node: SpanNode }): JSX.Element | null {}const mid = INDENT_PX / 2+ const connectorLines = connectorLinesOf(node)return (<span className="flex shrink-0 items-stretch self-stretch overflow-visible">{/* Continuation lines for ancestor levels */}- {node.connectorLines.slice(0, -1).map((hasContinuation, i) => (+ {connectorLines.slice(0, -1).map((hasContinuation, i) => (<spankey={i}className="shrink-0 relative overflow-visible"diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialog.tsxindex bb6f2ae1f2f3..f7b2f9d8735c 100644--- a/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx+++ b/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx@@ -1,15 +1,20 @@import { useActions, useValues } from 'kea'import { IconExternal } from '@posthog/icons'-import { LemonButton, LemonModal } from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, LemonModal, LemonTag, Spinner } from '@posthog/lemon-ui'import { traceUrl } from 'lib/components/ViewTraceButton/traceUrl'+import { pluralize } from 'lib/utils/strings'++import { formatDuration } from 'products/tracing/frontend/TraceWaterfallView'import { traceDialogLogic } from './traceDialogLogic'+import { TraceDialogSpanTree } from './TraceDialogSpanTree'export function TraceDialog(): JSX.Element | null {- const { isOpen, trace } = useValues(traceDialogLogic)- const { closeTraceDialog } = useActions(traceDialogLogic)+ const { isOpen, trace, traceSpans, traceSpansLoading, traceSpansFailed, summary, timeline } =+ useValues(traceDialogLogic)+ const { closeTraceDialog, loadTraceSpans } = useActions(traceDialogLogic)if (!trace) {return null@@ -19,8 +24,25 @@ export function TraceDialog(): JSX.Element | null {<LemonModalisOpen={isOpen}onClose={closeTraceDialog}- title="Trace"- description={<span translate="no">{trace.traceId}</span>}+ title={<span translate="no">{summary.rootSpan?.name ?? 'Trace'}</span>}+ description={+ <div className="flex flex-wrap items-center gap-2">+ <span className="font-mono text-xs" translate="no">+ {trace.traceId}+ </span>+ {traceSpans && traceSpans.spans.length > 0 && (+ <>+ <LemonTag>{formatDuration(timeline.durationUs * 1_000)}</LemonTag>+ <LemonTag>+ {pluralize(summary.spanCount, 'span')} · {pluralize(summary.serviceCount, 'service')}+ </LemonTag>+ {summary.errorCount > 0 && (+ <LemonTag type="danger">{pluralize(summary.errorCount, 'error')}</LemonTag>+ )}+ </>+ )}+ </div>+ }forceAbovePopoverswidth="90vw"maxWidth={1600}@@ -36,7 +58,35 @@ export function TraceDialog(): JSX.Element | null {</LemonButton>}>- <div className="min-h-80" />+ {/* The span list virtualizes, so it needs a definite height to measure against. */}+ <div className="flex flex-col gap-2 h-[65vh]">+ {traceSpans?.truncated && (+ <LemonBanner type="info">+ Showing the first {summary.spanCount.toLocaleString()} spans. Open this trace in Tracing to see+ all of them.+ </LemonBanner>+ )}+ {traceSpansLoading ? (+ <div className="flex flex-1 items-center justify-center">+ <Spinner className="text-2xl" />+ </div>+ ) : traceSpansFailed ? (+ <div className="flex flex-1 flex-col items-center justify-center gap-2">+ <span>Couldn't load this trace.</span>+ <LemonButton type="secondary" onClick={() => loadTraceSpans(trace)}>+ Try again+ </LemonButton>+ </div>+ ) : !traceSpans || traceSpans.spans.length === 0 ? (+ <div className="flex flex-1 items-center justify-center text-muted">+ No spans found for this trace. Open it in Tracing to search other time ranges.+ </div>+ ) : (+ <div className="flex-1 min-h-0">+ <TraceDialogSpanTree />+ </div>+ )}+ </div></LemonModal>)}diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogMoreSpansRow.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogMoreSpansRow.tsxnew file mode 100644index 000000000000..4750f4db8739--- /dev/null+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogMoreSpansRow.tsx@@ -0,0 +1,36 @@+import { LemonButton } from '@posthog/lemon-ui'++import type { SpanNode } from 'products/tracing/frontend/spanTree'++import { INDENT_PX, MAX_INDENT_DEPTH } from './TraceDialogSpanRow'++export interface TraceDialogMoreSpansRowProps {+ parent: SpanNode+ hiddenCount: number+ onShowAll: (spanId: string) => void+}++export function TraceDialogMoreSpansRow({ parent, hiddenCount, onShowAll }: TraceDialogMoreSpansRowProps): JSX.Element {+ return (+ <div className="flex items-center w-full h-full gap-2 text-xs text-muted border-l-[3px] border-l-transparent">+ <span className="w-16 shrink-0" aria-hidden />+ <span+ className="flex items-center gap-2"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ paddingLeft: Math.min(parent.depth + 1, MAX_INDENT_DEPTH) * INDENT_PX }}+ >+ <span>+ {hiddenCount.toLocaleString()} more {hiddenCount === 1 ? 'span' : 'spans'}+ </span>+ <LemonButton+ size="xsmall"+ type="tertiary"+ onClick={() => onShowAll(parent.span.span_id)}+ data-attr="trace-dialog-show-all-spans"+ >+ Show all+ </LemonButton>+ </span>+ </div>+ )+}diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanRow.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanRow.tsxnew file mode 100644index 000000000000..fc00308a25c2--- /dev/null+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanRow.tsx@@ -0,0 +1,156 @@+import { IconChevronRight, IconWarning } from '@posthog/icons'++import { getSeriesColor } from 'lib/colors'+import { cn } from 'lib/utils/css-classes'++import { parseTimestampUs, type SpanNode } from 'products/tracing/frontend/spanTree'+import { formatDuration } from 'products/tracing/frontend/TraceWaterfallView'++import type { TraceDialogTimeline } from './traceDialogLogic'++export const INDENT_PX = 12+// Deeper spans stop indenting, so the name keeps room in the fixed-width span column.+export const MAX_INDENT_DEPTH = 10+const ERROR_COLOR = 'var(--danger)'++export interface TraceDialogSpanRowProps {+ node: SpanNode+ timeline: TraceDialogTimeline+ serviceColorMap: Map<string, number>+ isSelected: boolean+ /** Set only on the span that emitted the record the dialog was opened from. */+ openedAtUs: number | null+ /** How many spans sit under this one. Zero for a span with no children. */+ descendantCount: number+ isCollapsed: boolean+ onSelect: (spanId: string) => void+ onToggleCollapsed: (spanId: string) => void+}++function percentOfTrace(us: number, timeline: TraceDialogTimeline): number {+ return timeline.durationUs > 0 ? ((us - timeline.startUs) / timeline.durationUs) * 100 : 0+}++export function TraceDialogSpanRow({+ node,+ timeline,+ serviceColorMap,+ isSelected,+ openedAtUs,+ descendantCount,+ isCollapsed,+ onSelect,+ onToggleCollapsed,+}: TraceDialogSpanRowProps): JSX.Element {+ const { span, isMissingParent = false } = node+ const startUs = parseTimestampUs(span.timestamp)+ const leftPct = Math.max(percentOfTrace(startUs, timeline), 0)+ const widthPct = Math.max(+ Math.min(+ timeline.durationUs > 0 ? (span.duration_nano / 1_000 / timeline.durationUs) * 100 : 100,+ 100 - leftPct+ ),+ 0.3+ )+ const isError = span.status_code === 2+ const serviceColor = getSeriesColor(serviceColorMap.get(span.service_name) ?? 0)+ const barColor = isError ? ERROR_COLOR : serviceColor+ const openedAtPct = openedAtUs != null ? Math.min(Math.max(percentOfTrace(openedAtUs, timeline), 0), 100) : null++ return (+ // The collapse toggle cannot sit inside the select button, so the button fills the row from+ // behind and the row's content lets clicks through to it.+ <div+ className={cn(+ 'relative flex items-center w-full h-full text-xs border-l-[3px]',+ isSelected+ ? 'bg-surface-primary-active border-l-accent'+ : 'border-l-transparent hover:bg-surface-primary-hover'+ )}+ >+ <button+ type="button"+ className="absolute inset-0 cursor-pointer"+ aria-pressed={isSelected}+ aria-label={span.name}+ title={isMissingParent ? span.name : `${span.name} · ${span.service_name}`}+ onClick={() => onSelect(span.span_id)}+ data-attr="trace-dialog-span-row"+ />+ <span className="pointer-events-none relative w-16 shrink-0 px-2 font-mono text-muted" translate="no">+ +{formatDuration(Math.max(startUs - timeline.startUs, 0) * 1_000)}+ </span>+ <span+ className="pointer-events-none relative w-80 shrink-0 flex items-center gap-1.5 min-w-0 pr-2"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ paddingLeft: Math.min(node.depth, MAX_INDENT_DEPTH) * INDENT_PX }}+ >+ {descendantCount > 0 ? (+ <button+ type="button"+ className="pointer-events-auto shrink-0 flex items-center gap-0.5 h-5 pl-0.5 pr-1 rounded border border-primary bg-surface-primary text-[11px] font-semibold text-secondary hover:border-secondary hover:text-primary"+ aria-expanded={!isCollapsed}+ aria-label={`${isCollapsed ? 'Show' : 'Hide'} ${descendantCount} nested ${+ descendantCount === 1 ? 'span' : 'spans'+ }`}+ onClick={() => onToggleCollapsed(span.span_id)}+ data-attr="trace-dialog-span-collapse"+ >+ <IconChevronRight className={cn('transition-transform', !isCollapsed && 'rotate-90')} />+ {descendantCount.toLocaleString()}+ </button>+ ) : (+ <span className="w-5 shrink-0" aria-hidden />+ )}+ {!isMissingParent && (+ <span+ className="size-2 rounded-full shrink-0"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ backgroundColor: serviceColor }}+ aria-hidden+ />+ )}+ {isError && <IconWarning className="shrink-0 text-danger" fontSize={14} aria-label="Error" />}+ <span+ className={cn(+ 'truncate font-mono',+ (isError || isMissingParent) && 'text-danger',+ isSelected && 'font-semibold'+ )}+ translate="no"+ >+ {span.name}+ </span>+ </span>+ <span className="pointer-events-none relative grow self-stretch my-1.5" aria-hidden>+ {!isMissingParent && (+ <span+ className="absolute inset-y-0"+ // eslint-disable-next-line react/forbid-dom-props+ style={{+ left: `${leftPct}%`,+ width: `${widthPct}%`,+ minWidth: 2,+ backgroundColor: `color-mix(in srgb, ${barColor} 20%, transparent)`,+ borderLeft: `1px solid ${barColor}`,+ }}+ />+ )}+ {openedAtPct != null && (+ <span+ className="absolute -inset-y-1 w-0.5 bg-accent"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ left: `${openedAtPct}%` }}+ data-attr="trace-dialog-opened-at-marker"+ />+ )}+ </span>+ <span+ className="pointer-events-none relative w-20 shrink-0 px-2 text-right font-mono text-muted"+ translate="no"+ >+ {isMissingParent ? '' : formatDuration(span.duration_nano)}+ </span>+ </div>+ )+}diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsxnew file mode 100644index 000000000000..909fe835fdb7--- /dev/null+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx@@ -0,0 +1,152 @@+import { useActions, useValues } from 'kea'+import { CSSProperties, useCallback, useMemo, useRef } from 'react'+import { List, useListRef } from 'react-window'++import { AutoSizer } from 'lib/components/AutoSizer'+import { SizeProps } from 'lib/components/AutoSizer/AutoSizer'++import { getTimelineTicks } from 'products/tracing/frontend/spanTree'+import { formatDuration } from 'products/tracing/frontend/TraceWaterfallView'++import { traceDialogLogic, type TraceDialogTimeline } from './traceDialogLogic'+import { TraceDialogMoreSpansRow } from './TraceDialogMoreSpansRow'+import type { TraceDialogRow } from './traceDialogRows'+import { TraceDialogSpanRow } from './TraceDialogSpanRow'++const ROW_HEIGHT = 32++interface SpanListRowData {+ spanRows: TraceDialogRow[]+ descendantCounts: Map<string, number>+ collapsedSpanIds: Set<string>+ timeline: TraceDialogTimeline+ serviceColorMap: Map<string, number>+ selectedSpanId: string | null+ openedSpanId: string | null+ openedAtUs: number | null+ onSelect: (spanId: string) => void+ onToggleCollapsed: (spanId: string) => void+ onShowAll: (spanId: string) => void+}++function SpanListRow({+ ariaAttributes,+ index,+ style,+ spanRows,+ descendantCounts,+ collapsedSpanIds,+ selectedSpanId,+ openedSpanId,+ openedAtUs,+ onShowAll,+ ...rowProps+}: {+ ariaAttributes: { 'aria-posinset': number; 'aria-setsize': number; role: 'listitem' }+ index: number+ style: CSSProperties+} & SpanListRowData): JSX.Element {+ const row = spanRows[index]+ return (+ // eslint-disable-next-line react/forbid-dom-props+ <div {...ariaAttributes} style={style}>+ {row.kind === 'more' ? (+ <TraceDialogMoreSpansRow parent={row.parent} hiddenCount={row.hiddenCount} onShowAll={onShowAll} />+ ) : (+ <TraceDialogSpanRow+ node={row.node}+ isSelected={row.node.span.span_id === selectedSpanId}+ openedAtUs={row.node.span.span_id === openedSpanId ? openedAtUs : null}+ descendantCount={descendantCounts.get(row.node.span.span_id) ?? 0}+ isCollapsed={collapsedSpanIds.has(row.node.span.span_id)}+ {...rowProps}+ />+ )}+ </div>+ )+}++export function TraceDialogSpanTree(): JSX.Element {+ const { spanRows, spanTree, collapsedSpanIds, timeline, serviceColorMap, selectedSpanId, trace, openedAtUs } =+ useValues(traceDialogLogic)+ const { selectSpan, toggleSpanCollapsed, showAllChildren } = useActions(traceDialogLogic)+ const listRef = useListRef(null)+ const openedSpanId = trace?.spanId ?? null++ const openedIndex = useMemo(+ () =>+ openedSpanId+ ? spanRows.findIndex((row) => row.kind === 'span' && row.node.span.span_id === openedSpanId)+ : -1,+ [spanRows, openedSpanId]+ )+ // Bring the span that emitted the log into view. The list measures itself only after it mounts, so+ // an early scroll is lost: retry each time the rendered rows change until the span is visible, then+ // leave scrolling to the user.+ const revealedIndexRef = useRef<number | null>(null)+ const revealOpenedSpan = useCallback(+ (visibleRows: { startIndex: number; stopIndex: number }): void => {+ if (openedIndex < 0 || revealedIndexRef.current === openedIndex) {+ return+ }+ if (openedIndex >= visibleRows.startIndex && openedIndex <= visibleRows.stopIndex) {+ revealedIndexRef.current = openedIndex+ return+ }+ listRef.current?.scrollToRow({ index: openedIndex, align: 'center' })+ },+ [openedIndex, listRef]+ )++ return (+ <div className="flex flex-col h-full min-h-0">+ <div className="flex items-center text-[11px] text-muted border-b py-1" aria-hidden>+ <span className="w-16 shrink-0 px-2">Start</span>+ <span className="w-80 shrink-0">Span</span>+ <span className="relative grow h-4">+ {getTimelineTicks(timeline.durationUs).map((tickUs) => (+ <span+ key={tickUs}+ className="absolute -translate-x-1/2 font-mono"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ left: `${(tickUs / timeline.durationUs) * 100}%` }}+ translate="no"+ >+ {formatDuration(tickUs * 1_000)}+ </span>+ ))}+ </span>+ <span className="w-20 shrink-0 px-2 text-right">Duration</span>+ </div>+ <div className="flex-1 min-h-0">+ <AutoSizer+ renderProp={({ width, height }: SizeProps) => (+ <List<SpanListRowData>+ // eslint-disable-next-line react/forbid-dom-props+ style={{ width, height }}+ overscanCount={10}+ rowCount={spanRows.length}+ rowHeight={ROW_HEIGHT}+ rowComponent={SpanListRow}+ rowProps={{+ spanRows,+ descendantCounts: spanTree.descendantCounts,+ collapsedSpanIds,+ timeline,+ serviceColorMap,+ selectedSpanId,+ openedSpanId,+ openedAtUs,+ onSelect: selectSpan,+ onToggleCollapsed: toggleSpanCollapsed,+ onShowAll: showAllChildren,+ }}+ listRef={listRef}+ onRowsRendered={revealOpenedSpan}+ />+ )}+ />+ </div>+ </div>+ )+}diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.tsindex 5b14e67247ce..9963b6ed5e42 100644--- a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts+++ b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts@@ -1,15 +1,47 @@import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import api from 'lib/api'+import { initKeaTests } from '~/test/init'+import type { Span } from 'products/tracing/frontend/types'+import { traceDialogLogic } from './traceDialogLogic'+type TracePage = Awaited<ReturnType<typeof api.tracing.getTrace>>++function span(spanId: string): Span {+ return {+ uuid: spanId,+ trace_id: 'abc123',+ span_id: spanId,+ parent_span_id: '',+ name: spanId,+ kind: 0,+ service_name: 'agent-worker',+ status_code: 0,+ timestamp: '2026-10-14T10:00:00.000000Z',+ end_time: '2026-10-14T10:00:01.000000Z',+ duration_nano: 1_000_000_000,+ is_root_span: false,+ matched_filter: true,+ attributes: {},+ resource_attributes: {},+ }+}++function page(spanIds: string[], nextOffset: number | null): TracePage {+ return { results: spanIds.map(span), hasMore: nextOffset != null, nextOffset }+}+describe('traceDialogLogic', () => {let logic: ReturnType<typeof traceDialogLogic.build>+ let getTraceSpy: jest.SpyInstancebeforeEach(() => {initKeaTests()+ getTraceSpy = jest.spyOn(api.tracing, 'getTrace').mockResolvedValue(page(['a'], null))router.actions.push('/logs')logic = traceDialogLogic()logic.mount()@@ -17,6 +49,7 @@ describe('traceDialogLogic', () => {afterEach(() => {logic.unmount()+ getTraceSpy.mockRestore()})it('keeps the trace after close so the exit animation does not flash an empty dialog', async () => {@@ -24,7 +57,7 @@ describe('traceDialogLogic', () => {await expectLogic(logic, () => {logic.actions.closeTraceDialog()- }).toMatchValues({ isOpen: false, trace: { traceId: 'abc123', spanId: 'def456' } })+ }).toMatchValues({ isOpen: false, trace: { traceId: 'abc123', spanId: 'DEF456' } })})it.each([@@ -38,4 +71,103 @@ describe('traceDialogLogic', () => {router.actions.push(url)}).toMatchValues({ isOpen: expectedOpen })})++ it.each([+ ['an id in the API case', 'B1'],+ // Logs carry lowercase hex, and the trace API returns uppercase.+ ['a lowercase hex id from a log', 'b1'],+ ])('selects the span the dialog was opened from, given %s', async (_name, openedSpanId) => {+ getTraceSpy.mockResolvedValueOnce({ results: [span('A1'), span('B1')], hasMore: false, nextOffset: null })++ await expectLogic(logic, () => {+ logic.actions.openTraceDialog({ traceId: 'abc123', spanId: openedSpanId })+ }).toDispatchActions(['loadTraceSpansSuccess'])++ expect(logic.values.selectedSpanId).toBe('B1')+ })++ it.each([+ // An overlapping page adds nothing, so paging on would spin forever on the same spans.+ ['stops when a page adds no new span', [page(['a', 'b'], 2), page(['a', 'b'], 4)], ['a', 'b'], false, 2],+ [+ 'marks the trace truncated at the page cap',+ Array.from({ length: 6 }, (_, i) => page([`s${i}`], i + 1)),+ ['s0', 's1', 's2', 's3', 's4'],+ true,+ 5,+ ],+ ])('%s', async (_name, pages, expectedSpanIds, expectedTruncated, expectedCalls) => {+ pages.forEach((p) => getTraceSpy.mockResolvedValueOnce(p))++ await expectLogic(logic, () => {+ logic.actions.openTraceDialog({ traceId: 'abc123' })+ }).toDispatchActions(['loadTraceSpansSuccess'])++ expect(logic.values.traceSpans?.spans.map((s) => s.span_id)).toEqual(expectedSpanIds)+ expect(logic.values.traceSpans?.truncated).toBe(expectedTruncated)+ expect(getTraceSpy).toHaveBeenCalledTimes(expectedCalls)+ })++ it('stops paging once the dialog closes', async () => {+ let resolveFirstPage: (p: TracePage) => void = () => {}+ getTraceSpy.mockReturnValueOnce(new Promise<TracePage>((resolve) => (resolveFirstPage = resolve)))++ logic.actions.openTraceDialog({ traceId: 'abc123' })+ logic.actions.closeTraceDialog()+ await expectLogic(logic, () => {+ resolveFirstPage(page(['a'], 1))+ }).toDispatchActions(['loadTraceSpansSuccess'])++ expect(getTraceSpy).toHaveBeenCalledTimes(1)+ })++ it('ignores a failure from a trace that a newer one replaced', async () => {+ let rejectFirstTrace: (error: Error) => void = () => {}+ getTraceSpy.mockReturnValueOnce(new Promise<TracePage>((_, reject) => (rejectFirstTrace = reject)))++ logic.actions.openTraceDialog({ traceId: 'first' })+ await expectLogic(logic, () => {+ logic.actions.openTraceDialog({ traceId: 'second' })+ }).toDispatchActions(['loadTraceSpansSuccess'])++ rejectFirstTrace(new Error('boom'))+ await expectLogic(logic)+ .toNotHaveDispatchedActions(['loadTraceSpansFailure'])+ .toMatchValues({ traceSpansFailed: false })+ })++ it('selects a span when collapsing it hides the selection, and lists only spans on screen', async () => {+ const child = (spanId: string, parentSpanId: string): Span => ({+ ...span(spanId),+ parent_span_id: parentSpanId,+ })+ getTraceSpy.mockResolvedValueOnce({+ results: [{ ...span('ROOT'), is_root_span: true }, child('A', 'ROOT'), child('A1', 'A')],+ hasMore: false,+ nextOffset: null,+ })+ await expectLogic(logic, () => {+ logic.actions.openTraceDialog({ traceId: 'abc123', spanId: 'A1' })+ }).toDispatchActions(['loadTraceSpansSuccess'])++ logic.actions.toggleSpanCollapsed('A')++ expect(logic.values.selectedSpanId).toBe('A')+ expect(logic.values.flatSpans.map((node) => node.span.span_id)).toEqual(['ROOT', 'A'])+ })++ it('clears the failure once a retry succeeds', async () => {+ getTraceSpy.mockRejectedValueOnce(new Error('boom'))+ await expectLogic(logic, () => {+ logic.actions.openTraceDialog({ traceId: 'abc123' })+ })+ .toDispatchActions(['loadTraceSpansFailure'])+ .toMatchValues({ traceSpansFailed: true })++ await expectLogic(logic, () => {+ logic.actions.loadTraceSpans({ traceId: 'abc123' })+ })+ .toDispatchActions(['loadTraceSpansSuccess'])+ .toMatchValues({ traceSpansFailed: false })+ })})diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.tsindex 68fdd5b6bc22..3428f4e1a25e 100644--- a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts+++ b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts@@ -1,17 +1,77 @@import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'import { router } from 'kea-router'import type { LocationChangedPayload } from 'kea-router/lib/types'+import api from 'lib/api'import type { TraceLinkParams } from 'lib/components/ViewTraceButton/traceUrl'+import { usableId } from 'lib/components/ViewTraceButton/usableId'import { FEATURE_FLAGS } from 'lib/constants'+import { dayjs } from 'lib/dayjs'import { type FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { buildSpanTree, parseTimestampUs, type SpanNode } from 'products/tracing/frontend/spanTree'+import { resolveTraceLookupRange } from 'products/tracing/frontend/traceLinks'+import { buildServiceColorMap } from 'products/tracing/frontend/TraceWaterfallView'+import type { Span } from 'products/tracing/frontend/types'++import { buildTraceDialogRows, countDescendantsById, type TraceDialogRow } from './traceDialogRows'++// The trace endpoint pages at 2,000 spans, so this caps the dialog at 10,000. Bigger traces open in+// Tracing, which pages in on scroll.+const TRACE_DIALOG_MAX_PAGES = 5++// The trace API returns hex span ids in uppercase, and logs and metrics carry them in lowercase. The+// dialog matches the opened span against the loaded spans exactly, so it keeps the API's case.+function inApiCase(spanId: string | null | undefined): string | null {+ if (!spanId) {+ return null+ }+ return usableId(spanId) ? spanId.toUpperCase() : spanId+}++export interface TraceDialogSpans {+ spans: Span[]+ truncated: boolean+}++export interface TraceDialogTree {+ roots: SpanNode[]+ nodesById: Map<string, SpanNode>+ descendantCounts: Map<string, number>+}++export interface TraceDialogTimeline {+ startUs: number+ durationUs: number+}++export interface TraceDialogSummary {+ rootSpan: Span | null+ spanCount: number+ serviceCount: number+ errorCount: number+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface traceDialogLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogic+ collapsedSpanIds: Set<string>dialogEnabled: boolean+ flatSpans: SpanNode[]+ fullChildListSpanIds: Set<string>isOpen: boolean+ openedAtUs: number | null+ selectedSpanId: string | null+ serviceColorMap: Map<string, number>+ spanRows: TraceDialogRow[]+ spanTree: TraceDialogTree+ summary: TraceDialogSummary+ timeline: TraceDialogTimelinetrace: TraceLinkParams | null+ traceSpans: TraceDialogSpans | null+ traceSpansFailed: boolean+ traceSpansLoading: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -40,8 +100,36 @@ export interface traceDialogLogicActions {closeTraceDialog: () => {value: true}+ loadTraceSpans: (trace: TraceLinkParams) => TraceLinkParams+ loadTraceSpansFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadTraceSpansSuccess: (+ traceSpans: TraceDialogSpans | null,+ payload?: TraceLinkParams+ ) => {+ traceSpans: TraceDialogSpans | null+ payload?: TraceLinkParams+ }openTraceDialog: (trace: TraceLinkParams) => {- trace: TraceLinkParams+ trace: {+ spanId: string | null+ traceId: string+ ts?: string | null | undefined+ }+ }+ selectSpan: (spanId: string) => {+ spanId: string+ }+ showAllChildren: (spanId: string) => {+ spanId: string+ }+ toggleSpanCollapsed: (spanId: string) => {+ spanId: string}}@@ -49,6 +137,18 @@ export interface traceDialogLogicActions {export interface traceDialogLogicMeta {__keaTypeGenInternalSelectorTypes: {dialogEnabled: (featureFlags: FeatureFlagsSet) => boolean+ spanTree: (traceSpans: TraceDialogSpans | null) => TraceDialogTree+ spanRows: (+ spanTree: TraceDialogTree,+ collapsedSpanIds: Set<string>,+ fullChildListSpanIds: Set<string>,+ trace: TraceLinkParams | null+ ) => TraceDialogRow[]+ flatSpans: (spanRows: TraceDialogRow[]) => SpanNode[]+ serviceColorMap: (traceSpans: TraceDialogSpans | null) => Map<string, number>+ timeline: (traceSpans: TraceDialogSpans | null) => TraceDialogTimeline+ summary: (traceSpans: TraceDialogSpans | null) => TraceDialogSummary+ openedAtUs: (trace: TraceLinkParams | null) => number | null}}@@ -66,9 +166,47 @@ export const traceDialogLogic = kea<traceDialogLogicType>([values: [featureFlagLogic, ['featureFlags']],})),actions({- openTraceDialog: (trace: TraceLinkParams) => ({ trace }),+ openTraceDialog: (trace: TraceLinkParams) => ({ trace: { ...trace, spanId: inApiCase(trace.spanId) } }),closeTraceDialog: true,+ selectSpan: (spanId: string) => ({ spanId }),+ toggleSpanCollapsed: (spanId: string) => ({ spanId }),+ showAllChildren: (spanId: string) => ({ spanId }),}),+ loaders(({ values }) => ({+ traceSpans: [+ null as TraceDialogSpans | null,+ {+ loadTraceSpans: async (trace: TraceLinkParams, breakpoint): Promise<TraceDialogSpans | null> => {+ const dateRange = resolveTraceLookupRange(trace.ts)+ const seen = new Set<string>()+ const spans: Span[] = []+ let offset: number | undefined = undefined+ try {+ for (let page = 0; page < TRACE_DIALOG_MAX_PAGES; page++) {+ const response = await api.tracing.getTrace(trace.traceId, { dateRange, offset })+ breakpoint()+ // A page that adds no new span means the pages overlap, so paging further only repeats them.+ const fresh = (response.results as Span[]).filter((span) => !seen.has(span.span_id))+ fresh.forEach((span) => seen.add(span.span_id))+ spans.push(...fresh)+ if (!response.hasMore || response.nextOffset == null || fresh.length === 0) {+ return { spans, truncated: false }+ }+ if (!values.isOpen) {+ return { spans, truncated: true }+ }+ offset = response.nextOffset+ }+ } catch (error) {+ // A failure from a load that a newer one replaced must not mark the newer trace as failed.+ breakpoint()+ throw error+ }+ return { spans, truncated: true }+ },+ },+ ],+ })),reducers({isOpen: [false,@@ -85,6 +223,43 @@ export const traceDialogLogic = kea<traceDialogLogicType>([openTraceDialog: (_, { trace }) => trace,},],+ traceSpans: {+ openTraceDialog: () => null,+ },+ traceSpansFailed: [+ false,+ {+ loadTraceSpans: () => false,+ loadTraceSpansFailure: () => true,+ },+ ],+ selectedSpanId: [+ null as string | null,+ {+ openTraceDialog: (_, { trace }) => trace.spanId ?? null,+ selectSpan: (_, { spanId }) => spanId,+ },+ ],+ collapsedSpanIds: [+ new Set<string>(),+ {+ openTraceDialog: () => new Set<string>(),+ toggleSpanCollapsed: (collapsed, { spanId }) => {+ const next = new Set(collapsed)+ if (!next.delete(spanId)) {+ next.add(spanId)+ }+ return next+ },+ },+ ],+ fullChildListSpanIds: [+ new Set<string>(),+ {+ openTraceDialog: () => new Set<string>(),+ showAllChildren: (shown, { spanId }) => new Set(shown).add(spanId),+ },+ ],}),selectors({// Every entry point checks this one place, so the flag cannot open the dialog from some@@ -93,8 +268,95 @@ export const traceDialogLogic = kea<traceDialogLogicType>([(s) => [s.featureFlags],(featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.TRACING_TRACE_DIALOG],],+ spanTree: [+ (s) => [s.traceSpans],+ (traceSpans: TraceDialogSpans | null): TraceDialogTree => {+ const roots = buildSpanTree(traceSpans?.spans ?? [])+ const nodesById = new Map<string, SpanNode>()+ const stack = [...roots]+ while (stack.length > 0) {+ const node = stack.pop()!+ nodesById.set(node.span.span_id, node)+ stack.push(...node.children)+ }+ return { roots, nodesById, descendantCounts: countDescendantsById(roots) }+ },+ ],+ spanRows: [+ (s) => [s.spanTree, s.collapsedSpanIds, s.fullChildListSpanIds, s.trace],+ (+ spanTree: TraceDialogTree,+ collapsedSpanIds: Set<string>,+ fullChildListSpanIds: Set<string>,+ trace: TraceLinkParams | null+ ): TraceDialogRow[] =>+ buildTraceDialogRows(+ spanTree.roots,+ collapsedSpanIds,+ fullChildListSpanIds,+ (trace?.spanId && spanTree.nodesById.get(trace.spanId)) || null+ ),+ ],+ // The spans on screen, in order, for stepping through them.+ flatSpans: [+ (s) => [s.spanRows],+ (spanRows: TraceDialogRow[]): SpanNode[] =>+ spanRows.flatMap((row) => (row.kind === 'span' ? [row.node] : [])),+ ],+ serviceColorMap: [+ (s) => [s.traceSpans],+ (traceSpans: TraceDialogSpans | null): Map<string, number> => buildServiceColorMap(traceSpans?.spans ?? []),+ ],+ timeline: [+ (s) => [s.traceSpans],+ (traceSpans: TraceDialogSpans | null): TraceDialogTimeline => {+ const spans = traceSpans?.spans ?? []+ if (spans.length === 0) {+ return { startUs: 0, durationUs: 0 }+ }+ const starts = spans.map((span) => parseTimestampUs(span.timestamp))+ const ends = spans.map((span, i) => starts[i] + span.duration_nano / 1_000)+ const startUs = Math.min(...starts)+ return { startUs, durationUs: Math.max(...ends) - startUs }+ },+ ],+ summary: [+ (s) => [s.traceSpans],+ (traceSpans: TraceDialogSpans | null): TraceDialogSummary => {+ const spans = traceSpans?.spans ?? []+ return {+ rootSpan: spans.find((span) => span.is_root_span) ?? null,+ spanCount: spans.length,+ serviceCount: new Set(spans.map((span) => span.service_name)).size,+ errorCount: spans.filter((span) => span.status_code === 2).length,+ }+ },+ ],+ // When the record that opened the dialog was written: a log's timestamp, so its span can show+ // when the log fired. Parsed to microseconds, like the timeline, so sub-millisecond spans place it right.+ openedAtUs: [+ (s) => [s.trace],+ (trace: TraceLinkParams | null): number | null =>+ trace?.ts && dayjs(trace.ts).isValid() ? parseTimestampUs(trace.ts) : null,+ ],}),listeners(({ values, actions, cache }) => ({+ openTraceDialog: ({ trace }) => {+ actions.loadTraceSpans(trace)+ },+ // Collapsing the span that holds the selection selects it, so the inspector shows a span on screen.+ toggleSpanCollapsed: ({ spanId }) => {+ if (!values.collapsedSpanIds.has(spanId) || !values.selectedSpanId) {+ return+ }+ const { nodesById } = values.spanTree+ for (let node = nodesById.get(values.selectedSpanId)?.parent; node; node = node.parent) {+ if (node.span.span_id === spanId) {+ actions.selectSpan(spanId)+ return+ }+ }+ },locationChanged: ({ pathname }) => {// Query and hash changes fire locationChanged too, so only a new pathname closes the dialog.if (pathname === cache.lastPathname) {diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogRows.test.ts b/products/tracing/frontend/components/TraceDialog/traceDialogRows.test.tsnew file mode 100644index 000000000000..c894c82c2cd0--- /dev/null+++ b/products/tracing/frontend/components/TraceDialog/traceDialogRows.test.ts@@ -0,0 +1,86 @@+import { buildSpanTree, type SpanNode } from 'products/tracing/frontend/spanTree'+import type { Span } from 'products/tracing/frontend/types'++import { buildTraceDialogRows, countDescendantsById, type TraceDialogRow } from './traceDialogRows'++function span(spanId: string, parentSpanId: string, offsetMs: number): Span {+ return {+ uuid: spanId,+ trace_id: 'abc123',+ span_id: spanId,+ parent_span_id: parentSpanId,+ name: spanId,+ kind: 0,+ service_name: 'agent-worker',+ status_code: 0,+ timestamp: new Date(Date.UTC(2026, 9, 14, 10) + offsetMs).toISOString(),+ end_time: new Date(Date.UTC(2026, 9, 14, 10) + offsetMs + 1).toISOString(),+ duration_nano: 1_000_000,+ is_root_span: parentSpanId === '',+ matched_filter: true,+ attributes: {},+ resource_attributes: {},+ }+}++function labels(rows: TraceDialogRow[]): string[] {+ return rows.map((row) => (row.kind === 'span' ? row.node.span.span_id : `+${row.hiddenCount}`))+}++function find(roots: SpanNode[], spanId: string): SpanNode {+ const stack = [...roots]+ while (stack.length > 0) {+ const node = stack.pop()!+ if (node.span.span_id === spanId) {+ return node+ }+ stack.push(...node.children)+ }+ throw new Error(`no span ${spanId}`)+}++describe('traceDialogRows', () => {+ // A root with twelve children in start order, the first of which has a child of its own.+ const roots = buildSpanTree([+ span('root', '', 0),+ ...Array.from({ length: 12 }, (_, i) => span(`c${i}`, 'root', 10 + i)),+ span('g0', 'c0', 11),+ ])+ const firstTen = Array.from({ length: 10 }, (_, i) => `c${i}`)++ it('counts every span under each span', () => {+ const counts = countDescendantsById(roots)++ expect([counts.get('root'), counts.get('c0'), counts.get('c1')]).toEqual([13, 1, 0])+ })++ it.each([+ [+ 'caps a wide fan-out with a more row',+ new Set<string>(),+ new Set<string>(),+ null,+ ['root', 'c0', 'g0', ...firstTen.slice(1), '+2'],+ ],+ ['hides a collapsed subtree', new Set(['c0']), new Set<string>(), null, ['root', ...firstTen, '+2']],+ [+ 'shows every child once asked',+ new Set<string>(),+ new Set(['root']),+ null,+ ['root', 'c0', 'g0', ...firstTen.slice(1), 'c10', 'c11'],+ ],+ // The span a log came from stays on screen when it sits past the cap.+ [+ 'keeps the pinned span past the cap',+ new Set<string>(),+ new Set<string>(),+ 'c11',+ ['root', 'c0', 'g0', ...firstTen.slice(1), 'c11', '+1'],+ ],+ ])('%s', (_name, collapsed, fullChildLists, pinnedId, expected) => {+ const pinned = pinnedId ? find(roots, pinnedId) : null++ expect(labels(buildTraceDialogRows(roots, collapsed, fullChildLists, pinned))).toEqual(expected)+ })+})diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogRows.ts b/products/tracing/frontend/components/TraceDialog/traceDialogRows.tsnew file mode 100644index 000000000000..bb9078ac55f6--- /dev/null+++ b/products/tracing/frontend/components/TraceDialog/traceDialogRows.ts@@ -0,0 +1,79 @@+import { parseTimestampUs, type SpanNode } from 'products/tracing/frontend/spanTree'++// A wide fan-out shows this many children until the person asks for the rest.+export const TRACE_DIALOG_CHILD_LIMIT = 10++export type TraceDialogRow = { kind: 'span'; node: SpanNode } | { kind: 'more'; parent: SpanNode; hiddenCount: number }++function byStart(nodes: SpanNode[]): SpanNode[] {+ return [...nodes].sort((a, b) => parseTimestampUs(a.span.timestamp) - parseTimestampUs(b.span.timestamp))+}++/** How many spans sit under each span, keyed by span id. One pass, so deep traces stay off the call stack. */+export function countDescendantsById(roots: SpanNode[]): Map<string, number> {+ const order: SpanNode[] = []+ const stack = [...roots]+ while (stack.length > 0) {+ const node = stack.pop()!+ order.push(node)+ stack.push(...node.children)+ }+ const counts = new Map<string, number>()+ // Children come after their parent in `order`, so walking it backwards totals each child first.+ for (let i = order.length - 1; i >= 0; i--) {+ const node = order[i]+ counts.set(+ node.span.span_id,+ node.children.reduce((total, child) => total + 1 + (counts.get(child.span.span_id) ?? 0), 0)+ )+ }+ return counts+}++/**+ * The rows the span list shows, depth first in start order. A collapsed span hides its subtree, and a+ * span with more than TRACE_DIALOG_CHILD_LIMIT children shows the first ones and a "more" row, unless+ * its children are shown in full. The pinned span stays visible past the limit, so the span a log came+ * from is on screen when the dialog opens.+ */+export function buildTraceDialogRows(+ roots: SpanNode[],+ collapsedSpanIds: Set<string>,+ fullChildListSpanIds: Set<string>,+ pinned: SpanNode | null+): TraceDialogRow[] {+ const pinnedPath = new Set<SpanNode>()+ for (let node = pinned; node; node = node.parent) {+ pinnedPath.add(node)+ }++ const rows: TraceDialogRow[] = []+ const stack: TraceDialogRow[] = byStart(roots)+ .reverse()+ .map((node) => ({ kind: 'span', node }))+ while (stack.length > 0) {+ const row = stack.pop()!+ rows.push(row)+ if (row.kind !== 'span') {+ continue+ }+ const { node } = row+ const spanId = node.span.span_id+ if (node.children.length === 0 || collapsedSpanIds.has(spanId)) {+ continue+ }+ let shown = byStart(node.children)+ if (shown.length > TRACE_DIALOG_CHILD_LIMIT && !fullChildListSpanIds.has(spanId)) {+ shown = shown.filter((child, i) => i < TRACE_DIALOG_CHILD_LIMIT || pinnedPath.has(child))+ }+ const next: TraceDialogRow[] = shown.map((child) => ({ kind: 'span', node: child }))+ const hiddenCount = node.children.length - shown.length+ if (hiddenCount > 0) {+ next.push({ kind: 'more', parent: node, hiddenCount })+ }+ for (let i = next.length - 1; i >= 0; i--) {+ stack.push(next[i])+ }+ }+ return rows+}diff --git a/products/tracing/frontend/components/TraceDialog/useOpenTraceDialog.test.tsx b/products/tracing/frontend/components/TraceDialog/useOpenTraceDialog.test.tsxindex 1ca2ffeb8885..400b834cd6a8 100644--- a/products/tracing/frontend/components/TraceDialog/useOpenTraceDialog.test.tsx+++ b/products/tracing/frontend/components/TraceDialog/useOpenTraceDialog.test.tsx@@ -62,7 +62,7 @@ describe('useOpenTraceDialog', () => {expect(traceDialogLogic.values.isOpen).toBe(expectDialog)if (expectDialog) {- expect(traceDialogLogic.values.trace).toMatchObject({ traceId: 'abc123', spanId: 'def456' })+ expect(traceDialogLogic.values.trace).toMatchObject({ traceId: 'abc123', spanId: 'DEF456' })// A dialog click must not also follow the link.expect(router.values.location.pathname).toBe(pathnameBeforeClick)}diff --git a/products/tracing/frontend/spanTree.test.ts b/products/tracing/frontend/spanTree.test.tsnew file mode 100644index 000000000000..d927791d5d0a--- /dev/null+++ b/products/tracing/frontend/spanTree.test.ts@@ -0,0 +1,59 @@+import { buildSpanTree, collectCollapsibleSpanIds, connectorLinesOf, countDescendants, flattenTree } from './spanTree'+import type { Span } from './types'++function span(spanId: string, parentSpanId: string, offsetMs: number): Span {+ return {+ uuid: spanId,+ trace_id: 'abc123',+ span_id: spanId,+ parent_span_id: parentSpanId,+ name: spanId,+ kind: 0,+ service_name: 'agent-worker',+ status_code: 0,+ timestamp: new Date(Date.UTC(2026, 9, 14, 10) + offsetMs).toISOString(),+ end_time: new Date(Date.UTC(2026, 9, 14, 10) + offsetMs + 1).toISOString(),+ duration_nano: 1_000_000,+ is_root_span: parentSpanId === '',+ matched_filter: true,+ attributes: {},+ resource_attributes: {},+ }+}++describe('spanTree', () => {+ it('flattens depth first with children in start order', () => {+ const tree = buildSpanTree([+ span('root', '', 0),+ span('late', 'root', 20),+ span('early', 'root', 10),+ span('grandchild', 'early', 15),+ ])++ expect(flattenTree(tree, new Set()).map((node) => [node.span.span_id, node.depth, node.isLastChild])).toEqual([+ ['root', 0, true],+ ['early', 1, false],+ ['grandchild', 2, true],+ ['late', 1, true],+ ])+ expect(flattenTree(tree, new Set(['early'])).map((node) => node.span.span_id)).toEqual([+ 'root',+ 'early',+ 'late',+ ])+ expect(connectorLinesOf(tree[0].children[0].children[0])).toEqual([false, true])+ })++ it('handles a parent/child chain deeper than the call stack', () => {+ const depth = 20_000+ const spans = Array.from({ length: depth }, (_, i) => span(`s${i}`, i === 0 ? '' : `s${i - 1}`, i))++ const tree = buildSpanTree(spans)+ const flat = flattenTree(tree, new Set())++ expect(flat).toHaveLength(depth)+ expect(flat[depth - 1].depth).toBe(depth - 1)+ expect(countDescendants(tree[0])).toBe(depth - 1)+ expect(collectCollapsibleSpanIds(tree).size).toBe(depth - 1)+ })+})diff --git a/products/tracing/frontend/spanTree.ts b/products/tracing/frontend/spanTree.tsnew file mode 100644index 000000000000..42dff9105d27--- /dev/null+++ b/products/tracing/frontend/spanTree.ts@@ -0,0 +1,208 @@+import type { Span } from './types'++/**+ * Parse an ISO 8601 timestamp string to microseconds since epoch.+ * `Date.getTime()` only gives millisecond resolution, losing sub-ms+ * precision from timestamps like "2024-01-15T10:30:00.123456Z".+ */+export function parseTimestampUs(iso: string): number {+ const ms = new Date(iso).getTime()+ // Extract fractional seconds beyond milliseconds+ const dot = iso.indexOf('.')+ if (dot === -1) {+ return ms * 1_000+ }+ // Find the end of fractional digits (before 'Z')+ const fracEnd = iso.search(/[Z+-](\d\d:\d\d)?$/i)+ if (fracEnd === -1) {+ return ms * 1_000+ }+ const fracStr = iso.slice(dot + 1, fracEnd)+ // Pad or truncate to 6 digits (microseconds)+ const padded = fracStr.padEnd(6, '0').slice(0, 6)+ const totalUs = parseInt(padded, 10)+ // ms already includes the first 3 fractional digits, so add the remaining sub-ms part+ const subMsUs = totalUs % 1_000+ return ms * 1_000 + subMsUs+}++export interface SpanNode {+ span: Span+ children: SpanNode[]+ depth: number+ isLastChild: boolean+ parent: SpanNode | null+ /** A placeholder for a parent span that is not in the trace. Its children are the spans that point to it. */+ isMissingParent?: boolean+}++const MISSING_PARENT_LABEL = '<parent span missing>'++function missingParentNode(parentSpanId: string, child: Span): SpanNode {+ return {+ span: {+ uuid: `missing-parent-${parentSpanId}`,+ trace_id: child.trace_id,+ span_id: parentSpanId,+ parent_span_id: '',+ name: MISSING_PARENT_LABEL,+ kind: 0,+ service_name: '',+ status_code: 0,+ timestamp: child.timestamp,+ end_time: child.timestamp,+ duration_nano: 0,+ is_root_span: false,+ matched_filter: true,+ attributes: {},+ resource_attributes: {},+ },+ children: [],+ depth: 0,+ isLastChild: false,+ parent: null,+ isMissingParent: true,+ }+}++// A root span has the all-zero OTel parent id, which the API returns as hex ("0000000000000000"), not "".+function parentSpanIdOf(span: Span): string | null {+ if (span.is_root_span || !span.parent_span_id || /^0+$/.test(span.parent_span_id)) {+ return null+ }+ return span.parent_span_id+}++export function buildSpanTree(spans: Span[]): SpanNode[] {+ const byId = new Map<string, SpanNode>()+ const missingParents = new Map<string, SpanNode>()+ const roots: SpanNode[] = []++ for (const span of spans) {+ byId.set(span.span_id, { span, children: [], depth: 0, isLastChild: false, parent: null })+ }++ for (const node of byId.values()) {+ const parentSpanId = parentSpanIdOf(node.span)+ if (parentSpanId && byId.has(parentSpanId)) {+ const parent = byId.get(parentSpanId)!+ parent.children.push(node)+ node.parent = parent+ } else if (parentSpanId) {+ let placeholder = missingParents.get(parentSpanId)+ if (!placeholder) {+ placeholder = missingParentNode(parentSpanId, node.span)+ missingParents.set(parentSpanId, placeholder)+ roots.push(placeholder)+ }+ placeholder.children.push(node)+ node.parent = placeholder+ // The placeholder sorts with the other roots by its earliest child.+ if (parseTimestampUs(node.span.timestamp) < parseTimestampUs(placeholder.span.timestamp)) {+ placeholder.span.timestamp = node.span.timestamp+ placeholder.span.end_time = node.span.timestamp+ }+ } else {+ roots.push(node)+ }+ }++ // Iterative so a deep parent/child chain cannot overflow the call stack.+ const groups: { nodes: SpanNode[]; depth: number }[] = [{ nodes: roots, depth: 0 }]+ while (groups.length > 0) {+ const { nodes, depth } = groups.pop()!+ for (let i = 0; i < nodes.length; i++) {+ const node = nodes[i]+ node.depth = depth+ node.isLastChild = i === nodes.length - 1+ if (node.children.length > 0) {+ node.children.sort(+ (a, b) => new Date(a.span.timestamp).getTime() - new Date(b.span.timestamp).getTime()+ )+ groups.push({ nodes: node.children, depth: depth + 1 })+ }+ }+ }++ return roots+}++/**+ * Whether each ancestor level, root first, continues below this node, so the waterfall can draw its tree+ * lines. Derived on demand for the rows on screen: storing it on every node costs memory quadratic in depth.+ */+export function connectorLinesOf(node: SpanNode): boolean[] {+ const lines: boolean[] = []+ for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) {+ lines.push(!ancestor.isLastChild)+ }+ return lines.reverse()+}++function sortChildren(nodes: SpanNode[]): SpanNode[] {+ return [...nodes].sort((a, b) => parseTimestampUs(a.span.timestamp) - parseTimestampUs(b.span.timestamp))+}++export function countDescendants(node: SpanNode): number {+ let total = 0+ const stack = [...node.children]+ while (stack.length > 0) {+ const current = stack.pop()!+ total += 1+ for (const child of current.children) {+ stack.push(child)+ }+ }+ return total+}++/** Depth-first flatten for rendering, skipping the subtree of any collapsed span. */+export function flattenTree(nodes: SpanNode[], collapsedSpanIds: Set<string>): SpanNode[] {+ const result: SpanNode[] = []+ // An explicit stack, in reverse so the earliest child pops first, keeps deep traces off the call stack.+ const stack = sortChildren(nodes).reverse()+ while (stack.length > 0) {+ const node = stack.pop()!+ result.push(node)+ if (!collapsedSpanIds.has(node.span.span_id)) {+ const children = sortChildren(node.children)+ for (let i = children.length - 1; i >= 0; i--) {+ stack.push(children[i])+ }+ }+ }+ return result+}++/** span_ids of every node that has children — the set of spans that can be collapsed. */+export function collectCollapsibleSpanIds(nodes: SpanNode[]): Set<string> {+ const ids = new Set<string>()+ const stack = [...nodes]+ while (stack.length > 0) {+ const node = stack.pop()!+ if (node.children.length > 0) {+ ids.add(node.span.span_id)+ }+ for (const child of node.children) {+ stack.push(child)+ }+ }+ return ids+}++/** Generate evenly spaced tick marks for the timeline (in microseconds) */+export function getTimelineTicks(durationUs: number): number[] {+ if (durationUs <= 0) {+ return []+ }+ const targetTickCount = 5+ const rawInterval = durationUs / targetTickCount+ const magnitude = Math.pow(10, Math.floor(Math.log10(rawInterval)))+ const niceIntervals = [1, 2, 5, 10]+ const interval = niceIntervals.find((n) => n * magnitude >= rawInterval)! * magnitude+ const ticks: number[] = []+ for (let t = interval; t < durationUs; t += interval) {+ ticks.push(t)+ }+ return ticks+}diff --git a/products/tracing/frontend/traceLinks.ts b/products/tracing/frontend/traceLinks.tsindex 23b422c9131f..8b796c0aeba5 100644--- a/products/tracing/frontend/traceLinks.ts+++ b/products/tracing/frontend/traceLinks.ts@@ -35,3 +35,13 @@ export function traceLookupDateRange(ts: string): { date_from: string; date_to:date_to: dayjs(ts).add(TRACE_LOOKUP_WINDOW_HOURS, 'hour').toISOString(),}}++// A ts hint (from a shared/cold link) bounds the lookup tightly around the trace. Without one, the+// lookup sends no date range, so the backend finds the trace by id in all retained spans instead of+// only in the scene's current window. Guard validity: a hand-edited/corrupted ts would otherwise make+// dayjs throw on toISOString().+export function resolveTraceLookupRange(+ ts: string | null | undefined+): { date_from: string; date_to: string } | undefined {+ return ts && dayjs(ts).isValid() ? traceLookupDateRange(ts) : undefined+}diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.tsindex 4855eb678d19..1b8298a7dc5f 100644--- a/products/tracing/frontend/tracingDataLogic.ts+++ b/products/tracing/frontend/tracingDataLogic.ts@@ -50,7 +50,7 @@ import {visibleDurationRange,} from './durationBuckets'import { type HeatmapBrushSelection, heatmapBrushToFilters } from './heatmapBrush'-import { traceLookupDateRange } from './traceLinks'+import { resolveTraceLookupRange } from './traceLinks'import { traceRows } from './traceRows'import {type TracingFilters,@@ -96,14 +96,6 @@ const DEFAULT_PAGE_SIZE = 100const OPERATIONS_AGGREGATION_LIMIT = 5000export const PREFETCH_SPANS = 20-// A ts hint (from a shared/cold link) bounds the lookup tightly around the trace. Without one, the-// lookup sends no date range, so the backend finds the trace by id in all retained spans instead of-// only in the scene's current window. Guard validity: a hand-edited/corrupted ts would otherwise make-// dayjs throw on toISOString().-function resolveTraceLookupRange(ts: string | null | undefined): { date_from: string; date_to: string } | undefined {- return ts && dayjs(ts).isValid() ? traceLookupDateRange(ts) : undefined-}-function captureTracingResults(count: number, queryType: 'spans' | 'aggregation'): void {if (count === 0) {posthog.capture('tracing no results returned', { query_type: queryType })