Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(tracing): show span attributes in expandable trace rows (#61113)

Jon McCallumcfce89557f47
diff --git a/products/tracing/backend/logic.py b/products/tracing/backend/logic.py
index 0b3d11494252..b7c42a36ba79 100644
--- a/products/tracing/backend/logic.py
+++ b/products/tracing/backend/logic.py
@@ -357,6 +357,8 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra
# Per-trace pagination key (earliest matching-span timestamp); identical for every
# span of a trace. Falls back to this row's timestamp on the off chance it is null.
"trace_start": (result[13] or result[8]).replace(tzinfo=ZoneInfo("UTC")),
+ # OTel span attributes the user set, as a key-value map.
+ "attributes": result[14],
}
results.append(row)
@@ -467,7 +469,8 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra
duration_nano,
is_root_span,
{where} as matched_filter,
- min(if({where_for_start}, timestamp, NULL)) OVER (PARTITION BY trace_id) as trace_start
+ min(if({where_for_start}, timestamp, NULL)) OVER (PARTITION BY trace_id) as trace_start,
+ attributes
FROM posthog.trace_spans
WHERE {filters} AND trace_id IN ({trace_id_query}) LIMIT {limit}
""",
diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsx
index bbdd0beb4ed5..9007769b055e 100644
--- a/products/tracing/frontend/TracingScene.tsx
+++ b/products/tracing/frontend/TracingScene.tsx
@@ -71,6 +71,7 @@ function TracingSceneContents(): JSX.Element {
compareFlameSpanName,
hasMoreToLoad,
visibleRowDateRange,
+ expandedSpanIds,
} = useValues(tracingSceneLogic({ tabId }))
const {
openTraceModal,
@@ -81,6 +82,7 @@ function TracingSceneContents(): JSX.Element {
closeCompareFlame,
fetchNextPage,
setVisibleRowRange,
+ toggleExpandSpan,
} = useActions(tracingSceneLogic({ tabId }))
const { addProductIntent } = useActions(teamLogic)
const compareMode = filters.compareMode
@@ -180,6 +182,8 @@ function TracingSceneContents(): JSX.Element {
hasMoreToLoad={hasMoreToLoad}
onLoadMore={fetchNextPage}
onVisibleRowRangeChange={setVisibleRowRange}
+ expandedSpanIds={expandedSpanIds}
+ onToggleExpand={toggleExpandSpan}
emptyState={
<div className="flex flex-col items-center gap-1">
<span>No spans found</span>
diff --git a/products/tracing/frontend/components/VirtualizedSpanList/ExpandedSpanContent.tsx b/products/tracing/frontend/components/VirtualizedSpanList/ExpandedSpanContent.tsx
new file mode 100644
index 000000000000..8dee4f575445
--- /dev/null
+++ b/products/tracing/frontend/components/VirtualizedSpanList/ExpandedSpanContent.tsx
@@ -0,0 +1,35 @@
+import { formatDuration } from '../../TraceFlameChart'
+import { SPAN_KIND_LABELS, STATUS_CODE_LABELS } from '../../types'
+import type { Span } from '../../types'
+import { SpanAttributes } from './SpanAttributes'
+
+export interface ExpandedSpanContentProps {
+ span: Span
+}
+
+export function ExpandedSpanContent({ span }: 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.
+ const attributes = span.attributes ?? {}
+
+ // The span's intrinsic identifying detail, shown alongside the user attributes.
+ const details: Record<string, string> = {
+ 'span.id': span.span_id,
+ 'parent.span.id': span.parent_span_id || '',
+ 'trace.id': span.trace_id,
+ 'service.name': span.service_name,
+ 'span.kind': SPAN_KIND_LABELS[span.kind] ?? String(span.kind),
+ 'status.code': status?.label ?? String(span.status_code),
+ duration: formatDuration(span.duration_nano),
+ 'start.time': new Date(span.timestamp).toISOString(),
+ 'end.time': new Date(span.end_time).toISOString(),
+ }
+
+ return (
+ <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} />
+ </div>
+ )
+}
diff --git a/products/tracing/frontend/components/VirtualizedSpanList/SpanAttributes.tsx b/products/tracing/frontend/components/VirtualizedSpanList/SpanAttributes.tsx
new file mode 100644
index 000000000000..f951511de899
--- /dev/null
+++ b/products/tracing/frontend/components/VirtualizedSpanList/SpanAttributes.tsx
@@ -0,0 +1,69 @@
+import { LemonTable } from '@posthog/lemon-ui'
+
+import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
+import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+
+interface AttributeRow {
+ key: string
+ value: string
+}
+
+export interface SpanAttributesProps {
+ attributes: Record<string, string>
+ title: string
+ emptyLabel?: string
+}
+
+// Key-value list rendering for span attributes, mirroring the Logs attribute KVP list
+// (products/logs/.../LogsViewer/LogAttributes). Kept presentational for now — the filter,
+// breakdown, and add-as-column actions from the logs version depend on logs-only infra.
+export function SpanAttributes({ attributes, title, emptyLabel = 'No attributes' }: SpanAttributesProps): JSX.Element {
+ const rows: AttributeRow[] = Object.entries(attributes).map(([key, value]) => ({ key, value }))
+
+ const columns: LemonTableColumns<AttributeRow> = [
+ {
+ title: 'Key',
+ key: 'key',
+ dataIndex: 'key',
+ width: 0,
+ render: (_, record): JSX.Element => (
+ <span className="font-mono text-xs text-muted whitespace-nowrap">{record.key}</span>
+ ),
+ },
+ {
+ title: 'Value',
+ key: 'value',
+ dataIndex: 'value',
+ render: (_, record): JSX.Element => {
+ if (record.value === '') {
+ return <span className="font-mono text-xs text-muted italic">(empty)</span>
+ }
+ return (
+ <CopyToClipboardInline
+ explicitValue={record.value}
+ description="attribute value"
+ iconSize="xsmall"
+ iconPosition="start"
+ selectable
+ className="gap-1 font-mono text-xs"
+ >
+ {record.value}
+ </CopyToClipboardInline>
+ )
+ },
+ },
+ ]
+
+ return (
+ <div className="bg-primary overflow-hidden rounded border border-border">
+ <div className="px-3 py-2 bg-bg-light border-b border-border">
+ <span className="text-xs font-semibold text-muted uppercase">{title}</span>
+ </div>
+ {rows.length === 0 ? (
+ <div className="px-3 py-2 text-xs text-muted italic">{emptyLabel}</div>
+ ) : (
+ <LemonTable embedded showHeader={false} size="small" rowKey="key" columns={columns} dataSource={rows} />
+ )}
+ </div>
+ )
+}
diff --git a/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.tsx b/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.tsx
index f2a9259ff538..8375b3d71c54 100644
--- a/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.tsx
+++ b/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.tsx
@@ -1,7 +1,8 @@
-import { CSSProperties, ReactNode, useCallback, useMemo, useRef } from 'react'
-import { List } from 'react-window'
+import { CSSProperties, ReactNode, useCallback, useEffect, useMemo, useRef } from 'react'
+import { List, useDynamicRowHeight, useListRef } from 'react-window'
-import { LemonTag } from '@posthog/lemon-ui'
+import { IconChevronRight } from '@posthog/icons'
+import { LemonButton, LemonTag } from '@posthog/lemon-ui'
import { AutoSizer } from 'lib/components/AutoSizer'
import { SizeProps } from 'lib/components/AutoSizer/AutoSizer'
@@ -10,17 +11,19 @@ import { cn } from 'lib/utils/css-classes'
import { formatDuration } from '../../TraceFlameChart'
import { SPAN_KIND_LABELS, STATUS_CODE_LABELS } from '../../types'
import type { Span } from '../../types'
+import { ExpandedSpanContent } from './ExpandedSpanContent'
const ROW_HEIGHT = 36
const HEADER_HEIGHT = 32
// Minimum content width so the fixed columns keep a sensible size and the row scrolls
// horizontally (rather than collapsing the name column) on narrow viewports.
-const MIN_ROW_WIDTH = 900
+const MIN_ROW_WIDTH = 932
// Trigger the next page once the bottom of the rendered window is within this many rows of the end.
const LOAD_MORE_THRESHOLD = 10
// Fixed column widths (px). The name column flexes to fill the remaining space.
const COL_WIDTH = {
+ expand: 32,
timestamp: 190,
service: 150,
kind: 90,
@@ -38,6 +41,8 @@ interface VirtualizedSpanListProps {
loading: boolean
onRowClick: (span: Span) => void
onVisibleRowRangeChange: (startIndex: number, stopIndex: number) => void
+ expandedSpanIds: Record<string, boolean>
+ onToggleExpand: (uuid: string) => void
hasMoreToLoad?: boolean
onLoadMore?: () => void
emptyState?: ReactNode
@@ -46,6 +51,9 @@ interface VirtualizedSpanListProps {
interface SpanRowProps {
dataSource: Span[]
onRowClick: (span: Span) => void
+ expandedSpanIds: Record<string, boolean>
+ onToggleExpand: (uuid: string) => void
+ dynamicRowHeight: ReturnType<typeof useDynamicRowHeight>
}
function Cell({ width, children }: { width?: number; children: React.ReactNode }): JSX.Element {
@@ -67,6 +75,7 @@ function SpanRowHeader(): JSX.Element {
// eslint-disable-next-line react/forbid-dom-props
style={{ height: HEADER_HEIGHT }}
>
+ <Cell width={COL_WIDTH.expand}> </Cell>
<Cell width={COL_WIDTH.timestamp}>Timestamp</Cell>
<Cell>Name</Cell>
<Cell width={COL_WIDTH.service}>Service</Cell>
@@ -78,12 +87,24 @@ function SpanRowHeader(): JSX.Element {
)
}
-function SpanRow({ span, onClick }: { span: Span; onClick: () => void }): JSX.Element {
+function SpanRow({
+ span,
+ isExpanded,
+ onToggleExpand,
+ onClick,
+}: {
+ span: Span
+ isExpanded: boolean
+ onToggleExpand: () => void
+ onClick: () => void
+}): JSX.Element {
const status = STATUS_CODE_LABELS[span.status_code] ?? { label: String(span.status_code), type: 'default' as const }
return (
<div
- className="flex h-full items-center cursor-pointer border-b border-border hover:bg-surface-primary-hover"
+ className="flex items-center cursor-pointer border-b border-border hover:bg-surface-primary-hover"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ height: ROW_HEIGHT }}
onClick={onClick}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
@@ -94,6 +115,17 @@ function SpanRow({ span, onClick }: { span: Span; onClick: () => void }): JSX.El
role="button"
tabIndex={0}
>
+ <Cell width={COL_WIDTH.expand}>
+ <LemonButton
+ size="xsmall"
+ icon={<IconChevronRight className={cn('transition-transform', isExpanded && 'rotate-90')} />}
+ tooltip={isExpanded ? 'Collapse' : 'Expand'}
+ onClick={(e) => {
+ e.stopPropagation()
+ onToggleExpand()
+ }}
+ />
+ </Cell>
<Cell width={COL_WIDTH.timestamp}>{new Date(span.timestamp).toLocaleString()}</Cell>
<Cell>
<span className="flex items-center gap-2 truncate">
@@ -126,16 +158,35 @@ function SpanListRow({
style,
dataSource,
onRowClick,
+ expandedSpanIds,
+ onToggleExpand,
+ dynamicRowHeight,
}: {
ariaAttributes: { 'aria-posinset': number; 'aria-setsize': number; role: 'listitem' }
index: number
style: CSSProperties
} & SpanRowProps): JSX.Element {
+ const rowRef = useRef<HTMLDivElement>(null)
const span = dataSource[index]
+ const isExpanded = !!expandedSpanIds[span.uuid]
+
+ // Report the rendered height back to react-window so expanded rows grow the list.
+ useEffect(() => {
+ if (rowRef.current) {
+ return dynamicRowHeight.observeRowElements([rowRef.current])
+ }
+ }, [dynamicRowHeight])
+
return (
// eslint-disable-next-line react/forbid-dom-props
- <div {...ariaAttributes} style={style} data-index={index} data-row-key={span.uuid}>
- <SpanRow span={span} onClick={() => onRowClick(span)} />
+ <div {...ariaAttributes} ref={rowRef} style={style} data-index={index} data-row-key={span.uuid}>
+ <SpanRow
+ span={span}
+ isExpanded={isExpanded}
+ onToggleExpand={() => onToggleExpand(span.uuid)}
+ onClick={() => onRowClick(span)}
+ />
+ {isExpanded && <ExpandedSpanContent span={span} />}
</div>
)
}
@@ -145,6 +196,8 @@ export function VirtualizedSpanList({
loading,
onRowClick,
onVisibleRowRangeChange,
+ expandedSpanIds,
+ onToggleExpand,
hasMoreToLoad = false,
onLoadMore,
emptyState = 'No spans found',
@@ -152,6 +205,9 @@ export function VirtualizedSpanList({
// Tracks the last range we dispatched so we don't fire on every overscan tick.
const lastVisibleRangeRef = useRef<{ startIndex: number; stopIndex: number } | null>(null)
+ const listRef = useListRef(null)
+ const dynamicRowHeight = useDynamicRowHeight({ defaultRowHeight: ROW_HEIGHT })
+
const handleRowsRendered = useCallback(
(
visibleRows: { startIndex: number; stopIndex: number },
@@ -175,7 +231,10 @@ export function VirtualizedSpanList({
[dataSource.length, hasMoreToLoad, loading, onLoadMore, onVisibleRowRangeChange]
)
- const rowProps = useMemo((): SpanRowProps => ({ dataSource, onRowClick }), [dataSource, onRowClick])
+ const rowProps = useMemo(
+ (): SpanRowProps => ({ dataSource, onRowClick, expandedSpanIds, onToggleExpand, dynamicRowHeight }),
+ [dataSource, onRowClick, expandedSpanIds, onToggleExpand, dynamicRowHeight]
+ )
if (dataSource.length === 0 && !loading) {
return (
@@ -208,10 +267,11 @@ export function VirtualizedSpanList({
style={{ height: height - HEADER_HEIGHT, width: rowWidth }}
overscanCount={10}
rowCount={dataSource.length}
- rowHeight={ROW_HEIGHT}
+ rowHeight={dynamicRowHeight}
rowComponent={SpanListRow}
rowProps={rowProps}
onRowsRendered={handleRowsRendered}
+ listRef={listRef}
/>
</div>
</div>
diff --git a/products/tracing/frontend/tracingDataLogic.test.ts b/products/tracing/frontend/tracingDataLogic.test.ts
index 720210a3a080..1d1ea3516278 100644
--- a/products/tracing/frontend/tracingDataLogic.test.ts
+++ b/products/tracing/frontend/tracingDataLogic.test.ts
@@ -34,6 +34,7 @@ const createMockSpan = (uuid: string, timestamp: string): Span => ({
duration_nano: 1000,
is_root_span: true,
matched_filter: true,
+ attributes: {},
})
const mockSpans: Span[] = [
diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.ts
index 6fb8d9d86674..ea8f9e37b16a 100644
--- a/products/tracing/frontend/tracingSceneLogic.ts
+++ b/products/tracing/frontend/tracingSceneLogic.ts
@@ -66,6 +66,7 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
})),
actions({
+ toggleExpandSpan: (uuid: string) => ({ uuid }),
openTraceModal: (traceId: string) => ({ traceId }),
closeTraceModal: true,
openCompareFlame: (spanName: string, serviceName: string) => ({ spanName, serviceName }),
@@ -75,6 +76,22 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
}),
reducers({
+ expandedSpanIds: [
+ {} as Record<string, boolean>,
+ {
+ toggleExpandSpan: (state, { uuid }) => {
+ const next = { ...state }
+ if (next[uuid]) {
+ delete next[uuid]
+ } else {
+ next[uuid] = true
+ }
+ return next
+ },
+ // Drop stale expansion state whenever the span list is refetched.
+ runQuery: () => ({}),
+ },
+ ],
selectedTraceId: [
null as string | null,
{
diff --git a/products/tracing/frontend/types.ts b/products/tracing/frontend/types.ts
index 0e143c36ab11..664316081b27 100644
--- a/products/tracing/frontend/types.ts
+++ b/products/tracing/frontend/types.ts
@@ -12,6 +12,8 @@ export interface Span {
duration_nano: number
is_root_span: boolean
matched_filter: boolean
+ // OTel span attributes the user set, as a key-value map.
+ attributes: Record<string, string>
}
export const SPAN_KIND_LABELS: Record<number, string> = {