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): collapse spans in waterfall view (#64298)

Frank Hamand77797d1e65ba
diff --git a/products/tracing/frontend/TraceWaterfallView.test.tsx b/products/tracing/frontend/TraceWaterfallView.test.tsx
index a7ca9e54d1e9..9a5623f3a9dc 100644
--- a/products/tracing/frontend/TraceWaterfallView.test.tsx
+++ b/products/tracing/frontend/TraceWaterfallView.test.tsx
@@ -71,4 +71,37 @@ describe('TraceWaterfallView', () => {
expect(onSpanSelect).toHaveBeenNthCalledWith(1, 'span-child')
expect(onSpanSelect).toHaveBeenNthCalledWith(2, null)
})
+
+ it('collapses a span subtree, hiding descendants without selecting the row', () => {
+ const onSpanSelect = jest.fn()
+ const { container } = render(<TraceWaterfallView spans={[root, child]} onSpanSelect={onSpanSelect} />)
+
+ expect(within(container).queryAllByText('child-operation').length).toBeGreaterThan(0)
+
+ fireEvent.click(within(container).getByLabelText('Collapse child spans'))
+
+ expect(within(container).queryByText('child-operation')).toBeNull()
+ // Toggling collapse must not double as selecting the row.
+ expect(onSpanSelect).not.toHaveBeenCalled()
+ // Re-expanding brings the child back.
+ fireEvent.click(within(container).getByLabelText('Expand child spans'))
+ expect(within(container).queryAllByText('child-operation').length).toBeGreaterThan(0)
+ })
+
+ it('collapses and expands every span via the header toggle', () => {
+ const { container } = render(<TraceWaterfallView spans={[root, child]} />)
+
+ fireEvent.click(within(container).getByLabelText('Collapse all spans'))
+ expect(within(container).queryByText('child-operation')).toBeNull()
+
+ fireEvent.click(within(container).getByLabelText('Expand all spans'))
+ expect(within(container).queryAllByText('child-operation').length).toBeGreaterThan(0)
+ })
+
+ it('does not render a collapse toggle for leaf spans', () => {
+ const { container } = render(<TraceWaterfallView spans={[child]} />)
+
+ expect(within(container).queryByLabelText('Collapse child spans')).toBeNull()
+ expect(within(container).queryByLabelText('Collapse all spans')).toBeNull()
+ })
})
diff --git a/products/tracing/frontend/TraceWaterfallView.tsx b/products/tracing/frontend/TraceWaterfallView.tsx
index 35b66bd51e74..d6e74315d85b 100644
--- a/products/tracing/frontend/TraceWaterfallView.tsx
+++ b/products/tracing/frontend/TraceWaterfallView.tsx
@@ -1,13 +1,14 @@
import { CSSProperties, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { List, useDynamicRowHeight, useListRef } from 'react-window'
-import { IconWarning } from '@posthog/icons'
+import { IconChevronRight, IconCollapse, IconExpand, IconWarning } from '@posthog/icons'
import { LemonButton, Spinner } from '@posthog/lemon-ui'
import { getSeriesColor } from 'lib/colors'
import { AutoSizer } from 'lib/components/AutoSizer'
import { SizeProps } from 'lib/components/AutoSizer/AutoSizer'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
+import { cn } from 'lib/utils/css-classes'
import type { Span } from './types'
@@ -67,10 +68,22 @@ function sortChildren(nodes: SpanNode[]): SpanNode[] {
return [...nodes].sort((a, b) => parseTimestampUs(a.span.timestamp) - parseTimestampUs(b.span.timestamp))
}
-function flattenTree(nodes: SpanNode[]): SpanNode[] {
+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)
}
@@ -81,6 +94,23 @@ function flattenTree(nodes: SpanNode[]): SpanNode[] {
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_000
if (us < 100) {
@@ -263,6 +293,8 @@ interface WaterfallRowData {
labelColumnWidth: number
selectedSpanId: string | null
onSelect: (spanId: string) => void
+ collapsedSpanIds: Set<string>
+ onToggleCollapse: (spanId: string) => void
dynamicRowHeight: ReturnType<typeof useDynamicRowHeight>
}
@@ -275,8 +307,13 @@ function WaterfallRow({
labelColumnWidth,
selectedSpanId,
onSelect,
+ collapsedSpanIds,
+ onToggleCollapse,
}: Omit<WaterfallRowData, 'flatSpans' | 'dynamicRowHeight'> & { node: SpanNode }): JSX.Element {
const { span } = node
+ const hasChildren = node.children.length > 0
+ const isCollapsed = collapsedSpanIds.has(span.span_id)
+ const hiddenDescendants = isCollapsed ? countDescendants(node) : 0
const spanStartUs = parseTimestampUs(span.timestamp)
const spanDurationUs = span.duration_nano / 1_000
const leftPct = traceDurationUs > 0 ? Math.max(((spanStartUs - traceStartUs) / traceDurationUs) * 100, 0) : 0
@@ -322,6 +359,27 @@ function WaterfallRow({
style={{ width: labelColumnWidth }}
>
<TreeIndent node={node} />
+ <span className="shrink-0 flex items-center justify-center w-4 self-stretch">
+ {hasChildren && (
+ <Tooltip title={isCollapsed ? 'Expand child spans' : 'Collapse child spans'}>
+ <button
+ type="button"
+ className="flex items-center justify-center w-4 h-4 rounded text-muted hover:text-default hover:bg-fill-button-tertiary-hover"
+ aria-label={isCollapsed ? 'Expand child spans' : 'Collapse child spans'}
+ aria-expanded={!isCollapsed}
+ onClick={(e) => {
+ e.stopPropagation()
+ onToggleCollapse(span.span_id)
+ }}
+ >
+ <IconChevronRight
+ className={cn('transition-transform', !isCollapsed && 'rotate-90')}
+ fontSize={14}
+ />
+ </button>
+ </Tooltip>
+ )}
+ </span>
{isError && (
<Tooltip title="This span has an error status">
<IconWarning className="text-danger shrink-0 mr-1" fontSize={14} />
@@ -336,6 +394,13 @@ function WaterfallRow({
{span.name}
</span>
</Tooltip>
+ {isCollapsed && (
+ <Tooltip title={`${hiddenDescendants} hidden child span${hiddenDescendants === 1 ? '' : 's'}`}>
+ <span className="shrink-0 ml-1 px-1 rounded text-[10px] leading-4 font-medium text-muted bg-fill-button-tertiary-hover">
+ {hiddenDescendants}
+ </span>
+ </Tooltip>
+ )}
</div>
{/* Timeline column */}
@@ -405,6 +470,8 @@ function WaterfallListRow({
labelColumnWidth,
selectedSpanId,
onSelect,
+ collapsedSpanIds,
+ onToggleCollapse,
dynamicRowHeight,
}: {
ariaAttributes: { 'aria-posinset': number; 'aria-setsize': number; role: 'listitem' }
@@ -432,6 +499,8 @@ function WaterfallListRow({
labelColumnWidth={labelColumnWidth}
selectedSpanId={selectedSpanId}
onSelect={onSelect}
+ collapsedSpanIds={collapsedSpanIds}
+ onToggleCollapse={onToggleCollapse}
/>
</div>
)
@@ -458,10 +527,29 @@ export function TraceWaterfallView({
labelSplitterDragCleanupRef.current?.()
}
}, [])
+ const [collapsedSpanIds, setCollapsedSpanIds] = useState<Set<string>>(() => new Set())
const serviceColorMap = useMemo(() => buildServiceColorMap(spans), [spans])
const tree = useMemo(() => buildSpanTree(spans), [spans])
- const flatSpans = useMemo(() => flattenTree(tree), [tree])
+ const flatSpans = useMemo(() => flattenTree(tree, collapsedSpanIds), [tree, collapsedSpanIds])
+ const collapsibleSpanIds = useMemo(() => collectCollapsibleSpanIds(tree), [tree])
+ const allCollapsed = collapsibleSpanIds.size > 0 && collapsedSpanIds.size >= collapsibleSpanIds.size
const dynamicRowHeight = useDynamicRowHeight({ defaultRowHeight: ROW_HEIGHT })
+
+ const handleToggleCollapse = useCallback((spanId: string): void => {
+ setCollapsedSpanIds((prev) => {
+ const next = new Set(prev)
+ if (next.has(spanId)) {
+ next.delete(spanId)
+ } else {
+ next.add(spanId)
+ }
+ return next
+ })
+ }, [])
+
+ const handleToggleCollapseAll = useCallback((): void => {
+ setCollapsedSpanIds((prev) => (prev.size >= collapsibleSpanIds.size ? new Set() : new Set(collapsibleSpanIds)))
+ }, [collapsibleSpanIds])
const listRef = useListRef(null)
// Infinite scroll: fetch the next page once the rendered window nears the end of the loaded spans.
@@ -651,11 +739,21 @@ export function TraceWaterfallView({
{/* Timeline header */}
<div className="flex border-b border-border sticky top-0 bg-surface-primary z-10">
<div
- className="shrink-0 text-xs font-medium text-muted px-2 flex items-center border-r border-border"
+ className="shrink-0 text-xs font-medium text-muted pl-2 pr-1 flex items-center justify-between gap-1 border-r border-border"
// eslint-disable-next-line react/forbid-dom-props
style={{ width: labelColumnWidth }}
>
- Span
+ <span>Span</span>
+ {collapsibleSpanIds.size > 0 && (
+ <Tooltip title={allCollapsed ? 'Expand all spans' : 'Collapse all spans'}>
+ <LemonButton
+ size="xsmall"
+ icon={allCollapsed ? <IconExpand /> : <IconCollapse />}
+ onClick={handleToggleCollapseAll}
+ aria-label={allCollapsed ? 'Expand all spans' : 'Collapse all spans'}
+ />
+ </Tooltip>
+ )}
</div>
<div className="relative grow h-7" ref={timelineRef}>
{(cursorPct === null || cursorPct > 5) && (
@@ -721,6 +819,8 @@ export function TraceWaterfallView({
labelColumnWidth,
selectedSpanId,
onSelect: handleSelect,
+ collapsedSpanIds,
+ onToggleCollapse: handleToggleCollapse,
dynamicRowHeight,
}}
onRowsRendered={handleRowsRendered}