:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tracing): make the compare table answer "what changed?" first (#69699)
Jon McCallum6fea8196725f
diff --git a/products/tracing/frontend/TraceCompareFlame.tsx b/products/tracing/frontend/TraceCompareFlame.tsxindex f8976a4f5ee7..08daf2727016 100644--- a/products/tracing/frontend/TraceCompareFlame.tsx+++ b/products/tracing/frontend/TraceCompareFlame.tsx@@ -9,6 +9,7 @@ import { humanFriendlyNumber } from 'lib/utils/numbers'import { SpanTreeNode } from '~/queries/schema/schema-general'+import { CHANGE_THRESHOLD, MIN_BASELINE_COUNT } from './compareUtils'import { formatDuration } from './TraceWaterfallView'interface TreeNode {@@ -215,14 +216,19 @@ function deltaColor(current: SpanTreeNode | null, previous: SpanTreeNode | null)if (previous.p50_duration_nano === 0) {return 'rgba(168, 168, 168, 0.6)'}+ // Same low-sample noise guard as the compare table's classification, so a node the table+ // calls unchanged can't render as a deep-red regression here.+ if (Math.min(current.count, previous.count) < MIN_BASELINE_COUNT) {+ return 'rgba(120, 150, 200, 0.45)'+ }const ratio = current.p50_duration_nano / previous.p50_duration_nano- if (ratio > 1.2) {+ if (ratio > 1 + CHANGE_THRESHOLD) {// Worse: red intensity scales with magnitude.- const intensity = Math.min(0.85, 0.35 + (ratio - 1.2) * 0.5)+ const intensity = Math.min(0.85, 0.35 + (ratio - (1 + CHANGE_THRESHOLD)) * 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)+ if (ratio < 1 - CHANGE_THRESHOLD) {+ const intensity = Math.min(0.85, 0.35 + (1 - CHANGE_THRESHOLD - ratio) * 0.5)return `rgba(80, 180, 100, ${intensity})`}return 'rgba(120, 150, 200, 0.45)'diff --git a/products/tracing/frontend/TraceCompareTable.tsx b/products/tracing/frontend/TraceCompareTable.tsxindex 289114f97615..0b91e1797753 100644--- a/products/tracing/frontend/TraceCompareTable.tsx+++ b/products/tracing/frontend/TraceCompareTable.tsx@@ -1,7 +1,7 @@import { CSSProperties, useMemo, useState } from 'react'import { List } from 'react-window'-import { Spinner, Tooltip } from '@posthog/lemon-ui'+import { LemonSegmentedButton, LemonTag, LemonTagType, Link, Spinner, Tooltip } from '@posthog/lemon-ui'import { AutoSizer } from 'lib/components/AutoSizer'import { SizeProps } from 'lib/components/AutoSizer/AutoSizer'@@ -11,6 +11,7 @@ import { humanFriendlyNumber } from 'lib/utils/numbers'import { AggregatedSpanRow } from '~/queries/schema/schema-general'+import { buildRows, changeMagnitude, type CompareRow, type CompareRowStatus, isLowSample } from './compareUtils'import { formatDuration } from './TraceWaterfallView'const ROW_HEIGHT = 44@@ -28,50 +29,24 @@ const COL_WIDTH = {const NAME_MIN_WIDTH = 200const MIN_ROW_WIDTH = Object.values(COL_WIDTH).reduce((sum, width) => sum + width, 0) + NAME_MIN_WIDTH-type SortColumn = 'service_name' | 'name' | 'count' | 'p50' | 'p95' | 'errors'+// 'change' is the default: biggest p95 movers (both directions) first, so the table answers+// "what changed?" without any clicking. Column header clicks switch to plain value sorts.+type SortColumn = 'change' | 'service_name' | 'name' | 'count' | 'p50' | 'p95' | 'errors'type SortOrder = 1 | -1-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}\0${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,- }))+type StatusFilter = 'all' | CompareRowStatus- // 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+// One record drives both the quick-filter bar (label) and the row badge (tagType, New/Gone only).+const STATUS_META: Partial<Record<CompareRowStatus, { label: string; tagType?: LemonTagType }>> = {+ regressed: { label: 'Regressed' },+ improved: { label: 'Improved' },+ new: { label: 'New', tagType: 'success' },+ gone: { label: 'Gone', tagType: 'muted' },}+const FILTERABLE_STATUSES = Object.keys(STATUS_META) as CompareRowStatus[]const SORTERS: Record<SortColumn, (a: CompareRow, b: CompareRow) => number> = {+ change: (a, b) => changeMagnitude(a) - changeMagnitude(b),service_name: (a, b) => a.service_name.localeCompare(b.service_name),name: (a, b) => a.name.localeCompare(b.name),count: (a, b) => (a.current?.count ?? 0) - (b.current?.count ?? 0),@@ -252,18 +227,24 @@ function CompareListRow({style: CSSProperties} & CompareRowProps): JSX.Element {const row = dataSource[index]+ const statusTag = STATUS_META[row.status]?.tagType ? STATUS_META[row.status] : undefined+ // Low-sample rows classify as unchanged; color-judging their deltas red/green would+ // contradict that in the same row, so they render neutral like the count delta.+ const judged = isLowSample(row) ? undefined : truereturn (<div{...ariaAttributes}// eslint-disable-next-line react/forbid-dom-propsstyle={style}data-index={index}- data-row-key={rowKey(row)}+ data-row-key={`${row.service_name}:${row.name}`}><divclassName={cn('flex items-center border-b border-border hover:bg-surface-primary-hover',- onRowClick && 'cursor-pointer'+ onRowClick && 'cursor-pointer',+ // Vanished call sites: keep them readable but visually secondary.+ !row.current && 'opacity-60')}// eslint-disable-next-line react/forbid-dom-propsstyle={{ height: ROW_HEIGHT }}@@ -285,7 +266,14 @@ function CompareListRow({<span className="font-mono">{row.service_name}</span></Cell><Cell>- <span className="font-mono">{row.name}</span>+ <span className="inline-flex items-center gap-1.5 max-w-full">+ <span className="font-mono truncate">{row.name}</span>+ {statusTag && (+ <LemonTag type={statusTag.tagType} size="small">+ {statusTag.label}+ </LemonTag>+ )}+ </span></Cell><Cell width={COL_WIDTH.count} align="right"><div className="flex flex-col items-end">@@ -299,7 +287,7 @@ function CompareListRow({<Deltacurrent={row.current?.p50_duration_nano}previous={row.previous?.p50_duration_nano}- higherIsWorse+ higherIsWorse={judged}format={formatDuration}/></div>@@ -310,7 +298,7 @@ function CompareListRow({<Deltacurrent={row.current?.p95_duration_nano}previous={row.previous?.p95_duration_nano}- higherIsWorse+ higherIsWorse={judged}format={formatDuration}/></div>@@ -318,7 +306,11 @@ function CompareListRow({<Cell width={COL_WIDTH.errors} align="right"><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 />+ <Delta+ current={row.current?.error_count}+ previous={row.previous?.error_count}+ higherIsWorse={judged}+ /></div></Cell></div>@@ -334,14 +326,30 @@ export interface TraceCompareTableProps {}export function TraceCompareTable({ current, previous, loading, onRowClick }: TraceCompareTableProps): JSX.Element {- const [sortColumn, setSortColumn] = useState<SortColumn>('count')+ const [sortColumn, setSortColumn] = useState<SortColumn>('change')const [sortOrder, setSortOrder] = useState<SortOrder>(-1)+ const [statusFilter, setStatusFilter] = useState<StatusFilter>('all')- const rows = useMemo(() => {+ const { allRows, statusCounts } = useMemo(() => {const built = buildRows(current, previous)+ const counts: Record<CompareRowStatus, number> = { regressed: 0, improved: 0, new: 0, gone: 0, unchanged: 0 }+ for (const row of built) {+ counts[row.status] += 1+ }+ return { allRows: built, statusCounts: counts }+ }, [current, previous])++ // A refetch can empty the selected bucket (e.g. baseline preset change) — fall back to+ // All instead of rendering a selected-but-disabled option over an empty table.+ const activeStatusFilter: StatusFilter =+ statusFilter === 'all' || statusCounts[statusFilter] > 0 ? statusFilter : 'all'++ const rows = useMemo(() => {+ const filtered =+ activeStatusFilter === 'all' ? allRows : allRows.filter((row) => row.status === activeStatusFilter)const sorter = SORTERS[sortColumn]- return [...built].sort((a, b) => sorter(a, b) * sortOrder)- }, [current, previous, sortColumn, sortOrder])+ return [...filtered].sort((a, b) => sorter(a, b) * sortOrder)+ }, [allRows, activeStatusFilter, sortColumn, sortOrder])const onSort = (column: SortColumn): void => {if (column === sortColumn) {@@ -354,7 +362,7 @@ export function TraceCompareTable({ current, previous, loading, onRowClick }: Trconst rowProps = useMemo((): CompareRowProps => ({ dataSource: rows, onRowClick }), [rows, onRowClick])- if (rows.length === 0) {+ if (allRows.length === 0) {return (<div className="flex items-center justify-center p-8 text-muted border rounded bg-bg-light">{loading ? <Spinner className="text-2xl" /> : 'No spans found'}@@ -362,38 +370,74 @@ export function TraceCompareTable({ current, previous, loading, onRowClick }: Tr)}+ const statusOptions = [+ { value: 'all' as StatusFilter, label: `All (${allRows.length})` },+ ...FILTERABLE_STATUSES.map((status) => ({+ value: status as StatusFilter,+ label: `${STATUS_META[status]?.label} (${statusCounts[status]})`,+ disabledReason: statusCounts[status] === 0 ? 'No spans in this bucket' : undefined,+ })),+ ]++ // Without a baseline dataset there are no buckets to filter — every row is 'unchanged'.+ const hasBaseline = previous !== null+return (- <div- className="flex flex-col flex-1 min-h-0 bg-bg-light border rounded overflow-hidden"- data-attr="tracing-compare-table"- >- <AutoSizer- renderProp={({ width, height }: SizeProps) => {- if (!width || !height) {- return null- }- const rowWidth = Math.max(width, MIN_ROW_WIDTH)- return (- // The viewport is fixed to the available box; the inner content can be wider- // (MIN_ROW_WIDTH) so columns scroll horizontally and rows align with the header.- // eslint-disable-next-line react/forbid-dom-props- <div className="overflow-x-auto" style={{ width, height }}>- {/* eslint-disable-next-line react/forbid-dom-props */}- <div style={{ width: rowWidth }}>- <CompareRowHeader sortColumn={sortColumn} sortOrder={sortOrder} onSort={onSort} />- <List<CompareRowProps>- style={{ height: height - HEADER_HEIGHT, width: rowWidth }}- overscanCount={10}- rowCount={rows.length}- rowHeight={ROW_HEIGHT}- rowComponent={CompareListRow}- rowProps={rowProps}- />+ <div className="flex flex-col flex-1 min-h-0 gap-2" data-attr="tracing-compare-table">+ {hasBaseline && (+ <div className="flex items-center gap-2 flex-wrap" data-attr="tracing-compare-status-filter">+ <LemonSegmentedButton<StatusFilter>+ size="small"+ value={activeStatusFilter}+ onChange={setStatusFilter}+ options={statusOptions}+ />+ {sortColumn !== 'change' && (+ <Link+ className="text-xs"+ onClick={() => onSort('change')}+ data-attr="tracing-compare-sort-change"+ >+ Sort by biggest change+ </Link>+ )}+ </div>+ )}+ <div className="flex flex-col flex-1 min-h-0 bg-bg-light border rounded overflow-hidden">+ <AutoSizer+ renderProp={({ width, height }: SizeProps) => {+ if (!width || !height) {+ return null+ }+ const rowWidth = Math.max(width, MIN_ROW_WIDTH)+ return (+ // The viewport is fixed to the available box; the inner content can be wider+ // (MIN_ROW_WIDTH) so columns scroll horizontally and rows align with the header.+ // eslint-disable-next-line react/forbid-dom-props+ <div className="overflow-x-auto" style={{ width, height }}>+ {/* eslint-disable-next-line react/forbid-dom-props */}+ <div style={{ width: rowWidth }}>+ <CompareRowHeader sortColumn={sortColumn} sortOrder={sortOrder} onSort={onSort} />+ {rows.length === 0 ? (+ <div className="flex items-center justify-center p-8 text-muted">+ No spans in this bucket+ </div>+ ) : (+ <List<CompareRowProps>+ style={{ height: height - HEADER_HEIGHT, width: rowWidth }}+ overscanCount={10}+ rowCount={rows.length}+ rowHeight={ROW_HEIGHT}+ rowComponent={CompareListRow}+ rowProps={rowProps}+ />+ )}+ </div></div>- </div>- )- }}- />+ )+ }}+ />+ </div></div>)}diff --git a/products/tracing/frontend/compareUtils.test.ts b/products/tracing/frontend/compareUtils.test.tsnew file mode 100644index 000000000000..be98d7680136--- /dev/null+++ b/products/tracing/frontend/compareUtils.test.ts@@ -0,0 +1,105 @@+import { AggregatedSpanRow } from '~/queries/schema/schema-general'++import { buildRows, changeMagnitude, classifyRow, type CompareRow, MIN_BASELINE_COUNT } from './compareUtils'++type CompareRowSides = Pick<CompareRow, 'current' | 'previous'>++const aggRow = (overrides: Partial<AggregatedSpanRow> = {}): AggregatedSpanRow =>+ ({+ service_name: 'web',+ name: 'GET /api',+ count: 100,+ p50_duration_nano: 1_000_000,+ p95_duration_nano: 10_000_000,+ p99_duration_nano: 20_000_000,+ error_count: 0,+ ...overrides,+ }) as AggregatedSpanRow++const row = (+ current: Partial<AggregatedSpanRow> | null,+ previous: Partial<AggregatedSpanRow> | null+): CompareRowSides => ({+ current: current ? aggRow(current) : null,+ previous: previous ? aggRow(previous) : null,+})++describe('compareUtils', () => {+ describe('classifyRow', () => {+ test.each([+ [+ 'p95 >20% worse is regressed',+ row({ p95_duration_nano: 13_000_000 }, { p95_duration_nano: 10_000_000 }),+ 'regressed',+ ],+ [+ 'p95 >20% better is improved',+ row({ p95_duration_nano: 7_000_000 }, { p95_duration_nano: 10_000_000 }),+ 'improved',+ ],+ [+ 'within the threshold is unchanged',+ row({ p95_duration_nano: 11_000_000 }, { p95_duration_nano: 10_000_000 }),+ 'unchanged',+ ],+ ['missing current is gone', row(null, {}), 'gone'],+ ['missing previous is new', row({}, null), 'new'],+ [+ 'a large delta on a tiny baseline is noise, not a regression',+ row(+ { p95_duration_nano: 50_000_000 },+ { p95_duration_nano: 10_000_000, count: MIN_BASELINE_COUNT - 1 }+ ),+ 'unchanged',+ ],+ [+ 'a large delta on a tiny current window is noise too',+ row(+ { p95_duration_nano: 50_000_000, count: MIN_BASELINE_COUNT - 1 },+ { p95_duration_nano: 10_000_000 }+ ),+ 'unchanged',+ ],+ [+ 'a zero baseline p95 is unchanged',+ row({ p95_duration_nano: 5_000_000 }, { p95_duration_nano: 0 }),+ 'unchanged',+ ],+ ])('%s', (_name, input, expected) => {+ expect(classifyRow(input)).toBe(expected)+ })+ })++ it('changeMagnitude orders new above big movers above small movers above gone under a descending sort', () => {+ const gone = row(null, {})+ const fresh = row({}, null)+ const bigMove = row({ p95_duration_nano: 30_000_000 }, { p95_duration_nano: 10_000_000 })+ const smallMove = row({ p95_duration_nano: 11_000_000 }, { p95_duration_nano: 10_000_000 })++ const sorted = [gone, smallMove, fresh, bigMove].sort((a, b) => changeMagnitude(b) - changeMagnitude(a))+ expect(sorted).toEqual([fresh, bigMove, smallMove, gone])+ })++ it('sparse new rows do not outrank real movers in the change sort', () => {+ const sparseFresh = row({ count: MIN_BASELINE_COUNT - 1 }, null)+ const bigMove = row({ p95_duration_nano: 30_000_000 }, { p95_duration_nano: 10_000_000 })++ expect(changeMagnitude(sparseFresh)).toBeLessThan(changeMagnitude(bigMove))+ })++ it('a null baseline dataset marks every row unchanged instead of new', () => {+ const rows = buildRows([aggRow()], null)+ expect(rows).toHaveLength(1)+ expect(rows[0].status).toBe('unchanged')+ })++ it('buildRows appends vanished rows so fully regressed call sites stay visible', () => {+ const current = [aggRow({ name: 'GET /api' })]+ const previous = [aggRow({ name: 'GET /api' }), aggRow({ name: 'GET /legacy' })]++ const rows = buildRows(current, previous)+ expect(rows).toHaveLength(2)+ expect(rows[1]).toMatchObject({ name: 'GET /legacy', current: null, status: 'gone' })+ expect(rows[0].previous).not.toBeNull()+ })+})diff --git a/products/tracing/frontend/compareUtils.ts b/products/tracing/frontend/compareUtils.tsnew file mode 100644index 000000000000..a88701139171--- /dev/null+++ b/products/tracing/frontend/compareUtils.ts@@ -0,0 +1,122 @@+import { AggregatedSpanRow } from '~/queries/schema/schema-general'++// Shared with TraceCompareFlame's node coloring so the table's Regressed/Improved buckets and+// the flame's red/green bars agree on what counts as a change: ±20% on the row's p95 (the+// flame colors per-node on p50, same threshold).+export const CHANGE_THRESHOLD = 0.2++// Rows with fewer baseline samples than this classify as unchanged — percentage deltas on a+// handful of spans are noise, and they'd otherwise dominate the change-first sort.+export const MIN_BASELINE_COUNT = 10++export type CompareRowStatus = 'regressed' | 'improved' | 'new' | 'gone' | 'unchanged'++export interface CompareRow {+ service_name: string+ name: string+ current: AggregatedSpanRow | null+ previous: AggregatedSpanRow | null+ status: CompareRowStatus+}++// NUL separator, not a space: span names routinely contain spaces, so a printable separator+// would let ("web api", "x") and ("web", "api x") collide on one key.+export const compareRowKey = (row: { service_name: string; name: string }): string => `${row.service_name}\0${row.name}`++export function buildRows(current: AggregatedSpanRow[], previous: AggregatedSpanRow[] | null): CompareRow[] {+ const previousByKey = new Map<string, AggregatedSpanRow>()+ for (const row of previous ?? []) {+ previousByKey.set(compareRowKey(row), row)+ }++ // A null `previous` means there is no baseline dataset at all (e.g. the compare fetch is+ // still in flight) — that must not classify every row as 'new'.+ const hasBaseline = previous !== null+ const makeRow = (+ base: { service_name: string; name: string },+ currentRow: AggregatedSpanRow | null,+ previousRow: AggregatedSpanRow | null+ ): CompareRow => ({+ service_name: base.service_name,+ name: base.name,+ current: currentRow,+ previous: previousRow,+ status: hasBaseline ? classifyRow({ current: currentRow, previous: previousRow }) : 'unchanged',+ })++ const rows: CompareRow[] = current.map((row) => makeRow(row, row, previousByKey.get(compareRowKey(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(compareRowKey))+ for (const row of previous ?? []) {+ if (!currentKeys.has(compareRowKey(row))) {+ rows.push(makeRow(row, null, row))+ }+ }++ return rows+}++/** Relative change (0.5 = +50%), or null when there's no meaningful baseline. */+function relativeDelta(current: number | null | undefined, previous: number | null | undefined): number | null {+ if (current === null || current === undefined || previous === null || previous === undefined || previous === 0) {+ return null+ }+ return (current - previous) / previous+}++type CompareRowSides = Pick<CompareRow, 'current' | 'previous'>++/**+ * Percentage deltas on a handful of spans are noise on either side: a row that dropped from+ * 1000 calls to 2 slow ones is not a p95 regression any more than a 2-sample baseline is.+ */+export function isLowSample(row: CompareRowSides): boolean {+ return !row.current || !row.previous || Math.min(row.current.count, row.previous.count) < MIN_BASELINE_COUNT+}++/** The row's p95 relative delta with the low-sample noise guard applied. */+function guardedP95Delta(row: CompareRowSides): number | null {+ if (!row.current || !row.previous || isLowSample(row)) {+ return null+ }+ return relativeDelta(row.current.p95_duration_nano, row.previous.p95_duration_nano)+}++export function classifyRow(row: CompareRowSides): CompareRowStatus {+ if (!row.current) {+ return 'gone'+ }+ if (!row.previous) {+ return 'new'+ }+ const delta = guardedP95Delta(row)+ if (delta === null) {+ return 'unchanged'+ }+ if (delta > CHANGE_THRESHOLD) {+ return 'regressed'+ }+ if (delta < -CHANGE_THRESHOLD) {+ return 'improved'+ }+ return 'unchanged'+}++/**+ * Sort key for the default change-first ordering: biggest movers (either direction) first.+ * New rows are by definition maximal change; gone rows sort below everything, including+ * unchanged rows, so vanished call sites collect at the bottom under a descending sort.+ */+export function changeMagnitude(row: CompareRowSides): number {+ if (!row.current) {+ return -1+ }+ if (!row.previous) {+ // Sparse new rows (unparameterized URLs and the like) would otherwise flood the top+ // of the change sort — the same noise the low-sample guard suppresses elsewhere.+ return row.current.count >= MIN_BASELINE_COUNT ? Number.MAX_VALUE : 0+ }+ return Math.abs(guardedP95Delta(row) ?? 0)+}