:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tracing): add operations aggregate tab (#65827)
Jon McCallum3d180ce096a6
diff --git a/products/tracing/frontend/OperationsTable.tsx b/products/tracing/frontend/OperationsTable.tsxnew file mode 100644index 000000000000..380aeaec705a--- /dev/null+++ b/products/tracing/frontend/OperationsTable.tsx@@ -0,0 +1,157 @@+import { useMemo } from 'react'++import { humanFriendlyNumber } from 'lib/utils/numbers'++import { AggregatedSpanRow } from '~/queries/schema/schema-general'++import { formatDuration } from './TraceWaterfallView'+import { VirtualizedTable, VirtualizedTableColumn } from './VirtualizedTable'++// Span count over the aggregation window, rendered as a request rate. Empty window → no rate.+function formatRate(count: number, windowMs: number): string {+ const seconds = windowMs / 1000+ if (!seconds) {+ return '—'+ }+ const perSec = count / seconds+ if (perSec >= 1) {+ return `${humanFriendlyNumber(perSec, perSec >= 10 ? 0 : 1)}/s`+ }+ const perMin = perSec * 60+ if (perMin >= 1) {+ return `${humanFriendlyNumber(perMin, 1)}/min`+ }+ return `${humanFriendlyNumber(perSec * 3600, 1)}/hr`+}++function errorRate(row: AggregatedSpanRow): number {+ return row.count > 0 ? row.error_count / row.count : 0+}++const durationCell =+ (pick: (row: AggregatedSpanRow) => number) =>+ (row: AggregatedSpanRow): JSX.Element => <span className="font-mono">{formatDuration(pick(row))}</span>++function buildColumns(windowMs: number): VirtualizedTableColumn<AggregatedSpanRow>[] {+ return [+ {+ key: 'service_name',+ title: 'Service',+ width: 150,+ sorter: (a, b) => a.service_name.localeCompare(b.service_name),+ render: (row) => <span className="font-mono">{row.service_name}</span>,+ },+ {+ key: 'name',+ title: 'Operation',+ sorter: (a, b) => a.name.localeCompare(b.name),+ render: (row) => <span className="font-mono">{row.name}</span>,+ },+ {+ key: 'requests',+ title: 'Requests',+ width: 120,+ align: 'right',+ sorter: (a, b) => a.count - b.count,+ render: (row) => (+ <div className="flex flex-col items-end">+ <span>{formatRate(row.count, windowMs)}</span>+ <span className="text-xs text-muted">{humanFriendlyNumber(row.count)}</span>+ </div>+ ),+ },+ {+ key: 'error_rate',+ title: 'Error rate',+ width: 90,+ align: 'right',+ sorter: (a, b) => errorRate(a) - errorRate(b),+ render: (row) => {+ const rate = errorRate(row)+ return (+ <span className={rate > 0 ? 'text-danger' : 'text-muted'}>+ {`${(rate * 100).toFixed(rate > 0 && rate < 0.01 ? 2 : 1)}%`}+ </span>+ )+ },+ },+ {+ key: 'errors',+ title: 'Errors',+ width: 80,+ align: 'right',+ sorter: (a, b) => a.error_count - b.error_count,+ render: (row) => (+ <span className={row.error_count > 0 ? 'text-danger' : 'text-muted'}>+ {humanFriendlyNumber(row.error_count)}+ </span>+ ),+ },+ {+ key: 'p50',+ title: 'p50',+ width: 80,+ align: 'right',+ sorter: (a, b) => a.p50_duration_nano - b.p50_duration_nano,+ render: durationCell((row) => row.p50_duration_nano),+ },+ {+ key: 'p95',+ title: 'p95',+ width: 80,+ align: 'right',+ sorter: (a, b) => a.p95_duration_nano - b.p95_duration_nano,+ render: durationCell((row) => row.p95_duration_nano),+ },+ {+ key: 'p99',+ title: 'p99',+ width: 80,+ align: 'right',+ sorter: (a, b) => a.p99_duration_nano - b.p99_duration_nano,+ render: durationCell((row) => row.p99_duration_nano),+ },+ {+ key: 'p999',+ title: 'p99.9',+ width: 80,+ align: 'right',+ sorter: (a, b) => a.p999_duration_nano - b.p999_duration_nano,+ render: durationCell((row) => row.p999_duration_nano),+ },+ {+ key: 'total_time',+ title: 'Total time',+ width: 100,+ align: 'right',+ // Per the JON-89 spike: wall-time, not self-time — nesting is double-counted; labelled as such.+ tooltip: 'Sum of span wall-clock durations; nested spans are counted in both parent and child.',+ sorter: (a, b) => a.total_duration_nano - b.total_duration_nano,+ render: durationCell((row) => row.total_duration_nano),+ },+ ]+}++export interface OperationsTableProps {+ rows: AggregatedSpanRow[]+ loading: boolean+ /** Resolved aggregation window (ms) — turns span counts into a request rate. */+ windowMs: number+ onRowClick?: (row: AggregatedSpanRow) => void+}++export function OperationsTable({ rows, loading, windowMs, onRowClick }: OperationsTableProps): JSX.Element {+ const columns = useMemo(() => buildColumns(windowMs), [windowMs])+ return (+ <VirtualizedTable<AggregatedSpanRow>+ columns={columns}+ dataSource={rows}+ loading={loading}+ rowKey={(row) => `${row.service_name}::${row.name}`}+ onRowClick={onRowClick}+ defaultSort={{ columnKey: 'total_time', order: -1 }}+ emptyLabel="No operations found for these filters"+ data-attr="tracing-operations-table"+ />+ )+}diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsxindex be52606c0afb..ac52ff099342 100644--- a/products/tracing/frontend/TracingScene.tsx+++ b/products/tracing/frontend/TracingScene.tsx@@ -1,9 +1,11 @@import { useActions, useValues } from 'kea'import posthog from 'posthog-js'-import { LemonBanner, LemonButton, LemonModal, Link } from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, LemonModal, LemonTabs, Link } from '@posthog/lemon-ui'+import { FEATURE_FLAGS } from 'lib/constants'import { IconFeedback } from 'lib/lemon-ui/icons'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'import { humanFriendlyNumber } from 'lib/utils/numbers'import { SceneExport } from 'scenes/sceneTypes'@@ -17,6 +19,7 @@ import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-generaimport { TracingSetupPrompt } from './components/SetupPrompt/SetupPrompt'import { TraceDrawer } from './components/TraceDrawer/TraceDrawer'import { VirtualizedSpanList } from './components/VirtualizedSpanList/VirtualizedSpanList'+import { OperationsTable } from './OperationsTable'import { TraceCompareFlame } from './TraceCompareFlame'import { TraceCompareTable } from './TraceCompareTable'import { tracingDataLogic } from './tracingDataLogic'@@ -74,7 +77,9 @@ function TracingSceneContents(): JSX.Element {visibleRowDurationRange,isDurationMode,expandedSpanIds,+ activeTracingTab,} = useValues(tracingSceneLogic())+ const { featureFlags } = useValues(featureFlagLogic)const {openTrace,closeTrace,@@ -88,9 +93,16 @@ function TracingSceneContents(): JSX.Element {setVisibleRowRange,toggleExpandSpan,setSort,+ setActiveTracingTab,} = useActions(tracingSceneLogic())const { addProductIntent } = useActions(teamLogic)const compareMode = filters.compareMode+ const operationsViewEnabled = !!featureFlags[FEATURE_FLAGS.TRACING_OPERATIONS_VIEW]++ // Resolved aggregation window (ms) — turns span counts into a request rate.+ // Use sparklineWindowMs which correctly resolves relative date strings (e.g. '-1h').+ const { sparklineWindowMs } = useValues(tracingFiltersLogic())+ const operationsWindowMs = sparklineWindowMs.endMs - sparklineWindowMs.startMsconst onDocsLinkClick = (): void => {addProductIntent({@@ -169,57 +181,77 @@ function TracingSceneContents(): JSX.Element {/><SceneDivider /><TracingFilterBar />- {/* No loading guard: keep the last (view-mode-independent) count visible across reloads,- so a Traces/Spans switch doesn't flicker the label out and back in. */}- {!compareMode && totalMatchingFilters > 0 && (- <div className="text-xs text-muted px-1">- {humanFriendlyNumber(totalMatchingFilters)} {filters.viewMode === 'spans' ? 'spans' : 'traces'}{' '}- matching filters- </div>+ {operationsViewEnabled && (+ <LemonTabs+ activeKey={activeTracingTab}+ onChange={(key) => setActiveTracingTab(key as 'traces' | 'operations')}+ tabs={[+ { key: 'traces', label: 'Traces' },+ { key: 'operations', label: 'Operations' },+ ]}+ />)}- {compareMode ? (- <TraceCompareTable- current={aggregation.current}- previous={aggregation.previous}+ {operationsViewEnabled && activeTracingTab === 'operations' ? (+ <OperationsTable+ rows={aggregation.current}loading={aggregationLoading}- onRowClick={(row) => openCompareFlame(row.name, row.service_name)}+ windowMs={operationsWindowMs}/>) : (- <VirtualizedSpanList- dataSource={listRows}- loading={spansLoading}- hasMoreToLoad={hasMoreToLoad}- onLoadMore={fetchNextPage}- onVisibleRowRangeChange={setVisibleRowRange}- expandedSpanIds={expandedSpanIds}- onToggleExpand={toggleExpandSpan}- orderBy={filters.orderBy}- orderDirection={filters.orderDirection}- onSort={(column) =>- // Click an active column to flip direction; a new column starts at DESC.- setSort(- column,- column === filters.orderBy && filters.orderDirection === 'DESC' ? 'ASC' : 'DESC'- )- }- emptyState={- <div className="flex flex-col items-center gap-1">- <span>No spans found</span>- <Link to={TRACING_DOCS_URL} onClick={onDocsLinkClick} target="_blank">- Learn how to send traces- </Link>+ <>+ {/* No loading guard: keep the last (view-mode-independent) count visible across reloads,+ so a Traces/Spans switch doesn't flicker the label out and back in. */}+ {!compareMode && totalMatchingFilters > 0 && (+ <div className="text-xs text-muted px-1">+ {humanFriendlyNumber(totalMatchingFilters)}{' '}+ {filters.viewMode === 'spans' ? 'spans' : 'traces'} matching filters</div>- }- onRowClick={(span: Span) => {- // 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?.()- // Anchor the waterfall on the clicked span — in Spans mode this is often a- // child span, so without spanId the drawer would open unfocused at the root.- openTrace(span.trace_id, { spanId: span.span_id, ts: span.timestamp })- }}- />+ )}+ {compareMode ? (+ <TraceCompareTable+ current={aggregation.current}+ previous={aggregation.previous}+ loading={aggregationLoading}+ onRowClick={(row) => openCompareFlame(row.name, row.service_name)}+ />+ ) : (+ <VirtualizedSpanList+ dataSource={listRows}+ loading={spansLoading}+ hasMoreToLoad={hasMoreToLoad}+ onLoadMore={fetchNextPage}+ onVisibleRowRangeChange={setVisibleRowRange}+ expandedSpanIds={expandedSpanIds}+ onToggleExpand={toggleExpandSpan}+ orderBy={filters.orderBy}+ orderDirection={filters.orderDirection}+ onSort={(column) =>+ // Click an active column to flip direction; a new column starts at DESC.+ setSort(+ column,+ column === filters.orderBy && filters.orderDirection === 'DESC' ? 'ASC' : 'DESC'+ )+ }+ emptyState={+ <div className="flex flex-col items-center gap-1">+ <span>No spans found</span>+ <Link to={TRACING_DOCS_URL} onClick={onDocsLinkClick} target="_blank">+ Learn how to send traces+ </Link>+ </div>+ }+ onRowClick={(span: Span) => {+ // 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?.()+ // Anchor the waterfall on the clicked span — in Spans mode this is often a+ // child span, so without spanId the drawer would open unfocused at the root.+ openTrace(span.trace_id, { spanId: span.span_id, ts: span.timestamp })+ }}+ />+ )}+ </>)}</TracingSetupPrompt><TraceDrawerdiff --git a/products/tracing/frontend/VirtualizedTable.tsx b/products/tracing/frontend/VirtualizedTable.tsxnew file mode 100644index 000000000000..1775dec9638a--- /dev/null+++ b/products/tracing/frontend/VirtualizedTable.tsx@@ -0,0 +1,258 @@+import { CSSProperties, ReactNode, useMemo, useState } from 'react'+import { List } from 'react-window'++import { Spinner, Tooltip } from '@posthog/lemon-ui'++import { AutoSizer } from 'lib/components/AutoSizer'+import { SizeProps } from 'lib/components/AutoSizer/AutoSizer'+import { SortingIndicator } from 'lib/lemon-ui/LemonTable/sorting'+import { cn } from 'lib/utils/css-classes'++// Config-driven virtualized table: owns react-window virtualization, client-side sort, and the+// header/row layout; callers pass column definitions + data. Extracted from TraceCompareTable so+// the compare view and the operations view share one implementation. The column-def contract+// mirrors logs' `VirtualizedTableColumn` (products/logs/frontend/components/VirtualizedLogsList);+// the two are intended to converge into a single shared lib/ primitive later.++const ROW_HEIGHT = 44+const HEADER_HEIGHT = 32+// Min width a flex (width-less) column reserves when computing the horizontal-scroll row width.+const FLEX_MIN_WIDTH = 200++export type VirtualizedSortOrder = 1 | -1++export interface VirtualizedTableColumn<T> {+ key: string+ title: ReactNode+ /** Fixed column width in px. Omit to flex-fill the remaining space. */+ width?: number+ align?: 'right'+ /** Header tooltip. */+ tooltip?: string+ render: (record: T) => ReactNode+ /** Provide to make the column sortable. */+ sorter?: (a: T, b: T) => number+}++function Cell({ width, align, children }: { width?: number; align?: 'right'; children: ReactNode }): JSX.Element {+ return (+ <div+ className={cn(+ 'shrink-0 truncate px-2 text-xs',+ width === undefined && 'flex-1 min-w-0',+ align === 'right' && 'text-right'+ )}+ // eslint-disable-next-line react/forbid-dom-props+ style={width !== undefined ? { width } : undefined}+ >+ {children}+ </div>+ )+}++function HeaderCell({+ column,+ sortKey,+ sortOrder,+ onSort,+}: {+ column: VirtualizedTableColumn<any>+ sortKey: string | null+ sortOrder: VirtualizedSortOrder+ onSort: (key: string) => void+}): JSX.Element {+ const label = column.tooltip ? <Tooltip title={column.tooltip}>{column.title}</Tooltip> : column.title+ if (!column.sorter) {+ return (+ <Cell width={column.width} align={column.align}>+ {label}+ </Cell>+ )+ }+ const active = sortKey === column.key+ return (+ <Cell width={column.width} align={column.align}>+ <button+ type="button"+ className={cn(+ 'flex items-center cursor-pointer hover:text-default',+ column.align === 'right' && 'ml-auto',+ active && 'text-default'+ )}+ onClick={() => onSort(column.key)}+ data-attr={`virtualized-table-sort-${column.key}`}+ >+ <span>{label}</span>+ <SortingIndicator order={active ? sortOrder : null} />+ </button>+ </Cell>+ )+}++// The generic T is erased to `any` at the react-window row boundary — type safety lives at the+// column-definition site (`columns: VirtualizedTableColumn<T>[]`), not inside the row renderer.+interface VirtualizedRowProps {+ columns: VirtualizedTableColumn<any>[]+ dataSource: any[]+ rowKey: (record: any) => string+ onRowClick?: (record: any) => void+}++function VirtualizedRow({+ ariaAttributes,+ index,+ style,+ columns,+ dataSource,+ rowKey,+ onRowClick,+}: {+ ariaAttributes: { 'aria-posinset': number; 'aria-setsize': number; role: 'listitem' }+ index: number+ style: CSSProperties+} & VirtualizedRowProps): JSX.Element {+ const record = dataSource[index]+ return (+ <div+ {...ariaAttributes}+ // eslint-disable-next-line react/forbid-dom-props+ style={style}+ data-index={index}+ data-row-key={rowKey(record)}+ >+ <div+ className={cn(+ 'flex items-center border-b border-border hover:bg-surface-primary-hover',+ onRowClick && 'cursor-pointer'+ )}+ // eslint-disable-next-line react/forbid-dom-props+ style={{ height: ROW_HEIGHT }}+ onClick={onRowClick ? () => onRowClick(record) : undefined}+ onKeyDown={+ onRowClick+ ? (e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault()+ onRowClick(record)+ }+ }+ : undefined+ }+ role={onRowClick ? 'button' : undefined}+ tabIndex={onRowClick ? 0 : undefined}+ >+ {columns.map((column) => (+ <Cell key={column.key} width={column.width} align={column.align}>+ {column.render(record)}+ </Cell>+ ))}+ </div>+ </div>+ )+}++export interface VirtualizedTableProps<T> {+ columns: VirtualizedTableColumn<T>[]+ dataSource: T[]+ loading: boolean+ rowKey: (record: T) => string+ onRowClick?: (record: T) => void+ defaultSort?: { columnKey: string; order: VirtualizedSortOrder }+ emptyLabel?: string+ 'data-attr'?: string+}++export function VirtualizedTable<T>({+ columns,+ dataSource,+ loading,+ rowKey,+ onRowClick,+ defaultSort,+ emptyLabel = 'No rows',+ 'data-attr': dataAttr,+}: VirtualizedTableProps<T>): JSX.Element {+ const [sortKey, setSortKey] = useState<string | null>(defaultSort?.columnKey ?? null)+ const [sortOrder, setSortOrder] = useState<VirtualizedSortOrder>(defaultSort?.order ?? -1)++ const minRowWidth = useMemo(+ () => columns.reduce((sum, column) => sum + (column.width ?? FLEX_MIN_WIDTH), 0),+ [columns]+ )++ const rows = useMemo(() => {+ const sorter = columns.find((column) => column.key === sortKey)?.sorter+ if (!sorter) {+ return dataSource+ }+ return [...dataSource].sort((a, b) => sorter(a, b) * sortOrder)+ }, [dataSource, columns, sortKey, sortOrder])++ const onSort = (key: string): void => {+ if (key === sortKey) {+ setSortOrder((order) => (order === 1 ? -1 : 1))+ } else {+ setSortKey(key)+ setSortOrder(-1)+ }+ }++ const rowProps = useMemo(+ (): VirtualizedRowProps => ({ columns, dataSource: rows, rowKey, onRowClick }),+ [columns, rows, rowKey, onRowClick]+ )++ if (rows.length === 0) {+ return (+ <div className="flex items-center justify-center p-8 text-muted border rounded bg-bg-light">+ {loading ? <Spinner className="text-2xl" /> : emptyLabel}+ </div>+ )+ }++ return (+ <div className="flex flex-col flex-1 min-h-0 bg-bg-light border rounded overflow-hidden" data-attr={dataAttr}>+ <AutoSizer+ renderProp={({ width, height }: SizeProps) => {+ if (!width || !height) {+ return null+ }+ const rowWidth = Math.max(width, minRowWidth)+ return (+ // The viewport is fixed to the available box; inner content can be wider+ // (minRowWidth) 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 }}>+ <div+ className="flex items-center border-b border-border bg-surface-secondary font-medium text-muted"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ height: HEADER_HEIGHT }}+ >+ {columns.map((column) => (+ <HeaderCell+ key={column.key}+ column={column}+ sortKey={sortKey}+ sortOrder={sortOrder}+ onSort={onSort}+ />+ ))}+ </div>+ <List<VirtualizedRowProps>+ style={{ height: height - HEADER_HEIGHT, width: rowWidth }}+ overscanCount={10}+ rowCount={rows.length}+ rowHeight={ROW_HEIGHT}+ rowComponent={VirtualizedRow}+ rowProps={rowProps}+ />+ </div>+ </div>+ )+ }}+ />+ </div>+ )+}diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.tsindex b94c43102e45..a34c710a5bcf 100644--- a/products/tracing/frontend/tracingSceneLogic.ts+++ b/products/tracing/frontend/tracingSceneLogic.ts@@ -92,6 +92,7 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([closeCompareFlame: true,syncUrlAndRunQuery: true,handleFilterChange: (filterType: string, extraProps?: Record<string, unknown>) => ({ filterType, extraProps }),+ setActiveTracingTab: (tab: 'traces' | 'operations') => ({ tab }),}),reducers({@@ -149,6 +150,12 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([closeCompareFlame: () => null,},],+ activeTracingTab: [+ 'traces' as 'traces' | 'operations',+ {+ setActiveTracingTab: (_, { tab }) => tab,+ },+ ],}),selectors({@@ -213,6 +220,10 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([handleFilterChange: ({ filterType, extraProps }) => {posthog.capture('tracing filter changed', { filter_type: filterType, ...extraProps })actions.syncUrlAndRunQuery()+ // Keep the Operations aggregate in sync with filters/date while that tab is active.+ if (values.activeTracingTab === 'operations') {+ actions.fetchAggregation()+ }},setDateRange: () => actions.handleFilterChange('date_range'),setServiceNames: () => actions.handleFilterChange('service_names'),@@ -236,6 +247,11 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([setFilters: () => {actions.syncUrlAndRunQuery()},+ setActiveTracingTab: ({ tab }) => {+ if (tab === 'operations') {+ actions.fetchAggregation()+ }+ },})),urlToAction(({ actions, values }) => ({