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 an operations tab to the trace view inspector (#120200)

Roy Cohen2180821ddbe1
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index e2e3948b7201..ac7bbb149132 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -8184,6 +8184,30 @@ snapshots:
hash: v1.k794b7964.d6977b391a9f26309799ef1ef522b6834aa7f0e23dab4e293069c58c2a0b54e4.IwwwLP99sni7rCWBvJCE_8dpsla1s7t7mGMyixDS0rI
products-tracing-traceaieventscapnotice--past-the-cap--light:
hash: v1.k794b7964.feda0df05e8e57c124b6730048dd57d0d678d429c263cff2c5fcb575f945b280.ahdaUiPk9d3Xp8PlnXG7oy3Y5sUkAslXiNwntmQsWAk
+ products-tracing-traceoperationstab--narrowest--dark:
+ hash: v1.k794b7964.9c1ed31c4c0123f4bfbc23b18606aa98d324c6f0bc919791690bbbe57ea74e47.w0TlHrz2y0DG_KB0biW0_61gj4rVsgOHfoFAjAVDuxQ
+ products-tracing-traceoperationstab--narrowest--light:
+ hash: v1.k794b7964.62833e302020c19c9f6be1e1436d2db8898252d7178caa08c57821fe577c6d02.k_FL7WgvVIU1VuHM9h2p1FJIy--kSDO510qQzqa8lJE
+ products-tracing-traceoperationstab--this-span--dark:
+ hash: v1.k794b7964.80d69a88e5459b0770a3dac91d2750bf707d73d15fc4611f546becae49bdf42c.UkrWzdmXzYHTRV8aTSKev-xcgxk0qiV2ryJYQlyJFb0
+ products-tracing-traceoperationstab--this-span--light:
+ hash: v1.k794b7964.0029a54b1ed3d124f160eaf5fefbcbb3883c3fa5a38f5f511db34efb7bdb8f52.m4zlAEr4bOCgl3_0RJA4e7JcE3MF7PJx6uBEYtXGO_c
+ products-tracing-traceoperationstab--whole-trace--dark:
+ hash: v1.k794b7964.6dc7a084dd321fd06596321dd67acc4c424ec54dc58646427fc863105982d9d4.aweoLqJcroGF4_Wc72w-KYqW9qLFz4SK_jxZYHkkJHA
+ products-tracing-traceoperationstab--whole-trace--light:
+ hash: v1.k794b7964.e1b29c6cfe8146f2803560536ec0cf935a0fc779d0f3f4bd201d26fe1559cdf2.YzMszjrf7rj1FxjKUzouXM3hJUFSXRqHEEYdUzn8ULE
+ products-tracing-traceoperationstable--capped--dark:
+ hash: v1.k794b7964.49420bc8c5771bb9dfa92e0cb236f323d9fc2b5efa6f07bae31d5027824e2473._ToUBlZDL1Dvmsg2NsOAOiqMLRaL8d1bTkGp9m0urm0
+ products-tracing-traceoperationstable--capped--light:
+ hash: v1.k794b7964.026c9915e99086e2546f09ad8d6c5c8be601548c946857b3627707753e133dff.qFIHmevdw80OgGlXTA8dBRLH2OMneoXCsEdRgbZxICk
+ products-tracing-traceoperationstable--default--dark:
+ hash: v1.k794b7964.54be2633e637c6c87bf6f058455f8ee6debff77f2ed6e8825a00e72e65a2cf79.ja3KUOj2KtArkDB-k8GvVY7uxfc3h7Zg0WcVi--kHqs
+ products-tracing-traceoperationstable--default--light:
+ hash: v1.k794b7964.3e1f071f75aaf78b8156d01b486535db7f37d6e64138d80abb0b989b0790e366.1R-nOKXm0aHOec5sMsUK5_AEksbkdc8ImVXX7y8Psxo
+ products-tracing-traceoperationstable--narrow--dark:
+ hash: v1.k794b7964.a5725d637781462f2220d218173853b210c750d09f2c0c9b8ed42ed3d0b86601.te8Ga3QG0gpkuXBfSi1mBNfy59G_Z4G8FlCl4L8ZzxA
+ products-tracing-traceoperationstable--narrow--light:
+ hash: v1.k794b7964.6d769306bbfd3f220d7cebc460c066e3712fbac76961c751422274d000322fa5.0mR0sL4fZ9_06uBaXMtRmRVbQLvpD8U_ybLKTDK4Z5w
products-tracing-virtualizedspanlist--custom-columns--dark:
hash: v1.k794b7964.706ec8b392aa8b7e63123ae73233f0aa49314df1f4c32894f6f48c7883c35cf3.4royX3fTwY_wCZ7DXohmhbu1njNM4B7nRI6YgxJaKiw
products-tracing-virtualizedspanlist--custom-columns--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 6932b8974826..3c8f48b23fbb 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -560,6 +560,7 @@ export const FEATURE_FLAGS = {
TRACING_SETTINGS_RETENTION_RULES: 'tracing-settings-retention-rules', // owner: #team-apm — gates the span retention rules in tracing settings
TRACING_SPAN_ERROR_BADGES: 'tracing-span-error-badges', // owner: #team-apm, badges span rows whose session hit errors and adds the Errors tab to the trace drawer
TRACING_TRACE_DIALOG: 'tracing-trace-dialog', // owner: #team-apm — opens traces in a dialog over the current page instead of navigating to tracing
+ TRACING_TRACE_OPERATIONS_TAB: 'tracing-trace-operations-tab', // owner: #team-apm — gates the Operations tab in the trace view's span inspector
TRACING_UI_V2: 'tracing-ui-v2',
TRAFFIC_TYPE_VIRTUAL_PROPERTIES: 'traffic-type-virtual-properties', // owner: #team-web-analytics
UNIFIED_APM_PRODUCT: 'unified-apm-product', // owner: #team-apm (@jonmcwest, @frankh), gates the shared APM product backing logs, tracing, and metrics
diff --git a/products/tracing/frontend/VirtualizedTable.tsx b/products/tracing/frontend/VirtualizedTable.tsx
index e97f969d75a0..7c122d5747de 100644
--- a/products/tracing/frontend/VirtualizedTable.tsx
+++ b/products/tracing/frontend/VirtualizedTable.tsx
@@ -20,9 +20,21 @@ import { ResizableColumns, useResizableColumns } from './components/TableColumns
const ROW_HEIGHT = 44
const HEADER_HEIGHT = 32
+/** The table frame's `border` class, on the top and the bottom. */
+const FRAME_BORDER_WIDTH = 1
+
+/** Height of a table that shows the header and `rowCount` rows with no vertical scroll. */
+export function virtualizedTableHeight(rowCount: number): number {
+ return HEADER_HEIGHT + rowCount * ROW_HEIGHT + 2 * FRAME_BORDER_WIDTH
+}
export type VirtualizedSortOrder = 1 | -1
+export interface VirtualizedSort {
+ columnKey: string
+ order: VirtualizedSortOrder
+}
+
export interface VirtualizedTableColumn<T> {
key: string
title: ReactNode
@@ -87,6 +99,7 @@ interface VirtualizedRowProps {
dataSource: any[]
rowKey: (record: any) => string
onRowClick?: (record: any) => void
+ rowClassName?: (record: any) => string | undefined
}
function VirtualizedRow({
@@ -98,6 +111,7 @@ function VirtualizedRow({
dataSource,
rowKey,
onRowClick,
+ rowClassName,
}: {
ariaAttributes: { 'aria-posinset': number; 'aria-setsize': number; role: 'listitem' }
index: number
@@ -115,7 +129,8 @@ function VirtualizedRow({
<div
className={cn(
'flex items-center border-b border-border hover:bg-surface-primary-hover',
- onRowClick && 'cursor-pointer'
+ onRowClick && 'cursor-pointer',
+ rowClassName?.(record)
)}
// eslint-disable-next-line react/forbid-dom-props
style={{ height: ROW_HEIGHT }}
@@ -151,7 +166,15 @@ export interface VirtualizedTableProps<T> {
loading: boolean
rowKey: (record: T) => string
onRowClick?: (record: T) => void
- defaultSort?: { columnKey: string; order: VirtualizedSortOrder }
+ /** Extra classes for one row, such as a highlight. */
+ rowClassName?: (record: T) => string | undefined
+ defaultSort?: VirtualizedSort
+ /**
+ * Controlled sort, which replaces `defaultSort` and the table's own sort state. A caller that sorts its
+ * full list before it cuts the list down owns the sort, because the table sees only the rows it gets.
+ */
+ sort?: VirtualizedSort | null
+ onSortChange?: (sort: VirtualizedSort | null) => void
emptyLabel?: string
'data-attr'?: string
}
@@ -163,12 +186,17 @@ export function VirtualizedTable<T>({
loading,
rowKey,
onRowClick,
+ rowClassName,
defaultSort,
+ sort: controlledSort,
+ onSortChange,
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 [internalSort, setInternalSort] = useState<VirtualizedSort | null>(defaultSort ?? null)
+ const sort = controlledSort === undefined ? internalSort : controlledSort
+ const sortKey = sort?.columnKey ?? null
+ const sortOrder = sort?.order ?? -1
const resizableColumns = useResizableColumns(tableKey, columns)
const rows = useMemo(() => {
@@ -180,12 +208,11 @@ export function VirtualizedTable<T>({
}, [dataSource, columns, sortKey, sortOrder])
const onSort = (key: string): void => {
- if (key === sortKey) {
- setSortOrder((order) => (order === 1 ? -1 : 1))
- } else {
- setSortKey(key)
- setSortOrder(-1)
+ const next: VirtualizedSort = { columnKey: key, order: key === sortKey && sortOrder === -1 ? 1 : -1 }
+ if (controlledSort === undefined) {
+ setInternalSort(next)
}
+ onSortChange?.(next)
}
if (rows.length === 0) {
@@ -235,7 +262,7 @@ export function VirtualizedTable<T>({
rowCount={rows.length}
rowHeight={ROW_HEIGHT}
rowComponent={VirtualizedRow}
- rowProps={{ columns, widths, dataSource: rows, rowKey, onRowClick }}
+ rowProps={{ columns, widths, dataSource: rows, rowKey, onRowClick, rowClassName }}
/>
</div>
</div>
diff --git a/products/tracing/frontend/components/SpanInspector/SpanInspector.tsx b/products/tracing/frontend/components/SpanInspector/SpanInspector.tsx
index 7cef3d4eef7a..5c52dff79a73 100644
--- a/products/tracing/frontend/components/SpanInspector/SpanInspector.tsx
+++ b/products/tracing/frontend/components/SpanInspector/SpanInspector.tsx
@@ -17,6 +17,8 @@ import { SpanLogsTab } from '../TraceDrawer/SpanLogsTab'
import { SpanMetricsTab } from '../TraceDrawer/SpanMetricsTab'
import { SpanSummaryHeader } from '../TraceDrawer/SpanSummaryHeader'
import { TraceErrorsTab } from '../TraceDrawer/TraceErrorsTab'
+import { TraceOperationsTab } from '../TraceView/TraceOperationsTab'
+import type { TraceOperationsScope } from '../TraceView/traceViewLogic'
import { ExpandedSpanContent } from '../VirtualizedSpanList/ExpandedSpanContent'
export interface SpanInspectorProps {
@@ -34,9 +36,22 @@ export interface SpanInspectorProps {
/** The spans the session is resolved from are still arriving. */
resolving: boolean
tab: SpanInspectorTab
- onSelectTab: (tab: SpanInspectorTab) => void
+ /**
+ * Called for every tab click. `changesShownTab` is false for a click on the tab already on screen, which is
+ * not always `tab`: a tab this span cannot show falls back to Attributes.
+ */
+ onSelectTab: (tab: SpanInspectorTab, changesShownTab: boolean) => void
/** Offer include, exclude and column actions on each attribute. Off where no span list can use them. */
showFilterActions?: boolean
+ /** Show the Operations tab, which breaks the trace down by operation. Omit where nothing shows the highlight. */
+ operations?: {
+ /** The trace's real spans. AI event rows are synthetic and have no operation of their own. */
+ spans: Span[]
+ highlightedOperationKey: string | null
+ onHighlightOperation: (operationKey: string | null, scope: TraceOperationsScope) => void
+ /** The trace has spans that are not loaded yet, so the counts do not cover the whole trace. */
+ partial: boolean
+ }
}
export function SpanInspector({
@@ -50,6 +65,7 @@ export function SpanInspector({
tab,
onSelectTab,
showFilterActions = true,
+ operations,
}: SpanInspectorProps): JSX.Element {
const { featureFlags } = useValues(featureFlagLogic)
@@ -60,14 +76,15 @@ export function SpanInspector({
// Only DB spans carry a query; the Query tab appears only when one is present.
const queryText = getQueryText(span)
- // The Query, Errors and Metrics tabs are conditional, so if the active tab disappears (a span
- // without a query, or one of the gates turning off), fall back to Attributes. Otherwise
- // activeKey would point at a tab LemonTabs has dropped and the inspector body would render
- // blank. Preference is preserved: a DB span re-shows Query.
+ // The Query, Errors, Operations and Metrics tabs are conditional, so if the active tab disappears
+ // (a span without a query, a caller without operations, or one of the gates turning off), fall
+ // back to Attributes. Otherwise activeKey would point at a tab LemonTabs has dropped and the
+ // inspector body would render blank. Preference is preserved: a DB span re-shows Query.
const activeTab: SpanInspectorTab =
(tab === 'query' && !queryText) ||
(tab === 'metrics' && !showMetricsTab) ||
- (tab === 'errors' && !showErrorsTab)
+ (tab === 'errors' && !showErrorsTab) ||
+ (tab === 'operations' && !operations)
? 'attributes'
: tab
@@ -76,7 +93,7 @@ export function SpanInspector({
<SpanSummaryHeader span={span} serviceColorMap={serviceColorMap} />
<LemonTabs
activeKey={activeTab}
- onChange={onSelectTab}
+ onChange={(next) => onSelectTab(next, next !== activeTab)}
data-attr="tracing-inspector-tabs"
tabs={[
{
@@ -134,6 +151,17 @@ export function SpanInspector({
),
}
: null,
+ // Conditional: only a caller whose span tree shows the highlight that a row click sets
+ // passes operations.
+ operations
+ ? {
+ key: 'operations',
+ label: 'Operations',
+ // Keyed by trace like the Logs tab: a new trace remounts to reset the scope
+ // toggle; selecting another span re-renders in place.
+ content: <TraceOperationsTab key={span.trace_id} span={span} {...operations} />,
+ }
+ : null,
// Conditional: needs the metrics product (flag + access) and its own flag.
showMetricsTab
? {
diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx
index 62d862e43d08..5bbd52f44c25 100644
--- a/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx
+++ b/products/tracing/frontend/components/TraceDialog/TraceDialog.tsx
@@ -100,11 +100,14 @@ export function TraceDialog(): JSX.Element | null {
) : (
<TraceView
traceId={trace.traceId}
+ surface="trace_dialog"
inspectorOpen={inspectorOpen}
sessionId={traceSessionId}
showErrorsTab={sessionErrorBadgesEnabled}
openedFrom={openedFrom}
openedAtUs={openedAtUs}
+ // The dialog loads a capped number of pages and offers Open in Tracing for the rest.
+ spansPartial={traceSpans.truncated}
/>
)}
</TraceViewDrawer>
diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogMoreSpansRow.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogMoreSpansRow.tsx
index 30b5951e18c3..8272f54e07e0 100644
--- a/products/tracing/frontend/components/TraceDialog/TraceDialogMoreSpansRow.tsx
+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogMoreSpansRow.tsx
@@ -1,14 +1,18 @@
import { LemonButton } from '@posthog/lemon-ui'
+import { cn } from 'lib/utils/css-classes'
+
import type { TraceDialogRow } from './traceDialogRows'
import { indentPx, TraceDialogTreeLines } from './TraceDialogTreeLines'
export interface TraceDialogMoreSpansRowProps {
row: Extract<TraceDialogRow, { kind: 'more' }>
+ /** None of the hidden spans belongs to the operation the Operations tab highlights. */
+ isDimmed: boolean
onShowAll: (spanId: string) => void
}
-export function TraceDialogMoreSpansRow({ row, onShowAll }: TraceDialogMoreSpansRowProps): JSX.Element {
+export function TraceDialogMoreSpansRow({ row, isDimmed, onShowAll }: TraceDialogMoreSpansRowProps): JSX.Element {
const { parent, hiddenCount } = row
return (
// Same columns and no gap as the span row, so the tree lines on both line up at any width.
@@ -20,7 +24,7 @@ export function TraceDialogMoreSpansRow({ row, onShowAll }: TraceDialogMoreSpans
style={{ paddingLeft: indentPx(row.depth) + 22 }}
>
<TraceDialogTreeLines row={row} />
- <span className="relative">
+ <span className={cn('relative', isDimmed && 'opacity-40')}>
{hiddenCount.toLocaleString()} more {hiddenCount === 1 ? 'span' : 'spans'}
</span>
<LemonButton
diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanRow.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanRow.tsx
index fadf69774921..5152c2ac8c0d 100644
--- a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanRow.tsx
+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanRow.tsx
@@ -23,6 +23,8 @@ export interface TraceDialogSpanRowProps {
/** Set only on the span that emitted the record the dialog was opened from. */
openedAtUs: number | null
openedFrom: TraceDialogSource | null
+ /** The row is outside the operation the Operations tab highlights. */
+ isDimmed: boolean
/** How many spans sit under this one. Zero for a span with no children. */
descendantCount: number
isCollapsed: boolean
@@ -53,6 +55,7 @@ export function TraceDialogSpanRow({
isSelected,
openedAtUs,
openedFrom,
+ isDimmed,
descendantCount,
isCollapsed,
onSelect,
@@ -76,7 +79,7 @@ export function TraceDialogSpanRow({
// A folded chain shows an error when any span in it errored, not only its first.
const isError = (row.kind === 'chain' ? row.nodes : [node]).some((member) => member.span.status_code === 2)
const serviceColor = getSeriesColor(serviceColorMap.get(span.service_name) ?? 0)
- const barColor = isError ? ERROR_COLOR : serviceColor
+ const barColor = isDimmed ? 'var(--border)' : isError ? ERROR_COLOR : serviceColor
const openedAtPct =
openedAtUs != null && openedFrom ? Math.min(Math.max(percentOfTrace(openedAtUs, timeline), 0), 100) : null
@@ -166,7 +169,8 @@ export function TraceDialogSpanRow({
'relative truncate font-mono',
(isError || isMissingParent) && 'text-danger',
chainLast && 'text-secondary',
- isSelected && 'font-semibold'
+ isSelected && 'font-semibold',
+ isDimmed && 'opacity-40'
)}
translate="no"
>
diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.test.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.test.tsx
index dcecc20261d8..923620337274 100644
--- a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.test.tsx
+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.test.tsx
@@ -1,13 +1,16 @@
import '@testing-library/jest-dom'
-import { cleanup, render, waitFor } from '@testing-library/react'
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react'
import { BindLogic, Provider } from 'kea'
import { expectLogic } from 'kea-test-utils'
import api from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { initKeaTests } from '~/test/init'
+import { compareRowKey } from 'products/tracing/frontend/compareUtils'
import type { Span } from 'products/tracing/frontend/types'
import { traceViewLogic } from '../TraceView/traceViewLogic'
@@ -45,6 +48,7 @@ describe('TraceDialogSpanTree', () => {
afterEach(() => {
cleanup()
jest.restoreAllMocks()
+ delete (Element.prototype as Partial<Element>).scrollTo
})
it('renders a loaded trace and steps the selection with J', async () => {
@@ -75,4 +79,77 @@ describe('TraceDialogSpanTree', () => {
)
)
})
+
+ // Fails when the highlight dims by the wrong key, or dims a folded chain that hides a span of the
+ // operation, which would tell the person the operation is not in there.
+ it('dims the rows outside the highlighted operation', async () => {
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TRACING_TRACE_OPERATIONS_TAB]: true })
+ const view = traceViewLogic({ id: 'span-tree-test' })
+ view.mount()
+ view.actions.showTrace(null, 'operations')
+ // ROOT > A, B and B > C > D > E > F, where A and D are the operation and C to E fold into a chain.
+ view.actions.setSpans([
+ span('ROOT', ''),
+ { ...span('A', 'ROOT'), name: 'cache GET' },
+ span('B', 'ROOT'),
+ span('C', 'B'),
+ { ...span('D', 'C'), name: 'cache GET' },
+ span('E', 'D'),
+ span('F', 'E'),
+ ])
+ view.actions.highlightOperation(compareRowKey({ service_name: 'agent-worker', name: 'cache GET' }))
+
+ render(
+ <Provider>
+ <BindLogic logic={traceViewLogic} props={{ id: 'span-tree-test' }}>
+ <TraceDialogSpanTree openedFrom={null} openedAtUs={null} />
+ </BindLogic>
+ </Provider>
+ )
+
+ await screen.findByText('cache GET')
+ const isDimmed = (name: string): boolean => screen.getByText(name).classList.contains('opacity-40')
+ expect(isDimmed('cache GET')).toBe(false)
+ expect(isDimmed('C span › … › E span')).toBe(false)
+ expect([isDimmed('ROOT span'), isDimmed('B span'), isDimmed('F span')]).toEqual([true, true, true])
+ })
+
+ // Fails when the page of spans that the scroll to the operation loads pulls the list back to the selected
+ // span, which leaves the highlighted spans off screen.
+ it('keeps the highlighted operation in view when another page of spans loads', async () => {
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TRACING_TRACE_OPERATIONS_TAB]: true })
+ const view = traceViewLogic({ id: 'span-tree-page-test' })
+ view.mount()
+ view.actions.showTrace(null, 'operations')
+ // ROOT > P0 to P9 > five spans each: 61 rows, more than the list shows. The last row is the operation.
+ const spans = [span('ROOT', ''), ...Array.from({ length: 10 }, (_, i) => span(`P${i}`, 'ROOT'))]
+ for (let i = 0; i < 10; i++) {
+ spans.push(...Array.from({ length: 5 }, (_, j) => span(`Q${i}-${j}`, `P${i}`)))
+ }
+ spans[spans.length - 1] = { ...spans[spans.length - 1], name: 'cache GET' }
+ view.actions.setSpans(spans)
+ // jsdom does not scroll, so a scroll sets the offset the list reads and fires the event it listens for.
+ Element.prototype.scrollTo = function (this: Element, options?: ScrollToOptions | number) {
+ this.scrollTop = typeof options === 'object' ? (options.top ?? 0) : 0
+ this.dispatchEvent(new Event('scroll'))
+ }
+ const onLoadMore = jest.fn()
+ render(
+ <Provider>
+ <BindLogic logic={traceViewLogic} props={{ id: 'span-tree-page-test' }}>
+ <TraceDialogSpanTree openedFrom={null} openedAtUs={null} hasMore onLoadMore={onLoadMore} />
+ </BindLogic>
+ </Provider>
+ )
+ await screen.findByText('ROOT span')
+
+ act(() => view.actions.highlightOperation(compareRowKey({ service_name: 'agent-worker', name: 'cache GET' })))
+ await screen.findByText('cache GET')
+ expect(onLoadMore).toHaveBeenCalled()
+ act(() => view.actions.setSpans([...spans, span('LATE', 'P9')]))
+
+ expect(screen.getByText('cache GET')).toBeInTheDocument()
+ })
})
diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx
index 7c0a69010d58..032938529cff 100644
--- a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx
+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx
@@ -29,6 +29,8 @@ interface SpanListRowData {
openedSpanId: string | null
openedAtUs: number | null
openedFrom: TraceDialogSource | null
+ /** Per row, whether it stands for a span of the highlighted operation. Null when nothing dims. */
+ operationRowMatches: boolean[] | null
onSelect: (spanId: string) => void
onToggleCollapsed: (spanId: string) => void
onToggleChain: (spanId: string) => void
@@ -46,6 +48,7 @@ function SpanListRow({
openedSpanId,
openedAtUs,
openedFrom,
+ operationRowMatches,
onShowAll,
...rowProps
}: {
@@ -54,11 +57,12 @@ function SpanListRow({
style: CSSProperties
} & SpanListRowData): JSX.Element {
const row = spanRows[index]
+ const isDimmed = operationRowMatches != null && !operationRowMatches[index]
return (
// eslint-disable-next-line react/forbid-dom-props
<div {...ariaAttributes} style={style}>
{row.kind === 'more' ? (
- <TraceDialogMoreSpansRow row={row} onShowAll={onShowAll} />
+ <TraceDialogMoreSpansRow row={row} isDimmed={isDimmed} onShowAll={onShowAll} />
) : (
<SpanOrChainRow
row={row}
@@ -66,6 +70,7 @@ function SpanListRow({
openedSpanId={openedSpanId}
openedAtUs={openedAtUs}
openedFrom={openedFrom}
+ isDimmed={isDimmed}
descendantCounts={descendantCounts}
collapsedSpanIds={collapsedSpanIds}
rowProps={rowProps}
@@ -81,6 +86,7 @@ function SpanOrChainRow({
openedSpanId,
openedAtUs,
openedFrom,
+ isDimmed,
descendantCounts,
collapsedSpanIds,
rowProps,
@@ -90,6 +96,7 @@ function SpanOrChainRow({
openedSpanId: string | null
openedAtUs: number | null
openedFrom: TraceDialogSource | null
+ isDimmed: boolean
descendantCounts: Map<string, number>
collapsedSpanIds: Set<string>
rowProps: Pick<SpanListRowData, 'timeline' | 'serviceColorMap' | 'onSelect' | 'onToggleCollapsed' | 'onToggleChain'>
@@ -101,6 +108,7 @@ function SpanOrChainRow({
isSelected={spanId === selectedSpanId}
openedAtUs={spanId === openedSpanId ? openedAtUs : null}
openedFrom={spanId === openedSpanId ? openedFrom : null}
+ isDimmed={isDimmed}
descendantCount={descendantCounts.get(spanId) ?? 0}
isCollapsed={collapsedSpanIds.has(spanId)}
{...rowProps}
@@ -131,6 +139,8 @@ export interface TraceDialogSpanTreeProps {
hasMore?: boolean
loadingMore?: boolean
onLoadMore?: () => void
+ /** Dim the rows outside the highlighted operation. Off while the inspector, which explains the dimming, is hidden. */
+ showOperationHighlight?: boolean
}
export function TraceDialogSpanTree({
@@ -139,6 +149,7 @@ export function TraceDialogSpanTree({
hasMore = false,
loadingMore = false,
onLoadMore,
+ showOperationHighlight = true,
}: TraceDialogSpanTreeProps): JSX.Element {
const {
spanRows,
@@ -149,6 +160,9 @@ export function TraceDialogSpanTree({
selectedSpan,
missingParentSpanId,
pinnedSpanId: openedSpanId,
+ highlightedOperationKey,
+ operationRowMatches,
+ firstOperationRowIndex,
} = useValues(traceViewLogic)
const { selectSpan, toggleSpanCollapsed, toggleChain, showAllChildren } = useActions(traceViewLogic)
const [topIndex, setTopIndex] = useState(0)
@@ -194,12 +208,43 @@ export function TraceDialogSpanTree({
// Keep each span J and K step to in view. While the opened span still waits for its centred reveal
// above, this leaves it alone.
const selectedSpanId = missingParentSpanId ?? selectedSpan?.span_id ?? null
+ const lastSelectionInputsRef = useRef({ spanTree, selectedSpanId })
useEffect(() => {
+ const last = lastSelectionInputsRef.current
+ lastSelectionInputsRef.current = { spanTree, selectedSpanId }
+ // A page of spans loads when the person scrolls near the end of the list. It changes the rows but not
+ // the selection, so the list stays where the person scrolled it, or where an operation highlight put it.
+ if (spanTree !== last.spanTree && selectedSpanId === last.selectedSpanId) {
+ return
+ }
const index = spanRows.findIndex((row) => rowSpanNode(row)?.span.span_id === selectedSpanId)
if (index >= 0 && (selectedSpanId !== openedSpanId || revealedIndexRef.current !== null)) {
listRef.current?.scrollToRow({ index, align: 'smart' })
}
- }, [spanRows, selectedSpanId, openedSpanId, listRef])
+ }, [spanRows, spanTree, selectedSpanId, openedSpanId, listRef])
+ // The first span of a large operation often sits far down the tree, so a click on the operations table
+ // scrolls to it. The logic has already opened what hid it, so it is the first row of the operation. The
+ // `start` alignment puts it at the top, so the rest of the operation's spans fill the list below it. The
+ // ref holds the key that last scrolled, so that a later collapse, expand or page of spans does not pull
+ // the list back. This effect runs after the selection scroll above, so its scroll wins when the opened
+ // rows trigger both.
+ const scrolledOperationKeyRef = useRef<string | null>(null)
+ useEffect(() => {
+ if (highlightedOperationKey == null) {
+ scrolledOperationKeyRef.current = null
+ return
+ }
+ if (scrolledOperationKeyRef.current === highlightedOperationKey || !listRef.current) {
+ return
+ }
+ if (firstOperationRowIndex >= 0) {
+ // The opened rows can move the opened span to a new index, which the reveal in `onRowsRendered`
+ // reads as a span still to bring into view. The person steers the list now, so that reveal stops.
+ revealedIndexRef.current = openedIndex
+ listRef.current.scrollToRow({ index: firstOperationRowIndex, align: 'start' })
+ scrolledOperationKeyRef.current = highlightedOperationKey
+ }
+ }, [highlightedOperationKey, firstOperationRowIndex, openedIndex, listRef])
const pinnedAncestors = scrolledPastAncestors(spanRows[topIndex])
const hiddenAncestorCount = Math.max(pinnedAncestors.length - MAX_PINNED_ANCESTORS, 0)
@@ -280,6 +325,7 @@ export function TraceDialogSpanTree({
openedSpanId,
openedAtUs,
openedFrom,
+ operationRowMatches: showOperationHighlight ? operationRowMatches : null,
onSelect: selectSpan,
onToggleCollapsed: toggleSpanCollapsed,
onToggleChain: toggleChain,
diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts
index 4901b65a4e1c..ea3b2798b593 100644
--- a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts
+++ b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts
@@ -11,6 +11,7 @@ import { initKeaTests } from '~/test/init'
import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'
import { logsViewerModalLogic } from 'products/logs/frontend/components/LogsViewer/LogsViewerModal/logsViewerModalLogic'
+import { compareRowKey } from 'products/tracing/frontend/compareUtils'
import type { Span } from 'products/tracing/frontend/types'
import { traceViewLogic } from '../TraceView/traceViewLogic'
@@ -498,5 +499,36 @@ describe('traceDialogLogic', () => {
})
)
})
+
+ // Fails when the highlight opens what hides its first span with the toggle actions, which the dialog
+ // counts as the person's own collapse toggles.
+ it('does not count the spans a highlight opens as collapse toggles', async () => {
+ // a > b > c > d > e, so b to d fold into a chain that hides c.
+ const chain = ['a', 'b', 'c', 'd', 'e'].map((spanId, i, ids) => ({
+ ...span(spanId),
+ parent_span_id: i === 0 ? '' : ids[i - 1],
+ }))
+ getTraceSpy.mockResolvedValue({ results: chain, hasMore: false, nextOffset: null })
+ logic.actions.openTraceDialog({ traceId: 'abc123' }, { entryPoint: 'log_details' })
+ await expectLogic(logic).toDispatchActions(['loadTraceSpansSuccess'])
+ expect(view.values.openChainIds).toEqual(new Set())
+
+ view.actions.highlightOperation(
+ compareRowKey({ service_name: 'agent-worker', name: 'c' }),
+ 'trace_dialog',
+ 'span'
+ )
+ expect(view.values.openChainIds).toEqual(new Set(['b']))
+ logic.actions.closeTraceDialog()
+
+ expect(captureSpy).toHaveBeenCalledWith('tracing trace operation highlighted', {
+ surface: 'trace_dialog',
+ scope: 'span',
+ })
+ expect(captureSpy).toHaveBeenCalledWith(
+ 'tracing trace dialog closed',
+ expect.objectContaining({ collapse_toggles: 0 })
+ )
+ })
})
})
diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts
index 35b2fc450135..50da45584eb6 100644
--- a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts
+++ b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts
@@ -189,7 +189,11 @@ export interface traceDialogLogicActions {
selectSpan: (spanId: string | null) => {
spanId: string | null
} // traceViewLogic
- setInspectorTab: (tab: SpanInspectorTab) => {
+ setInspectorTab: (
+ tab: SpanInspectorTab,
+ surface?: import('../TraceView/traceViewLogic').TraceViewSurface | undefined
+ ) => {
+ surface: null | import('../TraceView/traceViewLogic').TraceViewSurface
tab: SpanInspectorTab
} // traceViewLogic
setSpans: (spans: Span[]) => {
diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogRows.test.ts b/products/tracing/frontend/components/TraceDialog/traceDialogRows.test.ts
index 4e368d8371b0..fc319b2aebba 100644
--- a/products/tracing/frontend/components/TraceDialog/traceDialogRows.test.ts
+++ b/products/tracing/frontend/components/TraceDialog/traceDialogRows.test.ts
@@ -1,7 +1,17 @@
+import { compareRowKey } from 'products/tracing/frontend/compareUtils'
import { buildSpanTree, type SpanNode } from 'products/tracing/frontend/spanTree'
import type { Span } from 'products/tracing/frontend/types'
-import { buildTraceDialogRows, countDescendantsById, rowConnectorLines, type TraceDialogRow } from './traceDialogRows'
+import {
+ buildTraceDialogRows,
+ countDescendantsById,
+ firstOperationSpan,
+ markOperationSubtrees,
+ operationRowMatches,
+ revealSpanInRows,
+ rowConnectorLines,
+ type TraceDialogRow,
+} from './traceDialogRows'
function span(spanId: string, parentSpanId: string, offsetMs: number): Span {
return {
@@ -166,4 +176,74 @@ describe('traceDialogRows', () => {
expect(rowConnectorLines(f)).toEqual([false, false])
})
})
+ // Fails when the highlight leaves the operation's first span hidden, so the tree has no row to scroll to,
+ // or when it toggles something that was already open and hides more of the tree instead.
+ it.each([
+ { hiddenBy: 'the child cap', spanId: 'c11', collapsed: [], reveal: { fullChildListSpanIds: ['root'] } },
+ {
+ hiddenBy: 'nested child caps',
+ spanId: 'd11',
+ collapsed: [],
+ reveal: { fullChildListSpanIds: ['root', 'c11'] },
+ },
+ { hiddenBy: 'a collapsed span', spanId: 'g0', collapsed: ['c0'], reveal: { collapsedSpanIds: ['c0'] } },
+ { hiddenBy: 'a folded chain', spanId: 'b', collapsed: [], reveal: { chainIds: ['a'] } },
+ { hiddenBy: 'nothing, as the head of a folded chain', spanId: 'a', collapsed: [], reveal: {} },
+ ])('reveals a span hidden by $hiddenBy', ({ spanId, collapsed, reveal }) => {
+ // The root fans out to x and c0 to c11, so c9 to c11 sit past the cap. c11 fans out to d0 to d11 in
+ // turn. c0 has a child g0, and x > a > b > c > d folds a to c into a chain.
+ const tree = buildSpanTree([
+ span('root', '', 0),
+ span('x', 'root', 5),
+ ...Array.from({ length: 12 }, (_, i) => span(`c${i}`, 'root', 10 + i)),
+ ...Array.from({ length: 12 }, (_, i) => span(`d${i}`, 'c11', 30 + i)),
+ span('g0', 'c0', 11),
+ span('a', 'x', 6),
+ span('b', 'a', 7),
+ span('c', 'b', 8),
+ span('d', 'c', 9),
+ ])
+ const target = firstOperationSpan(tree, compareRowKey({ service_name: 'agent-worker', name: spanId }))
+
+ expect(
+ revealSpanInRows(tree, target!, {
+ collapsedSpanIds: new Set(collapsed),
+ fullChildListSpanIds: new Set(),
+ openChainIds: new Set(),
+ pinned: null,
+ })
+ ).toEqual({ collapsedSpanIds: [], fullChildListSpanIds: [], chainIds: [], ...reveal })
+ })
+ // Fails when a row that hides a span of the operation dims, which tells the person the operation is not in
+ // there, or when a collapsed span lights up for a match it does not hold.
+ it.each([
+ { row: 'a collapsed span with a match under it', label: 'c0', operation: 'g0', matches: true },
+ { row: 'a collapsed span with no match under it', label: 'c0', operation: 'c1', matches: false },
+ { row: 'a more row with a match under a hidden child', label: '+2', operation: 'h', matches: true },
+ ])('matches $row: $matches', ({ label, operation, matches }) => {
+ // The root fans out to c0 to c11, so c10 and c11 sit past the cap. c0 has a child g0, and c11 has h.
+ const tree = buildSpanTree([
+ span('root', '', 0),
+ ...Array.from({ length: 12 }, (_, i) => span(`c${i}`, 'root', 10 + i)),
+ span('g0', 'c0', 11),
+ span('h', 'c11', 22),
+ ])
+ const collapsedSpanIds = new Set(['c0'])
+ const rows = buildTraceDialogRows(tree, {
+ collapsedSpanIds,
+ fullChildListSpanIds: new Set(),
+ openChainIds: new Set(),
+ pinned: null,
+ })
+ const operationKey = compareRowKey({ service_name: 'agent-worker', name: operation })
+
+ const rowMatches = operationRowMatches(
+ rows,
+ operationKey,
+ markOperationSubtrees(tree, operationKey),
+ collapsedSpanIds
+ )
+
+ expect(rowMatches[labels(rows).indexOf(label)]).toBe(matches)
+ })
})
diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogRows.ts b/products/tracing/frontend/components/TraceDialog/traceDialogRows.ts
index b34ae33bbb7b..ef4a375013ad 100644
--- a/products/tracing/frontend/components/TraceDialog/traceDialogRows.ts
+++ b/products/tracing/frontend/components/TraceDialog/traceDialogRows.ts
@@ -1,3 +1,4 @@
+import { compareRowKey } from 'products/tracing/frontend/compareUtils'
import { parseTimestampUs, type SpanNode } from 'products/tracing/frontend/spanTree'
// A wide fan-out shows this many children until the person asks for the rest.
@@ -20,7 +21,8 @@ export type TraceDialogRow = TraceDialogRowBase &
}
/** The first span stands for the chain in selection and the inspector. */
| { kind: 'chain'; nodes: SpanNode[] }
- | { kind: 'more'; parent: SpanNode; hiddenCount: number }
+ /** `hidden` holds the children past the cap, in start order. */
+ | { kind: 'more'; parent: SpanNode; hiddenCount: number; hidden: SpanNode[] }
)
export function rowSpanNode(row: TraceDialogRow): SpanNode | null {
@@ -52,6 +54,14 @@ export function countDescendantsById(roots: SpanNode[]): Map<string, number> {
return counts
}
+/**
+ * Whether a parent's child cap hides the sibling at `index`. `siblings` are in start order. A sibling on the path to
+ * the pinned span always shows.
+ */
+function childCapHides<T>(siblings: T[], index: number, isPinned: (sibling: T) => boolean): boolean {
+ return siblings.length > TRACE_DIALOG_CHILD_LIMIT && index >= TRACE_DIALOG_CHILD_LIMIT && !isPinned(siblings[index])
+}
+
function singleChildRun(first: SpanNode, collapsedSpanIds: Set<string>): SpanNode[] {
const run: SpanNode[] = []
let node: SpanNode | undefined = first
@@ -86,12 +96,14 @@ export function buildTraceDialogRows(
// span in a run. Marking them keeps a deep pinned chain to one scan instead of one per member.
const noFold = new Set<SpanNode>()
const stack: (Pending | TraceDialogRow)[] = []
+ const isOnPinnedPath = (node: SpanNode): boolean => pinnedPath.has(node)
const pushChildren = (children: SpanNode[], owner: SpanNode, depth: number, parentRow: TraceDialogRow): void => {
- let shown = byStart(children)
- if (shown.length > TRACE_DIALOG_CHILD_LIMIT && !fullChildListSpanIds.has(owner.span.span_id)) {
- shown = shown.filter((child, i) => i < TRACE_DIALOG_CHILD_LIMIT || pinnedPath.has(child))
- }
- const hiddenCount = children.length - shown.length
+ const sorted = byStart(children)
+ const showsAll = fullChildListSpanIds.has(owner.span.span_id)
+ const isShown = (_child: SpanNode, i: number): boolean => showsAll || !childCapHides(sorted, i, isOnPinnedPath)
+ const shown = sorted.filter(isShown)
+ const hidden = sorted.filter((child, i) => !isShown(child, i))
+ const hiddenCount = hidden.length
const next: (Pending | TraceDialogRow)[] = shown.map((child, i) => ({
node: child,
depth,
@@ -99,7 +111,7 @@ export function buildTraceDialogRows(
parentRow,
}))
if (hiddenCount > 0) {
- next.push({ kind: 'more', parent: owner, hiddenCount, depth, isLast: true, parentRow })
+ next.push({ kind: 'more', parent: owner, hiddenCount, hidden, depth, isLast: true, parentRow })
}
for (let i = next.length - 1; i >= 0; i--) {
stack.push(next[i])
@@ -156,3 +168,116 @@ export function rowConnectorLines(row: TraceDialogRow): boolean[] {
}
return lines.reverse()
}
+
+/** The spans that are of the operation (`compareRowKey`) or have one under them. One pass from the leaves up. */
+export function markOperationSubtrees(roots: SpanNode[], operationKey: string): Set<SpanNode> {
+ const order: SpanNode[] = []
+ const stack = [...roots]
+ while (stack.length > 0) {
+ const node = stack.pop()!
+ order.push(node)
+ stack.push(...node.children)
+ }
+ const marked = new Set<SpanNode>()
+ // Children come after their parent in `order`, so walking it backwards marks each child first.
+ for (let i = order.length - 1; i >= 0; i--) {
+ const node = order[i]
+ if (compareRowKey(node.span) === operationKey || node.children.some((child) => marked.has(child))) {
+ marked.add(node)
+ }
+ }
+ return marked
+}
+
+/**
+ * Which rows stand for a span of the operation. A row stands for its own span and for every span it hides: the
+ * members of a folded chain, the spans under a collapsed span, and the children past the cap with every span
+ * under them. Nothing else on screen shows those spans, so a hidden match keeps its row bright.
+ */
+export function operationRowMatches(
+ rows: TraceDialogRow[],
+ operationKey: string,
+ subtreeMarks: Set<SpanNode>,
+ collapsedSpanIds: Set<string>
+): boolean[] {
+ return rows.map((row) => {
+ if (row.kind === 'chain') {
+ return row.nodes.some((node) => compareRowKey(node.span) === operationKey)
+ }
+ if (row.kind === 'more') {
+ return row.hidden.some((child) => subtreeMarks.has(child))
+ }
+ return collapsedSpanIds.has(row.node.span.span_id)
+ ? subtreeMarks.has(row.node)
+ : compareRowKey(row.node.span) === operationKey
+ })
+}
+
+/** The first span of the operation in the order the fully open tree lists spans: depth first, siblings by start. */
+export function firstOperationSpan(roots: SpanNode[], operationKey: string): SpanNode | null {
+ const stack = byStart(roots).reverse()
+ while (stack.length > 0) {
+ const node = stack.pop()!
+ if (compareRowKey(node.span) === operationKey) {
+ return node
+ }
+ stack.push(...byStart(node.children).reverse())
+ }
+ return null
+}
+
+/** What hides a span from the rows, as the ids each `traceViewLogic` action opens. */
+export interface TraceDialogReveal {
+ /** Collapsed ancestors, for `toggleSpanCollapsed`. */
+ collapsedSpanIds: string[]
+ /** Ancestors whose child cap hides the path to the span, for `showAllChildren`. */
+ fullChildListSpanIds: string[]
+ /** The first span of the folded chain that hides the span, for `toggleChain`. */
+ chainIds: string[]
+}
+
+/** `node` and the spans above it, root first. */
+function pathFromRoot(node: SpanNode): SpanNode[] {
+ const path: SpanNode[] = []
+ for (let ancestor: SpanNode | null = node; ancestor; ancestor = ancestor.parent) {
+ path.push(ancestor)
+ }
+ return path.reverse()
+}
+
+/** The ids to open so that `target` gets a row of its own, or heads a folded chain, which shows its name. */
+export function revealSpanInRows(
+ roots: SpanNode[],
+ target: SpanNode,
+ options: TraceDialogRowOptions
+): TraceDialogReveal {
+ const path = pathFromRoot(target)
+ const pinnedPath = new Set(options.pinned ? pathFromRoot(options.pinned) : [])
+ const isOnPinnedPath = (node: SpanNode): boolean => pinnedPath.has(node)
+ const collapsedSpanIds = path
+ .filter((node) => node !== target && options.collapsedSpanIds.has(node.span.span_id))
+ .map((node) => node.span.span_id)
+ // With the collapsed ancestors open, only the child caps along the path can still hide the target. A folded
+ // chain holds spans with one child each, so no cap sits inside one. One walk down the path finds every cap.
+ const fullChildListSpanIds: string[] = []
+ for (const node of path) {
+ if (!node.parent || options.fullChildListSpanIds.has(node.parent.span.span_id)) {
+ continue
+ }
+ const siblings = byStart(node.parent.children)
+ if (childCapHides(siblings, siblings.indexOf(node), isOnPinnedPath)) {
+ fullChildListSpanIds.push(node.parent.span.span_id)
+ }
+ }
+ // The row builder decides which runs fold, so this asks it rather than repeating its rules.
+ const collapsed = new Set(options.collapsedSpanIds)
+ collapsedSpanIds.forEach((spanId) => collapsed.delete(spanId))
+ const rows = buildTraceDialogRows(roots, {
+ ...options,
+ collapsedSpanIds: collapsed,
+ fullChildListSpanIds: new Set([...options.fullChildListSpanIds, ...fullChildListSpanIds]),
+ })
+ const chain = rows.find((row) => row.kind === 'chain' && row.nodes.includes(target))
+ const chainIds = chain?.kind === 'chain' && chain.nodes[0] !== target ? [chain.nodes[0].span.span_id] : []
+ return { collapsedSpanIds, fullChildListSpanIds, chainIds }
+}
diff --git a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.test.tsx b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.test.tsx
index 86ae1b23db4b..65e78c00aef6 100644
--- a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.test.tsx
+++ b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.test.tsx
@@ -1,6 +1,6 @@
import '@testing-library/jest-dom'
-import { cleanup, render, screen } from '@testing-library/react'
+import { cleanup, render, screen, within } from '@testing-library/react'
import { Provider } from 'kea'
import posthog from 'posthog-js'
@@ -13,6 +13,7 @@ import { tracingSpansTraceAiEventsRetrieve } from 'products/tracing/frontend/gen
import { makeSpan } from '../../__mocks__/span'
import { EMPTY_TRACE_IDENTITY } from '../../traceIdentity'
+import type { SpanInspectorTab } from '../../types'
import { traceViewLogic } from '../TraceView/traceViewLogic'
import { TraceDrawer, type TraceDrawerProps } from './TraceDrawer'
@@ -38,10 +39,10 @@ describe('TraceDrawer', () => {
captureSpy.mockRestore()
})
- const renderDrawer = (props: Partial<TraceDrawerProps>): void => {
+ const renderDrawer = (props: Partial<TraceDrawerProps>, tab: SpanInspectorTab = 'attributes'): void => {
const view = traceViewLogic({ id: 'trace-drawer-test' })
view.mount()
- view.actions.showTrace(null, 'attributes')
+ view.actions.showTrace(null, tab)
render(
<Provider>
<TraceDrawer
@@ -151,6 +152,55 @@ describe('TraceDrawer', () => {
expect(unavailableCaptures()).toEqual([])
})
+ // Fails when the view stops passing the trace's spans to the inspector: the Operations tab then
+ // disappears and the inspector falls back to Attributes. Also fails when the tab shows with its flag off,
+ // or when the flag empties the operation spans, which other views of the trace build on.
+ it.each([
+ { flagOn: true, shows: true },
+ { flagOn: false, shows: false },
+ ])('with the Operations tab flag on: $flagOn, shows the operations of the trace: $shows', ({ flagOn, shows }) => {
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TRACING_TRACE_OPERATIONS_TAB]: flagOn })
+ renderDrawer(
+ {
+ spans: [
+ makeSpan({ trace_id: 'abc123', span_id: 'span-1', is_root_span: true }),
+ makeSpan({
+ trace_id: 'abc123',
+ span_id: 'span-2',
+ parent_span_id: 'span-1',
+ is_root_span: false,
+ name: 'SELECT orders',
+ }),
+ ],
+ },
+ 'operations'
+ )
+
+ expect(screen.queryByText('Operations') !== null).toBe(shows)
+ expect(screen.queryByText('2 operations · 2 spans') !== null).toBe(shows)
+ expect(traceViewLogic({ id: 'trace-drawer-test' }).values.operationSpans).toHaveLength(2)
+ })
+
+ // Fails when a click on the tab already on screen sends the tab event. The span has no query, so the chosen
+ // Query tab falls back to Attributes, and a click on Attributes changes nothing the person sees. The click on
+ // Raw keeps the first check from passing on a tab bar that sends nothing at all.
+ it('sends the tab event only for a click that changes the tab on screen', () => {
+ renderDrawer({ spans: [makeSpan({ trace_id: 'abc123', span_id: 'span-1', is_root_span: true })] }, 'query')
+ const tabEvents = (): unknown[][] =>
+ captureSpy.mock.calls.filter(([event]) => event === 'tracing trace inspector tab changed')
+ // The tab content repeats some labels, so the clicks stay inside the tab bar.
+ const tabBar = within(
+ document.querySelector('[data-attr="tracing-inspector-tabs"] [role="tablist"]') as HTMLElement
+ )
+
+ tabBar.getByText('Attributes').click()
+ expect(tabEvents()).toEqual([])
+
+ tabBar.getByText('Raw').click()
+ expect(tabEvents()).toEqual([['tracing trace inspector tab changed', { tab: 'raw', surface: 'drawer' }]])
+ })
+
it('shows a retryable error when the AI events fetch fails and there are no spans', async () => {
mockAiEventsRetrieve.mockRejectedValueOnce(new Error('boom'))
featureFlagLogic.mount()
diff --git a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx
index 8813d96a76b1..4f24e1539cb3 100644
--- a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx
+++ b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx
@@ -168,6 +168,7 @@ export function TraceDrawer({
<TraceAiEventsCapNotice aiEvents={aiEvents} hasMore={hasMoreAiEvents} limit={aiEventsLimit} />
<TraceView
traceId={traceId ?? ''}
+ surface="drawer"
inspectorOpen={inspectorOpen}
sessionId={sessionId}
showErrorsTab={showErrorsTab}
diff --git a/products/tracing/frontend/components/TraceView/TraceOperationsTab.stories.tsx b/products/tracing/frontend/components/TraceView/TraceOperationsTab.stories.tsx
new file mode 100644
index 000000000000..f3d1404b3e36
--- /dev/null
+++ b/products/tracing/frontend/components/TraceView/TraceOperationsTab.stories.tsx
@@ -0,0 +1,96 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import type { Span } from '../../types'
+import { TraceOperationsTab } from './TraceOperationsTab'
+
+const T0 = Date.UTC(2026, 8, 3, 10, 0, 0)
+
+function span(
+ span_id: string,
+ parent_span_id: string,
+ service_name: string,
+ name: string,
+ startMs: number,
+ durationMs: number
+): Span {
+ return {
+ uuid: span_id,
+ trace_id: '0f3b7c1a5e2d48960b7a1c3e5d9f2048',
+ span_id,
+ parent_span_id,
+ name,
+ kind: parent_span_id ? 3 : 2,
+ service_name,
+ status_code: 1,
+ timestamp: new Date(T0 + startMs).toISOString(),
+ end_time: new Date(T0 + startMs + durationMs).toISOString(),
+ duration_nano: durationMs * 1_000_000,
+ is_root_span: !parent_span_id,
+ matched_filter: true,
+ attributes: {},
+ resource_attributes: {},
+ }
+}
+
+// A 3.8 s checkout trace. The first SELECT holds three of the cache reads, so "This span" has a subtree.
+const ROOT = span('root', '', 'checkout-api', 'POST /api/orders', 0, 3800)
+const SELECTS = Array.from({ length: 22 }, (_, i) =>
+ span(`select-${i}`, 'root', 'postgres', 'SELECT orders', 2 + i * 2, 18 + (i % 5) * 2)
+)
+const CACHE_GETS = Array.from({ length: 1751 }, (_, i) =>
+ i < 3
+ ? span(`cache-${i}`, 'select-0', 'checkout-api', 'cache GET', 3 + i * 2, 0.6)
+ : span(`cache-${i}`, 'root', 'checkout-api', 'cache GET', 120 + i * 2, 0.4 + (i % 7) * 0.1)
+)
+const RESERVES = Array.from({ length: 4 }, (_, i) =>
+ span(`reserve-${i}`, 'root', 'inventory', 'reserveStock', 400 + i * 700, 52)
+)
+const EMAIL = span('email', 'root', 'notifications', 'enqueueEmail', 3700, 12)
+const SPANS: Span[] = [ROOT, ...SELECTS, ...CACHE_GETS, ...RESERVES, EMAIL]
+
+const meta: Meta<typeof TraceOperationsTab> = {
+ title: 'Products/Tracing/TraceOperationsTab',
+ component: TraceOperationsTab,
+ tags: ['autodocs'],
+ args: {
+ span: ROOT,
+ spans: SPANS,
+ highlightedOperationKey: null,
+ onHighlightOperation: () => {},
+ partial: false,
+ },
+ // The table measures its container, so the story fixes the width of the inspector in a 1280px window.
+ decorators: [
+ (Story) => (
+ <div className="w-[420px]">
+ <Story />
+ </div>
+ ),
+ ],
+}
+export default meta
+
+type Story = StoryObj<typeof TraceOperationsTab>
+
+export const WholeTrace: Story = {}
+
+/** The inspector at its narrowest, 320px less its 16px left padding. Share stays in view, and long names truncate. */
+export const Narrowest: Story = {
+ decorators: [
+ (Story) => (
+ <div className="w-[304px]">
+ <Story />
+ </div>
+ ),
+ ],
+}
+
+/** One SELECT and the cache reads under it. */
+export const ThisSpan: Story = {
+ args: { span: SELECTS[0] },
+ play: async ({ canvas, userEvent }): Promise<void> => {
+ await userEvent.click(await canvas.findByText('This span'))
+ // The synthetic click leaves a focus ring that a person's click does not show.
+ ;(document.activeElement as HTMLElement | null)?.blur()
+ },
+}
diff --git a/products/tracing/frontend/components/TraceView/TraceOperationsTab.test.tsx b/products/tracing/frontend/components/TraceView/TraceOperationsTab.test.tsx
new file mode 100644
index 000000000000..f1bcecae81a6
--- /dev/null
+++ b/products/tracing/frontend/components/TraceView/TraceOperationsTab.test.tsx
@@ -0,0 +1,74 @@
+import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'
+
+import { initKeaTests } from '~/test/init'
+
+import { makeSpan } from '../../__mocks__/span'
+import { compareRowKey } from '../../compareUtils'
+import { TraceOperationsTab } from './TraceOperationsTab'
+
+// Give the table real dimensions so react-window renders its rows. AutoSizer measures 0x0 in jsdom.
+jest.mock('lib/components/AutoSizer', () => ({
+ AutoSizer: ({ renderProp }: { renderProp: (size: { height: number; width: number }) => React.ReactNode }) =>
+ renderProp({ height: 600, width: 800 }),
+}))
+
+const child = (span_id: string, parent_span_id: string, name: string): ReturnType<typeof makeSpan> =>
+ makeSpan({ uuid: span_id, span_id, parent_span_id, name, service_name: 'web', is_root_span: false })
+
+const root = makeSpan({ uuid: 'root', span_id: 'root', name: 'GET /x', service_name: 'web' })
+const select = child('select', 'root', 'SELECT')
+const SPANS = [
+ root,
+ child('cache-1', 'root', 'cache GET'),
+ child('cache-2', 'root', 'cache GET'),
+ select,
+ child('fetch', 'select', 'fetch rows'),
+ child('cache-3', 'fetch', 'cache GET'),
+]
+
+describe('TraceOperationsTab', () => {
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ afterEach(() => cleanup())
+
+ // Fails when the toggle does not change the span list the table summarizes, or when "This span"
+ // collects the wrong spans: the trace root counts 3 cache reads, and the direct children of SELECT
+ // miss the one a level further down. Also fails when the tab shows the full column set, which pushes
+ // Share out of the narrow inspector, or when a highlight reports a scope other than the one the counts are in.
+ it.each([
+ { scope: 'Whole trace', click: null, cacheGetCount: '3', header: '4 operations · 6 spans', value: 'trace' },
+ {
+ scope: 'This span',
+ click: 'This span',
+ cacheGetCount: '1',
+ header: '3 operations · 3 spans under SELECT',
+ value: 'span',
+ },
+ ])('counts the operations of the $scope scope and highlights in it', ({ click, cacheGetCount, header, value }) => {
+ const onHighlightOperation = jest.fn()
+ render(
+ <TraceOperationsTab
+ span={select}
+ spans={SPANS}
+ highlightedOperationKey={null}
+ onHighlightOperation={onHighlightOperation}
+ partial={false}
+ />
+ )
+ if (click) {
+ fireEvent.click(screen.getByText(click))
+ }
+
+ expect(screen.getByText(header)).toBeTruthy()
+ expect(screen.queryByText('Avg')).toBeNull()
+ const cacheGetRow = screen.getByText('cache GET').closest('[data-row-key]') as HTMLElement
+ expect(within(cacheGetRow).getByText(cacheGetCount)).toBeTruthy()
+
+ fireEvent.click(screen.getByText('cache GET'))
+ expect(onHighlightOperation.mock.calls).toEqual([
+ [compareRowKey({ service_name: 'web', name: 'cache GET' }), value],
+ ])
+ })
+})
diff --git a/products/tracing/frontend/components/TraceView/TraceOperationsTab.tsx b/products/tracing/frontend/components/TraceView/TraceOperationsTab.tsx
new file mode 100644
index 000000000000..78d3de1df294
--- /dev/null
+++ b/products/tracing/frontend/components/TraceView/TraceOperationsTab.tsx
@@ -0,0 +1,92 @@
+import { useCallback, useMemo, useState } from 'react'
+
+import { LemonSegmentedButton } from '@posthog/lemon-ui'
+
+import { pluralize } from 'lib/utils/strings'
+
+import { isAiEventSpan } from '../../aiEventSpans'
+import { childSpansByParentId, collectSubtreeSpans } from '../../spanTree'
+import { summarizeTraceOperations } from '../../traceOperations'
+import type { Span } from '../../types'
+import { TraceOperationsTable } from './TraceOperationsTable'
+import type { TraceOperationsScope } from './traceViewLogic'
+
+export interface TraceOperationsTabProps {
+ /** The inspected span. "This span" covers it and every span under it. */
+ span: Span
+ /** The trace's real spans. AI event rows are synthetic and have no operation of their own. */
+ spans: Span[]
+ highlightedOperationKey: string | null
+ /** Called with the scope the counts were in when the person picked the operation. */
+ onHighlightOperation: (operationKey: string | null, scope: TraceOperationsScope) => void
+ /** The trace has spans that are not loaded yet, so the counts do not cover the whole trace. */
+ partial: boolean
+}
+
+// The operations of the whole trace (default) or of the inspected span's subtree, with the same scope
+// toggle as the Logs tab. The span tree highlight matches an operation across the whole trace in both scopes.
+export function TraceOperationsTab({
+ span,
+ spans,
+ highlightedOperationKey,
+ onHighlightOperation,
+ partial,
+}: TraceOperationsTabProps): JSX.Element {
+ const [scope, setScope] = useState<TraceOperationsScope>('trace')
+ // An AI row has no OTel span id, so no span has it as a parent. It stays on the trace even when the
+ // user picked "This span" on a real span. The pick comes back when they select a real span.
+ const spanScopeDisabledReason = isAiEventSpan(span)
+ ? "AI events don't have their own span, so operations show for the whole trace"
+ : undefined
+ const effectiveScope: TraceOperationsScope = spanScopeDisabledReason ? 'trace' : scope
+
+ // Built once per span list, so that selecting another span in "This span" only walks its subtree.
+ const childrenByParentId = useMemo(() => childSpansByParentId(spans), [spans])
+ const scopedSpans = useMemo(
+ () => (effectiveScope === 'span' ? collectSubtreeSpans(span, childrenByParentId) : spans),
+ [effectiveScope, span, spans, childrenByParentId]
+ )
+ const { operations, spanCount } = useMemo(() => summarizeTraceOperations(scopedSpans), [scopedSpans])
+
+ const counts = `${pluralize(operations.length, 'operation')} · ${pluralize(spanCount, 'span')}`
+ // Stable between renders, so the memoized table skips the re-renders of an inspector resize drag.
+ const onHighlightInScope = useCallback(
+ (operationKey: string | null): void => onHighlightOperation(operationKey, effectiveScope),
+ [onHighlightOperation, effectiveScope]
+ )
+
+ return (
+ <div className="flex flex-col gap-2">
+ <LemonSegmentedButton
+ size="xsmall"
+ value={effectiveScope}
+ onChange={setScope}
+ options={[
+ // pinned: autocapture selects on these values, so renaming them breaks saved actions.
+ // LemonSegmentedButton puts no data-attr on its root, so each option carries one.
+ { value: 'trace', label: 'Whole trace', 'data-attr': 'tracing-operations-scope-trace' },
+ {
+ value: 'span',
+ label: 'This span',
+ disabledReason: spanScopeDisabledReason,
+ 'data-attr': 'tracing-operations-scope-span',
+ },
+ ]}
+ />
+ {/* The counts change as spans load, so they stay one text node that translation extensions skip. */}
+ <span className="text-xs text-muted truncate" translate="no">
+ {effectiveScope === 'span' ? `${counts} under ${span.name}` : counts}
+ </span>
+ <div>
+ <TraceOperationsTable
+ operations={operations}
+ highlightedOperationKey={highlightedOperationKey}
+ onHighlightOperation={onHighlightInScope}
+ partial={partial}
+ compact
+ shareOf={effectiveScope}
+ />
+ </div>
+ </div>
+ )
+}
diff --git a/products/tracing/frontend/components/TraceView/TraceOperationsTable.stories.tsx b/products/tracing/frontend/components/TraceView/TraceOperationsTable.stories.tsx
new file mode 100644
index 000000000000..8a955f1b6cc3
--- /dev/null
+++ b/products/tracing/frontend/components/TraceView/TraceOperationsTable.stories.tsx
@@ -0,0 +1,119 @@
+import { Decorator, Meta, StoryObj } from '@storybook/react'
+
+import { compareRowKey } from '../../compareUtils'
+import type { TraceOperation } from '../../traceOperations'
+import { TraceOperationsTable } from './TraceOperationsTable'
+
+const ms = (value: number): number => value * 1_000_000
+
+function operation(
+ service_name: string,
+ name: string,
+ stats: Omit<TraceOperation, 'key' | 'service_name' | 'name'>
+): TraceOperation {
+ return { key: compareRowKey({ service_name, name }), service_name, name, ...stats }
+}
+
+// A 3.8 s checkout trace. The root's child spans do not overlap, so the self times add up to 3.8 s and each
+// share is the self time over 3.8 s. The child spans have no children, so their self time is their total.
+const OPERATIONS: TraceOperation[] = [
+ operation('checkout-api', 'POST /api/orders', {
+ count: 1,
+ self_time_nano: ms(1898),
+ total_duration_nano: ms(3800),
+ avg_duration_nano: ms(3800),
+ p50_duration_nano: ms(3800),
+ share: 0.4995,
+ }),
+ operation('checkout-api', 'cache GET', {
+ count: 1751,
+ self_time_nano: ms(1200),
+ total_duration_nano: ms(1200),
+ avg_duration_nano: ms(0.685),
+ p50_duration_nano: ms(0.61),
+ share: 0.3158,
+ }),
+ operation('postgres', 'SELECT orders', {
+ count: 22,
+ self_time_nano: ms(480),
+ total_duration_nano: ms(480),
+ avg_duration_nano: ms(21.8),
+ p50_duration_nano: ms(18.4),
+ share: 0.1263,
+ }),
+ operation('inventory', 'reserveStock', {
+ count: 4,
+ self_time_nano: ms(210),
+ total_duration_nano: ms(210),
+ avg_duration_nano: ms(52.5),
+ p50_duration_nano: ms(51),
+ share: 0.0553,
+ }),
+ operation('notifications', 'enqueueEmail', {
+ count: 1,
+ self_time_nano: ms(12),
+ total_duration_nano: ms(12),
+ avg_duration_nano: ms(12),
+ p50_duration_nano: ms(12),
+ share: 0.0032,
+ }),
+]
+
+// 30 operations of spans with no children, so each self time is the total. The self times fall by 2 ms per
+// row and add up to 930 ms, so each share is the self time over 930 ms. The span counts rise by 1 per row, so
+// a sort by Spans shows the other end of the list.
+const MANY_OPERATIONS: TraceOperation[] = Array.from({ length: 30 }, (_, index) => {
+ const total = ms(60 - index * 2)
+ const count = index + 1
+ return operation('catalog-api', `GET /items/${index + 1}`, {
+ count,
+ self_time_nano: total,
+ total_duration_nano: total,
+ avg_duration_nano: total / count,
+ p50_duration_nano: total / count,
+ share: total / ms(930),
+ })
+})
+
+// The snapshot root shrinks to its content, so each story sets the width it snapshots at.
+const fixedWidth =
+ (className: string): Decorator =>
+ (Story) => (
+ <div className={className}>
+ <Story />
+ </div>
+ )
+
+const meta: Meta<typeof TraceOperationsTable> = {
+ title: 'Products/Tracing/TraceOperationsTable',
+ component: TraceOperationsTable,
+ tags: ['autodocs'],
+ args: {
+ operations: OPERATIONS,
+ highlightedOperationKey: null,
+ onHighlightOperation: () => {},
+ },
+}
+export default meta
+
+type Story = StoryObj<typeof TraceOperationsTable>
+
+export const Default: Story = {
+ args: { highlightedOperationKey: compareRowKey({ service_name: 'checkout-api', name: 'cache GET' }) },
+ decorators: [fixedWidth('w-[1100px]')],
+}
+
+/** The width of the trace drawer next to an open side panel, on a trace that has more spans to load. */
+export const Narrow: Story = {
+ args: { partial: true },
+ decorators: [fixedWidth('w-[520px]')],
+}
+
+/**
+ * A trace with more operations than the panel lists, so the note under the table shows. The panel shows
+ * the top 5 by the sorted column.
+ */
+export const Capped: Story = {
+ args: { operations: MANY_OPERATIONS },
+ decorators: [fixedWidth('w-[1100px]')],
+}
diff --git a/products/tracing/frontend/components/TraceView/TraceOperationsTable.test.tsx b/products/tracing/frontend/components/TraceView/TraceOperationsTable.test.tsx
new file mode 100644
index 000000000000..b61739ba657f
--- /dev/null
+++ b/products/tracing/frontend/components/TraceView/TraceOperationsTable.test.tsx
@@ -0,0 +1,105 @@
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+
+import { initKeaTests } from '~/test/init'
+
+import { compareRowKey } from '../../compareUtils'
+import type { TraceOperation } from '../../traceOperations'
+import { TraceOperationsTable } from './TraceOperationsTable'
+
+// Give the table real dimensions so react-window renders its rows. AutoSizer measures 0x0 in jsdom.
+jest.mock('lib/components/AutoSizer', () => ({
+ AutoSizer: ({ renderProp }: { renderProp: (size: { height: number; width: number }) => React.ReactNode }) =>
+ renderProp({ height: 600, width: 800 }),
+}))
+
+function makeOperation(
+ service_name: string,
+ name: string,
+ self_time_nano: number,
+ count = 1,
+ total_duration_nano = self_time_nano
+): TraceOperation {
+ return {
+ key: compareRowKey({ service_name, name }),
+ service_name,
+ name,
+ count,
+ self_time_nano,
+ total_duration_nano,
+ avg_duration_nano: total_duration_nano / count,
+ p50_duration_nano: total_duration_nano / count,
+ share: self_time_nano / 3_000_000,
+ }
+}
+
+const orders = makeOperation('checkout-api', 'POST /api/orders', 2_000_000)
+const cache = makeOperation('checkout-api', 'cache GET', 1_000_000)
+
+describe('TraceOperationsTable', () => {
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ afterEach(() => cleanup())
+
+ it('highlights the clicked operation and clears the highlight when the same operation is clicked again', () => {
+ // The second click must emit null. If it emits the key again, a click on the table can never
+ // clear the dimming in the span tree. The clicks go through the keyboard-reachable button, so
+ // the test also fails when one click toggles twice (the button and then its row), or when the
+ // button stops telling assistive technology which operation is highlighted.
+ const onHighlightOperation = jest.fn()
+ const { rerender } = render(
+ <TraceOperationsTable
+ operations={[orders, cache]}
+ highlightedOperationKey={null}
+ onHighlightOperation={onHighlightOperation}
+ />
+ )
+ // Text query, not a role query: role queries walk the whole DOM and are slow in jsdom.
+ const ordersButton = (): HTMLElement => screen.getByText('POST /api/orders').closest('button') as HTMLElement
+ expect(ordersButton().getAttribute('aria-pressed')).toBe('false')
+
+ fireEvent.click(ordersButton())
+ rerender(
+ <TraceOperationsTable
+ operations={[orders, cache]}
+ highlightedOperationKey={orders.key}
+ onHighlightOperation={onHighlightOperation}
+ />
+ )
+ expect(ordersButton().getAttribute('aria-pressed')).toBe('true')
+ fireEvent.click(ordersButton())
+
+ expect(onHighlightOperation.mock.calls).toEqual([[orders.key], [null]])
+ })
+
+ it.each([
+ // Fails when the cap keeps the wrong end of the list, or when the rows sort by total: op-29 has the least
+ // self time and the largest total.
+ { sortedBy: 'self time', header: null, shown: 'op-0', hidden: 'op-29' },
+ // Fails when the cap runs before the sort. That cap keeps the five largest self times, so op-0, the
+ // operation with the fewest spans, stays and op-29, the one with the most, never shows.
+ { sortedBy: 'span count', header: 'Spans', shown: 'op-29', hidden: 'op-0' },
+ ])('renders only the top operations by $sortedBy and says how many there are', ({ header, shown, hidden }) => {
+ // A trace with many operations must not render every row. The span counts and the totals rise as the
+ // self times fall, so the two sorts keep opposite ends of the list.
+ const operations = Array.from({ length: 30 }, (_, index) =>
+ makeOperation('catalog-api', `op-${index}`, (30 - index) * 1_000_000, index + 1, (index + 1) * 10_000_000)
+ )
+ const { container } = render(
+ <TraceOperationsTable
+ operations={operations}
+ highlightedOperationKey={null}
+ onHighlightOperation={jest.fn()}
+ />
+ )
+ if (header) {
+ fireEvent.click(screen.getByText(header))
+ }
+
+ expect(container.querySelectorAll('button[data-attr="tracing-trace-operations-highlight"]')).toHaveLength(5)
+ expect(screen.getByText('Showing 5 of 30 operations.')).toBeTruthy()
+ expect(screen.getByText(shown)).toBeTruthy()
+ expect(screen.queryByText(hidden)).toBeNull()
+ })
+})
diff --git a/products/tracing/frontend/components/TraceView/TraceOperationsTable.tsx b/products/tracing/frontend/components/TraceView/TraceOperationsTable.tsx
new file mode 100644
index 000000000000..cf47fbd77179
--- /dev/null
+++ b/products/tracing/frontend/components/TraceView/TraceOperationsTable.tsx
@@ -0,0 +1,240 @@
+import { memo, useCallback, useMemo, useState } from 'react'
+
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+import type { TraceOperation } from '../../traceOperations'
+import { formatDuration } from '../../TraceWaterfallView'
+import {
+ VirtualizedSort,
+ VirtualizedTable,
+ VirtualizedTableColumn,
+ virtualizedTableHeight,
+} from '../../VirtualizedTable'
+import { MIN_COLUMN_WIDTH } from '../TableColumns/columnWidths'
+
+// The table lists the main contributors and the span tree shows every span, so the table shows only the top 5
+// operations by the sorted column. The note under the table says how many operations there are in all.
+const MAX_OPERATIONS = 5
+
+const DEFAULT_SORT: VirtualizedSort = { columnKey: 'self', order: -1 }
+
+const HIGHLIGHTED_ROW_CLASS = 'bg-accent-highlight-secondary font-semibold'
+
+export interface TraceOperationsTableProps {
+ /** Sorted by self time descending, as summarizeTraceOperations returns them. */
+ operations: TraceOperation[]
+ highlightedOperationKey: string | null
+ /** Called with the row's key, or null when the highlighted row is clicked again. */
+ onHighlightOperation: (operationKey: string | null) => void
+ /** The trace has spans that are not loaded yet, so the counts do not cover the whole trace. */
+ partial?: boolean
+ /** Drop the Avg and p50 columns for a narrow container. The operation's tooltip shows them instead. */
+ compact?: boolean
+ /** What the operations cover, for the Share column's tooltip: the whole trace, or the inspected span's subtree. */
+ shareOf?: 'trace' | 'span'
+}
+
+function highlightTitle(isHighlighted: boolean): string {
+ return isHighlighted ? 'Clear the highlight' : 'Highlight these spans in the trace'
+}
+
+function nextHighlightKey(operation: TraceOperation, highlightedOperationKey: string | null): string | null {
+ return operation.key === highlightedOperationKey ? null : operation.key
+}
+
+function operationRowKey(operation: TraceOperation): string {
+ return operation.key
+}
+
+// The tooltip carries the duration numbers the columns leave out: the total always, and avg and p50 when compact.
+function withTimings(title: string, operation: TraceOperation, compact: boolean): string {
+ const timings = [
+ ...(compact
+ ? [
+ `avg ${formatDuration(operation.avg_duration_nano)}`,
+ `p50 ${formatDuration(operation.p50_duration_nano)}`,
+ ]
+ : []),
+ `total ${formatDuration(operation.total_duration_nano)}`,
+ ]
+ return `${title}\n${timings.join(' · ')}`
+}
+
+// The service name shares the Operation cell instead of a column of its own. Together the default widths
+// fit in 520px, the width of the drawer next to an open side panel. The compact set drops Avg and p50, so
+// that Share stays in view in the span inspector, which is narrower. Operation grows into the width the
+// numeric columns leave, and a person can drag it wider to read a long name. In the compact set it starts
+// at the narrowest width a column can have. The numeric columns then fit the inspector at its narrowest,
+// and Operation gives up width instead of pushing Share out of view.
+const SPANS_COLUMN: VirtualizedTableColumn<TraceOperation> = {
+ key: 'count',
+ title: 'Spans',
+ width: 72,
+ align: 'right',
+ sorter: (a, b) => a.count - b.count,
+ render: (row) => humanFriendlyNumber(row.count),
+}
+
+const SELF_TIME_COLUMN: VirtualizedTableColumn<TraceOperation> = {
+ key: 'self',
+ title: 'Self time',
+ width: 84,
+ align: 'right',
+ tooltip: 'Time these spans spend outside their child spans, so time in nested spans counts once.',
+ sorter: (a, b) => a.self_time_nano - b.self_time_nano,
+ render: (row) => <span className="font-mono">{formatDuration(row.self_time_nano)}</span>,
+}
+
+const AVG_COLUMN: VirtualizedTableColumn<TraceOperation> = {
+ key: 'avg',
+ title: 'Avg',
+ width: 72,
+ align: 'right',
+ tooltip: 'Average span duration, including time in child spans.',
+ sorter: (a, b) => a.avg_duration_nano - b.avg_duration_nano,
+ render: (row) => <span className="font-mono">{formatDuration(row.avg_duration_nano)}</span>,
+}
+
+const P50_COLUMN: VirtualizedTableColumn<TraceOperation> = {
+ key: 'p50',
+ title: 'p50',
+ width: 72,
+ align: 'right',
+ tooltip: 'Median span duration, including time in child spans.',
+ sorter: (a, b) => a.p50_duration_nano - b.p50_duration_nano,
+ render: (row) => <span className="font-mono">{formatDuration(row.p50_duration_nano)}</span>,
+}
+
+function shareColumn(tooltip: string): VirtualizedTableColumn<TraceOperation> {
+ return {
+ key: 'share',
+ title: 'Share',
+ width: 72,
+ align: 'right',
+ tooltip,
+ sorter: (a, b) => a.share - b.share,
+ render: (row) => `${(row.share * 100).toFixed(1)}%`,
+ }
+}
+
+const SHARE_COLUMNS: Record<'trace' | 'span', VirtualizedTableColumn<TraceOperation>> = {
+ trace: shareColumn('Self time as a share of the self time of every span in the trace.'),
+ span: shareColumn('Self time as a share of the self time of this span and the spans under it.'),
+}
+
+// Memoized because the drawer re-renders on every mousemove of an inspector resize drag. The props stay
+// the same during a drag, so the table skips that work. The columns stay the same object between renders,
+// so useResizableColumns reuses the widths it resolved last time.
+export const TraceOperationsTable = memo(function TraceOperationsTable({
+ operations,
+ highlightedOperationKey,
+ onHighlightOperation,
+ partial = false,
+ compact = false,
+ shareOf = 'trace',
+}: TraceOperationsTableProps): JSX.Element {
+ const [sort, setSort] = useState<VirtualizedSort | null>(DEFAULT_SORT)
+ const columns = useMemo(
+ (): VirtualizedTableColumn<TraceOperation>[] => [
+ {
+ key: 'name',
+ title: 'Operation',
+ width: compact ? MIN_COLUMN_WIDTH : 144,
+ grow: true,
+ sorter: (a, b) => a.name.localeCompare(b.name),
+ render: (row) => {
+ const isHighlighted = row.key === highlightedOperationKey
+ // The row's own role="button" cannot say which operation is highlighted, so the cell
+ // holds a real button whose aria-pressed tells assistive technology.
+ return (
+ <button
+ type="button"
+ // pinned: autocapture selects on this value, so renaming it breaks saved actions
+ data-attr="tracing-trace-operations-highlight"
+ aria-pressed={isHighlighted}
+ className="block w-full font-mono text-left cursor-pointer"
+ title={withTimings(highlightTitle(isHighlighted), row, compact)}
+ onClick={(event) => {
+ // Stop here so that the row handler does not toggle the highlight a second time.
+ event.stopPropagation()
+ onHighlightOperation(nextHighlightKey(row, highlightedOperationKey))
+ }}
+ >
+ {/* The operations of one trace often share a long service name, so the name comes first
+ and keeps its width: the service truncates to nothing before the name truncates. */}
+ <span
+ className="flex min-w-0 overflow-hidden"
+ title={withTimings(`${row.service_name} ${row.name}`, row, compact)}
+ translate="no"
+ >
+ <span className="shrink-0 max-w-full truncate">{row.name}</span>
+ <span className="min-w-0 truncate pl-1.5 text-muted">{row.service_name}</span>
+ </span>
+ </button>
+ )
+ },
+ },
+ SPANS_COLUMN,
+ SELF_TIME_COLUMN,
+ ...(compact ? [] : [AVG_COLUMN, P50_COLUMN]),
+ SHARE_COLUMNS[shareOf],
+ ],
+ [highlightedOperationKey, onHighlightOperation, compact, shareOf]
+ )
+ // A sort by a column the table no longer shows, such as Avg after the table turns compact, falls back to the
+ // default sort, so the header always marks the order the rows are in.
+ const effectiveSort = useMemo(
+ (): VirtualizedSort =>
+ sort && columns.some((column) => column.key === sort.columnKey && column.sorter) ? sort : DEFAULT_SORT,
+ [sort, columns]
+ )
+ // Sort the whole list before the cap. Otherwise a sort by Spans only reorders the five operations with
+ // the most self time, and the most-called operations of the trace stay hidden.
+ const visibleOperations = useMemo((): TraceOperation[] => {
+ const sorter = columns.find((column) => column.key === effectiveSort.columnKey)?.sorter
+ return sorter
+ ? [...operations].sort((a, b) => sorter(a, b) * effectiveSort.order).slice(0, MAX_OPERATIONS)
+ : operations.slice(0, MAX_OPERATIONS)
+ }, [operations, columns, effectiveSort])
+ const onRowClick = useCallback(
+ (row: TraceOperation): void => onHighlightOperation(nextHighlightKey(row, highlightedOperationKey)),
+ [highlightedOperationKey, onHighlightOperation]
+ )
+ const rowClassName = useCallback(
+ (row: TraceOperation): string | undefined =>
+ row.key === highlightedOperationKey ? HIGHLIGHTED_ROW_CLASS : undefined,
+ [highlightedOperationKey]
+ )
+
+ return (
+ <>
+ {partial && <p className="text-xs text-muted mb-1">Counts cover the spans loaded so far.</p>}
+ {/* VirtualizedTable needs a box of definite height. This one fits every visible row, so the table does not scroll. */}
+ <div
+ className="flex flex-col"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ height: virtualizedTableHeight(visibleOperations.length) }}
+ >
+ <VirtualizedTable<TraceOperation>
+ // pinned: identifies stored column widths, so renaming it resets everyone's widths
+ tableKey="trace-operations"
+ // pinned: autocapture and Playwright select on this value, so renaming it breaks them
+ data-attr="tracing-trace-operations-table"
+ columns={columns}
+ dataSource={visibleOperations}
+ loading={false}
+ rowKey={operationRowKey}
+ onRowClick={onRowClick}
+ rowClassName={rowClassName}
+ sort={effectiveSort}
+ onSortChange={setSort}
+ />
+ </div>
+ {operations.length > MAX_OPERATIONS && (
+ <p className="text-xs text-muted mt-1">
+ {`Showing ${MAX_OPERATIONS} of ${humanFriendlyNumber(operations.length)} operations.`}
+ </p>
+ )}
+ </>
+ )
+})
diff --git a/products/tracing/frontend/components/TraceView/TraceView.tsx b/products/tracing/frontend/components/TraceView/TraceView.tsx
index 03a9d9900d22..da9ac70a5a0b 100644
--- a/products/tracing/frontend/components/TraceView/TraceView.tsx
+++ b/products/tracing/frontend/components/TraceView/TraceView.tsx
@@ -1,5 +1,5 @@
import { useActions, useValues } from 'kea'
-import { type CSSProperties, useRef } from 'react'
+import { type CSSProperties, useCallback, useMemo, useRef } from 'react'
import { Resizer } from 'lib/components/Resizer/Resizer'
import { type ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'
@@ -7,16 +7,19 @@ import { type ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/res
import { SpanInspector } from 'products/tracing/frontend/components/SpanInspector/SpanInspector'
import { MissingParentSpanNotice } from 'products/tracing/frontend/components/TraceDrawer/MissingParentSpanNotice'
import type { ErrorScope } from 'products/tracing/frontend/errorCorrelation'
+import type { SpanInspectorTab } from 'products/tracing/frontend/types'
import type { TraceDialogSource } from '../TraceDialog/traceDialogLogic'
import { TraceDialogSpanTree } from '../TraceDialog/TraceDialogSpanTree'
-import { traceViewLogic } from './traceViewLogic'
+import { type TraceOperationsScope, traceViewLogic, type TraceViewSurface } from './traceViewLogic'
// Below this the attribute tables stop being readable, so a drag can't crush the inspector.
const MIN_INSPECTOR_WIDTH = 320
export interface TraceViewProps {
traceId: string
+ /** Where the view sits, for analytics. */
+ surface: TraceViewSurface
inspectorOpen: boolean
sessionId: string | null
showErrorsTab: boolean
@@ -28,6 +31,8 @@ export interface TraceViewProps {
/** Spans are still loading, so the inspector holds off on what it reads from them. */
resolving?: boolean
hasMoreSpans?: boolean
+ /** The loaded spans are not the whole trace, and the view cannot load the rest. */
+ spansPartial?: boolean
loadingMoreSpans?: boolean
onLoadMoreSpans?: () => void
}
@@ -35,6 +40,7 @@ export interface TraceViewProps {
/** The span tree beside the inspector for the selected span. Mount it inside a `BindLogic` for `traceViewLogic`. */
export function TraceView({
traceId,
+ surface,
inspectorOpen,
sessionId,
showErrorsTab,
@@ -44,6 +50,7 @@ export function TraceView({
showFilterActions = false,
resolving = false,
hasMoreSpans,
+ spansPartial,
loadingMoreSpans,
onLoadMoreSpans,
}: TraceViewProps): JSX.Element {
@@ -56,9 +63,51 @@ export function TraceView({
persistent: true,
}
const { desiredSize: inspectorWidth } = useValues(resizerLogic(inspectorResizerProps))
- const { selectedSpan, missingParentSpanId, serviceColorMap, summary, activeInspectorTab } =
- useValues(traceViewLogic)
- const { setInspectorTab } = useActions(traceViewLogic)
+ const {
+ selectedSpan,
+ missingParentSpanId,
+ serviceColorMap,
+ summary,
+ activeInspectorTab,
+ operationSpans,
+ highlightedOperationKey,
+ operationsTabEnabled,
+ } = useValues(traceViewLogic)
+ const { setInspectorTab, highlightOperation } = useActions(traceViewLogic)
+ // A click on the tab already shown still records the person's pick. Nothing on screen changes, so it passes
+ // no surface and sends no event.
+ const onSelectTab = useCallback(
+ (tab: SpanInspectorTab, changesShownTab: boolean): void =>
+ setInspectorTab(tab, changesShownTab ? surface : undefined),
+ [setInspectorTab, surface]
+ )
+ const onHighlightOperation = useCallback(
+ (operationKey: string | null, scope: TraceOperationsScope): void =>
+ highlightOperation(operationKey, surface, scope),
+ [highlightOperation, surface]
+ )
+ // Without real spans the tab would only show an empty table, so the inspector leaves it out, as it does while
+ // the tab's flag is off. A resize drag re-renders this component on every mousemove, and stable values keep
+ // the memoized table from rendering again for it.
+ const operations = useMemo(
+ () =>
+ operationsTabEnabled && operationSpans.length > 0
+ ? {
+ spans: operationSpans,
+ highlightedOperationKey,
+ onHighlightOperation,
+ partial: !!hasMoreSpans || !!spansPartial,
+ }
+ : undefined,
+ [
+ operationsTabEnabled,
+ operationSpans,
+ highlightedOperationKey,
+ onHighlightOperation,
+ hasMoreSpans,
+ spansPartial,
+ ]
+ )
return (
<div className="@container/trace-dialog flex flex-1 min-h-0">
@@ -70,6 +119,7 @@ export function TraceView({
hasMore={hasMoreSpans}
loadingMore={loadingMoreSpans}
onLoadMore={onLoadMoreSpans}
+ showOperationHighlight={inspectorOpen}
/>
</div>
{inspectorOpen && (missingParentSpanId || selectedSpan) && (
@@ -104,8 +154,9 @@ export function TraceView({
errorsScope={errorsScope}
resolving={resolving}
tab={activeInspectorTab}
- onSelectTab={setInspectorTab}
+ onSelectTab={onSelectTab}
showFilterActions={showFilterActions}
+ operations={operations}
/>
) : null}
</div>
diff --git a/products/tracing/frontend/components/TraceView/traceViewLogic.test.ts b/products/tracing/frontend/components/TraceView/traceViewLogic.test.ts
new file mode 100644
index 000000000000..a89f1dafccd9
--- /dev/null
+++ b/products/tracing/frontend/components/TraceView/traceViewLogic.test.ts
@@ -0,0 +1,101 @@
+import posthog from 'posthog-js'
+
+import { initKeaTests } from '~/test/init'
+
+import { makeSpan } from '../../__mocks__/span'
+import { compareRowKey } from '../../compareUtils'
+import type { Span } from '../../types'
+import { rowSpanNode } from '../TraceDialog/traceDialogRows'
+import { traceViewLogic } from './traceViewLogic'
+
+const child = (span_id: string, parent_span_id: string, name: string, offsetMs: number): Span =>
+ makeSpan({
+ uuid: span_id,
+ span_id,
+ parent_span_id,
+ name,
+ is_root_span: false,
+ timestamp: new Date(Date.UTC(2026, 8, 3, 10) + offsetMs).toISOString(),
+ })
+
+const root = makeSpan({ uuid: 'root', span_id: 'root', name: 'POST /api/orders' })
+const CACHE_GET = compareRowKey({ service_name: 'checkout-api', name: 'cache GET' })
+
+describe('traceViewLogic', () => {
+ let logic: ReturnType<typeof traceViewLogic.build>
+ let captureSpy: jest.SpyInstance
+
+ beforeEach(() => {
+ initKeaTests()
+ captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)
+ logic = traceViewLogic({ id: 'trace-view-test' })
+ logic.mount()
+ logic.actions.showTrace(null, 'operations')
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ captureSpy.mockRestore()
+ })
+
+ // A stale key dims the next trace's tree. Another inspector tab, or the missing-parent notice that
+ // replaces the inspector, would leave dimmed rows with nothing on screen to explain them. A switch to
+ // the Operations tab itself must keep the pick, or a caller that selects the tab after a highlight drops it.
+ // The tab event must count only the person's own switches: a trace that opens on a tab, or a click on the
+ // tab already shown, would inflate it.
+ it.each([
+ { action: 'opening a trace', act: () => logic.actions.showTrace(null, null), keeps: false, tabEvent: null },
+ {
+ action: 'selecting the Logs tab',
+ act: () => logic.actions.setInspectorTab('logs', 'drawer'),
+ keeps: false,
+ tabEvent: { tab: 'logs', surface: 'drawer' },
+ },
+ {
+ action: 'another logic setting the Logs tab',
+ act: () => logic.actions.setInspectorTab('logs'),
+ keeps: false,
+ tabEvent: null,
+ },
+ {
+ action: 'selecting the missing parent',
+ act: () => logic.actions.selectSpan('gone'),
+ keeps: false,
+ tabEvent: null,
+ },
+ {
+ action: 'selecting the Operations tab',
+ act: () => logic.actions.setInspectorTab('operations', 'trace_dialog'),
+ keeps: true,
+ tabEvent: null,
+ },
+ ])(
+ 'after $action, keeps the highlighted operation: $keeps, and sends a tab event only for a tab change',
+ ({ act, keeps, tabEvent }) => {
+ logic.actions.setSpans([root, child('orphan', 'gone', 'cache GET', 1)])
+ logic.actions.highlightOperation(CACHE_GET)
+
+ act()
+
+ expect(logic.values.highlightedOperationKey).toBe(keeps ? CACHE_GET : null)
+ expect(captureSpy.mock.calls.filter(([event]) => event === 'tracing trace inspector tab changed')).toEqual(
+ tabEvent ? [['tracing trace inspector tab changed', tabEvent]] : []
+ )
+ }
+ )
+
+ // Fails when the highlight stops opening the child list that hides the operation's first span, which
+ // leaves the tree nothing to scroll to, or when it moves the selection off the span the person inspects.
+ it('opens the child list that hides the first span of the highlighted operation, and keeps the selection', () => {
+ const children = Array.from({ length: 11 }, (_, i) => child(`c${i}`, 'root', 'SELECT orders', 10 + i))
+ logic.actions.setSpans([root, ...children, child('cache', 'root', 'cache GET', 30)])
+ logic.actions.selectSpan('c0')
+ const rowIds = (): (string | undefined)[] => logic.values.spanRows.map((row) => rowSpanNode(row)?.span.span_id)
+ expect(rowIds()).not.toContain('cache')
+
+ logic.actions.highlightOperation(CACHE_GET)
+
+ expect(rowIds()).toContain('cache')
+ expect(logic.values.selectedSpanId).toBe('c0')
+ })
+})
diff --git a/products/tracing/frontend/components/TraceView/traceViewLogic.ts b/products/tracing/frontend/components/TraceView/traceViewLogic.ts
index c0616a59f82c..fa69ffb026c7 100644
--- a/products/tracing/frontend/components/TraceView/traceViewLogic.ts
+++ b/products/tracing/frontend/components/TraceView/traceViewLogic.ts
@@ -11,7 +11,12 @@ import {
reducers,
selectors,
} from 'kea'
+import posthog from 'posthog-js'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { type FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { isAiEventSpan } from 'products/tracing/frontend/aiEventSpans'
import { buildSpanTree, parseTimestampUs, type SpanNode } from 'products/tracing/frontend/spanTree'
import { buildServiceColorMap } from 'products/tracing/frontend/TraceWaterfallView'
import { tracingCorrelationConfigLogic } from 'products/tracing/frontend/tracingCorrelationConfigLogic'
@@ -20,7 +25,12 @@ import type { Span, SpanInspectorTab } from 'products/tracing/frontend/types'
import {
buildTraceDialogRows,
countDescendantsById,
+ firstOperationSpan,
+ markOperationSubtrees,
+ operationRowMatches,
+ revealSpanInRows,
rowSpanNode,
+ type TraceDialogReveal,
type TraceDialogRow,
} from '../TraceDialog/traceDialogRows'
@@ -32,6 +42,15 @@ export interface TraceViewLogicProps {
id: string
}
+/** Where the view sits. Pinned: sent as the `surface` property of analytics events, so keep the values stable. */
+export type TraceViewSurface = 'drawer' | 'trace_dialog'
+
+/**
+ * What the Operations tab counts: the whole trace, or the inspected span and the spans under it.
+ * Pinned: sent as the `scope` property of analytics events, so keep the values stable.
+ */
+export type TraceOperationsScope = 'trace' | 'span'
+
export interface TraceViewTree {
roots: SpanNode[]
nodesById: Map<string, SpanNode>
@@ -52,6 +71,7 @@ export interface TraceViewSummary {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface traceViewLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
sessionErrorBadgesEnabled: boolean // tracingCorrelationConfigLogic
activeInspectorTab: SpanInspectorTab
chainStartIds: {
@@ -60,10 +80,16 @@ export interface traceViewLogicValues {
}
chosenInspectorTab: SpanInspectorTab | null
collapsedSpanIds: Set<string>
+ firstOperationRowIndex: number
flatSpans: SpanNode[]
fullChildListSpanIds: Set<string>
+ highlightedOperationKey: string | null
missingParentSpanId: string | null
openChainIds: Set<string>
+ operationRowMatches: boolean[] | null
+ operationSpans: Span[]
+ operationSubtreeMarks: Set<SpanNode> | null
+ operationsTabEnabled: boolean
pinnedSpan: Span | null
pinnedSpanId: string | null
selectedSpan: Span | null
@@ -90,9 +116,21 @@ export interface traceViewLogicActions {
expandSelectedSpan: () => {
value: true
}
+ highlightOperation: (
+ operationKey: string | null,
+ surface?: TraceViewSurface,
+ scope?: TraceOperationsScope
+ ) => {
+ operationKey: string | null
+ scope: TraceOperationsScope | null
+ surface: TraceViewSurface | null
+ }
keepSelectionOnScreen: () => {
value: true
}
+ revealSpans: (reveal: TraceDialogReveal) => {
+ reveal: TraceDialogReveal
+ }
selectNextSpan: () => {
value: true
}
@@ -102,7 +140,11 @@ export interface traceViewLogicActions {
selectSpan: (spanId: string | null) => {
spanId: string | null
}
- setInspectorTab: (tab: SpanInspectorTab) => {
+ setInspectorTab: (
+ tab: SpanInspectorTab,
+ surface?: TraceViewSurface
+ ) => {
+ surface: TraceViewSurface | null
tab: SpanInspectorTab
}
setSpans: (spans: Span[]) => {
@@ -154,6 +196,20 @@ export interface traceViewLogicMeta {
selectedSpan: Span | null,
sessionErrorBadgesEnabled: boolean
) => SpanInspectorTab
+ operationsTabEnabled: (featureFlags: FeatureFlagsSet) => boolean
+ operationSubtreeMarks: (
+ spanTree: TraceViewTree,
+ highlightedOperationKey: string | null,
+ operationsTabEnabled: boolean
+ ) => Set<SpanNode> | null
+ operationRowMatches: (
+ spanRows: TraceDialogRow[],
+ highlightedOperationKey: string | null,
+ operationSubtreeMarks: Set<SpanNode> | null,
+ collapsedSpanIds: Set<string>
+ ) => boolean[] | null
+ firstOperationRowIndex: (operationRowMatches: boolean[] | null) => number
+ operationSpans: (spans: Span[]) => Span[]
serviceColorMap: (spans: Span[]) => Map<string, number>
timeline: (spans: Span[]) => TraceViewTimeline
summary: (spans: Span[]) => TraceViewSummary
@@ -172,7 +228,7 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLog
key((props) => props.id),
path((key) => ['products', 'tracing', 'frontend', 'components', 'TraceView', 'traceViewLogic', key]),
connect(() => ({
- values: [tracingCorrelationConfigLogic, ['sessionErrorBadgesEnabled']],
+ values: [tracingCorrelationConfigLogic, ['sessionErrorBadgesEnabled'], featureFlagLogic, ['featureFlags']],
})),
actions({
showTrace: (pinnedSpanId: string | null, tab: SpanInspectorTab | null) => ({ pinnedSpanId, tab }),
@@ -187,9 +243,19 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLog
showAllChildren: (spanId: string) => ({ spanId }),
toggleChain: (spanId: string) => ({ spanId }),
keepSelectionOnScreen: true,
- setInspectorTab: (tab: SpanInspectorTab) => ({ tab }),
+ setInspectorTab: (tab: SpanInspectorTab, surface?: TraceViewSurface) => ({ tab, surface: surface ?? null }),
enableSpanKeys: (containerSelector: string) => ({ containerSelector }),
disableSpanKeys: true,
+ highlightOperation: (
+ operationKey: string | null,
+ surface?: TraceViewSurface,
+ scope?: TraceOperationsScope
+ ) => ({
+ operationKey,
+ surface: surface ?? null,
+ scope: scope ?? null,
+ }),
+ revealSpans: (reveal: TraceDialogReveal) => ({ reveal }),
}),
reducers({
spans: [
@@ -224,6 +290,11 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLog
}
return next
},
+ revealSpans: (collapsed, { reveal }) => {
+ const next = new Set(collapsed)
+ reveal.collapsedSpanIds.forEach((spanId) => next.delete(spanId))
+ return next
+ },
},
],
fullChildListSpanIds: [
@@ -231,6 +302,7 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLog
{
showTrace: () => new Set<string>(),
showAllChildren: (shown, { spanId }) => new Set(shown).add(spanId),
+ revealSpans: (shown, { reveal }) => new Set([...shown, ...reveal.fullChildListSpanIds]),
},
],
// Chains fold by default, so this holds the opened ones.
@@ -245,6 +317,7 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLog
}
return next
},
+ revealSpans: (opened, { reveal }) => new Set([...opened, ...reveal.chainIds]),
},
],
// A tab the person picked sticks while they move between spans. Until they pick one, the
@@ -256,6 +329,18 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLog
setInspectorTab: (_, { tab }) => tab,
},
],
+ // The `compareRowKey` of the operation whose spans the tree highlights. The key only has a meaning
+ // against the spans of one trace, so opening a trace clears it. The Operations tab is the only place
+ // that explains the dimmed rows, so a switch to another tab clears it too. A switch to the Operations
+ // tab itself keeps it, so that a caller can select the tab after the highlight.
+ highlightedOperationKey: [
+ null as string | null,
+ {
+ highlightOperation: (_, { operationKey }) => operationKey,
+ showTrace: () => null,
+ setInspectorTab: (key, { tab }) => (tab === 'operations' ? key : null),
+ },
+ ],
}),
selectors({
spanTree: [
@@ -333,6 +418,41 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLog
(chosen: SpanInspectorTab | null, selectedSpan: Span | null, errorsTabEnabled: boolean): SpanInspectorTab =>
chosen ?? (errorsTabEnabled && selectedSpan?.status_code === 2 ? 'errors' : 'logs'),
],
+ operationsTabEnabled: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.TRACING_TRACE_OPERATIONS_TAB],
+ ],
+ // The spans of the highlighted operation and their ancestors, so that a row that hides a match stays bright.
+ // With the flag off nothing dims, because no Operations tab is on screen to explain the dimmed rows.
+ operationSubtreeMarks: [
+ (s) => [s.spanTree, s.highlightedOperationKey, s.operationsTabEnabled],
+ (
+ spanTree: TraceViewTree,
+ operationKey: string | null,
+ operationsTabEnabled: boolean
+ ): Set<SpanNode> | null =>
+ operationsTabEnabled && operationKey ? markOperationSubtrees(spanTree.roots, operationKey) : null,
+ ],
+ // Worked out once per change of rows or key, not per rendered row, because a "more" row stands for
+ // whole subtrees and J and K re-render the rows on screen.
+ operationRowMatches: [
+ (s) => [s.spanRows, s.highlightedOperationKey, s.operationSubtreeMarks, s.collapsedSpanIds],
+ (
+ spanRows: TraceDialogRow[],
+ operationKey: string | null,
+ subtreeMarks: Set<SpanNode> | null,
+ collapsedSpanIds: Set<string>
+ ): boolean[] | null =>
+ operationKey && subtreeMarks
+ ? operationRowMatches(spanRows, operationKey, subtreeMarks, collapsedSpanIds)
+ : null,
+ ],
+ firstOperationRowIndex: [
+ (s) => [s.operationRowMatches],
+ (matches: boolean[] | null): number => matches?.indexOf(true) ?? -1,
+ ],
+ // AI event rows are synthetic and have no operation of their own.
+ operationSpans: [(s) => [s.spans], (spans: Span[]): Span[] => spans.filter((span) => !isAiEventSpan(span))],
serviceColorMap: [(s) => [s.spans], (spans: Span[]): Map<string, number> => buildServiceColorMap(spans)],
timeline: [
(s) => [s.spans],
@@ -356,7 +476,7 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLog
}),
],
}),
- listeners(({ values, actions, cache }) => ({
+ listeners(({ values, actions, cache, selectors }) => ({
enableSpanKeys: ({ containerSelector }) => {
// Capture phase, and stopped there, so the page under the view does not also act on
// the key: with log details open, the logs list binds J and K to its own cursor.
@@ -404,6 +524,48 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLog
disableSpanKeys: () => {
cache.disposables.dispose('spanKeys')
},
+ // The inspector's tab bar passes a surface only for a click that changes the tab on screen, so a tab that
+ // another logic sets, or a click on the tab already shown, sends nothing. The check against the previous
+ // tab also stops a caller that passes a surface for the tab already active.
+ setInspectorTab: ({ tab, surface }, _, __, previousState) => {
+ if (surface && tab !== selectors.activeInspectorTab(previousState)) {
+ // pinned: analytics event name, so renaming it breaks the insights built on it
+ posthog.capture('tracing trace inspector tab changed', { tab, surface })
+ }
+ },
+ highlightOperation: ({ operationKey, surface, scope }) => {
+ if (!operationKey) {
+ return
+ }
+ // pinned: analytics event name, so renaming it breaks the insights built on it
+ posthog.capture('tracing trace operation highlighted', { surface, scope })
+ // The first span of a large operation often sits past a child cap, in a folded chain, or under
+ // a collapsed span. Open what hides it, so that the tree has a row to scroll to. The selection
+ // stays where it is, because the inspector shows the Operations tab the person is using.
+ const { roots, nodesById } = values.spanTree
+ const target = firstOperationSpan(roots, operationKey)
+ if (!target) {
+ return
+ }
+ const reveal = revealSpanInRows(roots, target, {
+ collapsedSpanIds: values.collapsedSpanIds,
+ fullChildListSpanIds: values.fullChildListSpanIds,
+ openChainIds: values.openChainIds,
+ pinned: (values.pinnedSpanId && nodesById.get(values.pinnedSpanId)) || null,
+ })
+ // One action that only opens. The toggle actions flip state, and the trace dialog counts them as the
+ // person's own collapse toggles.
+ if (reveal.collapsedSpanIds.length + reveal.fullChildListSpanIds.length + reveal.chainIds.length > 0) {
+ actions.revealSpans(reveal)
+ }
+ },
+ // The missing-parent notice replaces the whole inspector, Operations tab included, so a highlight
+ // left in place would dim rows with nothing on screen to explain it.
+ selectSpan: () => {
+ if (values.missingParentSpanId && values.highlightedOperationKey) {
+ actions.highlightOperation(null)
+ }
+ },
selectNextSpan: () => {
actions.spanStepped()
// A missing-parent row is selectable too, so step from it rather than from the root fallback.
diff --git a/products/tracing/frontend/spanTree.ts b/products/tracing/frontend/spanTree.ts
index 42dff9105d27..aea4dd695f6e 100644
--- a/products/tracing/frontend/spanTree.ts
+++ b/products/tracing/frontend/spanTree.ts
@@ -156,6 +156,46 @@ export function countDescendants(node: SpanNode): number {
return total
}
+/** Child spans by parent span id. A root by the rule `buildSpanTree` uses gets no entry as a child. */
+export function childSpansByParentId(spans: Span[]): Map<string, Span[]> {
+ const children = new Map<string, Span[]>()
+ for (const span of spans) {
+ const parentSpanId = parentSpanIdOf(span)
+ if (!parentSpanId) {
+ continue
+ }
+ const siblings = children.get(parentSpanId)
+ if (siblings) {
+ siblings.push(span)
+ } else {
+ children.set(parentSpanId, [span])
+ }
+ }
+ return children
+}
+
+/**
+ * The span and every span under it. The visited set holds span objects, not ids, so a parent cycle in
+ * malformed data cannot loop and two spans that share an id both count.
+ */
+export function collectSubtreeSpans(root: Span, childrenByParentId: Map<string, Span[]>): Span[] {
+ const subtree: Span[] = []
+ const visited = new Set<Span>()
+ const stack = [root]
+ while (stack.length > 0) {
+ const span = stack.pop()!
+ if (visited.has(span)) {
+ continue
+ }
+ visited.add(span)
+ subtree.push(span)
+ for (const child of childrenByParentId.get(span.span_id) ?? []) {
+ stack.push(child)
+ }
+ }
+ return subtree
+}
+
/** Depth-first flatten for rendering, skipping the subtree of any collapsed span. */
export function flattenTree(nodes: SpanNode[], collapsedSpanIds: Set<string>): SpanNode[] {
const result: SpanNode[] = []
diff --git a/products/tracing/frontend/traceOperations.test.ts b/products/tracing/frontend/traceOperations.test.ts
new file mode 100644
index 000000000000..c25aa8a931b4
--- /dev/null
+++ b/products/tracing/frontend/traceOperations.test.ts
@@ -0,0 +1,87 @@
+import { makeSpan } from './__mocks__/span'
+import { compareRowKey } from './compareUtils'
+import { summarizeTraceOperations } from './traceOperations'
+import type { Span } from './types'
+
+const TRACE_START_MS = Date.parse('2026-09-03T10:00:00.000Z')
+
+function opSpan(
+ id: string,
+ service_name: string,
+ name: string,
+ offsetMs: number,
+ durationMs: number,
+ parent_span_id = ''
+): Span {
+ return makeSpan({
+ uuid: id,
+ span_id: id,
+ parent_span_id,
+ is_root_span: !parent_span_id,
+ service_name,
+ name,
+ timestamp: new Date(TRACE_START_MS + offsetMs).toISOString(),
+ duration_nano: durationMs * 1_000_000,
+ })
+}
+
+describe('summarizeTraceOperations', () => {
+ // root 0-100 ms ── db 10-60 ── cache-1 20-40, cache-2 30-60 (they overlap)
+ // ├─ gateway 65-90
+ // └─ cache-3 90-190 (runs past the root's end)
+ it('groups by service and span name, sorts by self time, and derives count, self time, total, avg, p50 and share', () => {
+ // The root has the second largest total but little self time, the input order differs from the output
+ // order, and the cache durations are unsorted. So the test fails if the operations sort by total, if
+ // either sort is dropped, if overlapping children count twice (db would get 0 ms), or if a child is not
+ // clipped to its parent (the root would get 0 ms instead of 15 ms).
+ const summary = summarizeTraceOperations([
+ opSpan('cache-3', 'web', 'cache GET', 90, 100, 'root'),
+ opSpan('gateway', 'gateway', 'GET /x', 65, 25, 'root'),
+ opSpan('db', 'db', 'SELECT', 10, 50, 'root'),
+ opSpan('root', 'web', 'GET /x', 0, 100),
+ opSpan('cache-1', 'web', 'cache GET', 20, 20, 'db'),
+ opSpan('cache-2', 'web', 'cache GET', 30, 30, 'db'),
+ ])
+
+ expect(summary.spanCount).toBe(6)
+ expect(summary.operations.map((o) => [o.service_name, o.name, o.count, o.self_time_nano, o.share])).toEqual([
+ ['web', 'cache GET', 3, 150_000_000, 0.75],
+ ['gateway', 'GET /x', 1, 25_000_000, 0.125],
+ ['web', 'GET /x', 1, 15_000_000, 0.075],
+ ['db', 'SELECT', 1, 10_000_000, 0.05],
+ ])
+ expect(summary.operations[0]).toMatchObject({
+ key: compareRowKey({ service_name: 'web', name: 'cache GET' }),
+ total_duration_nano: 150_000_000,
+ avg_duration_nano: 50_000_000,
+ p50_duration_nano: 30_000_000,
+ })
+ // "This span" summarizes one subtree, and its shares add up to 100% of that subtree's self time too.
+ const dbSubtree = summarizeTraceOperations([
+ opSpan('db', 'db', 'SELECT', 10, 50, 'root'),
+ opSpan('cache-1', 'web', 'cache GET', 20, 20, 'db'),
+ opSpan('cache-2', 'web', 'cache GET', 30, 30, 'db'),
+ ])
+ expect(dbSubtree.operations.map((o) => [o.name, o.share])).toEqual([
+ ['cache GET', 50 / 60],
+ ['SELECT', 10 / 60],
+ ])
+ expect(dbSubtree.operations.reduce((sum, o) => sum + o.share, 0)).toBeCloseTo(1)
+ })
+
+ it.each<[number[], number]>([
+ [[10, 20, 30], 20],
+ [[10, 20, 30, 40], 25],
+ ])('p50 is the median (%j ms)', (durationsMs, expectedMs) => {
+ const spans = durationsMs.map((ms, i) => opSpan(`span-${i}`, 'web', 'cache GET', 0, ms))
+
+ expect(summarizeTraceOperations(spans).operations[0].p50_duration_nano).toBe(expectedMs * 1_000_000)
+ })
+
+ it('returns an empty summary for no spans and a zero share when the spans have no self time', () => {
+ expect(summarizeTraceOperations([])).toEqual({ operations: [], spanCount: 0 })
+
+ const summary = summarizeTraceOperations([opSpan('root', 'web', 'GET /x', 0, 0)])
+ expect(summary.operations[0]).toMatchObject({ self_time_nano: 0, share: 0 })
+ })
+})
diff --git a/products/tracing/frontend/traceOperations.ts b/products/tracing/frontend/traceOperations.ts
new file mode 100644
index 000000000000..725bfffbe3e9
--- /dev/null
+++ b/products/tracing/frontend/traceOperations.ts
@@ -0,0 +1,125 @@
+import { compareRowKey } from './compareUtils'
+import { childSpansByParentId, parseTimestampUs } from './spanTree'
+import type { Span } from './types'
+
+export interface TraceOperation {
+ /** compareRowKey(span): the row identity the span tree highlight matches on. */
+ key: string
+ service_name: string
+ name: string
+ count: number
+ /** The time the operation's spans spend outside their loaded child spans. See selfTimeNanoBySpan. */
+ self_time_nano: number
+ /** Sum of span durations, so a span and the spans nested in it both count. */
+ total_duration_nano: number
+ avg_duration_nano: number
+ p50_duration_nano: number
+ /** self_time_nano / the self time of every span summarized, so the shares add up to 1. 0 when that sum is 0. */
+ share: number
+}
+
+export interface TraceOperationsSummary {
+ operations: TraceOperation[]
+ spanCount: number
+}
+
+interface OperationAccumulator {
+ service_name: string
+ name: string
+ durations: number[]
+ total: number
+ selfTime: number
+}
+
+function median(sortedValues: number[]): number {
+ const mid = Math.floor(sortedValues.length / 2)
+ return sortedValues.length % 2 === 1 ? sortedValues[mid] : (sortedValues[mid - 1] + sortedValues[mid]) / 2
+}
+
+/**
+ * Each span's self time in nanoseconds: its duration minus the union of its loaded child spans' intervals. A child
+ * interval is clipped to the span first, because a child can start before its parent or end after it, such as an
+ * async job the span only enqueued. Children that overlap count once. A child that is not loaded counts as self time.
+ * Keyed by span object, so two spans that share an id in malformed data each get their own value.
+ */
+export function selfTimeNanoBySpan(spans: Span[]): Map<Span, number> {
+ const childrenByParentId = childSpansByParentId(spans)
+ const selfTimes = new Map<Span, number>()
+ for (const span of spans) {
+ const startUs = parseTimestampUs(span.timestamp)
+ const endUs = startUs + span.duration_nano / 1_000
+ const intervals: [number, number][] = []
+ for (const child of childrenByParentId.get(span.span_id) ?? []) {
+ const childStartUs = parseTimestampUs(child.timestamp)
+ const clippedStartUs = Math.max(childStartUs, startUs)
+ const clippedEndUs = Math.min(childStartUs + child.duration_nano / 1_000, endUs)
+ if (clippedEndUs > clippedStartUs) {
+ intervals.push([clippedStartUs, clippedEndUs])
+ }
+ }
+ intervals.sort((a, b) => a[0] - b[0])
+ // Sorted by start, everything from an interval's start up to the furthest end so far is already covered,
+ // so each interval adds only the part past that end.
+ let coveredUs = 0
+ let coveredUntilUs = -Infinity
+ for (const [intervalStartUs, intervalEndUs] of intervals) {
+ const newFromUs = Math.max(intervalStartUs, coveredUntilUs)
+ if (intervalEndUs > newFromUs) {
+ coveredUs += intervalEndUs - newFromUs
+ coveredUntilUs = intervalEndUs
+ }
+ }
+ // Rounded to whole nanoseconds, and floored at 0, so float error in the microsecond math does not show.
+ selfTimes.set(span, Math.max(0, Math.round(span.duration_nano - coveredUs * 1_000)))
+ }
+ return selfTimes
+}
+
+function compareOperations(a: TraceOperation, b: TraceOperation): number {
+ if (a.self_time_nano !== b.self_time_nano) {
+ return b.self_time_nano - a.self_time_nano
+ }
+ if (a.count !== b.count) {
+ return b.count - a.count
+ }
+ // Code unit order, not localeCompare, so that the row order does not change with the viewer's locale.
+ return a.key < b.key ? -1 : a.key > b.key ? 1 : 0
+}
+
+/**
+ * The spans grouped by operation. Self time measures where the time goes, because it counts each moment once: the
+ * shares add up to 1 over the spans passed in, whether that is the whole trace or one span's subtree.
+ */
+export function summarizeTraceOperations(spans: Span[]): TraceOperationsSummary {
+ const selfTimes = selfTimeNanoBySpan(spans)
+ const groups = new Map<string, OperationAccumulator>()
+ let selfTimeSum = 0
+ for (const span of spans) {
+ const key = compareRowKey(span)
+ let group = groups.get(key)
+ if (!group) {
+ group = { service_name: span.service_name, name: span.name, durations: [], total: 0, selfTime: 0 }
+ groups.set(key, group)
+ }
+ const selfTime = selfTimes.get(span) ?? 0
+ group.durations.push(span.duration_nano)
+ group.total += span.duration_nano
+ group.selfTime += selfTime
+ selfTimeSum += selfTime
+ }
+
+ const operations: TraceOperation[] = Array.from(groups, ([key, group]) => ({
+ key,
+ service_name: group.service_name,
+ name: group.name,
+ count: group.durations.length,
+ self_time_nano: group.selfTime,
+ total_duration_nano: group.total,
+ avg_duration_nano: group.total / group.durations.length,
+ p50_duration_nano: median(group.durations.sort((a, b) => a - b)),
+ share: selfTimeSum > 0 ? group.selfTime / selfTimeSum : 0,
+ }))
+ operations.sort(compareOperations)
+
+ return { operations, spanCount: spans.length }
+}
diff --git a/products/tracing/frontend/tracingViewerLogic.ts b/products/tracing/frontend/tracingViewerLogic.ts
index 70a46332824c..1cec1cc909d4 100644
--- a/products/tracing/frontend/tracingViewerLogic.ts
+++ b/products/tracing/frontend/tracingViewerLogic.ts
@@ -121,7 +121,11 @@ export interface tracingViewerLogicActions {
selectViewSpan: (spanId: string | null) => {
spanId: string | null
} // traceViewLogic
- setInspectorTab: (tab: SpanInspectorTab) => {
+ setInspectorTab: (
+ tab: SpanInspectorTab,
+ surface?: import('./components/TraceView/traceViewLogic').TraceViewSurface | undefined
+ ) => {
+ surface: null | import('./components/TraceView/traceViewLogic').TraceViewSurface
tab: SpanInspectorTab
} // traceViewLogic
showTrace: (
diff --git a/products/tracing/frontend/types.ts b/products/tracing/frontend/types.ts
index f96bb26f51bc..565719534638 100644
--- a/products/tracing/frontend/types.ts
+++ b/products/tracing/frontend/types.ts
@@ -40,6 +40,7 @@ export const STATUS_CODE_LABELS: Record<number, { label: string; type: 'success'
2: { label: 'Error', type: 'danger' },
}
-// The trace drawer's inspector tabs. Query, Metrics and Errors are conditional, so the active tab
-// can point at a tab the drawer is not currently rendering.
-export type SpanInspectorTab = 'attributes' | 'query' | 'logs' | 'metrics' | 'errors' | 'raw'
+// The trace drawer's inspector tabs. Query, Errors, Operations and Metrics are conditional, so the
+// active tab can point at a tab the drawer is not currently rendering. Pinned: analytics events send
+// these values as the `tab` property, so renaming one breaks the insights built on it.
+export type SpanInspectorTab = 'attributes' | 'query' | 'logs' | 'errors' | 'operations' | 'metrics' | 'raw'