: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): load spans and show missing parent spans for orphan traces (#113106)
Frank Hamand189bc53bd1a3
diff --git a/products/tracing/frontend/TraceWaterfallView.test.tsx b/products/tracing/frontend/TraceWaterfallView.test.tsxindex 47d54c1b5c89..3c5046f9db5c 100644--- a/products/tracing/frontend/TraceWaterfallView.test.tsx+++ b/products/tracing/frontend/TraceWaterfallView.test.tsx@@ -99,12 +99,31 @@ describe('TraceWaterfallView', () => {})it('does not render a collapse toggle for leaf spans', () => {- const { container } = render(<TraceWaterfallView spans={[child]} />)+ const { container } = render(<TraceWaterfallView spans={[root]} />)expect(within(container).queryByLabelText('Collapse child spans')).toBeNull()expect(within(container).queryByLabelText('Collapse all spans')).toBeNull()})+ it('puts spans whose parent is not loaded under one parent span missing row, which selects the missing id', () => {+ const onSpanSelect = jest.fn()+ const sibling = makeSpan({+ uuid: 'uuid-sibling',+ span_id: 'span-sibling',+ parent_span_id: 'span-root',+ name: 'sibling-operation',+ })+ const { container } = render(<TraceWaterfallView spans={[child, sibling]} onSpanSelect={onSpanSelect} />)++ expect(container.querySelectorAll('[data-row-key^="missing-parent-"]')).toHaveLength(1)+ clickSpanRow(container, '<parent span missing>')+ expect(onSpanSelect).toHaveBeenCalledWith('span-root')++ fireEvent.click(within(container).getByLabelText('Collapse child spans'))+ expect(within(container).queryByText('child-operation')).toBeNull()+ expect(within(container).queryByText('sibling-operation')).toBeNull()+ })+it('does not request more spans when hasMore is false', () => {const onLoadMore = jest.fn()render(<TraceWaterfallView spans={[root, child]} hasMore={false} onLoadMore={onLoadMore} />)diff --git a/products/tracing/frontend/TraceWaterfallView.tsx b/products/tracing/frontend/TraceWaterfallView.tsxindex 7f2794a09c34..84d441a38c10 100644--- a/products/tracing/frontend/TraceWaterfallView.tsx+++ b/products/tracing/frontend/TraceWaterfallView.tsx@@ -30,10 +30,42 @@ interface SpanNode {depth: numberisLastChild: booleanconnectorLines: 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,+ }}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) {@@ -41,9 +73,23 @@ function buildSpanTree(spans: Span[]): SpanNode[] {}for (const node of byId.values()) {- if (node.span.parent_span_id && byId.has(node.span.parent_span_id)) {- const parent = byId.get(node.span.parent_span_id)!+ const parentSpanId = node.span.parent_span_id+ 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)}@@ -310,7 +356,7 @@ function WaterfallRow({collapsedSpanIds,onToggleCollapse,}: Omit<WaterfallRowData, 'flatSpans' | 'dynamicRowHeight'> & { node: SpanNode }): JSX.Element {- const { span } = node+ const { span, isMissingParent = false } = nodeconst hasChildren = node.children.length > 0const isCollapsed = collapsedSpanIds.has(span.span_id)const hiddenDescendants = isCollapsed ? countDescendants(node) : 0@@ -328,7 +374,6 @@ function WaterfallRow({// Select by span_id (the OTel id the tree is keyed by, and what the inspector/URL resolve),// not the ClickHouse row uuid.const isSelected = selectedSpanId === span.span_id-return (<div><div@@ -387,7 +432,7 @@ function WaterfallRow({)}<Tooltip title={span.name}><span- className={`text-xs truncate ${isError ? 'text-danger' : ''} ${+ className={`text-xs truncate ${isError || isMissingParent ? 'text-danger' : ''} ${isSelected || isError ? 'font-semibold' : 'font-medium'} ${isUnmatched ? 'opacity-40' : ''}`}>@@ -423,35 +468,37 @@ function WaterfallRow({})}{/* Span bar */}- <Tooltip- title={- <span>- <strong>{span.name}</strong>- <br />- {span.service_name} · {formatDuration(span.duration_nano)}- {isError ? ' · Error' : ''}- </span>- }- >- <div- className="absolute h-full flex items-center px-1.5 overflow-hidden"- // 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}`,- }}+ {!isMissingParent && (+ <Tooltip+ title={+ <span>+ <strong>{span.name}</strong>+ <br />+ {span.service_name} · {formatDuration(span.duration_nano)}+ {isError ? ' · Error' : ''}+ </span>+ }>- <span- className={`text-[11px] truncate whitespace-nowrap flex items-center gap-1.5 ${isUnmatched ? 'opacity-40' : ''}`}+ <div+ className="absolute h-full flex items-center px-1.5 overflow-hidden"+ // 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}`,+ }}>- <span className="text-muted-alt font-medium">{span.service_name}</span>- <span className="text-muted">{formatDuration(span.duration_nano)}</span>- </span>- </div>- </Tooltip>+ <span+ className={`text-[11px] truncate whitespace-nowrap flex items-center gap-1.5 ${isUnmatched ? 'opacity-40' : ''}`}+ >+ <span className="text-muted-alt font-medium">{span.service_name}</span>+ <span className="text-muted">{formatDuration(span.duration_nano)}</span>+ </span>+ </div>+ </Tooltip>+ )}</div></div></div>diff --git a/products/tracing/frontend/components/TraceDrawer/MissingParentSpanNotice.tsx b/products/tracing/frontend/components/TraceDrawer/MissingParentSpanNotice.tsxnew file mode 100644index 000000000000..ffb1ba711d08--- /dev/null+++ b/products/tracing/frontend/components/TraceDrawer/MissingParentSpanNotice.tsx@@ -0,0 +1,25 @@+import { CopyableId } from './SpanSummaryHeader'++// Shown in the inspector when the waterfall's "<parent span missing>" row is selected, in place of span details.+export function MissingParentSpanNotice({+ traceId,+ parentSpanId,+}: {+ traceId: string+ parentSpanId: string+}): JSX.Element {+ return (+ <div className="flex flex-col gap-1.5 px-1 pb-2" data-attr="tracing-missing-parent-notice">+ <span className="font-semibold text-danger">Parent span missing</span>+ <p className="m-0">+ Spans in this trace have a parent span that we can't find. This can happen if the parent span is recent+ and we're still processing it, or if it comes from a separate service that doesn't send spans to+ PostHog.+ </p>+ <div className="flex items-center gap-x-3 gap-y-1 flex-wrap text-xs text-muted">+ <CopyableId label="Missing span ID" value={parentSpanId} />+ <CopyableId label="Trace ID" value={traceId} />+ </div>+ </div>+ )+}diff --git a/products/tracing/frontend/components/TraceDrawer/SpanSummaryHeader.tsx b/products/tracing/frontend/components/TraceDrawer/SpanSummaryHeader.tsxindex b1825fd52b90..bb8dc0c7b8d8 100644--- a/products/tracing/frontend/components/TraceDrawer/SpanSummaryHeader.tsx+++ b/products/tracing/frontend/components/TraceDrawer/SpanSummaryHeader.tsx@@ -28,7 +28,7 @@ function ServiceDot({ colorIndex }: { colorIndex: number | undefined }): JSX.Ele// A labelled, copyable identifier. Trace/parent IDs live here (not just the span ID) because the// summary header replaces the old "Span details" table — they're the only copyable home for the// correlation handles a user needs to pivot across distributed-trace tooling.-function CopyableId({ label, value }: { label: string; value: string }): JSX.Element {+export function CopyableId({ label, value }: { label: string; value: string }): JSX.Element {return (<span>{label}:{' '}diff --git a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsxindex 6cc13a0f127d..80009d20a185 100644--- a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx+++ b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx@@ -25,6 +25,7 @@ import { absoluteTraceUrl } from '../../traceLinks'import { buildServiceColorMap, formatDuration, TraceWaterfallView } from '../../TraceWaterfallView'import type { Span, SpanInspectorTab } from '../../types'import { ExpandedSpanContent } from '../VirtualizedSpanList/ExpandedSpanContent'+import { MissingParentSpanNotice } from './MissingParentSpanNotice'import { SpanLogsTab } from './SpanLogsTab'import { SpanMetricsTab } from './SpanMetricsTab'import { SpanSummaryHeader } from './SpanSummaryHeader'@@ -119,6 +120,14 @@ export function TraceDrawer({() => (selectedSpanId ? (spans.find((span) => span.span_id === selectedSpanId) ?? null) : null),[spans, selectedSpanId])+ // The waterfall's "<parent span missing>" row selects an id that only appears as a parent id.+ const missingParentSpanId = useMemo(+ () =>+ selectedSpanId && !selectedSpan && spans.some((span) => span.parent_span_id === selectedSpanId)+ ? selectedSpanId+ : null,+ [spans, selectedSpanId, selectedSpan]+ )// Shared with the waterfall so a service is the same color in the bars and the summary header.const serviceColorMap = useMemo(() => buildServiceColorMap(spans), [spans])@@ -201,7 +210,9 @@ export function TraceDrawer({data-attr="tracing-span-inspector"><Resizer {...inspectorResizerProps} />- {inspectedSpan ? (+ {missingParentSpanId ? (+ <MissingParentSpanNotice traceId={traceId ?? ''} parentSpanId={missingParentSpanId} />+ ) : inspectedSpan ? (<><SpanSummaryHeader span={inspectedSpan} serviceColorMap={serviceColorMap} /><LemonTabsdiff --git a/products/tracing/frontend/tracingViewerLogic.test.ts b/products/tracing/frontend/tracingViewerLogic.test.tsindex 15633150377f..f0f33ba2ff15 100644--- a/products/tracing/frontend/tracingViewerLogic.test.ts+++ b/products/tracing/frontend/tracingViewerLogic.test.ts@@ -38,16 +38,17 @@ describe('tracingViewerLogic', () => {})// The prefetch decision drives whether opening a trace refetches it by id: a partial- // prefetch batch is the trace's complete span set (no fetch), while a cold link (zero- // loaded spans) or a possibly-truncated full batch must fetch. Getting this wrong either- // refetches every drawer open or shows truncated waterfalls on cold links.+ // prefetch batch with its root is the trace's complete span set (no fetch), while a cold link+ // (zero loaded spans), an orphan batch (no root span), or a possibly-truncated full batch must+ // fetch. Getting this wrong either refetches every drawer open or shows truncated waterfalls.it.each([- ['no loaded spans (cold link)', 0, true],- ['a partial prefetch batch', 2, false],- ['a possibly-truncated full batch', PREFETCH_SPANS, true],- ])('openTrace with %s %s', (_name, spanCount, shouldFetch) => {+ ['no loaded spans (cold link)', 0, true, true],+ ['a partial prefetch batch', 2, true, false],+ ['a partial prefetch batch with no root span (orphan)', 2, false, true],+ ['a possibly-truncated full batch', PREFETCH_SPANS, true, true],+ ])('openTrace with %s', (_name, spanCount, hasRoot, shouldFetch) => {const spans = Array.from({ length: spanCount }, (_, i) =>- makeSpan({ uuid: `span-${i}`, span_id: `span-${i}`, trace_id: 'trace-x' })+ makeSpan({ uuid: `span-${i}`, span_id: `span-${i}`, trace_id: 'trace-x', is_root_span: hasRoot && i === 0 }))tracingDataLogic().actions.fetchSpansSuccess(spans)diff --git a/products/tracing/frontend/tracingViewerLogic.ts b/products/tracing/frontend/tracingViewerLogic.tsindex ce1b1a1b2f5e..e131efb992a8 100644--- a/products/tracing/frontend/tracingViewerLogic.ts+++ b/products/tracing/frontend/tracingViewerLogic.ts@@ -385,9 +385,11 @@ export const tracingViewerLogic = kea<tracingViewerLogicType>([openTrace: ({ traceId, ts }) => {posthog.capture('tracing trace opened')const prefetchedSpans = values.spans.filter((s: Span) => s.trace_id === traceId)- // Zero prefetched spans = the trace isn't in the loaded list (cold link) — fetch it by- // id. A full prefetch batch (>= PREFETCH_SPANS) may be truncated — fetch the rest.- if (prefetchedSpans.length === 0 || prefetchedSpans.length >= PREFETCH_SPANS) {+ // 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.+ const hasRootSpan = prefetchedSpans.some((s: Span) => s.is_root_span)+ if (!hasRootSpan || prefetchedSpans.length >= PREFETCH_SPANS) {actions.loadTraceSpans({ traceId, ts })}},