: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
fix(tracing): show traces whose root span never arrived (#112158)
Frank Hamand42e33f2d259a
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex b233e542ee71..4b03eaa18548 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7458,10 +7458,18 @@ snapshots:hash: v1.k794b7964.5590e8e6497de2fefefa74cf07edd5f814a798deb8f7e5f0102a383f5e8ac6c8.ZvuooUS3qT6kDX8yW2_oQ1iDgO1DwVFMAWM517bhCHwproducts-tracing-virtualizedspanlist--empty--light:hash: v1.k794b7964.72ff685c9162da170263d416510a2cc5229c999691288c0b8038143000a40f15.ebvPm2A_7cN8QvjEaroudYEO1lp9qFUooW98MMcDBwY+ products-tracing-virtualizedspanlist--spans-view--dark:+ hash: v1.k794b7964.d6cf5ccbc379f67404b237b878878ce7e60512d45869c05c24dfab7784335406.OfSo7jy1Oxb3_DY3IE02sphHajUZ8P1sJdfc_vZWjH0+ products-tracing-virtualizedspanlist--spans-view--light:+ hash: v1.k794b7964.7ec7e24fc514e8eac101ce26ef491c0becbbe2cc6aeb8759c1c451b5977e6aa7.tDvQvxyjpxBsOjo-NOt-XQSkhdki5QRjgPJhS_BmBhIproducts-tracing-virtualizedspanlist--with-error-badges--dark:hash: v1.k794b7964.c399531ee10ef73a5ca2b732484e1eae553f40b5b95c98fc0ab0b6a5d9711188.juWZKdvphiQP-rSsWPBDvU-9cRByiTb3dLrcfV1Qh3Yproducts-tracing-virtualizedspanlist--with-error-badges--light:hash: v1.k794b7964.7064ad6b5165631307d602ba3adcfd3fd5eb02107c8d3835c88c00df43bcad7f.3hK9J7DUCY3pFw2181ZBZbZsWlFkjm4Ydl5VNnzR5fA+ products-tracing-virtualizedspanlist--with-orphan-trace--dark:+ hash: v1.k794b7964.ffd642ad06f07044cfc19ae0428701c71f50b8bfa26a52e16d6186046817ca68.SuqNsoGMpBV72ep80L-fo-FUblkoaEajv2a8Bc12v6M+ products-tracing-virtualizedspanlist--with-orphan-trace--light:+ hash: v1.k794b7964.0c34340a4b3d88ec4569071212de94d3de749797457cfeca2408cd6f7547ae2e.ZJM2__v3UjG9ApKTQ9XpcDqbJqwhW8dD5CoOowxvxxwproducts-web-analytics-content-autopilot-brief--brief--dark:hash: v1.k794b7964.e9ebb3e96a4339f3e8116d76ca50f449e2650feb0ae5d65b8d56f2a6aefa03c5.ATu5igj4eqzRTqipkJ4O6N2ocrXDVmeoY_5y8B25UEAproducts-web-analytics-content-autopilot-brief--brief--light:diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 9897e343b470..5b32879c3c8e 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -2811,6 +2811,8 @@ const api = {after?: stringoffset?: numberprefetchSpans?: number+ // true (default) only selects traces with a root span.+ rootSpans?: boolean// false (default) groups by trace_id and returns root spans; true returns every// matching span (root and child) flat. See products/tracing/backend logic.py.flatSpans?: booleandiff --git a/products/tracing/backend/logic.py b/products/tracing/backend/logic.pyindex e5af9342b300..77037327edeb 100644--- a/products/tracing/backend/logic.py+++ b/products/tracing/backend/logic.py@@ -582,8 +582,9 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra# order, so keyset would pay its cost for none of its benefit).sort_key_sql = "max(duration_nano)" if by_duration else "min(timestamp)"- # rootSpans is opt-in and gated on `is True` (not truthiness): the frontend never sends it- # (None), so its prefetch-driven waterfall is untouched. An explicit True narrows the+ # rootSpans is gated on `is True` (not truthiness), so None leaves the prefetch-driven+ # waterfall untouched. The list endpoint defaults it to True, and the span list sends False+ # so that traces whose root never arrived still show. An explicit True narrows the# trace-selection subquery to `is_root_span = 1`, so we only pick traces whose root matches# the filter. The outer fetch is deliberately left unfiltered — it still prefetches every# span of the selected traces so the waterfall gets its children.diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsxindex fcd5fb7278a9..00d0ac4e688d 100644--- a/products/tracing/frontend/TracingScene.tsx+++ b/products/tracing/frontend/TracingScene.tsx@@ -301,6 +301,7 @@ function TracingSceneContents(): JSX.Element {<VirtualizedSpanListdataSource={listRows}spanColumns={spanColumns}+ showRootTag={filters.viewMode === 'spans'}loading={spansLoading}hasMoreToLoad={hasMoreToLoad}onLoadMore={fetchNextPage}diff --git a/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.stories.tsx b/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.stories.tsxindex da15159fb5f6..499db38f5e5b 100644--- a/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.stories.tsx+++ b/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.stories.tsx@@ -68,6 +68,10 @@ export const Empty: Story = {}// One row per badge tier, plus two rows with no errors, so the column's alignment shows.+export const SpansView: Story = {+ args: { showRootTag: true },+}+export const WithErrorBadges: Story = {args: {spanErrors: {@@ -95,3 +99,32 @@ export const CustomColumns: Story = {],},}++export const WithOrphanTrace: Story = {+ args: {+ dataSource: [+ span(1, {+ parent_span_id: '',+ is_root_span: true,+ name: 'POST /api/v2/checkout/session/confirm',+ timestamp: '2026-08-28T10:24:29.000Z',+ }),+ span(2, {+ trace_id: '7C2E9A4B1D6F43058E1B2A9C7D4F6E31',+ name: 'GET /api/v2/cart',+ kind: 2,+ service_name: 'cart-api',+ duration_nano: 42_000_000,+ timestamp: '2026-08-28T10:24:28.000Z',+ root_missing: true,+ }),+ span(3, {+ trace_id: '2A8D5F0C3B9E41A7962C4E8B1F0D7A53',+ parent_span_id: '',+ is_root_span: true,+ name: 'GET /api/v2/orders',+ duration_nano: 9_200_000,+ }),+ ],+ },+}diff --git a/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.tsx b/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.tsxindex 104addd5b640..97b854b76041 100644--- a/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.tsx+++ b/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.tsx@@ -7,6 +7,7 @@ import { AutoSizer } from 'lib/components/AutoSizer'import { SizeProps } from 'lib/components/AutoSizer/AutoSizer'import { TZLabel } from 'lib/components/TZLabel'import { SortingIndicator } from 'lib/lemon-ui/LemonTable/sorting'+import { Tooltip } from 'lib/lemon-ui/Tooltip'import { cn } from 'lib/utils/css-classes'import { TRACING_DATE_FORMAT, TRACING_DISPLAY_TIMEZONE, TRACING_TIME_FORMAT } from '../../dateFormats'@@ -38,10 +39,6 @@ const LOAD_MORE_THRESHOLD = 10// pinned: identifies stored column widths — renaming resets everyone's widthsconst TABLE_KEY = 'spans'-function isRootSpan(span: Span): boolean {- return !span.parent_span_id-}-interface SortProps {orderBy: TracingOrderByorderDirection: TracingOrderDirection@@ -66,6 +63,8 @@ interface VirtualizedSpanListProps extends SortProps {emptyState?: ReactNodespanErrors?: SpanErrorsspanColumns: SpanColumnConfig[]+ // Tag root spans. Only useful when the list mixes roots and children.+ showRootTag?: boolean}interface SpanRowProps {@@ -74,6 +73,7 @@ interface SpanRowProps {widths: Record<string, number>onRowClick: (span: Span) => voidspanErrors: SpanErrors | undefined+ showRootTag: boolean}/** Header cell wired to the shared resize handle. `sort` marks the column as server-sortable. */@@ -162,7 +162,7 @@ function SpanRowHeader({)}-function spanCellContent(column: SpanColumnConfig, span: Span): JSX.Element | null {+function spanCellContent(column: SpanColumnConfig, span: Span, showRootTag: boolean): JSX.Element | null {switch (column.type) {case 'timestamp':return (@@ -180,11 +180,18 @@ function spanCellContent(column: SpanColumnConfig, span: Span): JSX.Element | nureturn (<span className="flex items-center gap-2 truncate"><span className="truncate">{span.name}</span>- {isRootSpan(span) && (+ {showRootTag && span.is_root_span && (<LemonTag type="highlight" size="small">trace</LemonTag>)}+ {span.root_missing && (+ <Tooltip title="Parent span not found">+ <LemonTag type="muted" size="small">+ orphan+ </LemonTag>+ </Tooltip>+ )}</span>)case 'service':@@ -219,12 +226,14 @@ function SpanRow({spanColumns,widths,spanErrors,+ showRootTag,onClick,}: {span: SpanspanColumns: SpanColumnConfig[]widths: Record<string, number>spanErrors: SpanErrors | undefined+ showRootTag: booleanonClick: () => void}): JSX.Element {const errorBadge = spanErrors?.badges.get(span.uuid)@@ -250,7 +259,7 @@ function SpanRow({const key = spanColumnKey(column)return (<TableCell key={key} width={widths[key]}>- {spanCellContent(column, span)}+ {spanCellContent(column, span, showRootTag)}</TableCell>)})}@@ -281,6 +290,7 @@ function SpanListRow({spanColumns,widths,spanErrors,+ showRootTag,onRowClick,}: {ariaAttributes: { 'aria-posinset': number; 'aria-setsize': number; role: 'listitem' }@@ -297,6 +307,7 @@ function SpanListRow({spanColumns={spanColumns}widths={widths}spanErrors={spanErrors}+ showRootTag={showRootTag}onClick={() => onRowClick(span)}/></div>@@ -313,6 +324,7 @@ export function VirtualizedSpanList({emptyState = 'No spans found',spanErrors,spanColumns,+ showRootTag = false,orderBy,orderDirection,onSort,@@ -392,7 +404,7 @@ export function VirtualizedSpanList({rowCount={dataSource.length}rowHeight={ROW_HEIGHT}rowComponent={SpanListRow}- rowProps={{ dataSource, spanColumns, widths, spanErrors, onRowClick }}+ rowProps={{ dataSource, spanColumns, widths, spanErrors, showRootTag, onRowClick }}onRowsRendered={handleRowsRendered}listRef={listRef}/>diff --git a/products/tracing/frontend/traceRows.test.ts b/products/tracing/frontend/traceRows.test.tsnew file mode 100644index 000000000000..54eb497fe938--- /dev/null+++ b/products/tracing/frontend/traceRows.test.ts@@ -0,0 +1,74 @@+import { traceRows } from './traceRows'+import type { Span } from './types'++function span(overrides: Partial<Span>): Span {+ return {+ uuid: overrides.span_id ?? 'u',+ trace_id: 'trace-1',+ span_id: 'span-1',+ parent_span_id: '',+ name: 'op',+ kind: 2,+ service_name: 'svc',+ status_code: 0,+ timestamp: '2026-06-02T08:00:00.000Z',+ end_time: '2026-06-02T08:00:01.000Z',+ duration_nano: 1e9,+ is_root_span: false,+ matched_filter: true,+ attributes: {},+ resource_attributes: {},+ ...overrides,+ }+}++const rootA = span({ trace_id: 'a', span_id: 'a1', is_root_span: true, trace_start: '2026-06-02T08:00:00.000Z' })+const rootC = span({ trace_id: 'c', span_id: 'c1', is_root_span: true, trace_start: '2026-06-02T08:00:02.000Z' })+// Trace b: its parent `upstream` was never received.+const orphanTop = span({+ trace_id: 'b',+ span_id: 'b1',+ parent_span_id: 'upstream',+ timestamp: '2026-06-02T08:00:01.000Z',+ trace_start: '2026-06-02T08:00:01.000Z',+})+const orphanChild = span({+ trace_id: 'b',+ span_id: 'b2',+ parent_span_id: 'b1',+ timestamp: '2026-06-02T08:00:00.500Z',+ trace_start: '2026-06-02T08:00:01.000Z',+})++describe('traceRows', () => {+ it('returns root spans as-is when every trace has a root', () => {+ const child = span({ trace_id: 'a', span_id: 'a2', parent_span_id: 'a1' })+ expect(traceRows([rootA, rootC, child], 'timestamp', 'DESC')).toEqual([rootA, rootC])+ })++ it('promotes the top span of a trace with no root, even if a child started earlier', () => {+ const rows = traceRows([rootA, orphanChild, orphanTop], 'timestamp', 'ASC')+ expect(rows.map((s) => s.span_id)).toEqual(['a1', 'b1'])+ expect(rows[1].root_missing).toBe(true)+ })++ it.each([+ ['ASC', ['a1', 'b1', 'c1']],+ ['DESC', ['c1', 'b1', 'a1']],+ ] as const)('puts promoted rows in trace order (%s)', (direction, expected) => {+ const rows = traceRows([rootC, rootA, orphanTop, orphanChild], 'timestamp', direction)+ expect(rows.map((s) => s.span_id)).toEqual(expected)+ })++ it('orders by trace duration under duration sort', () => {+ const rows = traceRows(+ [+ { ...rootA, trace_duration: 5 },+ { ...orphanTop, trace_duration: 9 },+ ],+ 'duration',+ 'DESC'+ )+ expect(rows.map((s) => s.span_id)).toEqual(['b1', 'a1'])+ })+})diff --git a/products/tracing/frontend/traceRows.ts b/products/tracing/frontend/traceRows.tsnew file mode 100644index 000000000000..64f5dfc5dc03--- /dev/null+++ b/products/tracing/frontend/traceRows.ts@@ -0,0 +1,37 @@+import { dayjs } from 'lib/dayjs'++import type { TracingOrderBy, TracingOrderDirection } from './tracingFiltersLogic'+import type { Span } from './types'++// One row per trace. If the root span never arrived (e.g. an upstream service started the trace+// but doesn't export to PostHog), the top loaded span stands in for it.+export function traceRows(spans: Span[], orderBy: TracingOrderBy, orderDirection: TracingOrderDirection): Span[] {+ const roots = spans.filter((s) => s.is_root_span)+ const tracesWithRoot = new Set(roots.map((s) => s.trace_id))+ const orphans = new Map<string, Span[]>()+ for (const span of spans) {+ if (!tracesWithRoot.has(span.trace_id)) {+ const traceSpans = orphans.get(span.trace_id) ?? []+ traceSpans.push(span)+ orphans.set(span.trace_id, traceSpans)+ }+ }+ if (orphans.size === 0) {+ return roots+ }++ const promoted = [...orphans.values()].map((traceSpans) => {+ const ids = new Set(traceSpans.map((s) => s.span_id))+ const tops = traceSpans.filter((s) => !ids.has(s.parent_span_id))+ const top = (tops.length > 0 ? tops : traceSpans).reduce((a, b) =>+ dayjs(b.timestamp).isBefore(a.timestamp) ? b : a+ )+ return { ...top, root_missing: true }+ })++ // The API sorts root rows first, so put promoted rows back in trace order.+ const key = (s: Span): number =>+ orderBy === 'duration' ? (s.trace_duration ?? s.duration_nano) : dayjs(s.trace_start ?? s.timestamp).valueOf()+ const dir = orderDirection === 'ASC' ? 1 : -1+ return [...roots, ...promoted].sort((a, b) => (key(a) - key(b)) * dir)+}diff --git a/products/tracing/frontend/tracingAgentContext.ts b/products/tracing/frontend/tracingAgentContext.tsindex d591066c4878..95ebd618e35a 100644--- a/products/tracing/frontend/tracingAgentContext.ts+++ b/products/tracing/frontend/tracingAgentContext.ts@@ -167,8 +167,8 @@ function spanFilter(key: string, value: string[]): UniversalFiltersGroupValue {* omitted field resets to the viewer default so the page shows the query's results exactly, with* the same complete-query semantics the tool ran with.*- * rootSpans has no viewer facet to mirror: the span list never sends it, and the backend reads an- * omitted value as false, so only flatSpans picks the view mode.+ * rootSpans has no viewer facet to mirror: the span list always sends false, so only flatSpans+ * picks the view mode.*/export function apmSpansQueryToViewerFilters(input: Record<string, unknown>): Partial<TracingFilters> {// All query-apm-spans params are nested inside `query`; fall back to the raw input defensively.diff --git a/products/tracing/frontend/tracingDataLogic.test.ts b/products/tracing/frontend/tracingDataLogic.test.tsindex ee3360e5c97d..b186a2ab58c4 100644--- a/products/tracing/frontend/tracingDataLogic.test.ts+++ b/products/tracing/frontend/tracingDataLogic.test.ts@@ -128,7 +128,12 @@ describe('tracingDataLogic', () => {it('ignores non-root spans when deriving the range', () => {const withChild = [createMockSpan('root-1', '2024-01-01T00:00:00Z'),- { ...createMockSpan('child-1', '2024-01-01T05:00:00Z'), parent_span_id: 'root-1', is_root_span: false },+ {+ ...createMockSpan('child-1', '2024-01-01T05:00:00Z'),+ trace_id: 'trace-root-1',+ parent_span_id: 'root-1',+ is_root_span: false,+ },createMockSpan('root-2', '2024-01-01T01:00:00Z'),]logic.actions.fetchSpansSuccess(withChild)@@ -199,7 +204,12 @@ describe('tracingDataLogic', () => {describe('view mode', () => {const withChildSpans: Span[] = [createMockSpan('root-1', '2024-01-01T00:00:00Z'),- { ...createMockSpan('child-1', '2024-01-01T00:00:01Z'), parent_span_id: 'root-1', is_root_span: false },+ {+ ...createMockSpan('child-1', '2024-01-01T00:00:01Z'),+ trace_id: 'trace-root-1',+ parent_span_id: 'root-1',+ is_root_span: false,+ },createMockSpan('root-2', '2024-01-01T01:00:00Z'),]@@ -231,7 +241,10 @@ describe('tracingDataLogic', () => {const listSpansSpy = jest.spyOn(api.tracing, 'listSpans').mockResolvedValue({ results: [], hasMore: false })logic = mountWithSpans([])await logic.asyncActions.fetchSpans()- expect(listSpansSpy).toHaveBeenCalledWith(expect.objectContaining({ flatSpans: false }), expect.anything())+ expect(listSpansSpy).toHaveBeenCalledWith(+ expect.objectContaining({ flatSpans: false, rootSpans: false }),+ expect.anything()+ )listSpansSpy.mockRestore()})diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.tsindex 2308dfa3ec81..ecf72775ac08 100644--- a/products/tracing/frontend/tracingDataLogic.ts+++ b/products/tracing/frontend/tracingDataLogic.ts@@ -48,6 +48,7 @@ import {} from './durationBuckets'import { type HeatmapBrushSelection, heatmapBrushToFilters } from './heatmapBrush'import { traceLookupDateRange } from './traceLinks'+import { traceRows } from './traceRows'import {type TracingFilters,type TracingOrderBy,@@ -886,6 +887,8 @@ export const tracingDataLogic = kea<tracingDataLogicType>([filterGroup: values.queryFilterGroup as PropertyGroupFilter,prefetchSpans: PREFETCH_SPANS,flatSpans: values.filters.viewMode === 'spans',+ // The API defaults to root-only trace selection, which drops traces whose root never arrived.+ rootSpans: false,limit: DEFAULT_PAGE_SIZE,},controller.signal@@ -921,6 +924,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([filterGroup: values.queryFilterGroup as PropertyGroupFilter,prefetchSpans: PREFETCH_SPANS,flatSpans: values.filters.viewMode === 'spans',+ rootSpans: false,limit: DEFAULT_PAGE_SIZE,...pagination,},@@ -1302,13 +1306,13 @@ export const tracingDataLogic = kea<tracingDataLogicType>([filters.chartType === 'heatmap' &&!compareActive,],- // The rows the list renders. 'traces' mode shows root spans only (one row per trace);+ // The rows the list renders. 'traces' mode shows one row per trace (see traceRows);// 'spans' mode shows every matching span (root and child) flat. The fetch passes flatSpans// to match, so in 'spans' mode the loaded spans are already the flat set.listRows: [(s) => [s.spans, s.filters],(spans: Span[], filters: TracingFilters): Span[] => {- return filters.viewMode === 'spans' ? spans : spans.filter((s) => s.is_root_span)+ return filters.viewMode === 'spans' ? spans : traceRows(spans, filters.orderBy, filters.orderDirection)},],// Memoized separately so visibleRowDurationRange (recomputed on every scroll tick) doesn'tdiff --git a/products/tracing/frontend/types.ts b/products/tracing/frontend/types.tsindex d8070a7973a2..f96bb26f51bc 100644--- a/products/tracing/frontend/types.ts+++ b/products/tracing/frontend/types.ts@@ -16,6 +16,10 @@ export interface Span {attributes: Record<string, string>// OTel resource attributes (who/what emitted the span: service.version, host, k8s, ...).resource_attributes: Record<string, string>+ trace_start?: string+ trace_duration?: number+ // Set on a span shown in place of a root span that was not found.+ root_missing?: boolean}export const SPAN_KIND_LABELS: Record<number, string> = {