: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): add an adaptive span summary header to the inspector (#63047)
Jon McCallumd4087e4773ce
diff --git a/products/tracing/frontend/TraceWaterfallView.tsx b/products/tracing/frontend/TraceWaterfallView.tsxindex ec53cb8e4c7a..8a66efb906fa 100644--- a/products/tracing/frontend/TraceWaterfallView.tsx+++ b/products/tracing/frontend/TraceWaterfallView.tsx@@ -113,7 +113,7 @@ function parseTimestampUs(iso: string): number {return ms * 1_000 + subMsUs}-function buildServiceColorMap(spans: Span[]): Map<string, number> {+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>()services.forEach((service, i) => map.set(service, i))diff --git a/products/tracing/frontend/components/TraceDrawer/SpanSummaryHeader.tsx b/products/tracing/frontend/components/TraceDrawer/SpanSummaryHeader.tsxnew file mode 100644index 000000000000..2b260a3caf76--- /dev/null+++ b/products/tracing/frontend/components/TraceDrawer/SpanSummaryHeader.tsx@@ -0,0 +1,106 @@+import { useMemo } from 'react'++import { LemonTag } from '@posthog/lemon-ui'++import { getSeriesColor } from 'lib/colors'+import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'+import { dayjs } from 'lib/dayjs'++import { deriveSpanSummary } from '../../spanSummary'+import { formatDuration } from '../../TraceWaterfallView'+import type { Span } from '../../types'++// A service indicator (not an error indicator — error state is the status badge's job). Colored+// from the waterfall's shared palette; neutral when the service isn't a span in this trace (e.g. an+// external peer), so we don't borrow an unrelated service's color.+function ServiceDot({ colorIndex }: { colorIndex: number | undefined }): JSX.Element {+ return (+ <span+ className="inline-block size-2 rounded-full shrink-0"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ backgroundColor: colorIndex === undefined ? 'var(--border-bold)' : getSeriesColor(colorIndex) }}+ />+ )+}++// 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 {+ return (+ <span>+ {label}:{' '}+ <CopyToClipboardInline+ explicitValue={value}+ description={label.toLowerCase()}+ iconSize="xsmall"+ iconPosition="end"+ className="font-mono"+ >+ {value}+ </CopyToClipboardInline>+ </span>+ )+}++// Adaptive summary of the inspected span, above the inspector tabs. Each piece renders only when+// the span carries the data (see deriveSpanSummary), so it reflows from a bare internal span up to+// a full HTTP-to-k8s call. Service dots reuse the waterfall's service palette for cross-pane consistency.+export function SpanSummaryHeader({+ span,+ serviceColorMap,+}: {+ span: Span+ serviceColorMap: Map<string, number>+}): JSX.Element {+ // Memoized so a parent resize-drag (re-renders every mousemove) doesn't re-scan the attributes.+ const summary = useMemo(() => deriveSpanSummary(span), [span])++ return (+ <div className="flex flex-col gap-1.5 px-1 pb-2" data-attr="tracing-span-summary">+ <div className="flex items-center gap-2">+ {/* min-w-0 lets the flex item shrink so a long operation ellipsizes instead of+ shoving the status tag off; the tag holds its size. */}+ <span className="font-semibold truncate min-w-0">{summary.operation}</span>+ <LemonTag type={summary.status.type} className="shrink-0">+ {summary.status.label}+ </LemonTag>+ </div>++ <div className="flex items-center gap-x-3 gap-y-1 flex-wrap text-xs text-muted">+ <span className="flex items-center gap-1.5">+ <ServiceDot colorIndex={serviceColorMap.get(summary.service)} />+ <span>{summary.service}</span>+ {summary.peerService && (+ <>+ <span aria-hidden>→</span>+ <ServiceDot colorIndex={serviceColorMap.get(summary.peerService)} />+ <span>{summary.peerService}</span>+ </>+ )}+ </span>+ <span>{formatDuration(summary.durationNano)}</span>+ {/* UTC to match the waterfall/sparkline (displayTimezone="UTC"). end shows time-only —+ same day as start in all but pathological spans, so the date would just be noise. */}+ <span>+ {dayjs(summary.timestamp).tz('UTC').format('MMM D HH:mm:ss.SSS')}+ {' → '}+ {dayjs(summary.endTimestamp).tz('UTC').format('HH:mm:ss.SSS')}+ </span>+ </div>++ <div className="flex items-center gap-x-3 gap-y-1 flex-wrap text-xs text-muted">+ <CopyableId label="Span ID" value={summary.spanId} />+ <CopyableId label="Trace ID" value={summary.traceId} />+ {summary.parentSpanId && <CopyableId label="Parent span ID" value={summary.parentSpanId} />}+ </div>++ <div className="flex items-center gap-1.5 flex-wrap">+ {summary.type && <LemonTag type="muted">{summary.type}</LemonTag>}+ <LemonTag type="muted">{summary.kind}</LemonTag>+ {summary.cluster && <LemonTag>Cluster: {summary.cluster}</LemonTag>}+ {summary.pod && <LemonTag>Pod: {summary.pod}</LemonTag>}+ </div>+ </div>+ )+}diff --git a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsxindex 5b47d6fcbce1..e8c4e72708c8 100644--- a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx+++ b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx@@ -12,10 +12,11 @@ import { cn } from 'lib/utils/css-classes'import { useKeepMountedWhileOpen } from '../../hooks/useKeepMountedWhileOpen'import { absoluteTraceUrl } from '../../traceLinks'-import { formatDuration, TraceWaterfallView } from '../../TraceWaterfallView'+import { buildServiceColorMap, formatDuration, TraceWaterfallView } from '../../TraceWaterfallView'import type { Span } from '../../types'import { ExpandedSpanContent } from '../VirtualizedSpanList/ExpandedSpanContent'import { SpanLogsTab } from './SpanLogsTab'+import { SpanSummaryHeader } from './SpanSummaryHeader'type InspectorTab = 'attributes' | 'logs'@@ -69,6 +70,8 @@ export function TraceDrawer({() => (selectedSpanId ? (spans.find((span) => span.span_id === selectedSpanId) ?? null) : null),[spans, selectedSpanId])+ // Shared with the waterfall so a service is the same color in the bars and the summary header.+ const serviceColorMap = useMemo(() => buildServiceColorMap(spans), [spans])// Gate mounting so a closed drawer holds no react-modal portal (and its listener surface).const shouldRender = useKeepMountedWhileOpen(isOpen)@@ -132,26 +135,31 @@ export function TraceDrawer({><Resizer {...inspectorResizerProps} />{inspectedSpan ? (- <LemonTabs- activeKey={inspectorTab}- onChange={setInspectorTab}- data-attr="tracing-inspector-tabs"- tabs={[- {- key: 'attributes',- label: 'Attributes',- content: <ExpandedSpanContent span={inspectedSpan} />,- },- {- key: 'logs',- label: 'Logs',- // Not keyed by span: the embedded viewer (keyed by trace_id) and the memoized- // pinned filter re-query in place when the selected span changes, so a remount- // would only churn its logics and lose scroll.- content: <SpanLogsTab span={inspectedSpan} />,- },- ]}- />+ <>+ <SpanSummaryHeader span={inspectedSpan} serviceColorMap={serviceColorMap} />+ <LemonTabs+ activeKey={inspectorTab}+ onChange={setInspectorTab}+ data-attr="tracing-inspector-tabs"+ tabs={[+ {+ key: 'attributes',+ label: 'Attributes',+ // The summary header carries the headline facts, so the tab+ // shows only the user attributes (no duplicate details table).+ content: <ExpandedSpanContent span={inspectedSpan} showDetails={false} />,+ },+ {+ key: 'logs',+ label: 'Logs',+ // Not keyed by span: the embedded viewer (keyed by trace_id) and the memoized+ // pinned filter re-query in place when the selected span changes, so a remount+ // would only churn its logics and lose scroll.+ content: <SpanLogsTab span={inspectedSpan} />,+ },+ ]}+ />+ </>) : (<div className="text-muted p-4">No spans in this trace</div>)}diff --git a/products/tracing/frontend/components/VirtualizedSpanList/ExpandedSpanContent.tsx b/products/tracing/frontend/components/VirtualizedSpanList/ExpandedSpanContent.tsxindex c6d34ab0f09e..24b86a778ac8 100644--- a/products/tracing/frontend/components/VirtualizedSpanList/ExpandedSpanContent.tsx+++ b/products/tracing/frontend/components/VirtualizedSpanList/ExpandedSpanContent.tsx@@ -5,9 +5,15 @@ import { SpanAttributes } from './SpanAttributes'export interface ExpandedSpanContentProps {span: Span+ /**+ * Render the "Span details" KVP table alongside the attributes. The drawer's summary header+ * already surfaces these facts, so it passes false; the span-list expand-row (no header) keeps+ * the default. @default true+ */+ showDetails?: boolean}-export function ExpandedSpanContent({ span }: ExpandedSpanContentProps): JSX.Element {+export function ExpandedSpanContent({ span, showDetails = true }: ExpandedSpanContentProps): JSX.Element {const status = STATUS_CODE_LABELS[span.status_code]// The OTel attributes the user set on the span — the thing the row is here to surface.@@ -29,7 +35,7 @@ export function ExpandedSpanContent({ span }: ExpandedSpanContentProps): JSX.Elereturn (<div className="flex flex-col gap-2 p-2 bg-primary border-t border-border"><SpanAttributes title="Attributes" attributes={attributes} emptyLabel="No attributes set on this span" />- <SpanAttributes title="Span details" attributes={details} />+ {showDetails && <SpanAttributes title="Span details" attributes={details} />}</div>)}diff --git a/products/tracing/frontend/spanSummary.test.ts b/products/tracing/frontend/spanSummary.test.tsnew file mode 100644index 000000000000..d920c6ff8333--- /dev/null+++ b/products/tracing/frontend/spanSummary.test.ts@@ -0,0 +1,95 @@+import { deriveSpanSummary } from './spanSummary'+import type { Span } from './types'++function makeSpan(overrides: Partial<Span>): Span {+ return {+ uuid: 'u',+ trace_id: 'trace-1',+ span_id: 'span-1',+ parent_span_id: '',+ name: 'internal-work',+ kind: 1,+ service_name: 'load-generator',+ status_code: 0,+ timestamp: '2026-06-11T10:45:47.752Z',+ end_time: '2026-06-11T10:45:47.762Z',+ duration_nano: 10_500_000,+ is_root_span: false,+ matched_filter: true,+ attributes: {},+ ...overrides,+ }+}++describe('deriveSpanSummary', () => {+ it('falls back to native fields for a bare internal span', () => {+ const s = deriveSpanSummary(makeSpan({}))+ expect(s.operation).toBe('internal-work')+ expect(s.status).toEqual({ label: 'OK', type: 'success' })+ expect(s.service).toBe('load-generator')+ expect(s.peerService).toBeNull()+ expect(s.type).toBeNull()+ expect(s.cluster).toBeNull()+ expect(s.pod).toBeNull()+ expect(s.parentSpanId).toBeNull()+ expect(s.kind).toBe('Internal')+ })++ it('carries the correlation IDs, kind, and end time the header surfaces', () => {+ const s = deriveSpanSummary(makeSpan({ parent_span_id: 'span-0', kind: 2 }))+ expect(s.spanId).toBe('span-1')+ expect(s.traceId).toBe('trace-1')+ expect(s.parentSpanId).toBe('span-0')+ expect(s.kind).toBe('Server')+ expect(s.endTimestamp).toBe('2026-06-11T10:45:47.762Z')+ })++ it('lights up an HTTP client span to a k8s peer', () => {+ const s = deriveSpanSummary(+ makeSpan({+ attributes: {+ 'http.request.method': 'GET',+ 'http.route': '/api/cart',+ 'http.response.status_code': '200',+ 'peer.service': 'frontend-proxy',+ 'k8s.cluster.name': 'k8s-demo',+ 'k8s.pod.name': 'load-generator-59f4b49995-w585b',+ },+ })+ )+ expect(s.operation).toBe('GET /api/cart')+ expect(s.status).toEqual({ label: '200', type: 'success' })+ expect(s.peerService).toBe('frontend-proxy')+ expect(s.type).toBe('HTTP')+ expect(s.cluster).toBe('k8s-demo')+ expect(s.pod).toBe('load-generator-59f4b49995-w585b')+ })++ it.each([+ ['500', 'danger'],+ ['404', 'warning'],+ ['301', 'default'],+ ['204', 'success'],+ ])('colors http status %s as %s', (code, type) => {+ const s = deriveSpanSummary(makeSpan({ attributes: { 'http.status_code': code } }))+ expect(s.status).toEqual({ label: code, type })+ })++ it('accepts the old semconv method key and an absent route', () => {+ const s = deriveSpanSummary(makeSpan({ attributes: { 'http.method': 'POST' } }))+ expect(s.operation).toBe('POST')+ expect(s.type).toBe('HTTP')+ })++ it('uses the OTel status when there is no http status', () => {+ expect(deriveSpanSummary(makeSpan({ status_code: 2 })).status).toEqual({ label: 'Error', type: 'danger' })+ })++ it.each([+ [{ 'db.system': 'postgres' }, 'Database'],+ [{ 'rpc.method': 'GetCart' }, 'RPC'],+ [{ 'messaging.system': 'kafka' }, 'Messaging'],+ ])('derives type from the attribute namespace (%j)', (attributes, type) => {+ expect(deriveSpanSummary(makeSpan({ attributes })).type).toBe(type)+ })+})diff --git a/products/tracing/frontend/spanSummary.ts b/products/tracing/frontend/spanSummary.tsnew file mode 100644index 000000000000..dc96ddd2c412--- /dev/null+++ b/products/tracing/frontend/spanSummary.ts@@ -0,0 +1,116 @@+// Derive the adaptive span-summary header (JON-37) from a span's native fields + well-known OTel+// attributes. Every field is optional in the output where the data is — the header renders only+// what resolves and reflows, so a bare internal span shows little and an HTTP-to-k8s span lights up.++import type { Span } from './types'+import { SPAN_KIND_LABELS, STATUS_CODE_LABELS } from './types'++export type SummaryStatusType = 'success' | 'warning' | 'danger' | 'default'++export interface SpanSummary {+ /** http method+route if present, else the span name. */+ operation: string+ /** http status (colored by class) if present, else the OTel status. */+ status: { label: string; type: SummaryStatusType }+ service: string+ /** Callee, if a peer attribute is set — drives the "service → peer" arrow. */+ peerService: string | null+ durationNano: number+ spanId: string+ traceId: string+ /** Empty for a root span — the header renders the parent link only when set. */+ parentSpanId: string | null+ /** OTel span kind label (Internal / Server / Client / Producer / Consumer). */+ kind: string+ timestamp: string+ endTimestamp: string+ /** HTTP / Database / RPC / Messaging, derived from the attribute namespace; null if unknown. */+ type: string | null+ cluster: string | null+ pod: string | null+}++// new and old semantic-convention spellings, tried in order.+const METHOD_KEYS = ['http.request.method', 'http.method']+const ROUTE_KEYS = ['http.route', 'http.target', 'url.path']+const HTTP_STATUS_KEYS = ['http.response.status_code', 'http.status_code']+// Logical service-identity attributes only — NOT transport-layer addresses like `server.address`+// (a host/IP that any DB/Redis/gRPC client span carries), which would render a misleading+// "service → 10.0.0.5:5432" peer arrow.+const PEER_KEYS = ['peer.service', 'net.peer.name']++function firstAttr(attrs: Record<string, string>, keys: string[]): string | null {+ for (const key of keys) {+ if (attrs[key]) {+ return attrs[key]+ }+ }+ return null+}++function httpStatusType(code: number): SummaryStatusType {+ if (code >= 500) {+ return 'danger'+ }+ if (code >= 400) {+ return 'warning'+ }+ if (code >= 200 && code < 300) {+ return 'success'+ }+ return 'default'+}++function deriveType(attrs: Record<string, string>): string | null {+ for (const key of Object.keys(attrs)) {+ if (key.startsWith('http.') || key.startsWith('url.')) {+ return 'HTTP'+ }+ if (key.startsWith('db.')) {+ return 'Database'+ }+ if (key.startsWith('rpc.')) {+ return 'RPC'+ }+ if (key.startsWith('messaging.')) {+ return 'Messaging'+ }+ }+ return null+}++export function deriveSpanSummary(span: Span): SpanSummary {+ const attrs = span.attributes ?? {}++ const method = firstAttr(attrs, METHOD_KEYS)+ const route = firstAttr(attrs, ROUTE_KEYS)+ const operation = method ? `${method} ${route ?? ''}`.trim() : span.name++ const httpStatus = firstAttr(attrs, HTTP_STATUS_KEYS)+ let status: { label: string; type: SummaryStatusType }+ if (httpStatus) {+ const code = parseInt(httpStatus, 10)+ status = { label: httpStatus, type: Number.isNaN(code) ? 'default' : httpStatusType(code) }+ } else {+ status = STATUS_CODE_LABELS[span.status_code] ?? { label: String(span.status_code), type: 'default' }+ }++ return {+ operation,+ status,+ service: span.service_name,+ peerService: firstAttr(attrs, PEER_KEYS),+ durationNano: span.duration_nano,+ spanId: span.span_id,+ traceId: span.trace_id,+ parentSpanId: span.parent_span_id || null,+ kind: SPAN_KIND_LABELS[span.kind] ?? String(span.kind),+ timestamp: span.timestamp,+ endTimestamp: span.end_time,+ type: deriveType(attrs),+ // k8s.* are OTel *resource* attributes; these only resolve when the collector flattens them+ // into span attributes (our Span type carries no separate resource attributes). Absent → no chip.+ cluster: attrs['k8s.cluster.name'] || null,+ pod: attrs['k8s.pod.name'] || null,+ }+}