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): add compare toggle and span aggregation list view (#58294)

Frank Hamand63344bda3cb2
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index bcf1050b645e..0c52e18a723a 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -2821,21 +2821,24 @@ const api = {
},
tracing: {
- async listSpans(query: {
- dateRange?: { date_from?: string | null; date_to?: string | null }
- serviceNames?: string[]
- statusCodes?: number[]
- filterGroup?: PropertyGroupFilter
- orderBy?: 'latest' | 'earliest'
- limit?: number
- after?: string
- prefetchSpans?: number
- }): Promise<{
+ async listSpans(
+ query: {
+ dateRange?: { date_from?: string | null; date_to?: string | null }
+ serviceNames?: string[]
+ statusCodes?: number[]
+ filterGroup?: PropertyGroupFilter
+ orderBy?: 'latest' | 'earliest'
+ limit?: number
+ after?: string
+ prefetchSpans?: number
+ },
+ signal?: AbortSignal
+ ): Promise<{
results: Record<string, any>[]
hasMore: boolean
nextCursor?: string
}> {
- return new ApiRequest().tracingSpans().withAction('query').create({ data: { query } })
+ return new ApiRequest().tracingSpans().withAction('query').create({ signal, data: { query } })
},
async getTrace(
traceId: string,
@@ -2856,38 +2859,47 @@ const api = {
},
})
},
- async sparkline(query: {
- dateRange?: { date_from?: string | null; date_to?: string | null }
- serviceNames?: string[]
- statusCodes?: number[]
- filterGroup?: PropertyGroupFilter
- }): Promise<{
+ async sparkline(
+ query: {
+ dateRange?: { date_from?: string | null; date_to?: string | null }
+ serviceNames?: string[]
+ statusCodes?: number[]
+ filterGroup?: PropertyGroupFilter
+ },
+ signal?: AbortSignal
+ ): Promise<{
results: { time: string; service: string; count: number }[]
}> {
- return new ApiRequest().tracingSpans().withAction('sparkline').create({ data: { query } })
+ return new ApiRequest().tracingSpans().withAction('sparkline').create({ signal, data: { query } })
},
- async aggregate(query: {
- dateRange?: { date_from?: string | null; date_to?: string | null }
- serviceNames?: string[]
- filterGroup?: PropertyGroupFilter
- compareFilter?: { compare?: boolean; compare_to?: string | null }
- }): Promise<{
+ async aggregate(
+ query: {
+ dateRange?: { date_from?: string | null; date_to?: string | null }
+ serviceNames?: string[]
+ filterGroup?: PropertyGroupFilter
+ compareFilter?: { compare?: boolean; compare_to?: string | null }
+ },
+ signal?: AbortSignal
+ ): Promise<{
results: AggregatedSpanRow[]
compare?: AggregatedSpanRow[] | null
}> {
- return new ApiRequest().tracingSpans().withAction('aggregate').create({ data: { query } })
- },
- async tree(query: {
- spanName: string
- dateRange?: { date_from?: string | null; date_to?: string | null }
- serviceNames?: string[]
- filterGroup?: PropertyGroupFilter
- compareFilter?: { compare?: boolean; compare_to?: string | null }
- }): Promise<{
+ return new ApiRequest().tracingSpans().withAction('aggregate').create({ signal, data: { query } })
+ },
+ async tree(
+ query: {
+ spanName: string
+ dateRange?: { date_from?: string | null; date_to?: string | null }
+ serviceNames?: string[]
+ filterGroup?: PropertyGroupFilter
+ compareFilter?: { compare?: boolean; compare_to?: string | null }
+ },
+ signal?: AbortSignal
+ ): Promise<{
results: SpanTreeNode[]
compare?: SpanTreeNode[] | null
}> {
- return new ApiRequest().tracingSpans().withAction('tree').create({ data: { query } })
+ return new ApiRequest().tracingSpans().withAction('tree').create({ signal, data: { query } })
},
async serviceNames(params: { dateRange?: string; search?: string }): Promise<{ results: { name: string }[] }> {
return new ApiRequest()
diff --git a/products/tracing/frontend/SparklineCompareOverlay.tsx b/products/tracing/frontend/SparklineCompareOverlay.tsx
new file mode 100644
index 000000000000..92af2f6cdc4a
--- /dev/null
+++ b/products/tracing/frontend/SparklineCompareOverlay.tsx
@@ -0,0 +1,256 @@
+import { useEffect, useLayoutEffect, useRef, useState } from 'react'
+
+interface Window {
+ startMs: number
+ endMs: number
+}
+
+interface SparklineCompareOverlayProps {
+ /** Full visible time window the sparkline covers, in ms — used for pixel mapping and clamping. */
+ fullStartMs: number
+ fullEndMs: number
+ currentWindow: Window
+ previousWindow: Window
+ /** Fires on mouseup with the final positions of both windows. */
+ onChange: (current: Window, previous: Window) => void
+}
+
+type DragKind = 'current-body' | 'previous-body' | 'current-left' | 'current-right' | 'previous-left' | 'previous-right'
+
+interface DragState {
+ kind: DragKind
+ startX: number
+ initialCurrent: Window
+ initialPrevious: Window
+}
+
+const CURRENT_COLOR = 'rgba(255, 165, 0, 0.25)' // light orange
+const CURRENT_BORDER = 'rgba(255, 140, 0, 0.85)'
+const PREVIOUS_COLOR = 'rgba(99, 179, 237, 0.25)' // light blue
+const PREVIOUS_BORDER = 'rgba(56, 145, 212, 0.85)'
+
+const EDGE_WIDTH_PX = 6
+const MIN_DURATION_MS = 60_000
+
+function clampWindowToBounds(w: Window, fullStartMs: number, fullEndMs: number): Window {
+ let { startMs, endMs } = w
+ const duration = endMs - startMs
+ if (startMs < fullStartMs) {
+ startMs = fullStartMs
+ endMs = startMs + duration
+ }
+ if (endMs > fullEndMs) {
+ endMs = fullEndMs
+ startMs = endMs - duration
+ }
+ return { startMs, endMs }
+}
+
+export function SparklineCompareOverlay({
+ fullStartMs,
+ fullEndMs,
+ currentWindow,
+ previousWindow,
+ onChange,
+}: SparklineCompareOverlayProps): JSX.Element {
+ const containerRef = useRef<HTMLDivElement>(null)
+ const [width, setWidth] = useState(0)
+ const [drag, setDrag] = useState<DragState | null>(null)
+ // In-flight preview during drag; committed via onChange on mouseup.
+ const [previewCurrent, setPreviewCurrent] = useState<Window | null>(null)
+ const [previewPrevious, setPreviewPrevious] = useState<Window | null>(null)
+
+ useLayoutEffect(() => {
+ if (!containerRef.current) {
+ return
+ }
+ const el = containerRef.current
+ setWidth(el.clientWidth)
+ const observer = new ResizeObserver((entries) => {
+ for (const entry of entries) {
+ setWidth(entry.contentRect.width)
+ }
+ })
+ observer.observe(el)
+ return () => observer.disconnect()
+ }, [])
+
+ const totalMs = fullEndMs - fullStartMs
+ const pxPerMs = totalMs > 0 && width > 0 ? width / totalMs : 0
+ const msPerPx = pxPerMs > 0 ? 1 / pxPerMs : 0
+
+ const effectiveCurrent = previewCurrent ?? currentWindow
+ const effectivePrevious = previewPrevious ?? previousWindow
+
+ function msToPx(ms: number): number {
+ return (ms - fullStartMs) * pxPerMs
+ }
+
+ function applyDrag(kind: DragKind, dxMs: number, initialCurrent: Window, initialPrevious: Window): void {
+ const initialDuration = initialCurrent.endMs - initialCurrent.startMs
+
+ if (kind === 'current-body') {
+ const startMs = initialCurrent.startMs + dxMs
+ const moved = clampWindowToBounds({ startMs, endMs: startMs + initialDuration }, fullStartMs, fullEndMs)
+ setPreviewCurrent(moved)
+ return
+ }
+ if (kind === 'previous-body') {
+ const startMs = initialPrevious.startMs + dxMs
+ const moved = clampWindowToBounds({ startMs, endMs: startMs + initialDuration }, fullStartMs, fullEndMs)
+ setPreviewPrevious(moved)
+ return
+ }
+
+ // Edge drag: the dragged edge tracks the cursor. The opposite edge of the same window
+ // stays put. Duration is shared, so the OTHER window keeps its startMs and adopts
+ // the new duration.
+ let draggedStart = 0
+ let draggedEnd = 0
+ let draggedIsCurrent = false
+
+ if (kind === 'current-left') {
+ draggedStart = initialCurrent.startMs + dxMs
+ draggedEnd = initialCurrent.endMs
+ draggedIsCurrent = true
+ } else if (kind === 'current-right') {
+ draggedStart = initialCurrent.startMs
+ draggedEnd = initialCurrent.endMs + dxMs
+ draggedIsCurrent = true
+ } else if (kind === 'previous-left') {
+ draggedStart = initialPrevious.startMs + dxMs
+ draggedEnd = initialPrevious.endMs
+ } else if (kind === 'previous-right') {
+ draggedStart = initialPrevious.startMs
+ draggedEnd = initialPrevious.endMs + dxMs
+ }
+
+ // Clamp dragged edge to sparkline bounds.
+ draggedStart = Math.max(fullStartMs, draggedStart)
+ draggedEnd = Math.min(fullEndMs, draggedEnd)
+ if (draggedEnd - draggedStart < MIN_DURATION_MS) {
+ return
+ }
+
+ const newDuration = draggedEnd - draggedStart
+ if (draggedIsCurrent) {
+ setPreviewCurrent({ startMs: draggedStart, endMs: draggedEnd })
+ const followerStart = initialPrevious.startMs
+ const follower = clampWindowToBounds(
+ { startMs: followerStart, endMs: followerStart + newDuration },
+ fullStartMs,
+ fullEndMs
+ )
+ setPreviewPrevious(follower)
+ } else {
+ setPreviewPrevious({ startMs: draggedStart, endMs: draggedEnd })
+ const followerStart = initialCurrent.startMs
+ const follower = clampWindowToBounds(
+ { startMs: followerStart, endMs: followerStart + newDuration },
+ fullStartMs,
+ fullEndMs
+ )
+ setPreviewCurrent(follower)
+ }
+ }
+
+ useEffect(() => {
+ if (!drag) {
+ return
+ }
+ const onMove = (e: MouseEvent): void => {
+ const dxPx = e.clientX - drag.startX
+ const dxMs = dxPx * msPerPx
+ applyDrag(drag.kind, dxMs, drag.initialCurrent, drag.initialPrevious)
+ }
+ const onUp = (): void => {
+ const finalCurrent = previewCurrent ?? drag.initialCurrent
+ const finalPrevious = previewPrevious ?? drag.initialPrevious
+ setDrag(null)
+ setPreviewCurrent(null)
+ setPreviewPrevious(null)
+ // Only fire onChange if something actually moved.
+ const moved =
+ finalCurrent.startMs !== drag.initialCurrent.startMs ||
+ finalCurrent.endMs !== drag.initialCurrent.endMs ||
+ finalPrevious.startMs !== drag.initialPrevious.startMs ||
+ finalPrevious.endMs !== drag.initialPrevious.endMs
+ if (moved) {
+ onChange(finalCurrent, finalPrevious)
+ }
+ }
+ window.addEventListener('mousemove', onMove)
+ window.addEventListener('mouseup', onUp)
+ return () => {
+ window.removeEventListener('mousemove', onMove)
+ window.removeEventListener('mouseup', onUp)
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [drag, msPerPx, previewCurrent, previewPrevious])
+
+ function beginDrag(kind: DragKind, e: React.MouseEvent): void {
+ e.preventDefault()
+ e.stopPropagation()
+ setDrag({
+ kind,
+ startX: e.clientX,
+ initialCurrent: currentWindow,
+ initialPrevious: previousWindow,
+ })
+ }
+
+ function renderWindow(
+ window: Window,
+ kind: 'current' | 'previous',
+ fill: string,
+ border: string
+ ): JSX.Element | null {
+ if (pxPerMs === 0) {
+ return null
+ }
+ const left = msToPx(window.startMs)
+ const right = msToPx(window.endMs)
+ const w = Math.max(2, right - left)
+ return (
+ <div
+ className="absolute top-0 h-full"
+ style={{
+ left,
+ width: w,
+ backgroundColor: fill,
+ borderLeft: `1px solid ${border}`,
+ borderRight: `1px solid ${border}`,
+ pointerEvents: 'auto',
+ cursor: 'grab',
+ }}
+ onMouseDown={(e) => beginDrag(`${kind}-body` as DragKind, e)}
+ >
+ <div
+ className="absolute top-0 h-full"
+ style={{
+ left: -EDGE_WIDTH_PX / 2,
+ width: EDGE_WIDTH_PX,
+ cursor: 'ew-resize',
+ }}
+ onMouseDown={(e) => beginDrag(`${kind}-left` as DragKind, e)}
+ />
+ <div
+ className="absolute top-0 h-full"
+ style={{
+ right: -EDGE_WIDTH_PX / 2,
+ width: EDGE_WIDTH_PX,
+ cursor: 'ew-resize',
+ }}
+ onMouseDown={(e) => beginDrag(`${kind}-right` as DragKind, e)}
+ />
+ </div>
+ )
+ }
+
+ return (
+ <div ref={containerRef} className="absolute inset-0" style={{ pointerEvents: 'none' }}>
+ {renderWindow(effectivePrevious, 'previous', PREVIOUS_COLOR, PREVIOUS_BORDER)}
+ {renderWindow(effectiveCurrent, 'current', CURRENT_COLOR, CURRENT_BORDER)}
+ </div>
+ )
+}
diff --git a/products/tracing/frontend/TraceCompareFlame.tsx b/products/tracing/frontend/TraceCompareFlame.tsx
new file mode 100644
index 000000000000..71d4dcb0f00b
--- /dev/null
+++ b/products/tracing/frontend/TraceCompareFlame.tsx
@@ -0,0 +1,610 @@
+import clsx from 'clsx'
+import { useEffect, useMemo, useState } from 'react'
+import React from 'react'
+
+import { IconChevronRight } from '@posthog/icons'
+import { LemonDropdown, Link, SpinnerOverlay, Tooltip } from '@posthog/lemon-ui'
+
+import { humanFriendlyNumber } from 'lib/utils'
+
+import { SpanTreeNode } from '~/queries/schema/schema-general'
+
+import { formatDuration } from './TraceFlameChart'
+
+interface TreeNode {
+ serviceName: string
+ name: string
+ node: SpanTreeNode | null
+ previousNode: SpanTreeNode | null
+ children: TreeNode[]
+}
+
+const ROW_HEIGHT_PX = 28
+const ROOT_KEY = '\u0000<ROOT>'
+/** Children whose normalized share is below this fraction get bundled into a "+N more" group. */
+const MIN_VISIBLE_FRACTION = 0.01
+/** Need at least this many tiny children to bother bundling — a single 0.5% bar isn't worth a popover. */
+const MIN_GROUPED_COUNT = 2
+/** Floor for the bundled cell so it's always clickable regardless of how small the bundle is. */
+const GROUPED_CELL_MIN_WIDTH_PX = 48
+
+function nodeKey(serviceName: string, name: string): string {
+ return `${serviceName}\u0000${name}`
+}
+
+function nodeSize(n: TreeNode): number {
+ // Layout metric: max of current p50 and previous p50, so vanished and new nodes both
+ // claim non-zero space proportional to whichever window they appeared in.
+ return Math.max(n.node?.p50_duration_nano ?? 0, n.previousNode?.p50_duration_nano ?? 0)
+}
+
+function countDescendants(node: TreeNode): number {
+ let n = 1
+ for (const child of node.children) {
+ n += countDescendants(child)
+ }
+ return n
+}
+
+/**
+ * Merge multiple (parent → child) rows that describe the same span into a single node.
+ * The backend's tree query emits one row per (parent_service, parent_name, service_name,
+ * name) edge, so a span with multiple parents shows up multiple times. Summing across
+ * rows is what makes the per-span totals here match the per-span totals in the
+ * aggregation list.
+ *
+ * Percentiles can't be combined exactly without raw samples; we use a count-weighted
+ * average, which is close enough for this UI's purpose (relative comparison).
+ */
+function mergeRows(rows: SpanTreeNode[]): SpanTreeNode {
+ let totalCount = 0
+ let totalDuration = 0
+ let errorCount = 0
+ let p50Weighted = 0
+ let p95Weighted = 0
+ let avgDurationWeighted = 0
+ let startOffsetWeighted = 0
+ for (const row of rows) {
+ totalCount += row.count
+ totalDuration += row.total_duration_nano
+ errorCount += row.error_count
+ p50Weighted += row.p50_duration_nano * row.count
+ p95Weighted += row.p95_duration_nano * row.count
+ avgDurationWeighted += row.avg_duration_nano * row.count
+ startOffsetWeighted += row.avg_start_offset_nano * row.count
+ }
+ const denom = totalCount || 1
+ const first = rows[0]
+ return {
+ ...first,
+ count: totalCount,
+ total_duration_nano: totalDuration,
+ error_count: errorCount,
+ p50_duration_nano: p50Weighted / denom,
+ p95_duration_nano: p95Weighted / denom,
+ avg_duration_nano: avgDurationWeighted / denom,
+ avg_start_offset_nano: startOffsetWeighted / denom,
+ }
+}
+
+/**
+ * Build a tree from the flat (parent_service, parent_name) → (service_name, name) edges.
+ * Both windows contribute nodes; previous-only nodes still appear so vanished call sites
+ * are visible in the diff.
+ */
+function buildTree(current: SpanTreeNode[], previous: SpanTreeNode[] | null): TreeNode {
+ const allNodes = new Map<string, { currentRows: SpanTreeNode[]; previousRows: SpanTreeNode[] }>()
+ const childrenByParent = new Map<string, Set<string>>()
+
+ function record(row: SpanTreeNode, isCurrent: boolean): void {
+ const key = nodeKey(row.service_name, row.name)
+ if (!allNodes.has(key)) {
+ allNodes.set(key, { currentRows: [], previousRows: [] })
+ }
+ const entry = allNodes.get(key)!
+ if (isCurrent) {
+ entry.currentRows.push(row)
+ } else {
+ entry.previousRows.push(row)
+ }
+
+ const parentKey = row.parent_name === '<ROOT>' ? ROOT_KEY : nodeKey(row.parent_service, row.parent_name)
+ if (!childrenByParent.has(parentKey)) {
+ childrenByParent.set(parentKey, new Set())
+ }
+ childrenByParent.get(parentKey)!.add(key)
+ }
+
+ for (const row of current) {
+ record(row, true)
+ }
+ for (const row of previous ?? []) {
+ record(row, false)
+ }
+
+ // Cycle guard: the backend's name-grouped edges can describe a cycle
+ // (e.g. <ROOT> → A → B → A when traces are crafted recursively). Without this,
+ // `build` would recurse indefinitely and freeze the browser tab. We skip any
+ // child key that already appears on the current build path.
+ function build(key: string, serviceName: string, name: string, ancestors: Set<string>): TreeNode {
+ const entry = allNodes.get(key) ?? { currentRows: [], previousRows: [] }
+ const nextAncestors = new Set(ancestors)
+ nextAncestors.add(key)
+ const childKeys = Array.from(childrenByParent.get(key) ?? []).filter((k) => !ancestors.has(k))
+ const children = childKeys
+ .map((childKey) => {
+ const childEntry = allNodes.get(childKey)!
+ const ref = childEntry.currentRows[0] ?? childEntry.previousRows[0]!
+ return build(childKey, ref.service_name, ref.name, nextAncestors)
+ })
+ // Order children by typical start offset (left = earlier).
+ .sort((a, b) => (a.node?.avg_start_offset_nano ?? 0) - (b.node?.avg_start_offset_nano ?? 0))
+ return {
+ serviceName,
+ name,
+ node: entry.currentRows.length > 0 ? mergeRows(entry.currentRows) : null,
+ previousNode: entry.previousRows.length > 0 ? mergeRows(entry.previousRows) : null,
+ children,
+ }
+ }
+
+ return build(ROOT_KEY, '', '<ROOT>', new Set())
+}
+
+interface DeltaPctProps {
+ current: number | null | undefined
+ previous: number | null | undefined
+ /** When true, increases are bad (red); decreases good (green). For latency/errors. */
+ higherIsWorse?: boolean
+}
+
+function DeltaPct({ current, previous, higherIsWorse }: DeltaPctProps): JSX.Element | null {
+ if (current === null || current === undefined || previous === null || previous === undefined) {
+ return null
+ }
+ if (previous === 0 && current === 0) {
+ return null
+ }
+ if (previous === 0) {
+ // Can't compute a percentage from a zero baseline — surface it qualitatively.
+ return <span className="text-success ml-1">(new)</span>
+ }
+ const diff = current - previous
+ if (diff === 0) {
+ return null
+ }
+ const pct = (diff / previous) * 100
+ const sign = diff > 0 ? '+' : ''
+ const worse = higherIsWorse ? diff > 0 : diff < 0
+ const color = higherIsWorse === undefined ? 'text-muted' : worse ? 'text-danger' : 'text-success'
+ return (
+ <span className={`${color} ml-1`}>
+ ({sign}
+ {pct.toFixed(1)}%)
+ </span>
+ )
+}
+
+function deltaColor(current: SpanTreeNode | null, previous: SpanTreeNode | null): string {
+ if (!current || !previous) {
+ // New or vanished — neutral neon.
+ return 'rgba(168, 168, 168, 0.6)'
+ }
+ if (previous.p50_duration_nano === 0) {
+ return 'rgba(168, 168, 168, 0.6)'
+ }
+ const ratio = current.p50_duration_nano / previous.p50_duration_nano
+ if (ratio > 1.2) {
+ // Worse: red intensity scales with magnitude.
+ const intensity = Math.min(0.85, 0.35 + (ratio - 1.2) * 0.5)
+ return `rgba(220, 80, 80, ${intensity})`
+ }
+ if (ratio < 0.8) {
+ const intensity = Math.min(0.85, 0.35 + (0.8 - ratio) * 0.5)
+ return `rgba(80, 180, 100, ${intensity})`
+ }
+ return 'rgba(120, 150, 200, 0.45)'
+}
+
+interface FlameRowProps {
+ node: TreeNode
+ depth: number
+ /** This node's width as a fraction (0..1) of the row it lives in. */
+ fraction: number
+ /** Focus path from the synthetic root down to (and including) this node. */
+ selfPath: string[]
+ /** Sets the active focus to a given path. */
+ onFocus: (path: string[]) => void
+}
+
+function FlameRow({ node, fraction, selfPath, onFocus }: FlameRowProps): JSX.Element {
+ const own = nodeSize(node)
+ const color = deltaColor(node.node, node.previousNode)
+
+ const current = node.node
+ const previous = node.previousNode
+
+ const fmtCount = (n: SpanTreeNode | null): string => (n ? humanFriendlyNumber(n.count) : '—')
+ const fmtDur = (v: number | undefined): string => (v === undefined ? '—' : formatDuration(v))
+ const tooltipContent = (
+ <span>
+ <strong>{node.name}</strong>
+ <br />
+ {node.serviceName}
+ <br />
+ count: {fmtCount(current)}
+ <DeltaPct current={current?.count} previous={previous?.count} />
+ {previous ? ` (prev ${fmtCount(previous)})` : ''}
+ <br />
+ p50: {fmtDur(current?.p50_duration_nano)}
+ <DeltaPct current={current?.p50_duration_nano} previous={previous?.p50_duration_nano} higherIsWorse />
+ {previous ? ` (prev ${fmtDur(previous.p50_duration_nano)})` : ''}
+ <br />
+ p95: {fmtDur(current?.p95_duration_nano)}
+ <DeltaPct current={current?.p95_duration_nano} previous={previous?.p95_duration_nano} higherIsWorse />
+ {previous ? ` (prev ${fmtDur(previous.p95_duration_nano)})` : ''}
+ <br />
+ total: {fmtDur(current?.total_duration_nano)}
+ <DeltaPct current={current?.total_duration_nano} previous={previous?.total_duration_nano} higherIsWorse />
+ {previous ? ` (prev ${fmtDur(previous.total_duration_nano)})` : ''}
+ {current && current.error_count > 0 ? (
+ <>
+ <br />
+ errors: {humanFriendlyNumber(current.error_count)}
+ <DeltaPct current={current.error_count} previous={previous?.error_count} higherIsWorse />
+ </>
+ ) : null}
+ </span>
+ )
+
+ return (
+ <div
+ // flex-grow proportional to fraction, basis 0 so siblings share container width
+ // proportionally with no risk of summed widths exceeding 100% (the cause of the
+ // visual overlap when using width: X% across rounded percentages).
+ style={{ flex: `${Math.max(fraction, 0)} 1 0`, minWidth: 0 }}
+ className="flex flex-col overflow-hidden"
+ >
+ <Tooltip title={tooltipContent} delayMs={100} placement="top">
+ <div
+ role="button"
+ tabIndex={0}
+ onClick={() => onFocus(selfPath)}
+ className="flex items-center px-2 overflow-hidden min-w-0 text-xs font-mono cursor-pointer border-r border-b border-bg-bg transition-[filter] hover:brightness-125"
+ style={{
+ height: ROW_HEIGHT_PX,
+ backgroundColor: color,
+ // Marker for "new in current window" (no previous data).
+ outline: !previous && current ? '1px dashed rgba(80, 180, 100, 0.85)' : undefined,
+ // Marker for "vanished" (no current data).
+ opacity: !current && previous ? 0.5 : 1,
+ }}
+ >
+ <span className="truncate">{node.name}</span>
+ </div>
+ </Tooltip>
+ {node.children.length > 0 && (
+ <ChildrenRow parent={node} parentTotal={own} ancestorPath={selfPath} onFocus={onFocus} />
+ )}
+ </div>
+ )
+}
+
+interface ChildrenRowProps {
+ parent: TreeNode
+ parentTotal: number
+ /** Path from the synthetic root to the parent of these children. */
+ ancestorPath: string[]
+ onFocus: (path: string[]) => void
+}
+
+/**
+ * Lays out one row of children. Their widths are normalized so that visible siblings
+ * always sum to 100% — preventing the "spans overlap" effect that happens when
+ * aggregate child durations exceed the parent (concurrent execution). Tiny children
+ * (< 1% of the visible row) are bundled into a "+N more" cell that opens a popover
+ * with that subset rendered at full width.
+ */
+function ChildrenRow({ parent, parentTotal, ancestorPath, onFocus }: ChildrenRowProps): JSX.Element {
+ const childrenWithSize = parent.children.map((child) => ({
+ child,
+ size: nodeSize(child),
+ }))
+ const totalSize = childrenWithSize.reduce((acc, c) => acc + c.size, 0)
+ // Normalization base: use the larger of parent's own total and the summed children
+ // total — the latter wins under concurrency so siblings always fit inside 100%.
+ const base = Math.max(parentTotal, totalSize, 1)
+
+ const visible: { child: TreeNode; fraction: number }[] = []
+ const grouped: { child: TreeNode; fraction: number }[] = []
+ for (const { child, size } of childrenWithSize) {
+ const fraction = size / base
+ if (fraction >= MIN_VISIBLE_FRACTION) {
+ visible.push({ child, fraction })
+ } else {
+ grouped.push({ child, fraction })
+ }
+ }
+ // If only one child is below the threshold, don't bother bundling it — show it inline.
+ if (grouped.length > 0 && grouped.length < MIN_GROUPED_COUNT) {
+ visible.push(...grouped)
+ grouped.length = 0
+ }
+
+ const visibleSum = visible.reduce((acc, v) => acc + v.fraction, 0)
+ const groupedSum = grouped.reduce((acc, v) => acc + v.fraction, 0)
+ const remainder = Math.max(0, 1 - visibleSum - groupedSum)
+
+ return (
+ <div className="flex w-full min-w-0 overflow-hidden">
+ {visible.map(({ child, fraction }) => (
+ <FlameRow
+ key={nodeKey(child.serviceName, child.name)}
+ node={child}
+ depth={0}
+ fraction={fraction}
+ selfPath={[...ancestorPath, nodeKey(child.serviceName, child.name)]}
+ onFocus={onFocus}
+ />
+ ))}
+ {grouped.length > 0 && (
+ <GroupedCell
+ items={grouped}
+ fraction={groupedSum + remainder}
+ ancestorPath={ancestorPath}
+ onFocus={onFocus}
+ />
+ )}
+ </div>
+ )
+}
+
+interface GroupedCellProps {
+ items: { child: TreeNode; fraction: number }[]
+ /** Combined width fraction of the bundle inside the row. */
+ fraction: number
+ ancestorPath: string[]
+ onFocus: (path: string[]) => void
+}
+
+function GroupedCell({ items, fraction, ancestorPath, onFocus }: GroupedCellProps): JSX.Element {
+ const [open, setOpen] = useState(false)
+ // Count every span in the bundled subtrees, not just the top-level grouped children —
+ // a single grouped child can hide a deep subtree of small spans.
+ const totalSpanCount = items.reduce((acc, i) => acc + countDescendants(i.child), 0)
+ // Inside the popover, redistribute the bundle's items to fill the full width.
+ const bundleTotal = items.reduce((acc, i) => acc + nodeSize(i.child), 0) || 1
+ return (
+ <LemonDropdown
+ visible={open}
+ onClickOutside={() => setOpen(false)}
+ overlay={
+ <div className="flex flex-col gap-1 max-w-[640px]">
+ <div className="text-xs text-muted px-1">{totalSpanCount} small spans</div>
+ <div className="flex w-full" style={{ minWidth: 480 }}>
+ {items
+ .slice()
+ .sort((a, b) => nodeSize(b.child) - nodeSize(a.child))
+ .map((item) => (
+ <FlameRow
+ key={nodeKey(item.child.serviceName, item.child.name)}
+ node={item.child}
+ depth={0}
+ fraction={nodeSize(item.child) / bundleTotal}
+ selfPath={[...ancestorPath, nodeKey(item.child.serviceName, item.child.name)]}
+ onFocus={(p) => {
+ setOpen(false)
+ onFocus(p)
+ }}
+ />
+ ))}
+ </div>
+ </div>
+ }
+ >
+ <div
+ style={{
+ flex: `${Math.max(fraction, 0)} 1 0`,
+ height: ROW_HEIGHT_PX,
+ minWidth: GROUPED_CELL_MIN_WIDTH_PX,
+ }}
+ className="flex items-center justify-center text-xs cursor-pointer border-r border-b border-bg-bg bg-fill-tertiary hover:brightness-110"
+ onClick={() => setOpen(!open)}
+ role="button"
+ tabIndex={0}
+ >
+ <span className="truncate px-1 text-muted">+ {totalSpanCount} more</span>
+ </div>
+ </LemonDropdown>
+ )
+}
+
+interface TraceCompareFlameProps {
+ current: SpanTreeNode[]
+ previous: SpanTreeNode[] | null
+ loading: boolean
+ /** Span name the modal was opened for — the flame initially focuses on this node. */
+ initialSpanName?: string | null
+}
+
+/** DFS the tree for the first node matching `name`. Returns the path of node keys to it (excluding root). */
+function findPathByName(root: TreeNode, name: string): string[] | null {
+ for (const child of root.children) {
+ if (child.name === name) {
+ return [nodeKey(child.serviceName, child.name)]
+ }
+ const sub = findPathByName(child, name)
+ if (sub) {
+ return [nodeKey(child.serviceName, child.name), ...sub]
+ }
+ }
+ return null
+}
+
+export function TraceCompareFlame({
+ current,
+ previous,
+ loading,
+ initialSpanName,
+}: TraceCompareFlameProps): JSX.Element {
+ const tree = useMemo(() => buildTree(current, previous), [current, previous])
+ // Focus path: keys of nodes from the synthetic root down to the currently focused span.
+ // Each click on a flame bar appends; breadcrumb clicks truncate.
+ const [focusPath, setFocusPath] = useState<string[]>([])
+
+ // Whenever the tree (or the initial span we were opened with) changes, reset focus to
+ // that span. The user may then drill in/out via flame clicks and breadcrumb segments.
+ useEffect(() => {
+ if (!initialSpanName) {
+ setFocusPath([])
+ return
+ }
+ const path = findPathByName(tree, initialSpanName)
+ setFocusPath(path ?? [])
+ }, [tree, initialSpanName])
+
+ // Walk the tree to resolve the focused node + its ancestor chain.
+ const breadcrumb: TreeNode[] = []
+ let focused: TreeNode = tree
+ for (const key of focusPath) {
+ const next = focused.children.find((c) => nodeKey(c.serviceName, c.name) === key)
+ if (!next) {
+ break
+ }
+ focused = next
+ breadcrumb.push(focused)
+ }
+
+ if (loading) {
+ return (
+ <div className="relative min-h-32">
+ <SpinnerOverlay />
+ </div>
+ )
+ }
+
+ if (tree.children.length === 0) {
+ return <div className="text-muted text-center py-8">No spans found in the call tree for this row.</div>
+ }
+
+ return (
+ <div className="flex flex-col gap-2">
+ <FocusBreadcrumb breadcrumb={breadcrumb} onSelect={(depth) => setFocusPath(focusPath.slice(0, depth))} />
+ <div className="overflow-x-auto">
+ {focusPath.length === 0 ? (
+ // No focus → render top-level children directly (the synthetic root has no real bar).
+ <ChildrenRow
+ parent={focused}
+ parentTotal={focused.children.reduce((sum, c) => sum + nodeSize(c), 0)}
+ ancestorPath={focusPath}
+ onFocus={setFocusPath}
+ />
+ ) : (
+ // Focused span sits at the top as a full-width bar; its children stack below.
+ <div className="flex">
+ <FlameRow node={focused} depth={0} fraction={1} selfPath={focusPath} onFocus={setFocusPath} />
+ </div>
+ )}
+ </div>
+ <div className="flex gap-3 text-xs text-muted">
+ <span className="flex items-center gap-1">
+ <span
+ className="inline-block w-3 h-3 rounded"
+ style={{ backgroundColor: 'rgba(220, 80, 80, 0.7)' }}
+ />
+ slower
+ </span>
+ <span className="flex items-center gap-1">
+ <span
+ className="inline-block w-3 h-3 rounded"
+ style={{ backgroundColor: 'rgba(80, 180, 100, 0.7)' }}
+ />
+ faster
+ </span>
+ <span className="flex items-center gap-1">
+ <span
+ className="inline-block w-3 h-3 rounded"
+ style={{ backgroundColor: 'rgba(120, 150, 200, 0.45)' }}
+ />
+ similar
+ </span>
+ <span className="flex items-center gap-1">
+ <span
+ className="inline-block w-3 h-3 rounded"
+ style={{
+ backgroundColor: 'rgba(168, 168, 168, 0.6)',
+ outline: '1px dashed rgba(80, 180, 100, 0.85)',
+ }}
+ />
+ new
+ </span>
+ <span className="flex items-center gap-1">
+ <span
+ className="inline-block w-3 h-3 rounded"
+ style={{ backgroundColor: 'rgba(168, 168, 168, 0.3)' }}
+ />
+ vanished
+ </span>
+ </div>
+ </div>
+ )
+}
+
+interface FocusBreadcrumbProps {
+ breadcrumb: TreeNode[]
+ /** Called with the new desired depth (0 = top). */
+ onSelect: (depth: number) => void
+}
+
+/** Truncate from the left, keeping the most-specific suffix that usually disambiguates span names. */
+function truncateLeft(s: string, maxChars: number): string {
+ return s.length > maxChars ? '…' + s.slice(-maxChars) : s
+}
+
+function FocusBreadcrumb({ breadcrumb, onSelect }: FocusBreadcrumbProps): JSX.Element {
+ const items: {
+ fullLabel: string
+ displayLabel: string
+ isCurrent: boolean
+ onClick: () => void
+ mono?: boolean
+ }[] = [
+ {
+ fullLabel: 'Root',
+ displayLabel: 'Root',
+ isCurrent: breadcrumb.length === 0,
+ onClick: () => onSelect(0),
+ },
+ ...breadcrumb.map((node, i) => {
+ const isCurrent = i === breadcrumb.length - 1
+ return {
+ fullLabel: node.name,
+ displayLabel: truncateLeft(node.name, isCurrent ? 30 : 15),
+ isCurrent,
+ onClick: () => onSelect(i + 1),
+ mono: true,
+ }
+ }),
+ ]
+ return (
+ <div className="flex items-center gap-x-2 overflow-x-auto">
+ {items.map((item, idx) => {
+ const truncated = item.displayLabel !== item.fullLabel
+ const labelNode = <span className={clsx(item.mono && 'font-mono')}>{item.displayLabel}</span>
+ const content = truncated ? <Tooltip title={item.fullLabel}>{labelNode}</Tooltip> : labelNode
+ return (
+ <React.Fragment key={idx}>
+ {item.isCurrent ? (
+ <span className="text-sm font-semibold shrink-0">{content}</span>
+ ) : (
+ <Link className="text-sm text-muted shrink-0 whitespace-nowrap" onClick={item.onClick}>
+ {content}
+ </Link>
+ )}
+ {idx < items.length - 1 && <IconChevronRight className="text-base text-muted shrink-0" />}
+ </React.Fragment>
+ )
+ })}
+ </div>
+ )
+}
diff --git a/products/tracing/frontend/TraceCompareTable.tsx b/products/tracing/frontend/TraceCompareTable.tsx
new file mode 100644
index 000000000000..3345f12a8ed0
--- /dev/null
+++ b/products/tracing/frontend/TraceCompareTable.tsx
@@ -0,0 +1,194 @@
+import { useMemo } from 'react'
+
+import { LemonTable, LemonTableColumns, Tooltip } from '@posthog/lemon-ui'
+
+import { humanFriendlyNumber } from 'lib/utils'
+
+import { AggregatedSpanRow } from '~/queries/schema/schema-general'
+
+import { formatDuration } from './TraceFlameChart'
+
+interface CompareRow {
+ service_name: string
+ name: string
+ current: AggregatedSpanRow | null
+ previous: AggregatedSpanRow | null
+}
+
+const rowKey = (row: { service_name: string; name: string }): string => `${row.service_name}\u0000${row.name}`
+
+function buildRows(current: AggregatedSpanRow[], previous: AggregatedSpanRow[] | null): CompareRow[] {
+ const previousByKey = new Map<string, AggregatedSpanRow>()
+ for (const row of previous ?? []) {
+ previousByKey.set(rowKey(row), row)
+ }
+
+ const rows: CompareRow[] = current.map((row) => ({
+ service_name: row.service_name,
+ name: row.name,
+ current: row,
+ previous: previousByKey.get(rowKey(row)) ?? null,
+ }))
+
+ // Append rows that existed in the previous window but disappeared in the current window —
+ // useful for spotting fully regressed call sites.
+ const currentKeys = new Set(current.map(rowKey))
+ for (const row of previous ?? []) {
+ const key = rowKey(row)
+ if (!currentKeys.has(key)) {
+ rows.push({
+ service_name: row.service_name,
+ name: row.name,
+ current: null,
+ previous: row,
+ })
+ }
+ }
+
+ return rows
+}
+
+interface DeltaProps {
+ current: number | null | undefined
+ previous: number | null | undefined
+ /** When true, an increase is treated as bad (red). For latency/errors. */
+ higherIsWorse?: boolean
+ format?: (value: number) => string
+}
+
+function Delta({ current, previous, higherIsWorse, format }: DeltaProps): JSX.Element | null {
+ if (previous === null || previous === undefined || current === null || current === undefined) {
+ return null
+ }
+ if (previous === 0 && current === 0) {
+ return null
+ }
+ const diff = current - previous
+ if (diff === 0) {
+ return <span className="text-xs text-muted">—</span>
+ }
+ const pct = previous === 0 ? null : (diff / previous) * 100
+ const sign = diff > 0 ? '+' : ''
+ // When `higherIsWorse` is undefined the metric is informational (e.g. count) and the
+ // delta is shown without a good/bad value judgement — neutral muted text.
+ const colorClass =
+ higherIsWorse === undefined
+ ? 'text-muted'
+ : (higherIsWorse ? diff > 0 : diff < 0)
+ ? 'text-danger'
+ : 'text-success'
+ const label =
+ pct === null ? `${sign}${format ? format(diff) : humanFriendlyNumber(diff)}` : `${sign}${pct.toFixed(1)}%`
+ return (
+ <Tooltip
+ title={`${format ? format(previous) : humanFriendlyNumber(previous)} → ${
+ format ? format(current) : humanFriendlyNumber(current)
+ }`}
+ >
+ <span className={`text-xs ${colorClass}`}>{label}</span>
+ </Tooltip>
+ )
+}
+
+export interface TraceCompareTableProps {
+ current: AggregatedSpanRow[]
+ previous: AggregatedSpanRow[] | null
+ loading: boolean
+ onRowClick?: (row: { service_name: string; name: string }) => void
+}
+
+export function TraceCompareTable({ current, previous, loading, onRowClick }: TraceCompareTableProps): JSX.Element {
+ const rows = useMemo(() => buildRows(current, previous), [current, previous])
+
+ const columns: LemonTableColumns<CompareRow> = [
+ {
+ title: 'Service',
+ key: 'service_name',
+ render: (_, row) => <span className="font-mono text-xs">{row.service_name}</span>,
+ sorter: (a, b) => a.service_name.localeCompare(b.service_name),
+ },
+ {
+ title: 'Span name',
+ key: 'name',
+ render: (_, row) => <span className="font-mono text-xs">{row.name}</span>,
+ sorter: (a, b) => a.name.localeCompare(b.name),
+ },
+ {
+ title: 'Count',
+ key: 'count',
+ align: 'right',
+ render: (_, row) => (
+ <div className="flex flex-col items-end">
+ <span>{row.current ? humanFriendlyNumber(row.current.count) : '—'}</span>
+ <Delta current={row.current?.count} previous={row.previous?.count} />
+ </div>
+ ),
+ sorter: (a, b) => (a.current?.count ?? 0) - (b.current?.count ?? 0),
+ },
+ {
+ title: 'p50',
+ key: 'p50',
+ align: 'right',
+ render: (_, row) => (
+ <div className="flex flex-col items-end">
+ <span>{row.current ? formatDuration(row.current.p50_duration_nano) : '—'}</span>
+ <Delta
+ current={row.current?.p50_duration_nano}
+ previous={row.previous?.p50_duration_nano}
+ higherIsWorse
+ format={formatDuration}
+ />
+ </div>
+ ),
+ sorter: (a, b) => (a.current?.p50_duration_nano ?? 0) - (b.current?.p50_duration_nano ?? 0),
+ },
+ {
+ title: 'p95',
+ key: 'p95',
+ align: 'right',
+ render: (_, row) => (
+ <div className="flex flex-col items-end">
+ <span>{row.current ? formatDuration(row.current.p95_duration_nano) : '—'}</span>
+ <Delta
+ current={row.current?.p95_duration_nano}
+ previous={row.previous?.p95_duration_nano}
+ higherIsWorse
+ format={formatDuration}
+ />
+ </div>
+ ),
+ sorter: (a, b) => (a.current?.p95_duration_nano ?? 0) - (b.current?.p95_duration_nano ?? 0),
+ },
+ {
+ title: 'Errors',
+ key: 'errors',
+ align: 'right',
+ render: (_, row) => (
+ <div className="flex flex-col items-end">
+ <span>{row.current ? humanFriendlyNumber(row.current.error_count) : '—'}</span>
+ <Delta current={row.current?.error_count} previous={row.previous?.error_count} higherIsWorse />
+ </div>
+ ),
+ sorter: (a, b) => (a.current?.error_count ?? 0) - (b.current?.error_count ?? 0),
+ },
+ ]
+
+ return (
+ <LemonTable
+ columns={columns}
+ dataSource={rows}
+ loading={loading}
+ rowKey={(row) => rowKey(row)}
+ emptyState="No spans found"
+ defaultSorting={{ columnKey: 'count', order: -1 }}
+ onRow={
+ onRowClick
+ ? (row) => ({
+ onClick: () => onRowClick({ service_name: row.service_name, name: row.name }),
+ className: 'cursor-pointer',
+ })
+ : undefined
+ }
+ />
+ )
+}
diff --git a/products/tracing/frontend/TracingFilterBar.tsx b/products/tracing/frontend/TracingFilterBar.tsx
index 927e6f72ed22..e3d1781649fb 100644
--- a/products/tracing/frontend/TracingFilterBar.tsx
+++ b/products/tracing/frontend/TracingFilterBar.tsx
@@ -2,7 +2,7 @@ import { BindLogic, useActions, useValues } from 'kea'
import { useRef, useState } from 'react'
import { IconChevronDown, IconMinusSquare, IconPlusSquare, IconRefresh } from '@posthog/icons'
-import { LemonButton, LemonCheckbox, LemonDropdown, LemonInput, LemonTag } from '@posthog/lemon-ui'
+import { LemonButton, LemonCheckbox, LemonDropdown, LemonInput, LemonSwitch, LemonTag } from '@posthog/lemon-ui'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'
@@ -30,6 +30,7 @@ import {
import { tracingDataLogic } from './tracingDataLogic'
import { tracingFiltersLogic } from './tracingFiltersLogic'
import { tracingServiceFilterLogic, TracingServiceFilterLogicProps } from './tracingServiceFilterLogic'
+import { useTracingTabId } from './TracingTabContext'
const taxonomicFilterLogicKey = 'tracing'
const taxonomicGroupTypes = [
@@ -79,11 +80,12 @@ const dateMapping: DateMappingOption[] = [
]
export function TracingFilterBar(): JSX.Element {
- const { spansLoading } = useValues(tracingDataLogic)
- const { runQuery } = useActions(tracingDataLogic)
- const { filters, utcDateRange } = useValues(tracingFiltersLogic)
- const { setDateRange, setServiceNames, setFilterGroup } = useActions(tracingFiltersLogic)
- const { dateRange, serviceNames, filterGroup } = filters
+ const tabId = useTracingTabId()
+ const { spansLoading } = useValues(tracingDataLogic({ tabId }))
+ const { runQuery } = useActions(tracingDataLogic({ tabId }))
+ const { filters, utcDateRange } = useValues(tracingFiltersLogic({ tabId }))
+ const { setDateRange, setServiceNames, setFilterGroup, setCompareMode } = useActions(tracingFiltersLogic({ tabId }))
+ const { dateRange, serviceNames, filterGroup, compareMode } = filters
return (
<TracingFilterGroup filterGroup={filterGroup} onFilterGroupChange={setFilterGroup}>
@@ -145,6 +147,13 @@ export function TracingFilterBar(): JSX.Element {
}}
/>
</div>
+ <LemonSwitch
+ label="Compare"
+ checked={compareMode}
+ onChange={setCompareMode}
+ bordered
+ size="small"
+ />
<LemonButton
size="small"
icon={<IconRefresh />}
@@ -169,7 +178,8 @@ function TracingFilterGroup({
onFilterGroupChange: (filterGroup: UniversalFiltersGroup) => void
children: React.ReactNode
}): JSX.Element {
- const { utcDateRange, filters } = useValues(tracingFiltersLogic)
+ const tabId = useTracingTabId()
+ const { utcDateRange, filters } = useValues(tracingFiltersLogic({ tabId }))
const endpointFilters = {
dateRange: { ...utcDateRange, date_to: utcDateRange.date_to ?? dayjs().toISOString() },
@@ -194,7 +204,8 @@ function TracingFilterGroup({
function TracingFilterSearch(): JSX.Element {
const [visible, setVisible] = useState<boolean>(false)
- const { utcDateRange, filters: tracingFilters } = useValues(tracingFiltersLogic)
+ const tabIdForSearch = useTracingTabId()
+ const { utcDateRange, filters: tracingFilters } = useValues(tracingFiltersLogic({ tabId: tabIdForSearch }))
const { addGroupFilter, setGroupValues } = useActions(universalFiltersLogic)
const { filterGroup } = useValues(universalFiltersLogic)
diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsx
index e7bfb981b776..802ed457cd9a 100644
--- a/products/tracing/frontend/TracingScene.tsx
+++ b/products/tracing/frontend/TracingScene.tsx
@@ -3,6 +3,7 @@ import { useActions, useValues } from 'kea'
import { LemonModal, LemonTable, LemonTableColumns, LemonTag } from '@posthog/lemon-ui'
import { SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'
+import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { SceneExport } from 'scenes/sceneTypes'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
@@ -10,14 +11,19 @@ import { SceneDivider } from '~/layout/scenes/components/SceneDivider'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ProductKey } from '~/queries/schema/schema-general'
+import { TraceCompareFlame } from './TraceCompareFlame'
+import { TraceCompareTable } from './TraceCompareTable'
import { formatDuration, TraceFlameChart } from './TraceFlameChart'
+import { tracingDataLogic } from './tracingDataLogic'
import { TracingFilterBar } from './TracingFilterBar'
-import { tracingSceneLogic } from './tracingSceneLogic'
+import { tracingFiltersLogic } from './tracingFiltersLogic'
+import { tracingSceneLogic, TracingSceneLogicProps } from './tracingSceneLogic'
import { TracingSparkline } from './TracingSparkline'
+import { TracingTabIdProvider, useTracingTabId } from './TracingTabContext'
import { SPAN_KIND_LABELS, STATUS_CODE_LABELS } from './types'
import type { Span } from './types'
-export const scene: SceneExport = {
+export const scene: SceneExport<TracingSceneLogicProps> = {
component: TracingScene,
logic: tracingSceneLogic,
productKey: ProductKey.TRACING,
@@ -80,7 +86,22 @@ const columns: LemonTableColumns<Span> = [
},
]
-export default function TracingScene(): JSX.Element {
+export default function TracingScene(props: TracingSceneLogicProps = {}): JSX.Element {
+ const sceneLogic = tracingSceneLogic(props)
+ // Keep filters + data logic alive across tab switches by attaching them to the scene
+ // root. The root itself is kept mounted by `tabAwareScene()` even when the tab is inactive.
+ useAttachedLogic(tracingFiltersLogic({ tabId: props.tabId }), sceneLogic)
+ useAttachedLogic(tracingDataLogic({ tabId: props.tabId }), sceneLogic)
+
+ return (
+ <TracingTabIdProvider value={props.tabId}>
+ <TracingSceneContents />
+ </TracingTabIdProvider>
+ )
+}
+
+function TracingSceneContents(): JSX.Element {
+ const tabId = useTracingTabId()
const {
rootSpans,
spansLoading,
@@ -91,8 +112,35 @@ export default function TracingScene(): JSX.Element {
totalSpansMatchingFilters,
modalSpans,
isLoadingFullTrace,
- } = useValues(tracingSceneLogic)
- const { openTraceModal, closeTraceModal, setDateRange } = useActions(tracingSceneLogic)
+ aggregation,
+ aggregationLoading,
+ filters,
+ currentWindowMs,
+ previousWindowMs,
+ spanTree,
+ spanTreeLoading,
+ compareFlameSpanName,
+ } = useValues(tracingSceneLogic({ tabId }))
+ const { openTraceModal, closeTraceModal, setDateRange, setOverlayWindows, openCompareFlame, closeCompareFlame } =
+ useActions(tracingSceneLogic({ tabId }))
+ const compareMode = filters.compareMode
+
+ // Anchor the overlay's coordinate space to the *fetched* sparkline data so overlay
+ // drags never shift the canvas underfoot. The sparkline only refetches when dateRange
+ // changes (via the DateFilter), never via overlay interaction.
+ const sparklineFirstMs = sparklineData.dates.length > 0 ? new Date(sparklineData.dates[0]).valueOf() : null
+ const sparklineLastMs =
+ sparklineData.dates.length > 0 ? new Date(sparklineData.dates[sparklineData.dates.length - 1]).valueOf() : null
+ const compareConfig =
+ compareMode && sparklineFirstMs !== null && sparklineLastMs !== null
+ ? {
+ fullStartMs: sparklineFirstMs,
+ fullEndMs: sparklineLastMs,
+ currentWindow: currentWindowMs,
+ previousWindow: previousWindowMs,
+ onChange: setOverlayWindows,
+ }
+ : undefined
return (
<SceneContent>
@@ -108,6 +156,7 @@ export default function TracingScene(): JSX.Element {
sparklineLoading={sparklineLoading}
onDateRangeChange={setDateRange}
displayTimezone="UTC"
+ compare={compareConfig}
/>
<SceneDivider />
<TracingFilterBar />
@@ -116,23 +165,32 @@ export default function TracingScene(): JSX.Element {
{totalSpansMatchingFilters.toLocaleString()} spans matching filters
</div>
)}
- <LemonTable
- columns={columns}
- dataSource={rootSpans}
- loading={spansLoading}
- rowKey="uuid"
- emptyState="No spans found"
- onRow={(span) => ({
- onClick: () => {
- // Clicking a row leaves the scrollable <main tabIndex="0"> as the active
- // element; react-modal then scrolls it back into view when restoring focus
- // on close. Blur so the restore target is <body>, which doesn't scroll.
- ;(document.activeElement as HTMLElement | null)?.blur?.()
- openTraceModal(span.trace_id)
- },
- className: 'cursor-pointer',
- })}
- />
+ {compareMode ? (
+ <TraceCompareTable
+ current={aggregation.current}
+ previous={aggregation.previous}
+ loading={aggregationLoading}
+ onRowClick={(row) => openCompareFlame(row.name)}
+ />
+ ) : (
+ <LemonTable
+ columns={columns}
+ dataSource={rootSpans}
+ loading={spansLoading}
+ rowKey="uuid"
+ emptyState="No spans found"
+ onRow={(span) => ({
+ onClick: () => {
+ // Clicking a row leaves the scrollable <main tabIndex="0"> as the active
+ // element; react-modal then scrolls it back into view when restoring focus
+ // on close. Blur so the restore target is <body>, which doesn't scroll.
+ ;(document.activeElement as HTMLElement | null)?.blur?.()
+ openTraceModal(span.trace_id)
+ },
+ className: 'cursor-pointer',
+ })}
+ />
+ )}
<LemonModal
title={`Trace ${selectedTraceId}`}
isOpen={isTraceModalOpen}
@@ -144,6 +202,19 @@ export default function TracingScene(): JSX.Element {
<TraceFlameChart spans={modalSpans} />
</div>
</LemonModal>
+ <LemonModal
+ title={`Call tree diff: ${compareFlameSpanName ?? ''}`}
+ isOpen={compareFlameSpanName !== null}
+ onClose={closeCompareFlame}
+ width="90vw"
+ >
+ <TraceCompareFlame
+ current={spanTree.current}
+ previous={spanTree.previous}
+ loading={spanTreeLoading}
+ initialSpanName={compareFlameSpanName}
+ />
+ </LemonModal>
</SceneContent>
)
}
diff --git a/products/tracing/frontend/TracingSparkline.tsx b/products/tracing/frontend/TracingSparkline.tsx
index 3cb09f560656..4506c2d1ab04 100644
--- a/products/tracing/frontend/TracingSparkline.tsx
+++ b/products/tracing/frontend/TracingSparkline.tsx
@@ -10,13 +10,23 @@ import { cn } from 'lib/utils/css-classes'
import { DateRange } from '~/queries/schema/schema-general'
+import { SparklineCompareOverlay } from './SparklineCompareOverlay'
import type { TracingSparklineData } from './tracingDataLogic'
+interface CompareConfig {
+ fullStartMs: number
+ fullEndMs: number
+ currentWindow: { startMs: number; endMs: number }
+ previousWindow: { startMs: number; endMs: number }
+ onChange: (current: { startMs: number; endMs: number }, previous: { startMs: number; endMs: number }) => void
+}
+
interface TracingSparklineProps {
sparklineData: TracingSparklineData
sparklineLoading: boolean
onDateRangeChange: (dateRange: DateRange) => void
displayTimezone: string
+ compare?: CompareConfig
}
export function TracingSparkline({
@@ -24,6 +34,7 @@ export function TracingSparkline({
sparklineLoading,
onDateRangeChange,
displayTimezone,
+ compare,
}: TracingSparklineProps): JSX.Element | null {
const [collapsed, setCollapsed] = useState(false)
@@ -123,7 +134,7 @@ export function TracingSparkline({
labels={sparklineLabels}
data={sparklineData.data}
className="w-full h-full"
- onSelectionChange={onSelectionChange}
+ onSelectionChange={compare ? undefined : onSelectionChange}
withXScale={withXScale}
renderLabel={renderLabel}
tooltipRowCutoff={100}
@@ -135,6 +146,15 @@ export function TracingSparkline({
No results matching filters
</div>
) : null}
+ {compare && sparklineData.data.length > 0 && (
+ <SparklineCompareOverlay
+ fullStartMs={compare.fullStartMs}
+ fullEndMs={compare.fullEndMs}
+ currentWindow={compare.currentWindow}
+ previousWindow={compare.previousWindow}
+ onChange={compare.onChange}
+ />
+ )}
{sparklineLoading && <SpinnerOverlay />}
</div>
)}
diff --git a/products/tracing/frontend/TracingTabContext.tsx b/products/tracing/frontend/TracingTabContext.tsx
new file mode 100644
index 000000000000..4fefbfbe55c9
--- /dev/null
+++ b/products/tracing/frontend/TracingTabContext.tsx
@@ -0,0 +1,16 @@
+import { createContext, useContext } from 'react'
+
+/**
+ * Provides the active scene `tabId` to children so they can mount the tab-aware
+ * `tracingFiltersLogic` / `tracingDataLogic` instances under the right key.
+ *
+ * `undefined` is a valid value — kea falls back to the default-keyed instance, which
+ * keeps the scene usable outside of an internal-tab context (e.g. Storybook).
+ */
+const TracingTabIdContext = createContext<string | undefined>(undefined)
+
+export const TracingTabIdProvider = TracingTabIdContext.Provider
+
+export function useTracingTabId(): string | undefined {
+ return useContext(TracingTabIdContext)
+}
diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.ts
index 63f1f8dff7dc..274bf39c6be5 100644
--- a/products/tracing/frontend/tracingDataLogic.ts
+++ b/products/tracing/frontend/tracingDataLogic.ts
@@ -1,4 +1,4 @@
-import { actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'
+import { actions, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { lemonToast } from '@posthog/lemon-ui'
@@ -7,6 +7,7 @@ import api from 'lib/api'
import { dataColorVars } from 'lib/colors'
import { humanFriendlyDetailedTime } from 'lib/utils'
+import { AggregatedSpanRow, SpanTreeNode } from '~/queries/schema/schema-general'
import { PropertyGroupFilter } from '~/types'
import type { tracingDataLogicType } from './tracingDataLogicType'
@@ -34,12 +35,21 @@ function isUserInitiatedError(error: unknown): boolean {
return error === NEW_QUERY_STARTED_ERROR_MESSAGE || errorStr.includes('abort')
}
+export interface TracingDataLogicProps {
+ tabId?: string
+}
+
export const tracingDataLogic = kea<tracingDataLogicType>([
- path(['products', 'tracing', 'frontend', 'tracingDataLogic']),
+ props({} as TracingDataLogicProps),
+ key((p) => p.tabId ?? 'default'),
+ path((tabId) => ['products', 'tracing', 'frontend', 'tracingDataLogic', tabId]),
- connect({
- values: [tracingFiltersLogic, ['filters', 'utcDateRange']],
- }),
+ connect((p: TracingDataLogicProps) => ({
+ values: [
+ tracingFiltersLogic({ tabId: p.tabId }),
+ ['filters', 'utcDateRange', 'currentWindowMs', 'previousWindowMs'],
+ ],
+ })),
actions({
runQuery: true,
@@ -47,10 +57,26 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
clearSpans: true,
cancelInProgressSpans: (controller: AbortController | null) => ({ controller }),
cancelInProgressSparkline: (controller: AbortController | null) => ({ controller }),
+ cancelInProgressAggregation: (controller: AbortController | null) => ({ controller }),
+ cancelInProgressSpanTree: (controller: AbortController | null) => ({ controller }),
setSpansAbortController: (controller: AbortController | null) => ({ controller }),
setSparklineAbortController: (controller: AbortController | null) => ({ controller }),
+ setAggregationAbortController: (controller: AbortController | null) => ({ controller }),
+ setSpanTreeAbortController: (controller: AbortController | null) => ({ controller }),
setHasMoreToLoad: (hasMore: boolean) => ({ hasMore }),
setNextCursor: (cursor: string | null) => ({ cursor }),
+ /**
+ * Snapshot the resolved time windows used for the last aggregation fetch.
+ * The drill-down flame query reads this snapshot instead of recomputing from
+ * the (potentially shifted) `-1h`-style relative date range, so its numbers
+ * line up with the row the user clicked.
+ */
+ setLastAggregationWindow: (window: {
+ currentStartMs: number
+ currentEndMs: number
+ previousStartMs: number
+ previousEndMs: number
+ }) => ({ window }),
}),
reducers({
@@ -62,6 +88,23 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
null as AbortController | null,
{ setSparklineAbortController: (_, { controller }) => controller },
],
+ aggregationAbortController: [
+ null as AbortController | null,
+ { setAggregationAbortController: (_, { controller }) => controller },
+ ],
+ spanTreeAbortController: [
+ null as AbortController | null,
+ { setSpanTreeAbortController: (_, { controller }) => controller },
+ ],
+ lastAggregationWindow: [
+ null as null | {
+ currentStartMs: number
+ currentEndMs: number
+ previousStartMs: number
+ previousEndMs: number
+ },
+ { setLastAggregationWindow: (_, { window }) => window },
+ ],
hasRunQuery: [
false as boolean,
{
@@ -88,6 +131,22 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
fetchSparklineFailure: () => false,
},
],
+ aggregationLoading: [
+ false as boolean,
+ {
+ fetchAggregation: () => true,
+ fetchAggregationSuccess: () => false,
+ fetchAggregationFailure: () => false,
+ },
+ ],
+ spanTreeLoading: [
+ false as boolean,
+ {
+ fetchSpanTree: () => true,
+ fetchSpanTreeSuccess: () => false,
+ fetchSpanTreeFailure: () => false,
+ },
+ ],
hasMoreToLoad: [
true as boolean,
{
@@ -113,14 +172,18 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
const controller = new AbortController()
actions.cancelInProgressSpans(controller)
- const response = await api.tracing.listSpans({
- dateRange: values.utcDateRange,
- orderBy: values.filters.orderBy,
- serviceNames: values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,
- filterGroup: values.filters.filterGroup as PropertyGroupFilter,
- prefetchSpans: PREFETCH_SPANS,
- limit: DEFAULT_PAGE_SIZE,
- })
+ const response = await api.tracing.listSpans(
+ {
+ dateRange: values.utcDateRange,
+ orderBy: values.filters.orderBy,
+ serviceNames:
+ values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,
+ filterGroup: values.filters.filterGroup as PropertyGroupFilter,
+ prefetchSpans: PREFETCH_SPANS,
+ limit: DEFAULT_PAGE_SIZE,
+ },
+ controller.signal
+ )
actions.setSpansAbortController(null)
actions.setHasMoreToLoad(!!response.hasMore)
@@ -135,14 +198,18 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
const controller = new AbortController()
actions.cancelInProgressSpans(controller)
- const response = await api.tracing.listSpans({
- dateRange: values.utcDateRange,
- orderBy: values.filters.orderBy,
- serviceNames: values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,
- filterGroup: values.filters.filterGroup as PropertyGroupFilter,
- limit: DEFAULT_PAGE_SIZE,
- after: values.nextCursor,
- })
+ const response = await api.tracing.listSpans(
+ {
+ dateRange: values.utcDateRange,
+ orderBy: values.filters.orderBy,
+ serviceNames:
+ values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,
+ filterGroup: values.filters.filterGroup as PropertyGroupFilter,
+ limit: DEFAULT_PAGE_SIZE,
+ after: values.nextCursor,
+ },
+ controller.signal
+ )
actions.setSpansAbortController(null)
actions.setHasMoreToLoad(!!response.hasMore)
@@ -167,6 +234,101 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
},
},
],
+ spanTree: [
+ {
+ spanName: null as string | null,
+ current: [] as SpanTreeNode[],
+ previous: null as SpanTreeNode[] | null,
+ },
+ {
+ fetchSpanTree: async (params: { spanName: string }) => {
+ // Abort any in-flight tree fetch so rapid row-clicks can't deliver a stale
+ // response that overwrites the newer one — matches the pattern used by
+ // fetchSpans / fetchSparkline / fetchAggregation.
+ const controller = new AbortController()
+ actions.cancelInProgressSpanTree(controller)
+
+ // Use the snapshotted window from the last aggregation fetch when available
+ // so the drill-down numbers align with the row the user clicked. Fall back
+ // to the live computed window only on a cold start (e.g. deep link before
+ // any aggregation has run).
+ const snapshot = values.lastAggregationWindow
+ const currentStartMs = snapshot?.currentStartMs ?? values.currentWindowMs.startMs
+ const currentEndMs = snapshot?.currentEndMs ?? values.currentWindowMs.endMs
+ const previousStartMs = snapshot?.previousStartMs ?? values.previousWindowMs.startMs
+
+ const response = await api.tracing.tree(
+ {
+ spanName: params.spanName,
+ dateRange: {
+ date_from: new Date(currentStartMs).toISOString(),
+ date_to: new Date(currentEndMs).toISOString(),
+ },
+ serviceNames:
+ values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,
+ filterGroup: values.filters.filterGroup as PropertyGroupFilter,
+ compareFilter: {
+ compare: values.filters.compareMode,
+ compare_to: new Date(previousStartMs).toISOString(),
+ },
+ },
+ controller.signal
+ )
+
+ actions.setSpanTreeAbortController(null)
+ return {
+ spanName: params.spanName,
+ current: response.results ?? [],
+ previous: response.compare ?? null,
+ }
+ },
+ },
+ ],
+ aggregation: [
+ { current: [] as AggregatedSpanRow[], previous: null as AggregatedSpanRow[] | null },
+ {
+ fetchAggregation: async () => {
+ const controller = new AbortController()
+ actions.cancelInProgressAggregation(controller)
+
+ // Snapshot the resolved windows so the drill-down flame query uses the
+ // same absolute timestamps as this aggregation, even if the user's
+ // relative `-1h` range has since shifted forward in time. Dispatched
+ // BEFORE the await so a concurrent `fetchSpanTree` (e.g. fired from the
+ // same `setOverlayWindows` listener) reads the new window, not the old.
+ const window = {
+ currentStartMs: values.currentWindowMs.startMs,
+ currentEndMs: values.currentWindowMs.endMs,
+ previousStartMs: values.previousWindowMs.startMs,
+ previousEndMs: values.previousWindowMs.endMs,
+ }
+ actions.setLastAggregationWindow(window)
+
+ const response = await api.tracing.aggregate(
+ {
+ dateRange: {
+ date_from: new Date(window.currentStartMs).toISOString(),
+ date_to: new Date(window.currentEndMs).toISOString(),
+ },
+ serviceNames:
+ values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,
+ filterGroup: values.filters.filterGroup as PropertyGroupFilter,
+ compareFilter: {
+ compare: values.filters.compareMode,
+ compare_to: new Date(window.previousStartMs).toISOString(),
+ },
+ },
+ controller.signal
+ )
+
+ actions.setAggregationAbortController(null)
+ return {
+ current: response.results ?? [],
+ previous: response.compare ?? null,
+ }
+ },
+ },
+ ],
rawSparklineData: [
[] as SparklineRow[],
{
@@ -174,11 +336,15 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
const controller = new AbortController()
actions.cancelInProgressSparkline(controller)
- const response = await api.tracing.sparkline({
- dateRange: values.utcDateRange,
- serviceNames: values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,
- filterGroup: values.filters.filterGroup as PropertyGroupFilter,
- })
+ const response = await api.tracing.sparkline(
+ {
+ dateRange: values.utcDateRange,
+ serviceNames:
+ values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,
+ filterGroup: values.filters.filterGroup as PropertyGroupFilter,
+ },
+ controller.signal
+ )
actions.setSparklineAbortController(null)
return response.results
@@ -254,8 +420,12 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
listeners(({ actions, values }) => ({
runQuery: () => {
actions.clearSpans()
- actions.fetchSpans()
actions.fetchSparkline()
+ if (values.filters.compareMode) {
+ actions.fetchAggregation()
+ } else {
+ actions.fetchSpans()
+ }
},
cancelInProgressSpans: ({ controller }) => {
if (values.spansAbortController !== null) {
@@ -269,6 +439,18 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
}
actions.setSparklineAbortController(controller)
},
+ cancelInProgressAggregation: ({ controller }) => {
+ if (values.aggregationAbortController !== null) {
+ values.aggregationAbortController.abort(NEW_QUERY_STARTED_ERROR_MESSAGE)
+ }
+ actions.setAggregationAbortController(controller)
+ },
+ cancelInProgressSpanTree: ({ controller }) => {
+ if (values.spanTreeAbortController !== null) {
+ values.spanTreeAbortController.abort(NEW_QUERY_STARTED_ERROR_MESSAGE)
+ }
+ actions.setSpanTreeAbortController(controller)
+ },
fetchSpansFailure: ({ error }) => {
if (!isUserInitiatedError(error)) {
lemonToast.error(`Failed to load traces: ${error}`)
@@ -279,6 +461,16 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
// Sparkline failures are non-critical, don't show toast
}
},
+ fetchAggregationFailure: ({ error }) => {
+ if (!isUserInitiatedError(error)) {
+ lemonToast.error(`Failed to load span aggregation: ${error}`)
+ }
+ },
+ fetchSpanTreeFailure: ({ error }) => {
+ if (!isUserInitiatedError(error)) {
+ lemonToast.error(`Failed to load call tree: ${error}`)
+ }
+ },
})),
events(({ values }) => ({
@@ -289,6 +481,12 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
if (values.sparklineAbortController) {
values.sparklineAbortController.abort('unmounting component')
}
+ if (values.spanTreeAbortController) {
+ values.spanTreeAbortController.abort('unmounting component')
+ }
+ if (values.aggregationAbortController) {
+ values.aggregationAbortController.abort('unmounting component')
+ }
},
})),
])
diff --git a/products/tracing/frontend/tracingFiltersLogic.ts b/products/tracing/frontend/tracingFiltersLogic.ts
index 0ceb5914bdda..924f97466cda 100644
--- a/products/tracing/frontend/tracingFiltersLogic.ts
+++ b/products/tracing/frontend/tracingFiltersLogic.ts
@@ -1,4 +1,4 @@
-import { actions, kea, path, reducers, selectors } from 'kea'
+import { actions, kea, key, path, props, reducers, selectors } from 'kea'
import { DEFAULT_UNIVERSAL_GROUP_FILTER } from 'lib/components/UniversalFilters/universalFiltersLogic'
import { dayjs } from 'lib/dayjs'
@@ -14,21 +14,42 @@ export const DEFAULT_ORDER_BY = 'latest' as const
export type TracingOrderBy = 'latest' | 'earliest'
+export interface OverlayWindow {
+ startMs: number
+ endMs: number
+}
+
export interface TracingFilters {
dateRange: DateRange
serviceNames: string[]
filterGroup: UniversalFiltersGroup
orderBy: TracingOrderBy
+ compareMode: boolean
+ /** User-positioned overrides for the two compare windows. Null until the overlay is dragged. */
+ currentWindowOverride: OverlayWindow | null
+ previousWindowOverride: OverlayWindow | null
+}
+
+export interface TracingFiltersLogicProps {
+ tabId?: string
}
export const tracingFiltersLogic = kea<tracingFiltersLogicType>([
- path(['products', 'tracing', 'frontend', 'tracingFiltersLogic']),
+ props({} as TracingFiltersLogicProps),
+ key((p) => p.tabId ?? 'default'),
+ path((tabId) => ['products', 'tracing', 'frontend', 'tracingFiltersLogic', tabId]),
actions({
setDateRange: (dateRange: DateRange) => ({ dateRange }),
setServiceNames: (serviceNames: string[]) => ({ serviceNames }),
setFilterGroup: (filterGroup: UniversalFiltersGroup) => ({ filterGroup }),
setOrderBy: (orderBy: TracingOrderBy) => ({ orderBy }),
+ setCompareMode: (compareMode: boolean) => ({ compareMode }),
+ /**
+ * Persist the user-dragged overlay windows. Both must be supplied. Setting these
+ * never touches dateRange — the sparkline range is locked once compare mode is on.
+ */
+ setOverlayWindows: (current: OverlayWindow, previous: OverlayWindow) => ({ current, previous }),
setFilters: (filters: Partial<TracingFilters>) => ({ filters }),
}),
@@ -63,16 +84,62 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([
setFilters: (state, { filters }) => (filters.orderBy as TracingOrderBy) ?? state,
},
],
+ compareMode: [
+ false as boolean,
+ {
+ setCompareMode: (_, { compareMode }) => compareMode,
+ setFilters: (state, { filters }) => filters.compareMode ?? state,
+ },
+ ],
+ currentWindowOverride: [
+ null as OverlayWindow | null,
+ {
+ setOverlayWindows: (_, { current }) => current,
+ // Any date-range change invalidates user-positioned windows — they were absolute
+ // ms positions inside the old sparkline range, meaningless in a new one.
+ setDateRange: () => null,
+ setCompareMode: () => null,
+ setFilters: (state, { filters }) => filters.currentWindowOverride ?? state,
+ },
+ ],
+ previousWindowOverride: [
+ null as OverlayWindow | null,
+ {
+ setOverlayWindows: (_, { previous }) => previous,
+ setDateRange: () => null,
+ setCompareMode: () => null,
+ setFilters: (state, { filters }) => filters.previousWindowOverride ?? state,
+ },
+ ],
}),
selectors({
filters: [
- (s) => [s.dateRange, s.serviceNames, s.filterGroup, s.orderBy],
- (dateRange, serviceNames, filterGroup, orderBy): TracingFilters => ({
+ (s) => [
+ s.dateRange,
+ s.serviceNames,
+ s.filterGroup,
+ s.orderBy,
+ s.compareMode,
+ s.currentWindowOverride,
+ s.previousWindowOverride,
+ ],
+ (
dateRange,
serviceNames,
filterGroup,
orderBy,
+ compareMode,
+ currentWindowOverride,
+ previousWindowOverride
+ ): TracingFilters => ({
+ dateRange,
+ serviceNames,
+ filterGroup,
+ orderBy,
+ compareMode,
+ currentWindowOverride,
+ previousWindowOverride,
}),
],
utcDateRange: [
@@ -86,5 +153,64 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([
: dateRange.date_to,
}),
],
+ sparklineWindowMs: [(s) => [s.dateRange], (dateRange: DateRange): OverlayWindow => resolveWindow(dateRange)],
+ currentWindowMs: [
+ (s) => [s.sparklineWindowMs, s.currentWindowOverride],
+ (sparklineWindowMs: OverlayWindow, override: OverlayWindow | null): OverlayWindow => {
+ if (override) {
+ return override
+ }
+ // Default: right-aligned, 40% of the sparkline duration.
+ const duration = sparklineWindowMs.endMs - sparklineWindowMs.startMs
+ const windowDuration = duration * 0.4
+ return { startMs: sparklineWindowMs.endMs - windowDuration, endMs: sparklineWindowMs.endMs }
+ },
+ ],
+ previousWindowMs: [
+ (s) => [s.sparklineWindowMs, s.previousWindowOverride],
+ (sparklineWindowMs: OverlayWindow, override: OverlayWindow | null): OverlayWindow => {
+ if (override) {
+ return override
+ }
+ // Default: same 40% width, shifted -50% of sparkline duration from current's
+ // right edge — i.e., right edge at end - 50% of duration.
+ const duration = sparklineWindowMs.endMs - sparklineWindowMs.startMs
+ const windowDuration = duration * 0.4
+ const endMs = sparklineWindowMs.endMs - duration * 0.5
+ return { startMs: endMs - windowDuration, endMs }
+ },
+ ],
}),
])
+
+function resolveWindow(dateRange: DateRange): { startMs: number; endMs: number } {
+ const endMs =
+ dateRange.date_to && dayjs(dateRange.date_to).isValid() ? dayjs(dateRange.date_to).valueOf() : Date.now()
+ const startMs =
+ dateRange.date_from && dayjs(dateRange.date_from).isValid()
+ ? dayjs(dateRange.date_from).valueOf()
+ : resolveRelativeMs(dateRange.date_from ?? '-1h', endMs)
+ return { startMs, endMs }
+}
+
+const RELATIVE_RE = /^-(\d+)([smhdM])$/
+
+function resolveRelativeMs(input: string | null | undefined, anchorMs: number): number {
+ if (!input) {
+ return anchorMs
+ }
+ const match = RELATIVE_RE.exec(input.trim())
+ if (!match) {
+ return anchorMs
+ }
+ const [, nRaw, unit] = match
+ const n = Number(nRaw)
+ const unitMap: Record<string, dayjs.UnitType> = {
+ s: 'second',
+ m: 'minute',
+ h: 'hour',
+ d: 'day',
+ M: 'month',
+ }
+ return dayjs(anchorMs).subtract(n, unitMap[unit]).valueOf()
+}
diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.ts
index 632a4f93288a..753ffde56443 100644
--- a/products/tracing/frontend/tracingSceneLogic.ts
+++ b/products/tracing/frontend/tracingSceneLogic.ts
@@ -1,22 +1,33 @@
import equal from 'fast-deep-equal'
-import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
-import { actionToUrl, router, urlToAction } from 'kea-router'
+import { actions, connect, kea, listeners, path, props, reducers, selectors } from 'kea'
+import { router } from 'kea-router'
import { DEFAULT_UNIVERSAL_GROUP_FILTER } from 'lib/components/UniversalFilters/universalFiltersLogic'
+import { tabAwareActionToUrl } from 'lib/logic/scenes/tabAwareActionToUrl'
+import { tabAwareScene } from 'lib/logic/scenes/tabAwareScene'
+import { tabAwareUrlToAction } from 'lib/logic/scenes/tabAwareUrlToAction'
import { parseTagsFilter } from 'lib/utils'
import { Params } from 'scenes/sceneTypes'
+import { Breadcrumb } from '~/types'
+
import { PREFETCH_SPANS, tracingDataLogic } from './tracingDataLogic'
import { DEFAULT_DATE_RANGE, DEFAULT_ORDER_BY, DEFAULT_SERVICE_NAMES, tracingFiltersLogic } from './tracingFiltersLogic'
import type { tracingSceneLogicType } from './tracingSceneLogicType'
import type { Span } from './types'
+export interface TracingSceneLogicProps {
+ tabId?: string
+}
+
export const tracingSceneLogic = kea<tracingSceneLogicType>([
+ props({} as TracingSceneLogicProps),
path(['products', 'tracing', 'frontend', 'tracingSceneLogic']),
+ tabAwareScene(),
- connect({
+ connect((p: TracingSceneLogicProps) => ({
values: [
- tracingDataLogic,
+ tracingDataLogic({ tabId: p.tabId }),
[
'spans',
'spansLoading',
@@ -28,21 +39,35 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
'totalSpansMatchingFilters',
'traceSpans',
'traceSpansLoading',
+ 'aggregation',
+ 'aggregationLoading',
+ 'spanTree',
+ 'spanTreeLoading',
],
- tracingFiltersLogic,
- ['filters', 'utcDateRange'],
+ tracingFiltersLogic({ tabId: p.tabId }),
+ ['filters', 'utcDateRange', 'sparklineWindowMs', 'currentWindowMs', 'previousWindowMs'],
],
actions: [
- tracingDataLogic,
- ['runQuery', 'fetchNextPage', 'loadTraceSpans'],
- tracingFiltersLogic,
- ['setDateRange', 'setServiceNames', 'setFilterGroup', 'setOrderBy', 'setFilters'],
+ tracingDataLogic({ tabId: p.tabId }),
+ ['runQuery', 'fetchNextPage', 'loadTraceSpans', 'fetchAggregation', 'fetchSpanTree'],
+ tracingFiltersLogic({ tabId: p.tabId }),
+ [
+ 'setDateRange',
+ 'setServiceNames',
+ 'setFilterGroup',
+ 'setOrderBy',
+ 'setCompareMode',
+ 'setOverlayWindows',
+ 'setFilters',
+ ],
],
- }),
+ })),
actions({
openTraceModal: (traceId: string) => ({ traceId }),
closeTraceModal: true,
+ openCompareFlame: (spanName: string) => ({ spanName }),
+ closeCompareFlame: true,
syncUrlAndRunQuery: true,
}),
@@ -54,6 +79,13 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
closeTraceModal: () => null,
},
],
+ compareFlameSpanName: [
+ null as string | null,
+ {
+ openCompareFlame: (_, { spanName }) => spanName,
+ closeCompareFlame: () => null,
+ },
+ ],
}),
selectors({
@@ -75,6 +107,16 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
},
],
isLoadingFullTrace: [(s) => [s.traceSpansLoading], (traceSpansLoading: boolean): boolean => traceSpansLoading],
+ breadcrumbs: [
+ () => [],
+ (): Breadcrumb[] => [
+ {
+ key: 'tracing',
+ name: 'Tracing',
+ iconType: 'tracing',
+ },
+ ],
+ ],
}),
listeners(({ actions, values }) => ({
@@ -84,6 +126,9 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
actions.loadTraceSpans(traceId)
}
},
+ openCompareFlame: ({ spanName }) => {
+ actions.fetchSpanTree({ spanName })
+ },
setDateRange: () => {
actions.syncUrlAndRunQuery()
},
@@ -96,12 +141,24 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
setOrderBy: () => {
actions.syncUrlAndRunQuery()
},
+ setCompareMode: () => {
+ actions.syncUrlAndRunQuery()
+ },
+ setOverlayWindows: () => {
+ // Overlay drags only refetch the aggregation — the sparkline canvas range
+ // stays fixed while the user moves windows around within it. If the compare-flame
+ // modal is open we also refetch its tree so it doesn't display stale windows.
+ actions.fetchAggregation()
+ if (values.compareFlameSpanName) {
+ actions.fetchSpanTree({ spanName: values.compareFlameSpanName })
+ }
+ },
setFilters: () => {
actions.syncUrlAndRunQuery()
},
})),
- urlToAction(({ actions, values }) => ({
+ tabAwareUrlToAction(({ actions, values }) => ({
'/tracing': (_, searchParams) => {
const filtersFromUrl: Record<string, any> = {}
let hasChanges = false
@@ -157,6 +214,12 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
}
}
+ const compareFromUrl = searchParams.compare === 'true' || searchParams.compare === true
+ if (compareFromUrl !== values.filters.compareMode) {
+ filtersFromUrl.compareMode = compareFromUrl
+ hasChanges = true
+ }
+
if (hasChanges) {
actions.setFilters(filtersFromUrl)
} else if (!values.hasRunQuery) {
@@ -165,7 +228,7 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
},
})),
- actionToUrl(({ values, actions }) => {
+ tabAwareActionToUrl(({ values, actions }) => {
const buildUrl = (): [string, Params, Record<string, any>, { replace: boolean }] => {
const searchParams: Params = {}
@@ -181,6 +244,9 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
if (values.filters.orderBy !== DEFAULT_ORDER_BY) {
searchParams.orderBy = values.filters.orderBy
}
+ if (values.filters.compareMode) {
+ searchParams.compare = 'true'
+ }
actions.runQuery()
return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]