:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tracing): fold runs of repeated sibling spans in the span tree (#120589)
Roy Cohenb6d3872e7c92
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex f4119f9050cf..135b31886d49 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -561,6 +561,7 @@ export const FEATURE_FLAGS = {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 drawerTRACING_TRACE_CALL_TREE: 'tracing-trace-call-tree', // owner: #team-apm — gates the call tree view toggle in the trace viewTRACING_TRACE_DIALOG: 'tracing-trace-dialog', // owner: #team-apm — opens traces in a dialog over the current page instead of navigating to tracing+ TRACING_TRACE_FOLDED_RUNS: 'tracing-trace-folded-runs', // owner: #team-apm — folds runs of repeated sibling spans in the trace view's span treeTRACING_TRACE_OPERATIONS_TAB: 'tracing-trace-operations-tab', // owner: #team-apm — gates the Operations tab in the trace view's span inspectorTRACING_UI_V2: 'tracing-ui-v2',TRAFFIC_TYPE_VIRTUAL_PROPERTIES: 'traffic-type-virtual-properties', // owner: #team-web-analyticsdiff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogMoreSpansRow.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogMoreSpansRow.tsxindex 8272f54e07e0..646deb5c76e4 100644--- a/products/tracing/frontend/components/TraceDialog/TraceDialogMoreSpansRow.tsx+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogMoreSpansRow.tsx@@ -6,14 +6,21 @@ import type { TraceDialogRow } from './traceDialogRows'import { indentPx, TraceDialogTreeLines } from './TraceDialogTreeLines'export interface TraceDialogMoreSpansRowProps {- row: Extract<TraceDialogRow, { kind: 'more' }>+ row: Extract<TraceDialogRow, { kind: 'more' | 'fewer' }>/** None of the hidden spans belongs to the operation the Operations tab highlights. */isDimmed: booleanonShowAll: (spanId: string) => void+ onShowFewer: (spanId: string) => void}-export function TraceDialogMoreSpansRow({ row, isDimmed, onShowAll }: TraceDialogMoreSpansRowProps): JSX.Element {- const { parent, hiddenCount } = row+export function TraceDialogMoreSpansRow({+ row,+ isDimmed,+ onShowAll,+ onShowFewer,+}: TraceDialogMoreSpansRowProps): JSX.Element {+ const { parent } = row+ const onClick = row.kind === 'more' ? onShowAll : onShowFewerreturn (// Same columns and no gap as the span row, so the tree lines on both line up at any width.<div className="flex items-center w-full h-full text-xs text-muted border-l-[3px] border-l-transparent">@@ -24,16 +31,18 @@ export function TraceDialogMoreSpansRow({ row, isDimmed, onShowAll }: TraceDialostyle={{ paddingLeft: indentPx(row.depth) + 22 }}><TraceDialogTreeLines row={row} />- <span className={cn('relative', isDimmed && 'opacity-40')}>- {hiddenCount.toLocaleString()} more {hiddenCount === 1 ? 'span' : 'spans'}- </span>+ {row.kind === 'more' && (+ <span className={cn('relative', isDimmed && 'opacity-40')}>+ {row.hiddenCount.toLocaleString()} more {row.hiddenCount === 1 ? 'span' : 'spans'}+ </span>+ )}<LemonButtonsize="xsmall"type="tertiary"- onClick={() => onShowAll(parent.span.span_id)}- data-attr="trace-dialog-show-all-spans"+ onClick={() => onClick(parent.span.span_id)}+ data-attr={row.kind === 'more' ? 'trace-dialog-show-all-spans' : 'trace-dialog-show-fewer-spans'}>- Show all+ {row.kind === 'more' ? 'Show all' : 'Show fewer'}</LemonButton></span><span className="grow min-w-16" aria-hidden />diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanRow.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanRow.tsxindex 5152c2ac8c0d..c6b3ff8bf0de 100644--- a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanRow.tsx+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanRow.tsx@@ -1,22 +1,25 @@+import { type MouseEvent, useMemo } from 'react'+import { IconChevronRight, IconWarning } from '@posthog/icons'import { LemonTag, Tooltip } from '@posthog/lemon-ui'import { getSeriesColor } from 'lib/colors'import { cn } from 'lib/utils/css-classes'+import { humanFriendlyNumber } from 'lib/utils/numbers'import { parseTimestampUs } from 'products/tracing/frontend/spanTree'import { formatDuration } from 'products/tracing/frontend/TraceWaterfallView'-import type { TraceViewTimeline } from '../TraceView/traceViewLogic'+import type { TraceRunToggleMethod, TraceViewTimeline } from '../TraceView/traceViewLogic'import type { TraceDialogSource } from './traceDialogLogic'import { LOG_MARK_TAG_TYPE, TraceDialogLogMark } from './TraceDialogLogMark'-import type { TraceDialogRow } from './traceDialogRows'+import { summarizeRun, type TraceDialogRow } from './traceDialogRows'import { indentPx, MAX_VISUAL_DEPTH, TraceDialogTreeLines } from './TraceDialogTreeLines'const ERROR_COLOR = 'var(--danger)'export interface TraceDialogSpanRowProps {- row: Extract<TraceDialogRow, { kind: 'span' | 'chain' }>+ row: Extract<TraceDialogRow, { kind: 'span' | 'chain' | 'run' }>timeline: TraceViewTimelineserviceColorMap: Map<string, number>isSelected: boolean@@ -31,6 +34,13 @@ export interface TraceDialogSpanRowProps {onSelect: (spanId: string) => voidonToggleCollapsed: (spanId: string) => voidonToggleChain: (spanId: string) => void+ /** Takes the id of the run's first span. */+ onToggleRun: (spanId: string, method: TraceRunToggleMethod) => void+}++// Enter or Space on a focused button fires a click without a pointer press, which leaves `detail` at 0.+function toggleMethod(event: MouseEvent): TraceRunToggleMethod {+ return event.detail === 0 ? 'key' : 'click'}// Clock skew between a service's logs and spans can put the log outside the span it names.@@ -61,23 +71,34 @@ export function TraceDialogSpanRow({onSelect,onToggleCollapsed,onToggleChain,+ onToggleRun,}: TraceDialogSpanRowProps): JSX.Element {- const node = row.kind === 'chain' ? row.nodes[0] : row.node+ const node = row.kind === 'span' ? row.node : row.nodes[0]const chainLast = row.kind === 'chain' ? row.nodes[row.nodes.length - 1] : nullconst openChainLength = row.kind === 'span' ? row.openChainLength : undefined+ const openRunLength = row.kind === 'span' ? row.openRunLength : undefined+ const runNodes = row.kind === 'run' ? row.nodes : null+ // A run can hold thousands of spans, and the list renders its rows again on every scroll and selection. A row+ // object stays the same until the rows rebuild after a fold, an expand or a new page of spans, so this pass+ // over the members runs once per run and not once per render.+ const run = useMemo(() => (runNodes ? summarizeRun(runNodes) : null), [runNodes])+ const runCountText = runNodes ? humanFriendlyNumber(runNodes.length) : nullconst { span, isMissingParent = false } = nodeconst name = chainLast ? `${span.name} › … › ${chainLast.span.name}` : span.name- const startUs = parseTimestampUs(span.timestamp)+ const startUs = run ? run.startUs : parseTimestampUs(span.timestamp)+ const durationUs = run ? run.endUs - run.startUs : span.duration_nano / 1_000const leftPct = Math.max(percentOfTrace(startUs, timeline), 0)const widthPct = Math.max(- Math.min(- timeline.durationUs > 0 ? (span.duration_nano / 1_000 / timeline.durationUs) * 100 : 100,- 100 - leftPct- ),+ Math.min(timeline.durationUs > 0 ? (durationUs / timeline.durationUs) * 100 : 100, 100 - leftPct),0.3)- // 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)+ // A folded chain or run shows an error when any span in it errored, not only its first.+ const isError = run+ ? run.errorCount > 0+ : (row.kind === 'chain' ? row.nodes : [node]).some((member) => member.span.status_code === 2)+ // A folded run also hides the spans under its own. An error there gets only the icon, so that a failure under+ // the calls reads apart from a failed call.+ const hasNestedError = !!run && run.nestedErrorCount > 0const serviceColor = getSeriesColor(serviceColorMap.get(span.service_name) ?? 0)const barColor = isDimmed ? 'var(--border)' : isError ? ERROR_COLOR : serviceColorconst openedAtPct =@@ -94,15 +115,43 @@ export function TraceDialogSpanRow({: 'border-l-transparent hover:bg-surface-primary-hover')}>- <button- type="button"- className="absolute inset-0 cursor-pointer"- aria-pressed={isSelected}- aria-label={span.name}- title={isMissingParent ? name : `${name} · ${span.service_name}`}- onClick={() => onSelect(span.span_id)}- data-attr="trace-dialog-span-row"- />+ {run ? (+ // Opening a run never selects a span, so the inspector stays on the span the person picked.+ <button+ type="button"+ className="absolute inset-0 cursor-pointer"+ aria-expanded={false}+ aria-label={`Show ${runCountText} ${span.name} spans`}+ title={[+ `${span.name} ×${runCountText} · ${span.service_name}`,+ `${runCountText} spans, ${formatDuration(run.totalDurationNano)} in total`,+ `+${formatDuration((run.startUs - timeline.startUs) * 1_000)} to +${formatDuration(+ (run.endUs - timeline.startUs) * 1_000+ )} from the trace start`,+ ...(run.errorCount > 0 ? [`${humanFriendlyNumber(run.errorCount)} with an error status`] : []),+ ...(run.nestedErrorCount > 0+ ? [+ `${humanFriendlyNumber(run.nestedErrorCount)} nested ${+ run.nestedErrorCount === 1 ? 'span' : 'spans'+ } with an error status`,+ ]+ : []),+ ].join('\n')}+ onClick={(event) => onToggleRun(span.span_id, toggleMethod(event))}+ // pinned: data-attr value, because renaming it breaks autocapture dashboards and Playwright selectors+ data-attr="tracing-trace-expand-run"+ />+ ) : (+ <button+ type="button"+ className="absolute inset-0 cursor-pointer"+ aria-pressed={isSelected}+ aria-label={span.name}+ title={isMissingParent ? name : `${name} · ${span.service_name}`}+ onClick={() => onSelect(span.span_id)}+ data-attr="trace-dialog-span-row"+ />+ )}<span className="pointer-events-none relative w-16 shrink-0 px-2 font-mono text-muted" translate="no">+{formatDuration(Math.max(startUs - timeline.startUs, 0) * 1_000)}</span>@@ -112,7 +161,33 @@ export function TraceDialogSpanRow({style={{ paddingLeft: indentPx(row.depth) }}><TraceDialogTreeLines row={row} />- {chainLast ? (+ {!!openRunLength && (+ // The open counterpart of the folded run's chip. Its own collapse chip, if any, follows it.+ <button+ type="button"+ className="pointer-events-auto relative shrink-0 flex items-center gap-0.5 h-5 pl-0.5 pr-1.5 rounded border border-dashed border-accent bg-surface-primary text-[11px] font-semibold text-accent hover:bg-accent-highlight-secondary"+ aria-expanded+ aria-label={`Fold ${humanFriendlyNumber(openRunLength)} ${span.name} spans`}+ // Next to the span's own collapse chip, the two chips look alike.+ title={`Fold ${humanFriendlyNumber(openRunLength)} ${span.name} spans`}+ onClick={(event) => onToggleRun(span.span_id, toggleMethod(event))}+ // pinned: data-attr value, because renaming it breaks autocapture dashboards and Playwright selectors+ data-attr="tracing-trace-fold-run"+ >+ <IconChevronRight className="rotate-90" />+ {/* "×" like the folded run's label, so the count reads as repeats, not as nested spans. */}+ <span translate="no">×{humanFriendlyNumber(openRunLength)}</span>+ </button>+ )}+ {runNodes ? (+ // The whole row opens the run, so this only marks it as folded, in the style of a folded chain.+ <span+ className="relative shrink-0 flex items-center h-5 pl-0.5 pr-0.5 rounded border border-dashed border-accent bg-surface-primary text-accent"+ aria-hidden+ >+ <IconChevronRight />+ </span>+ ) : chainLast ? (<buttontype="button"className="pointer-events-auto relative shrink-0 flex items-center gap-0.5 h-5 pl-0.5 pr-1.5 rounded border border-dashed border-accent bg-surface-primary text-[11px] font-semibold text-accent hover:bg-accent-highlight-secondary"@@ -143,7 +218,7 @@ export function TraceDialogSpanRow({<spanclassName={cn('relative flex shrink-0 items-center justify-center',- descendantCount === 0 && !chainLast && 'w-4'+ descendantCount === 0 && !chainLast && !runNodes && !openRunLength && 'w-4')}aria-hidden>@@ -163,7 +238,13 @@ export function TraceDialogSpanRow({L{row.depth}</span>)}- {isError && <IconWarning className="shrink-0 text-danger" fontSize={14} aria-label="Error" />}+ {(isError || hasNestedError) && (+ <IconWarning+ className="shrink-0 text-danger"+ fontSize={14}+ aria-label={isError ? 'Error' : 'Error in nested spans'}+ />+ )}<spanclassName={cn('relative truncate font-mono',@@ -176,6 +257,14 @@ export function TraceDialogSpanRow({>{name}</span>+ {runCountText && (+ <span+ className={cn('relative shrink-0 font-mono text-secondary', isDimmed && 'opacity-40')}+ translate="no"+ >+ ×{runCountText}+ </span>+ )}{openedAtPct != null && openedFrom && (<LemonTagsize="small"@@ -244,7 +333,7 @@ export function TraceDialogSpanRow({className="pointer-events-none relative w-20 shrink-0 px-2 text-right font-mono text-muted"translate="no">- {isMissingParent ? '' : formatDuration(span.duration_nano)}+ {isMissingParent ? '' : formatDuration(run ? durationUs * 1_000 : span.duration_nano)}</span></div>)diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.test.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.test.tsxindex 923620337274..2c5551281913 100644--- a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.test.tsx+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.test.tsx@@ -1,8 +1,9 @@import '@testing-library/jest-dom'-import { act, cleanup, render, screen, waitFor } from '@testing-library/react'+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import { BindLogic, Provider } from 'kea'import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'import api from 'lib/api'import { FEATURE_FLAGS } from 'lib/constants'@@ -15,7 +16,7 @@ import type { Span } from 'products/tracing/frontend/types'import { traceViewLogic } from '../TraceView/traceViewLogic'import { TRACE_DIALOG_VIEW_ID, traceDialogLogic } from './traceDialogLogic'-import { TraceDialogSpanTree } from './TraceDialogSpanTree'+import { TraceDialogSpanTree, type TraceDialogSpanTreeProps } from './TraceDialogSpanTree'function span(spanId: string, parentSpanId: string): Span {return {@@ -37,9 +38,29 @@ function span(spanId: string, parentSpanId: string): Span {}}+function renderTree(viewId: string, spans: Span[], props: Partial<TraceDialogSpanTreeProps> = {}): HTMLElement {+ const view = traceViewLogic({ id: viewId })+ view.mount()+ view.actions.showTrace(null, null)+ view.actions.setSpans(spans)+ view.actions.selectSpan(spans[0].span_id)+ return render(+ <Provider>+ <BindLogic logic={traceViewLogic} props={{ id: viewId }}>+ <TraceDialogSpanTree surface="drawer" openedFrom={null} openedAtUs={null} {...props} />+ </BindLogic>+ </Provider>+ ).container+}+describe('TraceDialogSpanTree', () => {+ let captureSpy: jest.SpyInstance+beforeEach(() => {initKeaTests()+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TRACING_TRACE_FOLDED_RUNS]: true })+ captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)// jsdom lays nothing out, so the virtualized list needs a size to render rows into.jest.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(600)jest.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(1000)@@ -66,7 +87,7 @@ describe('TraceDialogSpanTree', () => {const { container } = render(<Provider><BindLogic logic={traceViewLogic} props={{ id: TRACE_DIALOG_VIEW_ID }}>- <TraceDialogSpanTree openedFrom={null} openedAtUs={null} />+ <TraceDialogSpanTree surface="trace_dialog" openedFrom={null} openedAtUs={null} /></BindLogic></Provider>)@@ -103,7 +124,7 @@ describe('TraceDialogSpanTree', () => {render(<Provider><BindLogic logic={traceViewLogic} props={{ id: 'span-tree-test' }}>- <TraceDialogSpanTree openedFrom={null} openedAtUs={null} />+ <TraceDialogSpanTree surface="trace_dialog" openedFrom={null} openedAtUs={null} /></BindLogic></Provider>)@@ -115,7 +136,7 @@ describe('TraceDialogSpanTree', () => {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+ // Fails when a page of spans that loads after the scroll to the operation 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()@@ -136,10 +157,16 @@ describe('TraceDialogSpanTree', () => {this.dispatchEvent(new Event('scroll'))}const onLoadMore = jest.fn()- render(+ const { container } = render(<Provider><BindLogic logic={traceViewLogic} props={{ id: 'span-tree-page-test' }}>- <TraceDialogSpanTree openedFrom={null} openedAtUs={null} hasMore onLoadMore={onLoadMore} />+ <TraceDialogSpanTree+ surface="drawer"+ openedFrom={null}+ openedAtUs={null}+ hasMore+ onLoadMore={onLoadMore}+ /></BindLogic></Provider>)@@ -147,9 +174,182 @@ describe('TraceDialogSpanTree', () => {act(() => view.actions.highlightOperation(compareRowKey({ service_name: 'agent-worker', name: 'cache GET' })))await screen.findByText('cache GET')+ // The tree pages only once the person moves it, so a wheel at the operation loads the next page.+ fireEvent.wheel(container.querySelector('[role="list"]')!)expect(onLoadMore).toHaveBeenCalled()act(() => view.actions.setSpans([...spans, span('LATE', 'P9')]))expect(screen.getByText('cache GET')).toBeInTheDocument()})++ // A loop of identical calls must take one row, and opening that row must not select a span, which would+ // move the inspector to a span the person did not pick. Fails too when a click toggle reaches the logic+ // without its method or surface, when an Enter on the focused fold control counts as a click, or when the+ // fold, which shows the run again, sends the runs shown event a second time.+ it('opens a folded run on click without selecting a span, and folds it again', async () => {+ const reads = ['A', 'B', 'C'].map((spanId) => ({ ...span(spanId, 'ROOT'), name: 'cache GET' }))+ const container = renderTree('span-tree-run-test', [span('ROOT', ''), ...reads])+ const selectedSpanId = (): string | null => traceViewLogic({ id: 'span-tree-run-test' }).values.selectedSpanId++ await waitFor(() => expect(container.querySelector('[data-attr="tracing-trace-expand-run"]')).not.toBeNull())+ expect(screen.getAllByText('cache GET')).toHaveLength(1)+ // A pointer click counts its presses in `detail`. A click that Enter fires on a focused button counts none.+ fireEvent.click(container.querySelector('[data-attr="tracing-trace-expand-run"]')!, { detail: 1 })++ await waitFor(() => expect(screen.getAllByText('cache GET')).toHaveLength(3))+ expect(selectedSpanId()).toBe('ROOT')++ fireEvent.click(container.querySelector('[data-attr="tracing-trace-fold-run"]')!, { detail: 0 })+ await waitFor(() => expect(screen.getAllByText('cache GET')).toHaveLength(1))+ expect(selectedSpanId()).toBe('ROOT')+ expect(captureSpy.mock.calls.filter(([event]) => event === 'tracing trace run toggled')).toEqual([+ ['tracing trace run toggled', { action: 'open', span_count: 3, method: 'click', surface: 'drawer' }],+ ['tracing trace run toggled', { action: 'fold', span_count: 3, method: 'key', surface: 'drawer' }],+ ])+ expect(captureSpy.mock.calls.filter(([event]) => event === 'tracing trace runs shown')).toEqual([+ ['tracing trace runs shown', { run_count: 1, largest_run: 3, surface: 'drawer' }],+ ])+ })++ // A folded run hides the spans under its own spans too. Fails when an error down there leaves no mark on the+ // run's row, or when it marks the row red like a failed call of the run itself.+ it.each([+ { where: 'one of its spans', errored: 'B', label: 'Error', isRed: true },+ { where: 'a span under it', errored: 'B1', label: 'Error in nested spans', isRed: false },+ ])('marks a folded run with an error in $where', async ({ errored, label, isRed }) => {+ const reads = ['A', 'B', 'C'].map((spanId) => ({ ...span(spanId, 'ROOT'), name: 'cache GET' }))+ const spans = [span('ROOT', ''), ...reads, span('B1', 'B')].map((loaded) =>+ loaded.span_id === errored ? { ...loaded, status_code: 2 } : loaded+ )+ renderTree('span-tree-run-error-test', spans)++ await screen.findByLabelText(label)+ expect(screen.getByText('cache GET').classList.contains('text-danger')).toBe(isRed)+ })++ // Fails when Show all has no way back, when Show fewer leaves the full list on screen, or when it leaves the+ // inspector on a selected child that the shorter list hides.+ it('shortens a full child list again with Show fewer, and moves a hidden selection to the parent', async () => {+ const children = Array.from({ length: 12 }, (_, i) => span(`C${i}`, 'ROOT'))+ const container = renderTree('span-tree-show-fewer-test', [span('ROOT', ''), ...children])+ // jsdom has no layout, so the list renders only the overscan rows around its scroll position, and each change+ // of the rows scrolls back to the selected root. A scroll down brings the end of the child list into range.+ const scrollDown = (): void => {+ fireEvent.scroll(container.querySelector('[role="list"]')!, { target: { scrollTop: 400 } })+ }++ scrollDown()+ fireEvent.click(await screen.findByText('Show all'))+ scrollDown()+ await screen.findByText('C11 span')+ expect(screen.queryByText('2 more spans')).toBeNull()+ const view = traceViewLogic({ id: 'span-tree-show-fewer-test' })+ act(() => view.actions.selectSpan('C11'))++ fireEvent.click(container.querySelector('[data-attr="trace-dialog-show-fewer-spans"]')!)+ scrollDown()+ await screen.findByText('2 more spans')+ expect(screen.queryByText('C11 span')).toBeNull()+ expect(view.values.selectedSpanId).toBe('ROOT')+ })++ // Fails when a trace that folds no run sends the event, when a later page of the same trace sends it again,+ // when only the first page counts, which misses a trace whose runs arrive with a later page, or when the next+ // trace sends nothing because its runs replace the last trace's without a render of the empty list.+ it.each([+ {+ trace: 'a run, then a page with another run',+ first: ['A', 'B', 'C'].map((spanId) => ({ ...span(spanId, 'ROOT'), name: 'cache GET' })),+ more: ['D', 'E', 'F', 'G'].map((spanId) => ({ ...span(spanId, 'ROOT'), name: 'redis GET' })),+ nextTrace: false,+ sent: [{ run_count: 1, largest_run: 3, surface: 'drawer' }],+ },+ {+ trace: 'no run',+ first: [span('A', 'ROOT')],+ more: [span('B', 'ROOT')],+ nextTrace: false,+ sent: [],+ },+ {+ trace: 'a run only on its second page',+ first: [span('A', 'ROOT')],+ more: ['B', 'C', 'D', 'E'].map((spanId) => ({ ...span(spanId, 'ROOT'), name: 'cache GET' })),+ nextTrace: false,+ sent: [{ run_count: 1, largest_run: 4, surface: 'drawer' }],+ },+ {+ trace: 'a run, then a second trace with runs',+ first: ['A', 'B', 'C'].map((spanId) => ({ ...span(spanId, 'ROOT'), name: 'cache GET' })),+ more: ['D', 'E', 'F', 'G'].map((spanId) => ({ ...span(spanId, 'ROOT'), name: 'redis GET' })),+ nextTrace: true,+ sent: [+ { run_count: 1, largest_run: 3, surface: 'drawer' },+ { run_count: 2, largest_run: 4, surface: 'drawer' },+ ],+ },+ ])('sends the runs shown event once per trace, given $trace', ({ first, more, nextTrace, sent }) => {+ const loaded = [span('ROOT', ''), ...first]+ renderTree('span-tree-runs-shown-test', loaded)+ const view = traceViewLogic({ id: 'span-tree-runs-shown-test' })+ act(() => {+ if (nextTrace) {+ view.actions.showTrace(null, null)+ }+ view.actions.setSpans([...loaded, ...more])+ })++ expect(+ captureSpy.mock.calls.filter(([event]) => event === 'tracing trace runs shown').map(([, props]) => props)+ ).toEqual(sent)+ })++ // Folded runs can make a large trace a few rows tall, so the end of the list is in view from the start.+ // Fails when the tree pages on that alone, which loads the whole trace without the person asking for it, or+ // when a J step to the end of the loaded spans no longer pages, because the view's key handler stops J+ // before the list sees it.+ it.each([+ { movement: 'a wheel scroll', move: (list: Element) => fireEvent.wheel(list) },+ {+ movement: 'a J step',+ move: () => traceViewLogic({ id: 'span-tree-paging-test' }).actions.selectNextSpan(),+ },+ ])('loads more spans only once the person moves the tree, here with $movement', async ({ move }) => {+ const onLoadMore = jest.fn()+ const container = renderTree('span-tree-paging-test', [span('ROOT', ''), span('A', 'ROOT')], {+ hasMore: true,+ onLoadMore,+ })++ await screen.findByText('A span')+ expect(onLoadMore).not.toHaveBeenCalled()++ move(container.querySelector('[role="list"]')!)+ await waitFor(() => expect(onLoadMore).toHaveBeenCalledTimes(1))+ })++ // Fails when the paging guard outlives its trace. The logic can hand over the next trace's spans in the same+ // tick as showTrace, so no render shows the empty list, and the page requested at the last trace's span count+ // would then block the next trace's first page.+ it('pages the next trace once the person moves it, when its spans arrive in the same tick as the trace', async () => {+ const onLoadMore = jest.fn()+ const container = renderTree('span-tree-paging-trace-test', [span('ROOT', ''), span('A', 'ROOT')], {+ hasMore: true,+ onLoadMore,+ })+ await screen.findByText('A span')+ fireEvent.wheel(container.querySelector('[role="list"]')!)+ await waitFor(() => expect(onLoadMore).toHaveBeenCalledTimes(1))++ const view = traceViewLogic({ id: 'span-tree-paging-trace-test' })+ act(() => {+ view.actions.showTrace(null, null)+ view.actions.setSpans([span('NEXT', ''), span('B', 'NEXT')])+ })+ await screen.findByText('B span')+ expect(onLoadMore).toHaveBeenCalledTimes(1)++ fireEvent.wheel(container.querySelector('[role="list"]')!)+ await waitFor(() => expect(onLoadMore).toHaveBeenCalledTimes(2))+ })})diff --git a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsxindex d501b356df83..17fa9567c78d 100644--- a/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx+++ b/products/tracing/frontend/components/TraceDialog/TraceDialogSpanTree.tsx@@ -1,5 +1,5 @@import { useActions, useValues } from 'kea'-import { CSSProperties, useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { CSSProperties, KeyboardEvent, PointerEvent, useCallback, useEffect, useMemo, useRef, useState } from 'react'import { List, useListRef } from 'react-window'import { AutoSizer } from 'lib/components/AutoSizer'@@ -9,7 +9,12 @@ import { getTimelineTicks } from 'products/tracing/frontend/spanTree'import { formatDuration } from 'products/tracing/frontend/TraceWaterfallView'import { TraceLoadMoreFooter } from '../TraceView/TraceLoadMoreFooter'-import { traceViewLogic, type TraceViewTimeline } from '../TraceView/traceViewLogic'+import {+ type TraceRunToggleMethod,+ traceViewLogic,+ type TraceViewSurface,+ type TraceViewTimeline,+} from '../TraceView/traceViewLogic'import type { TraceDialogSource } from './traceDialogLogic'import { TraceDialogMoreSpansRow } from './TraceDialogMoreSpansRow'import { rowSpanNode, type TraceDialogRow } from './traceDialogRows'@@ -17,6 +22,7 @@ import { TraceDialogSpanRow } from './TraceDialogSpanRow'const ROW_HEIGHT = 32const LOAD_MORE_THRESHOLD = 10+const SCROLL_KEYS = new Set(['ArrowDown', 'ArrowUp', 'PageDown', 'PageUp', 'End', 'Home', ' '])interface SpanListRowData {spanRows: TraceDialogRow[]@@ -33,7 +39,9 @@ interface SpanListRowData {onSelect: (spanId: string) => voidonToggleCollapsed: (spanId: string) => voidonToggleChain: (spanId: string) => void+ onToggleRun: (spanId: string, method: TraceRunToggleMethod) => voidonShowAll: (spanId: string) => void+ onShowFewer: (spanId: string) => void}function SpanListRow({@@ -49,6 +57,7 @@ function SpanListRow({openedFrom,operationRowMatches,onShowAll,+ onShowFewer,...rowProps}: {ariaAttributes: { 'aria-posinset': number; 'aria-setsize': number; role: 'listitem' }@@ -60,10 +69,15 @@ function SpanListRow({return (// eslint-disable-next-line react/forbid-dom-props<div {...ariaAttributes} style={style}>- {row.kind === 'more' ? (- <TraceDialogMoreSpansRow row={row} isDimmed={isDimmed} onShowAll={onShowAll} />+ {row.kind === 'more' || row.kind === 'fewer' ? (+ <TraceDialogMoreSpansRow+ row={row}+ isDimmed={isDimmed}+ onShowAll={onShowAll}+ onShowFewer={onShowFewer}+ />) : (- <SpanOrChainRow+ <SpanChainOrRunRowrow={row}selectedSpanId={selectedSpanId}openedSpanId={openedSpanId}@@ -79,7 +93,7 @@ function SpanListRow({)}-function SpanOrChainRow({+function SpanChainOrRunRow({row,selectedSpanId,openedSpanId,@@ -90,7 +104,7 @@ function SpanOrChainRow({collapsedSpanIds,rowProps,}: {- row: Extract<TraceDialogRow, { kind: 'span' | 'chain' }>+ row: Extract<TraceDialogRow, { kind: 'span' | 'chain' | 'run' }>selectedSpanId: string | nullopenedSpanId: string | nullopenedAtUs: number | null@@ -98,9 +112,12 @@ function SpanOrChainRow({isDimmed: booleandescendantCounts: Map<string, number>collapsedSpanIds: Set<string>- rowProps: Pick<SpanListRowData, 'timeline' | 'serviceColorMap' | 'onSelect' | 'onToggleCollapsed' | 'onToggleChain'>+ rowProps: Pick<+ SpanListRowData,+ 'timeline' | 'serviceColorMap' | 'onSelect' | 'onToggleCollapsed' | 'onToggleChain' | 'onToggleRun'+ >}): JSX.Element {- const spanId = (row.kind === 'chain' ? row.nodes[0] : row.node).span.span_id+ const spanId = (row.kind === 'span' ? row.node : row.nodes[0]).span.span_idreturn (<TraceDialogSpanRowrow={row}@@ -133,6 +150,8 @@ function rowLabel(row: TraceDialogRow): string {const MAX_PINNED_ANCESTORS = 4export interface TraceDialogSpanTreeProps {+ /** Where the tree sits, for analytics. */+ surface: TraceViewSurfaceopenedFrom: TraceDialogSource | nullopenedAtUs: number | nullhasMore?: boolean@@ -143,6 +162,7 @@ export interface TraceDialogSpanTreeProps {}export function TraceDialogSpanTree({+ surface,openedFrom,openedAtUs,hasMore = false,@@ -162,8 +182,24 @@ export function TraceDialogSpanTree({highlightedOperationKey,operationRowMatches,firstOperationRowIndex,+ summary,+ foldedRunStartIds,+ shownTraceCount,} = useValues(traceViewLogic)- const { selectSpan, toggleSpanCollapsed, toggleChain, showAllChildren } = useActions(traceViewLogic)+ const { selectSpan, toggleSpanCollapsed, toggleChain, toggleRun, showAllChildren, showFewerChildren, runsShown } =+ useActions(traceViewLogic)+ const onToggleRun = useCallback(+ (spanId: string, method: TraceRunToggleMethod): void => toggleRun(spanId, method, surface),+ [toggleRun, surface]+ )+ // The logic sends its event once per trace. This reports when folded runs come on screen, and again for each+ // new trace, because the next trace's runs can replace this one's without a render of the empty list between.+ const showsFoldedRuns = foldedRunStartIds.size > 0+ useEffect(() => {+ if (showsFoldedRuns) {+ runsShown(surface)+ }+ }, [showsFoldedRuns, shownTraceCount, runsShown, surface])const [topIndex, setTopIndex] = useState(0)const listRef = useListRef(null)@@ -178,21 +214,46 @@ export function TraceDialogSpanTree({// an early scroll is lost: retry each time the rendered rows change until the span is visible, then// leave scrolling to the user.const revealedIndexRef = useRef<number | null>(null)- // Fires at most once per loaded row count, so a page that adds no rows can't retrigger on every render.- const lastRequestedRowCountRef = useRef(-1)+ // Folded runs can make a large trace a few rows tall, so the end of the list is often in view without a+ // scroll. Paging on that alone would load the whole trace on its own, so the next page waits for the person+ // to scroll, and the button below the list stays for the rest. A page whose spans all fold into runs on+ // screen adds no row, so the guard counts loaded spans and not rows.+ // The guard belongs to one shown trace, so a scroll in the previous trace cannot page this one. It starts+ // again on the logic's trace count and not on an empty list, because the logic can hand over the next+ // trace's spans before a render shows the empty list.+ const pagingRef = useRef({ shownTraceCount, personScrolled: false, lastRequestedSpanCount: -1 })+ const pagingGuard = useCallback((): typeof pagingRef.current => {+ if (pagingRef.current.shownTraceCount !== shownTraceCount) {+ pagingRef.current = { shownTraceCount, personScrolled: false, lastRequestedSpanCount: -1 }+ }+ return pagingRef.current+ }, [shownTraceCount])+ const lastVisibleIndexRef = useRef(-1)+ const loadMoreAfterScroll = useCallback((): void => {+ const guard = pagingGuard()+ if (+ !guard.personScrolled ||+ !onLoadMore ||+ !hasMore ||+ loadingMore ||+ lastVisibleIndexRef.current < spanRows.length - 1 - LOAD_MORE_THRESHOLD ||+ guard.lastRequestedSpanCount === summary.spanCount+ ) {+ return+ }+ guard.personScrolled = false+ guard.lastRequestedSpanCount = summary.spanCount+ onLoadMore()+ }, [pagingGuard, onLoadMore, hasMore, loadingMore, spanRows.length, summary.spanCount])+ const onPersonScroll = useCallback((): void => {+ pagingGuard().personScrolled = true+ loadMoreAfterScroll()+ }, [pagingGuard, loadMoreAfterScroll])const onRowsRendered = useCallback((visibleRows: { startIndex: number; stopIndex: number }): void => {setTopIndex(visibleRows.startIndex)- if (- onLoadMore &&- hasMore &&- !loadingMore &&- visibleRows.stopIndex >= spanRows.length - 1 - LOAD_MORE_THRESHOLD &&- lastRequestedRowCountRef.current !== spanRows.length- ) {- lastRequestedRowCountRef.current = spanRows.length- onLoadMore()- }+ lastVisibleIndexRef.current = visibleRows.stopIndex+ loadMoreAfterScroll()if (openedIndex < 0 || revealedIndexRef.current === openedIndex) {return}@@ -202,7 +263,7 @@ export function TraceDialogSpanTree({}listRef.current?.scrollToRow({ index: openedIndex, align: 'center' })},- [openedIndex, listRef, onLoadMore, hasMore, loadingMore, spanRows.length]+ [openedIndex, listRef, loadMoreAfterScroll])// 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.@@ -221,6 +282,17 @@ export function TraceDialogSpanTree({listRef.current?.scrollToRow({ index, align: 'smart' })}}, [spanRows, spanTree, selectedSpanId, openedSpanId, listRef])+ // The view's key handler stops J and K before the list sees them, so a step reaches the list as a new+ // selection. A new selection among the same spans counts as the person's own movement, so a step to the end+ // of the loaded spans pages too. New spans or a new trace do not count.+ const lastSelectionRef = useRef({ selectedSpanId, spanTree })+ useEffect(() => {+ const last = lastSelectionRef.current+ lastSelectionRef.current = { selectedSpanId, spanTree }+ if (last.spanTree === spanTree && last.selectedSpanId !== selectedSpanId) {+ onPersonScroll()+ }+ }, [selectedSpanId, spanTree, onPersonScroll])// 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@@ -328,10 +400,25 @@ export function TraceDialogSpanTree({onSelect: selectSpan,onToggleCollapsed: toggleSpanCollapsed,onToggleChain: toggleChain,+ onToggleRun,onShowAll: showAllChildren,+ onShowFewer: showFewerChildren,}}listRef={listRef}onRowsRendered={onRowsRendered}+ onWheel={onPersonScroll}+ onTouchMove={onPersonScroll}+ onKeyDown={(event: KeyboardEvent<HTMLDivElement>) => {+ if (SCROLL_KEYS.has(event.key)) {+ onPersonScroll()+ }+ }}+ onPointerDown={(event: PointerEvent<HTMLDivElement>) => {+ // A press past the content width lands on the scrollbar.+ if (event.nativeEvent.offsetX >= event.currentTarget.clientWidth) {+ onPersonScroll()+ }+ }}/>)}/>diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.tsindex 6ffc26856316..731df8a67f10 100644--- a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts+++ b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.test.ts@@ -61,6 +61,7 @@ describe('traceDialogLogic', () => {featureFlagLogic.actions.setFeatureFlags([], {[FEATURE_FLAGS.TRACING_SPAN_ERROR_BADGES]: true,[FEATURE_FLAGS.TRACING_SESSION_PERSON_LINKS]: true,+ [FEATURE_FLAGS.TRACING_TRACE_FOLDED_RUNS]: true,})getTraceSpy = jest.spyOn(api.tracing, 'getTrace').mockResolvedValue(page(['a'], null))router.actions.push('/logs')@@ -348,6 +349,38 @@ describe('traceDialogLogic', () => {expect(view.values.selectedSpanId).toBe('A')})+ // Fails when the dialog's span keys toggle runs without the dialog's surface, which leaves key toggles out+ // of the dialog's numbers in the run funnel.+ it('opens a folded run with the right arrow, and reports the key and the dialog surface', async () => {+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)+ getTraceSpy.mockResolvedValue({+ results: [+ { ...span('ROOT'), is_root_span: true },+ ...['R1', 'R2', 'R3'].map((spanId) => ({+ ...span(spanId),+ name: 'cache GET',+ parent_span_id: 'ROOT',+ })),+ ],+ hasMore: false,+ nextOffset: null,+ })+ logic.actions.openTraceDialog({ traceId: 'abc123', spanId: 'ROOT' }, { entryPoint: 'log_details' })+ await expectLogic(logic).toDispatchActions(['loadTraceSpansSuccess'])++ press('j')+ press('ArrowRight')++ expect(view.values.flatSpans.map((node) => node.span.span_id)).toEqual(['ROOT', 'R1', 'R2', 'R3'])+ expect(captureSpy).toHaveBeenCalledWith('tracing trace run toggled', {+ action: 'open',+ span_count: 3,+ method: 'key',+ surface: 'trace_dialog',+ })+ captureSpy.mockRestore()+ })+it('steps onto a missing parent row and on past it', async () => {const orphan = { ...span('b'), parent_span_id: 'GONE' }getTraceSpy.mockResolvedValue({ results: [span('a'), orphan], hasMore: false, nextOffset: null })@@ -480,6 +513,7 @@ describe('traceDialogLogic', () => {logic.actions.selectNextSpan()logic.actions.setInspectorTab('attributes')logic.actions.toggleSpanCollapsed('a')+ logic.actions.toggleRun('b')logic.actions.closeTraceDialog()expect(captureSpy).toHaveBeenCalledWith('tracing trace dialog opened', {@@ -495,41 +529,71 @@ describe('traceDialogLogic', () => {reason: 'dismissed',spans_selected: 1,keyboard_steps: 1,- collapse_toggles: 1,+ collapse_toggles: 2,tabs_viewed: ['attributes'],}))})- // 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 })- )- })+ // Fails when the highlight, or a selection from outside the tree, opens what hides its span with the+ // toggle actions, which the dialog counts as the person's own collapse toggles, or when the opened run+ // sends the event for the person's own run toggles.+ it.each([+ {+ opener: 'a highlight',+ // a > b > c > d > e, so b to d fold into a chain that hides c.+ spans: ['a', 'b', 'c', 'd', 'e'].map((spanId, i, ids) => ({+ ...span(spanId),+ parent_span_id: i === 0 ? '' : ids[i - 1],+ })),+ open: () =>+ view.actions.highlightOperation(+ compareRowKey({ service_name: 'agent-worker', name: 'c' }),+ 'trace_dialog',+ 'span'+ ),+ opened: () => view.values.openChainIds,+ expected: new Set(['b']),+ viewEvents: [['tracing trace operation highlighted', { surface: 'trace_dialog', scope: 'span' }]],+ },+ {+ opener: 'a selection from outside the tree',+ // a > r1, r2, r3 of one operation, so they fold into a run that hides r2.+ spans: [+ span('a'),+ ...['r1', 'r2', 'r3'].map((spanId) => ({+ ...span(spanId),+ name: 'cache GET',+ parent_span_id: 'a',+ })),+ ],+ open: () => view.actions.selectSpan('r2'),+ opened: () => view.values.openRunIds,+ expected: new Set(['r1']),+ viewEvents: [],+ },+ ])(+ 'does not count the spans $opener opens as toggles by the person',+ async ({ spans, open, opened, expected, viewEvents }) => {+ getTraceSpy.mockResolvedValue({ results: spans, hasMore: false, nextOffset: null })+ logic.actions.openTraceDialog({ traceId: 'abc123' }, { entryPoint: 'log_details' })+ await expectLogic(logic).toDispatchActions(['loadTraceSpansSuccess'])+ expect(opened()).toEqual(new Set())++ open()+ expect(opened()).toEqual(expected)+ logic.actions.closeTraceDialog()++ expect(+ captureSpy.mock.calls.filter(([event]) =>+ ['tracing trace operation highlighted', 'tracing trace run toggled'].includes(event)+ )+ ).toEqual(viewEvents)+ 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.tsindex 1fd92bcfd70b..07590a466df0 100644--- a/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts+++ b/products/tracing/frontend/components/TraceDialog/traceDialogLogic.ts@@ -170,17 +170,21 @@ export interface traceDialogLogicActions {modalContext: SessionPlayerModalContextsessionRecording: Pick<SessionRecordingType, 'id' | 'matching_events'>} // sessionPlayerModalLogic- collapseSelectedSpan: () => {- value: true+ collapseSelectedSpan: (surface: import('../TraceView/traceViewLogic').TraceViewSurface) => {+ surface: import('../TraceView/traceViewLogic').TraceViewSurface} // traceViewLogicdisableSpanKeys: () => {value: true} // traceViewLogic- enableSpanKeys: (containerSelector: string) => {+ enableSpanKeys: (+ containerSelector: string,+ surface: import('../TraceView/traceViewLogic').TraceViewSurface+ ) => {containerSelector: string+ surface: import('../TraceView/traceViewLogic').TraceViewSurface} // traceViewLogic- expandSelectedSpan: () => {- value: true+ expandSelectedSpan: (surface: import('../TraceView/traceViewLogic').TraceViewSurface) => {+ surface: import('../TraceView/traceViewLogic').TraceViewSurface} // traceViewLogicselectNextSpan: () => {value: true@@ -214,6 +218,15 @@ export interface traceDialogLogicActions {toggleChain: (spanId: string) => {spanId: string} // traceViewLogic+ toggleRun: (+ spanId: string,+ method?: import('../TraceView/traceViewLogic').TraceRunToggleMethod | undefined,+ surface?: import('../TraceView/traceViewLogic').TraceViewSurface | undefined+ ) => {+ method: null | import('../TraceView/traceViewLogic').TraceRunToggleMethod+ spanId: string+ surface: null | import('../TraceView/traceViewLogic').TraceViewSurface+ } // traceViewLogictoggleSpanCollapsed: (spanId: string) => {spanId: string} // traceViewLogic@@ -302,6 +315,7 @@ export const traceDialogLogic = kea<traceDialogLogicType>(['setInspectorTab','toggleSpanCollapsed','toggleChain',+ 'toggleRun','spanStepped','selectNextSpan','selectPreviousSpan',@@ -488,7 +502,7 @@ export const traceDialogLogic = kea<traceDialogLogicType>([})actions.showTrace(trace.spanId, null)actions.loadTraceSpans(trace)- actions.enableSpanKeys(TRACE_DIALOG_SELECTOR)+ actions.enableSpanKeys(TRACE_DIALOG_SELECTOR, 'trace_dialog')},closeTraceDialog: ({ reason }) => {actions.disableSpanKeys()@@ -548,6 +562,11 @@ export const traceDialogLogic = kea<traceDialogLogicType>([cache.session.collapseToggles += 1}},+ toggleRun: () => {+ if (cache.session) {+ cache.session.collapseToggles += 1+ }+ },// The player and the full-screen logs viewer are global modals that can sit below this one,// so opening either from the inspector would put it behind the dialog.openSessionPlayer: () => {diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogRows.test.ts b/products/tracing/frontend/components/TraceDialog/traceDialogRows.test.tsindex fc319b2aebba..fc6d7cb7e34e 100644--- a/products/tracing/frontend/components/TraceDialog/traceDialogRows.test.ts+++ b/products/tracing/frontend/components/TraceDialog/traceDialogRows.test.ts@@ -10,7 +10,9 @@ import {operationRowMatches,revealSpanInRows,rowConnectorLines,+ summarizeRun,type TraceDialogRow,+ type TraceDialogRowOptions,} from './traceDialogRows'function span(spanId: string, parentSpanId: string, offsetMs: number): Span {@@ -33,16 +35,42 @@ function span(spanId: string, parentSpanId: string, offsetMs: number): Span {}}+function opSpan(+ spanId: string,+ parentSpanId: string,+ offsetMs: number,+ name: string,+ serviceName = 'agent-worker'+): Span {+ return { ...span(spanId, parentSpanId, offsetMs), name, service_name: serviceName }+}+function labels(rows: TraceDialogRow[]): string[] {return rows.map((row) =>row.kind === 'span'? row.node.span.span_id: row.kind === 'chain'? `[${row.nodes.map((node) => node.span.span_id).join('>')}]`- : `+${row.hiddenCount}`+ : row.kind === 'run'+ ? `${row.nodes[0].span.span_id}×${row.nodes.length}`+ : row.kind === 'more'+ ? `+${row.hiddenCount}`+ : 'fewer')}+function rowOptions(overrides: Partial<TraceDialogRowOptions> = {}): TraceDialogRowOptions {+ return {+ collapsedSpanIds: new Set(),+ fullChildListSpanIds: new Set(),+ openChainIds: new Set(),+ foldRuns: true,+ openRunIds: new Set(),+ pinned: null,+ ...overrides,+ }+}+function find(roots: SpanNode[], spanId: string): SpanNode {const stack = [...roots]while (stack.length > 0) {@@ -79,12 +107,20 @@ describe('traceDialogRows', () => {['root', 'c0', 'g0', ...firstTen.slice(1), '+2'],],['hides a collapsed subtree', new Set(['c0']), new Set<string>(), null, ['root', ...firstTen, '+2']],+ // The full list ends with a row that shortens it again, but only where the cap would shorten it.['shows every child once asked',new Set<string>(),new Set(['root']),null,- ['root', 'c0', 'g0', ...firstTen.slice(1), 'c10', 'c11'],+ ['root', 'c0', 'g0', ...firstTen.slice(1), 'c10', 'c11', 'fewer'],+ ],+ [+ 'adds no show fewer row to a full list within the cap',+ new Set<string>(),+ new Set(['c0']),+ null,+ ['root', 'c0', 'g0', ...firstTen.slice(1), '+2'],],// The span a log came from stays on screen when it sits past the cap.[@@ -99,12 +135,10 @@ describe('traceDialogRows', () => {expect(labels(- buildTraceDialogRows(roots, {- collapsedSpanIds: collapsed,- fullChildListSpanIds: fullChildLists,- openChainIds: new Set(),- pinned,- })+ buildTraceDialogRows(+ roots,+ rowOptions({ collapsedSpanIds: collapsed, fullChildListSpanIds: fullChildLists, pinned })+ ))).toEqual(expected)})@@ -121,12 +155,7 @@ describe('traceDialogRows', () => {span('f', 'd', 6),])const build = (openChainIds: Set<string>, pinnedId: string | null = null): TraceDialogRow[] =>- buildTraceDialogRows(chain, {- collapsedSpanIds: new Set(),- fullChildListSpanIds: new Set(),- openChainIds,- pinned: pinnedId ? find(chain, pinnedId) : null,- })+ buildTraceDialogRows(chain, rowOptions({ openChainIds, pinned: pinnedId ? find(chain, pinnedId) : null }))it.each([[@@ -157,12 +186,7 @@ describe('traceDialogRows', () => {span('e', 'd', 5),span('f', 'e', 6),])- const rows = buildTraceDialogRows(long, {- collapsedSpanIds: new Set(),- fullChildListSpanIds: new Set(),- openChainIds: new Set(),- pinned: find(long, 'a'),- })+ const rows = buildTraceDialogRows(long, rowOptions({ pinned: find(long, 'a') }))expect(labels(rows)).toEqual(['root', 'a', '[b>c>d>e]', 'f'])})@@ -176,6 +200,161 @@ describe('traceDialogRows', () => {expect(rowConnectorLines(f)).toEqual([false, false])})})+ describe('runs', () => {+ // A root with three cache reads. The second read makes a call of its own.+ const cacheTree = buildSpanTree([+ span('root', '', 0),+ opSpan('cache-1', 'root', 1, 'cache GET'),+ opSpan('cache-2', 'root', 2, 'cache GET'),+ opSpan('redis-1', 'cache-2', 2, 'redis GET'),+ opSpan('cache-3', 'root', 3, 'cache GET'),+ ])+ const opened = ['root', 'cache-1', 'cache-2', 'redis-1', 'cache-3']++ // Fails when a loop of identical calls is listed span by span, when a folded run shows the calls its+ // spans make, or when batches split by another operation merge. The pair on another service shares the+ // name but not the operation.+ it('folds three or more adjacent siblings of one operation, and another operation between them splits the run', () => {+ const tree = buildSpanTree([+ span('root', '', 0),+ opSpan('a1', 'root', 1, 'cache GET'),+ opSpan('a1-call', 'a1', 1, 'redis GET'),+ opSpan('a2', 'root', 2, 'cache GET'),+ opSpan('a3', 'root', 3, 'cache GET'),+ opSpan('select', 'root', 4, 'SELECT'),+ opSpan('b1', 'root', 5, 'cache GET', 'worker'),+ opSpan('b2', 'root', 6, 'cache GET', 'worker'),+ opSpan('c1', 'root', 7, 'cache GET'),+ opSpan('c2', 'root', 8, 'cache GET'),+ opSpan('c3', 'root', 9, 'cache GET'),+ ])++ expect(labels(buildTraceDialogRows(tree, rowOptions()))).toEqual([+ 'root',+ 'a1×3',+ 'select',+ 'b1',+ 'b2',+ 'c1×3',+ ])+ })++ // Fails when a deep link lands on a span that a folded run hides, when a run that only the pin holds+ // open offers a fold control that would change nothing, or when a run folds with the flag off.+ it.each([+ { state: 'no state', options: {}, expected: ['root', 'cache-1×3'], openRunLength: undefined },+ {+ state: 'its id in openRunIds',+ options: { openRunIds: new Set(['cache-1']) },+ expected: opened,+ openRunLength: 3,+ },+ {+ state: 'the pin under one of its spans',+ options: { pinned: find(cacheTree, 'redis-1') },+ expected: opened,+ openRunLength: undefined,+ },+ {+ state: 'a collapsed parent',+ options: { collapsedSpanIds: new Set(['root']) },+ expected: ['root'],+ openRunLength: undefined,+ },+ {+ state: 'folding turned off',+ options: { foldRuns: false },+ expected: opened,+ openRunLength: undefined,+ },+ ])('with $state, lists the run as expected', ({ options, expected, openRunLength }) => {+ const rows = buildTraceDialogRows(cacheTree, rowOptions(options))++ expect(labels(rows)).toEqual(expected)+ expect(rows[1]?.kind === 'span' ? rows[1].openRunLength : undefined).toEqual(openRunLength)+ })++ it('never folds missing-parent placeholders, so each orphaned span keeps its own row', () => {+ const tree = buildSpanTree([1, 2, 3].map((i) => opSpan(`orphan-${i}`, `gone-${i}`, i, 'GET /x')))++ expect(labels(buildTraceDialogRows(tree, rowOptions()))).toEqual([+ 'gone-1',+ 'orphan-1',+ 'gone-2',+ 'orphan-2',+ 'gone-3',+ 'orphan-3',+ ])+ })++ // Fails when the cap counts spans before the fold, which shows ten reads of a run of thousands and a+ // "more" row for the rest, when the "more" row counts a hidden run as one span, or when the cap stops+ // counting spans with folding turned off.+ it.each([+ {+ folding: 'on',+ foldRuns: true,+ expected: ['root', 'get0×20', ...Array.from({ length: 9 }, (_, i) => `d${i}`), '+5'],+ },+ {+ folding: 'off',+ foldRuns: false,+ expected: ['root', ...Array.from({ length: 10 }, (_, i) => `get${i}`), '+24'],+ },+ ])(+ 'with folding $folding, caps the rows after the fold, and the more row counts the spans it hides',+ ({ foldRuns, expected }) => {+ const tree = buildSpanTree([+ span('root', '', 0),+ ...Array.from({ length: 20 }, (_, i) => opSpan(`get${i}`, 'root', 1 + i, 'cache GET')),+ ...Array.from({ length: 9 }, (_, i) => span(`d${i}`, 'root', 30 + i)),+ ...Array.from({ length: 5 }, (_, i) => opSpan(`put${i}`, 'root', 40 + i, 'cache PUT')),+ ])++ expect(labels(buildTraceDialogRows(tree, rowOptions({ foldRuns })))).toEqual(expected)+ }+ )++ // Fails when an opened run takes ten items of the cap, which hides the spans after it behind a more row.+ it('counts an opened run as one item of the cap and lists all of its spans', () => {+ const tree = buildSpanTree([+ span('root', '', 0),+ ...Array.from({ length: 20 }, (_, i) => opSpan(`get${i}`, 'root', 1 + i, 'cache GET')),+ ...Array.from({ length: 3 }, (_, i) => span(`d${i}`, 'root', 30 + i)),+ ])++ expect(labels(buildTraceDialogRows(tree, rowOptions({ openRunIds: new Set(['get0']) })))).toEqual([+ 'root',+ ...Array.from({ length: 20 }, (_, i) => `get${i}`),+ 'd0',+ 'd1',+ 'd2',+ ])+ })++ // Fails when the run's bar ends at its last span's end, which cuts off an earlier span that outlasts it, or+ // when an error two levels under the run's spans goes uncounted, which the folded run would hide.+ it('summarizes a run from the first start to the latest end', () => {+ const tree = buildSpanTree([+ span('root', '', 0),+ { ...opSpan('long', 'root', 1, 'cache GET'), duration_nano: 10_000_000, status_code: 2 },+ opSpan('short-1', 'root', 2, 'cache GET'),+ opSpan('short-2', 'root', 3, 'cache GET'),+ span('retry', 'short-1', 2),+ { ...span('socket', 'retry', 2), status_code: 2 },+ ])+ const start = Date.UTC(2026, 9, 14, 10) * 1_000++ expect(summarizeRun(tree[0].children)).toEqual({+ startUs: start + 1_000,+ endUs: start + 11_000,+ totalDurationNano: 12_000_000,+ errorCount: 1,+ nestedErrorCount: 1,+ })+ })+ })+// 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([@@ -189,15 +368,41 @@ describe('traceDialogRows', () => {{ 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: {} },+ { hiddenBy: 'a folded run', spanId: 'q', collapsed: [], reveal: { runIds: ['l0'] } },+ { hiddenBy: 'nested folded runs', spanId: 'z', collapsed: [], reveal: { runIds: ['l0', 'r0'] } },+ {+ hiddenBy: 'a folded run past the child cap',+ spanId: 'w',+ collapsed: [],+ reveal: { fullChildListSpanIds: ['root'], runIds: ['t0'] },+ },+ // The folded run row stands for its first span and carries the operation's name.+ { hiddenBy: 'nothing, as the first span of a folded run', spanId: 'loop', collapsed: [], reveal: {} },+ // The cap counts a folded run as one item, so the span is the eleventh child but only the ninth item.+ {+ hiddenBy: 'nothing, as a span that a folded run keeps inside the cap',+ spanId: 's6',+ 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.+ // The root fans out to x, c0 to c11 and a run of three tail spans, so c9 to c11 and the run sit past the+ // cap. The second tail span has a child w. c11 fans out to d0 to d11 in turn. c0 has a child g0, a run of+ // three loop spans and s0 to s6. The second loop span has a child q and a run of three inner spans, the+ // second of which has a child z. 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),+ ...[0, 1, 2].map((i) => opSpan(`l${i}`, 'c0', 12 + i, 'loop')),+ span('q', 'l1', 13),+ ...[0, 1, 2].map((i) => opSpan(`r${i}`, 'l1', 14 + i, 'inner')),+ span('z', 'r1', 15),+ ...Array.from({ length: 7 }, (_, i) => span(`s${i}`, 'c0', 20 + i)),+ ...[0, 1, 2].map((i) => opSpan(`t${i}`, 'root', 25 + i, 'tail')),+ span('w', 't1', 26),span('a', 'x', 6),span('b', 'a', 7),span('c', 'b', 8),@@ -205,14 +410,13 @@ describe('traceDialogRows', () => {])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 })+ expect(revealSpanInRows(tree, target!, rowOptions({ collapsedSpanIds: new Set(collapsed) }))).toEqual({+ collapsedSpanIds: [],+ fullChildListSpanIds: [],+ chainIds: [],+ runIds: [],+ ...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.@@ -220,21 +424,22 @@ describe('traceDialogRows', () => {{ 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 },+ { row: 'a folded run of the operation', label: 'l0×3', operation: 'loop', matches: true },+ { row: 'a folded run with a match under one of its spans', label: 'l0×3', operation: 'm', matches: true },+ { row: 'a folded run with no match in it', label: 'l0×3', operation: 'g0', matches: false },])('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.+ // c1 has a run of three loop spans, and the last one has a child m.const tree = buildSpanTree([span('root', '', 0),...Array.from({ length: 12 }, (_, i) => span(`c${i}`, 'root', 10 + i)),span('g0', 'c0', 11),+ ...[0, 1, 2].map((i) => opSpan(`l${i}`, 'c1', 12 + i, 'loop')),+ span('m', 'l2', 15),span('h', 'c11', 22),])const collapsedSpanIds = new Set(['c0'])- const rows = buildTraceDialogRows(tree, {- collapsedSpanIds,- fullChildListSpanIds: new Set(),- openChainIds: new Set(),- pinned: null,- })+ const rows = buildTraceDialogRows(tree, rowOptions({ collapsedSpanIds }))const operationKey = compareRowKey({ service_name: 'agent-worker', name: operation })const rowMatches = operationRowMatches(diff --git a/products/tracing/frontend/components/TraceDialog/traceDialogRows.ts b/products/tracing/frontend/components/TraceDialog/traceDialogRows.tsindex ef4a375013ad..1b0da0715c01 100644--- a/products/tracing/frontend/components/TraceDialog/traceDialogRows.ts+++ b/products/tracing/frontend/components/TraceDialog/traceDialogRows.ts@@ -4,6 +4,7 @@ import { parseTimestampUs, type SpanNode } from 'products/tracing/frontend/spanT// A wide fan-out shows this many children until the person asks for the rest.export const TRACE_DIALOG_CHILD_LIMIT = 10export const TRACE_DIALOG_MIN_CHAIN = 3+export const TRACE_DIALOG_MIN_RUN = 3interface TraceDialogRowBase {depth: number@@ -18,15 +19,26 @@ export type TraceDialogRow = TraceDialogRowBase &kind: 'span'node: SpanNodeopenChainLength?: number+ /** Set on the first span of an opened run that can fold again. */+ openRunLength?: number+ /** Set on every span of an opened run that can fold again: the run's first span, which stays listed. */+ openRunStart?: SpanNode}/** The first span stands for the chain in selection and the inspector. */| { kind: 'chain'; nodes: SpanNode[] }+ /**+ * Adjacent siblings of one operation, in start order. `key` is their `compareRowKey`. The first span+ * stands for the run in selection and the inspector, so J and K stop on it without opening it.+ */+ | { kind: 'run'; nodes: SpanNode[]; key: string }/** `hidden` holds the children past the cap, in start order. */| { kind: 'more'; parent: SpanNode; hiddenCount: number; hidden: SpanNode[] }+ /** Ends a full child list that is longer than the cap, so the person can shorten it again. */+ | { kind: 'fewer'; parent: SpanNode })export function rowSpanNode(row: TraceDialogRow): SpanNode | null {- return row.kind === 'span' ? row.node : row.kind === 'chain' ? row.nodes[0] : null+ return row.kind === 'span' ? row.node : row.kind === 'chain' || row.kind === 'run' ? row.nodes[0] : null}function byStart(nodes: SpanNode[]): SpanNode[] {@@ -76,51 +88,150 @@ export interface TraceDialogRowOptions {collapsedSpanIds: Set<string>fullChildListSpanIds: Set<string>openChainIds: Set<string>- /** The span a log came from. It stays on screen: past the child cap, and outside folded chains. */+ /** False gives every span a row of its own and makes the child cap count spans. */+ foldRuns: boolean+ /** Runs fold by default, so this holds the opened ones, by the id of their first span. */+ openRunIds: Set<string>+ /** The span a log came from. It stays on screen: past the child cap, and outside folded chains and runs. */pinned: SpanNode | null}-/** Chains fold so long call chains don't push the tree off the right edge. */+/** Siblings in start order, split where the operation changes. A group of one operation can fold into a run. */+function operationGroups(sorted: SpanNode[]): SpanNode[][] {+ const groups: SpanNode[][] = []+ let lastKey: string | null = null+ for (const node of sorted) {+ // Placeholders all share one label, but each one stands for a different absent parent, so they never fold.+ const key = node.isMissingParent ? null : compareRowKey(node.span)+ if (key !== null && key === lastKey) {+ groups[groups.length - 1].push(node)+ } else {+ groups.push([node])+ }+ lastKey = key+ }+ return groups+}++/**+ * The siblings that count as one item toward the child cap: a span, a folded run, or an opened run, which+ * lists all of its spans. `foldable` is false for a run that the pin holds open, because a fold would change+ * nothing.+ */+type Unit = { node: SpanNode } | { run: SpanNode[] } | { openRun: SpanNode[]; foldable: boolean }++function unitSpans(unit: Unit): SpanNode[] {+ return 'node' in unit ? [unit.node] : 'run' in unit ? unit.run : unit.openRun+}++// A run with the pinned span in it or under it never folds, so a folded run is never on the pinned path.+function unitOnPinnedPath(unit: Unit, pinnedPath: Set<SpanNode>): boolean {+ return !('run' in unit) && unitSpans(unit).some((node) => pinnedPath.has(node))+}++interface SiblingUnitOptions {+ foldRuns: boolean+ openRunIds: Set<string>+ pinnedPath: Set<SpanNode>+}++/** Siblings in start order, as items of the child cap. The row builder and the reveal both use it, so they agree. */+function siblingUnits(siblings: SpanNode[], { foldRuns, openRunIds, pinnedPath }: SiblingUnitOptions): Unit[] {+ if (!foldRuns) {+ return byStart(siblings).map((node) => ({ node }))+ }+ return operationGroups(byStart(siblings)).flatMap((group): Unit[] => {+ if (group.length < TRACE_DIALOG_MIN_RUN) {+ return group.map((node) => ({ node }))+ }+ if (group.some((member) => pinnedPath.has(member))) {+ return [{ openRun: group, foldable: false }]+ }+ return openRunIds.has(group[0].span.span_id) ? [{ openRun: group, foldable: true }] : [{ run: group }]+ })+}++/**+ * Chains fold so long call chains don't push the tree off the right edge. Runs of one operation under one parent+ * fold so a loop of identical calls doesn't push the rest of the trace out of view.+ */export function buildTraceDialogRows(roots: SpanNode[],- { collapsedSpanIds, fullChildListSpanIds, openChainIds, pinned }: TraceDialogRowOptions+ { collapsedSpanIds, fullChildListSpanIds, openChainIds, foldRuns, openRunIds, pinned }: TraceDialogRowOptions): TraceDialogRow[] {const pinnedPath = new Set<SpanNode>()for (let node = pinned; node; node = node.parent) {pinnedPath.add(node)}+ const unitOptions: SiblingUnitOptions = { foldRuns, openRunIds, pinnedPath }- type Pending = { node: SpanNode; depth: number; isLast: boolean; parentRow: TraceDialogRow | null }+ type Pending = {+ node: SpanNode+ depth: number+ isLast: boolean+ parentRow: TraceDialogRow | null+ openRunLength?: number+ openRunStart?: SpanNode+ }const rows: TraceDialogRow[] = []// Spans that must not start a fold: members of an opened chain, and spans at or above the pinned// 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 unitRows = (+ units: Unit[],+ depth: number,+ parentRow: TraceDialogRow | null,+ hasTrailingRow: boolean+ ): (Pending | TraceDialogRow)[] => {+ const entries = units.flatMap((unit): (Pending | TraceDialogRow)[] => {+ if ('run' in unit) {+ const key = compareRowKey(unit.run[0].span)+ return [{ kind: 'run', nodes: unit.run, key, depth, isLast: false, parentRow }]+ }+ if ('node' in unit) {+ return [{ node: unit.node, depth, isLast: false, parentRow }]+ }+ return unit.openRun.map((node, i) => ({+ node,+ depth,+ isLast: false,+ parentRow,+ ...(unit.foldable && i === 0 ? { openRunLength: unit.openRun.length } : {}),+ ...(unit.foldable ? { openRunStart: unit.openRun[0] } : {}),+ }))+ })+ if (!hasTrailingRow && entries.length > 0) {+ entries[entries.length - 1].isLast = true+ }+ return entries+ }+ const isUnitOnPinnedPath = (unit: Unit): boolean => unitOnPinnedPath(unit, pinnedPath)+ // The cap counts items after the fold, so a run of thousands of spans takes one item of the cap, folded+ // or opened. The list is virtualized, so an opened run can list all of its spans.const pushChildren = (children: SpanNode[], owner: SpanNode, depth: number, parentRow: TraceDialogRow): void => {- const sorted = byStart(children)+ const units = siblingUnits(children, unitOptions)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 isShown = (_unit: Unit, i: number): boolean => showsAll || !childCapHides(units, i, isUnitOnPinnedPath)+ const shown = units.filter(isShown)+ const hidden = units.filter((unit, i) => !isShown(unit, i)).flatMap(unitSpans)const hiddenCount = hidden.length- const next: (Pending | TraceDialogRow)[] = shown.map((child, i) => ({- node: child,- depth,- isLast: hiddenCount === 0 && i === shown.length - 1,- parentRow,- }))+ // A full child list that the cap would shorten ends with a row that shortens it again.+ const showsFewerRow = showsAll && units.length > TRACE_DIALOG_CHILD_LIMIT+ const next = unitRows(shown, depth, parentRow, hiddenCount > 0 || showsFewerRow)if (hiddenCount > 0) {next.push({ kind: 'more', parent: owner, hiddenCount, hidden, depth, isLast: true, parentRow })+ } else if (showsFewerRow) {+ next.push({ kind: 'fewer', parent: owner, depth, isLast: true, parentRow })}for (let i = next.length - 1; i >= 0; i--) {stack.push(next[i])}}- const sortedRoots = byStart(roots)- for (let i = sortedRoots.length - 1; i >= 0; i--) {- stack.push({ node: sortedRoots[i], depth: 0, isLast: i === sortedRoots.length - 1, parentRow: null })+ const rootRows = unitRows(siblingUnits(roots, unitOptions), 0, null, false)+ for (let i = rootRows.length - 1; i >= 0; i--) {+ stack.push(rootRows[i])}while (stack.length > 0) {const item = stack.pop()!@@ -128,7 +239,7 @@ export function buildTraceDialogRows(rows.push(item)continue}- const { node, depth, isLast, parentRow } = item+ const { node, depth, isLast, parentRow, openRunLength, openRunStart } = itemconst run =node.parent?.children.length === 1 && !noFold.has(node) ? singleChildRun(node, collapsedSpanIds) : []const pinnedAt = run.findLastIndex((member) => pinnedPath.has(member))@@ -152,6 +263,8 @@ export function buildTraceDialogRows(isLast,parentRow,...(foldable ? { openChainLength: run.length } : {}),+ ...(openRunLength ? { openRunLength } : {}),+ ...(openRunStart ? { openRunStart } : {}),}rows.push(row)if (node.children.length > 0 && !collapsedSpanIds.has(node.span.span_id)) {@@ -161,6 +274,40 @@ export function buildTraceDialogRows(return rows}+export interface TraceDialogRunSummary {+ startUs: number+ endUs: number+ totalDurationNano: number+ /** The run's own spans with an error status. */+ errorCount: number+ /** The spans under the run's spans with an error status. The folded run hides them, so its row reports them. */+ nestedErrorCount: number+}++export function summarizeRun(nodes: SpanNode[]): TraceDialogRunSummary {+ let startUs = Infinity+ let endUs = -Infinity+ let totalDurationNano = 0+ let errorCount = 0+ for (const { span } of nodes) {+ const spanStartUs = parseTimestampUs(span.timestamp)+ startUs = Math.min(startUs, spanStartUs)+ // An earlier span can outlast a later one, so the run ends at the latest end and not at the last span's end.+ endUs = Math.max(endUs, spanStartUs + span.duration_nano / 1_000)+ totalDurationNano += span.duration_nano+ errorCount += span.status_code === 2 ? 1 : 0+ }+ let nestedErrorCount = 0+ // A stack and not recursion, so a deep subtree under the run stays off the call stack.+ const stack = nodes.flatMap((node) => node.children)+ while (stack.length > 0) {+ const node = stack.pop()!+ nestedErrorCount += node.span.status_code === 2 ? 1 : 0+ stack.push(...node.children)+ }+ return { startUs, endUs, totalDurationNano, errorCount, nestedErrorCount }+}+export function rowConnectorLines(row: TraceDialogRow): boolean[] {const lines: boolean[] = []for (let ancestor = row.parentRow; ancestor && ancestor.depth > 0; ancestor = ancestor.parentRow) {@@ -191,8 +338,9 @@ export function markOperationSubtrees(roots: SpanNode[], operationKey: string):/*** 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.+ * members of a folded chain, the members of a folded run with every span under them, 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. The row that shortens a full child list stands for no span.*/export function operationRowMatches(rows: TraceDialogRow[],@@ -204,9 +352,15 @@ export function operationRowMatches(if (row.kind === 'chain') {return row.nodes.some((node) => compareRowKey(node.span) === operationKey)}+ if (row.kind === 'run') {+ return row.key === operationKey || row.nodes.some((node) => subtreeMarks.has(node))+ }if (row.kind === 'more') {return row.hidden.some((child) => subtreeMarks.has(child))}+ if (row.kind === 'fewer') {+ return false+ }return collapsedSpanIds.has(row.node.span.span_id)? subtreeMarks.has(row.node): compareRowKey(row.node.span) === operationKey@@ -234,6 +388,8 @@ export interface TraceDialogReveal {fullChildListSpanIds: string[]/** The first span of the folded chain that hides the span, for `toggleChain`. */chainIds: string[]+ /** The first span of each folded run that hides the span, outermost first, for `toggleRun`. */+ runIds: string[]}/** `node` and the spans above it, root first. */@@ -245,7 +401,9 @@ function pathFromRoot(node: SpanNode): SpanNode[] {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. */+/**+ * The ids to open so that `target` gets a row of its own, or heads a folded chain or run, which shows its name.+ */export function revealSpanInRows(roots: SpanNode[],target: SpanNode,@@ -253,31 +411,44 @@ export function revealSpanInRows(): TraceDialogReveal {const path = pathFromRoot(target)const pinnedPath = new Set(options.pinned ? pathFromRoot(options.pinned) : [])- const isOnPinnedPath = (node: SpanNode): boolean => pinnedPath.has(node)+ const unitOptions: SiblingUnitOptions = { foldRuns: options.foldRuns, openRunIds: options.openRunIds, pinnedPath }+ const isUnitOnPinnedPath = (unit: Unit): boolean => unitOnPinnedPath(unit, pinnedPath)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.+ // With the collapsed ancestors open, only the child caps and folded runs along the path can still hide the+ // target. A folded chain holds spans with one child each, so no cap or run sits inside one. A level's cap and+ // runs depend only on its own child list, and a folded run counts as one item of the cap like an opened one,+ // so one walk down the path finds every cap and run, outermost first.const fullChildListSpanIds: string[] = []+ const runIds: 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)) {+ const units = siblingUnits(node.parent ? node.parent.children : roots, unitOptions)+ const index = units.findIndex((unit) => unitSpans(unit).includes(node))+ const unit = units[index]+ // Roots have no child cap.+ if (+ node.parent &&+ !options.fullChildListSpanIds.has(node.parent.span.span_id) &&+ childCapHides(units, index, isUnitOnPinnedPath)+ ) {fullChildListSpanIds.push(node.parent.span.span_id)}+ // A folded run stands for its first span, so the target can head a run that stays folded.+ if ('run' in unit && unit.run[0] !== target) {+ runIds.push(unit.run[0].span.span_id)+ }}- // The row builder decides which runs fold, so this asks it rather than repeating its rules.+ // The row builder decides which chains 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]),+ openRunIds: new Set([...options.openRunIds, ...runIds]),})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 }+ return { collapsedSpanIds, fullChildListSpanIds, chainIds, runIds }}diff --git a/products/tracing/frontend/components/TraceView/TraceView.tsx b/products/tracing/frontend/components/TraceView/TraceView.tsxindex 9b50ac2b8d5f..4bc354c48fc4 100644--- a/products/tracing/frontend/components/TraceView/TraceView.tsx+++ b/products/tracing/frontend/components/TraceView/TraceView.tsx@@ -205,6 +205,7 @@ export function TraceView({/>) : (<TraceDialogSpanTree+ surface={surface}openedFrom={openedFrom}openedAtUs={openedAtUs}hasMore={hasMoreSpans}diff --git a/products/tracing/frontend/components/TraceView/traceViewLogic.test.ts b/products/tracing/frontend/components/TraceView/traceViewLogic.test.tsindex cba7ab92e326..7d6c5b90c86b 100644--- a/products/tracing/frontend/components/TraceView/traceViewLogic.test.ts+++ b/products/tracing/frontend/components/TraceView/traceViewLogic.test.ts@@ -30,6 +30,8 @@ describe('traceViewLogic', () => {beforeEach(() => {initKeaTests()+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TRACING_TRACE_FOLDED_RUNS]: true })captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)logic = traceViewLogic({ id: 'trace-view-test' })logic.mount()@@ -112,7 +114,7 @@ describe('traceViewLogic', () => {featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TRACING_TRACE_CALL_TREE]: flagOn })logic.actions.setSpans([root, child('a', 'root', 'SELECT orders', 1), child('b', 'root', 'cache GET', 2)])logic.actions.selectSpan('a')- logic.actions.enableSpanKeys('[data-attr="trace-view-test"]')+ logic.actions.enableSpanKeys('[data-attr="trace-view-test"]', 'drawer')logic.actions.setTraceViewMode('calltree', 'drawer')logic.actions.setTraceViewMode(view, 'drawer')const pageKeyDown = jest.fn()@@ -141,7 +143,8 @@ describe('traceViewLogic', () => {// 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))+ // One operation each, so that no run folds them and they fill the cap.+ const children = Array.from({ length: 11 }, (_, i) => child(`c${i}`, 'root', `SELECT orders ${i}`, 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)@@ -152,4 +155,111 @@ describe('traceViewLogic', () => {expect(rowIds()).toContain('cache')expect(logic.values.selectedSpanId).toBe('c0')})++ describe('runs', () => {+ // Three reads of one operation under the root, so they fold into one run.+ const reads = (...extra: Span[]): Span[] => [+ root,+ ...[1, 2, 3].map((i) => child(`get${i}`, 'root', 'cache GET', i)),+ ...extra,+ ]+ const rows = (): string[] =>+ logic.values.spanRows.map((row) =>+ row.kind === 'run' ? `${row.nodes.length} folded` : (rowSpanNode(row)?.span.span_id ?? '')+ )+ const toggleEvents = (): unknown[] =>+ captureSpy.mock.calls+ .filter(([event]) => event === 'tracing trace run toggled')+ .map(([, properties]) => properties)++ // Fails when the right arrow skips a folded run whose first span is a leaf, which leaves no key to open it,+ // or when the left arrow on any span of the opened run leaves the run open: a person deep in a long run must+ // not have to scroll back to its first span to fold it. Left treats every span of the run alike, so a span+ // with open children collapses them first. The toggle event must name the action, method and surface of+ // each toggle, so the funnel can tell an open from a fold.+ it.each([+ { member: 'its first span', extra: [], leftOn: 'get1', collapsesFirst: false },+ { member: 'a later span', extra: [], leftOn: 'get2', collapsesFirst: false },+ {+ member: 'its first span, which has open children',+ extra: [child('get1-call', 'get1', 'redis GET', 1)],+ leftOn: 'get1',+ collapsesFirst: true,+ },+ ])(+ 'opens a folded run with the right arrow, and folds it with the left arrow on $member',+ ({ extra, leftOn, collapsesFirst }) => {+ logic.actions.setSpans(reads(...extra))+ logic.actions.selectSpan('root')++ logic.actions.selectNextSpan()+ expect([logic.values.selectedSpanId, rows()]).toEqual(['get1', ['root', '3 folded']])++ logic.actions.expandSelectedSpan('drawer')+ const opened = ['root', 'get1', 'get2', 'get3']+ expect(rows()).toEqual(collapsesFirst ? ['root', 'get1', 'get1-call', 'get2', 'get3'] : opened)++ logic.actions.selectSpan(leftOn)+ if (collapsesFirst) {+ logic.actions.collapseSelectedSpan('drawer')+ expect([logic.values.collapsedSpanIds, rows()]).toEqual([new Set([leftOn]), opened])+ }+ logic.actions.collapseSelectedSpan('drawer')+ expect([logic.values.selectedSpanId, rows()]).toEqual(['get1', ['root', '3 folded']])+ expect(toggleEvents()).toEqual([+ { action: 'open', span_count: 3, method: 'key', surface: 'drawer' },+ { action: 'fold', span_count: 3, method: 'key', surface: 'drawer' },+ ])+ }+ )++ // Fails when the left arrow on a folded run collapses the span it stands for instead of moving to the+ // parent. The run's first span has a child, so a collapse would change the tree.+ it('moves from a folded run to its parent with the left arrow, and collapses nothing', () => {+ logic.actions.setSpans(reads(child('get1-call', 'get1', 'redis GET', 1)))+ logic.actions.selectSpan('get1')++ logic.actions.collapseSelectedSpan('drawer')++ expect([logic.values.selectedSpanId, logic.values.collapsedSpanIds, rows()]).toEqual([+ 'root',+ new Set(),+ ['root', '3 folded'],+ ])+ })++ // Fails when a fold that hides the selected span moves the selection up to the parent, which takes the+ // person out of the run they folded, or when a click toggle sends the wrong action or method.+ it.each([+ { selection: 'a span of the run', selectedSpanId: 'get2' },+ { selection: 'a span under a span of the run', selectedSpanId: 'get2-call' },+ ])('keeps the selection on the run when a fold hides $selection', ({ selectedSpanId }) => {+ logic.actions.setSpans(reads(child('get2-call', 'get2', 'redis GET', 2)))+ logic.actions.toggleRun('get1', 'click', 'trace_dialog')+ logic.actions.selectSpan(selectedSpanId)++ logic.actions.toggleRun('get1', 'click', 'trace_dialog')++ expect([logic.values.selectedSpanId, rows()]).toEqual(['get1', ['root', '3 folded']])+ expect(toggleEvents()).toEqual([+ { action: 'open', span_count: 3, method: 'click', surface: 'trace_dialog' },+ { action: 'fold', span_count: 3, method: 'click', surface: 'trace_dialog' },+ ])+ })++ // Fails when a later page folds the selected span into a run with the spans it adds, which hides the+ // selection, so J and K jump to the root. The reveal is not the person's own toggle, so it sends no event.+ it('opens the run that a later page folds the selected span into', () => {+ const [, get1, get2] = reads()+ logic.actions.setSpans([root, get1, get2])+ logic.actions.selectSpan('get2')++ logic.actions.setSpans(reads())+ expect(rows()).toEqual(['root', 'get1', 'get2', 'get3'])+ logic.actions.selectNextSpan()++ expect(logic.values.selectedSpanId).toBe('get3')+ expect(toggleEvents()).toEqual([])+ })+ })})diff --git a/products/tracing/frontend/components/TraceView/traceViewLogic.ts b/products/tracing/frontend/components/TraceView/traceViewLogic.tsindex fc6f78ea1734..351a3f266ef8 100644--- a/products/tracing/frontend/components/TraceView/traceViewLogic.ts+++ b/products/tracing/frontend/components/TraceView/traceViewLogic.ts@@ -10,7 +10,9 @@ import {props,reducers,selectors,+ sharedListeners,} from 'kea'+import type { BreakPointFunction } from 'kea'import posthog from 'posthog-js'import { FEATURE_FLAGS } from 'lib/constants'@@ -59,6 +61,12 @@ export type TraceViewSurface = 'drawer' | 'trace_dialog'*/export type TraceOperationsScope = 'trace' | 'span'+/**+ * How the person opened or folded a run: a click, or a key (Enter or Space on a focused run control, Left or Right).+ * Pinned: sent as the `method` property of analytics events, so keep the values stable.+ */+export type TraceRunToggleMethod = 'click' | 'key'+export interface TraceViewTree {roots: SpanNode[]nodesById: Map<string, SpanNode>@@ -93,10 +101,13 @@ export interface traceViewLogicValues {collapsedSpanIds: Set<string>firstOperationRowIndex: numberflatSpans: SpanNode[]+ foldedRunStartIds: Set<string>+ foldedRunsEnabled: booleanfullChildListSpanIds: Set<string>highlightedOperationKey: string | nullmissingParentSpanId: string | nullopenChainIds: Set<string>+ openRunIds: Set<string>operationRowMatches: boolean[] | nulloperationSpans: Span[]operationSubtreeMarks: Set<SpanNode> | null@@ -106,11 +117,13 @@ export interface traceViewLogicValues {selectedSpan: Span | nullselectedSpanId: string | nullserviceColorMap: Map<string, number>+ shownTraceCount: numberspanRows: TraceDialogRow[]spanTree: TraceViewTreespans: Span[]summary: TraceViewSummarytimeline: TraceViewTimeline+ visibleSpanIds: Set<string>}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -122,17 +135,21 @@ export interface traceViewLogicActions {surface: TraceViewSurfacetraceViewMode: 'calltree' | 'waterfall'} // tracingConfigLogic- collapseSelectedSpan: () => {- value: true+ collapseSelectedSpan: (surface: TraceViewSurface) => {+ surface: TraceViewSurface}disableSpanKeys: () => {value: true}- enableSpanKeys: (containerSelector: string) => {+ enableSpanKeys: (+ containerSelector: string,+ surface: TraceViewSurface+ ) => {containerSelector: string+ surface: TraceViewSurface}- expandSelectedSpan: () => {- value: true+ expandSelectedSpan: (surface: TraceViewSurface) => {+ surface: TraceViewSurface}highlightOperation: (operationKey: string | null,@@ -149,6 +166,9 @@ export interface traceViewLogicActions {revealSpans: (reveal: TraceDialogReveal) => {reveal: TraceDialogReveal}+ runsShown: (surface: TraceViewSurface) => {+ surface: TraceViewSurface+ }selectNextSpan: () => {value: true}@@ -171,6 +191,9 @@ export interface traceViewLogicActions {showAllChildren: (spanId: string) => {spanId: string}+ showFewerChildren: (spanId: string) => {+ spanId: string+ }showTrace: (pinnedSpanId: string | null,tab: SpanInspectorTab | null@@ -184,6 +207,15 @@ export interface traceViewLogicActions {toggleChain: (spanId: string) => {spanId: string}+ toggleRun: (+ spanId: string,+ method?: TraceRunToggleMethod,+ surface?: TraceViewSurface+ ) => {+ method: TraceRunToggleMethod | null+ spanId: string+ surface: TraceViewSurface | null+ }toggleSpanCollapsed: (spanId: string) => {spanId: string}@@ -192,6 +224,17 @@ export interface traceViewLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface traceViewLogicMeta {key: string+ sharedListeners: {+ revealSelectedSpan: (+ payload: any,+ breakpoint: BreakPointFunction,+ action: {+ type: string+ payload: any+ },+ previousState: any+ ) => void | Promise<void>+ }__keaTypeGenInternalSelectorTypes: {spanTree: (spans: Span[]) => TraceViewTreespanRows: (@@ -199,13 +242,17 @@ export interface traceViewLogicMeta {collapsedSpanIds: Set<string>,fullChildListSpanIds: Set<string>,openChainIds: Set<string>,+ foldedRunsEnabled: boolean,+ openRunIds: Set<string>,pinnedSpanId: string | null) => TraceDialogRow[]flatSpans: (spanRows: TraceDialogRow[]) => SpanNode[]+ visibleSpanIds: (flatSpans: SpanNode[]) => Set<string>chainStartIds: (spanRows: TraceDialogRow[]) => {folded: Set<string>opened: Set<string>}+ foldedRunStartIds: (spanRows: TraceDialogRow[]) => Set<string>selectedSpan: (spans: Span[], selectedSpanId: string | null, summary: TraceViewSummary) => Span | nullmissingParentSpanId: (spanTree: TraceViewTree, selectedSpanId: string | null) => string | nullpinnedSpan: (spans: Span[], pinnedSpanId: string | null) => Span | null@@ -215,6 +262,7 @@ export interface traceViewLogicMeta {sessionErrorBadgesEnabled: boolean) => SpanInspectorTaboperationsTabEnabled: (featureFlags: FeatureFlagsSet) => boolean+ foldedRunsEnabled: (featureFlags: FeatureFlagsSet) => booleanoperationSubtreeMarks: (spanTree: TraceViewTree,highlightedOperationKey: string | null,@@ -263,15 +311,23 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLogselectSpan: (spanId: string | null) => ({ spanId }),selectNextSpan: true,selectPreviousSpan: true,- collapseSelectedSpan: true,- expandSelectedSpan: true,+ collapseSelectedSpan: (surface: TraceViewSurface) => ({ surface }),+ expandSelectedSpan: (surface: TraceViewSurface) => ({ surface }),spanStepped: true,toggleSpanCollapsed: (spanId: string) => ({ spanId }),showAllChildren: (spanId: string) => ({ spanId }),+ showFewerChildren: (spanId: string) => ({ spanId }),toggleChain: (spanId: string) => ({ spanId }),+ // Only the person's own toggles pass a method, so only they send the toggle event.+ toggleRun: (spanId: string, method?: TraceRunToggleMethod, surface?: TraceViewSurface) => ({+ spanId,+ method: method ?? null,+ surface: surface ?? null,+ }),+ runsShown: (surface: TraceViewSurface) => ({ surface }),keepSelectionOnScreen: true,setInspectorTab: (tab: SpanInspectorTab, surface?: TraceViewSurface) => ({ tab, surface: surface ?? null }),- enableSpanKeys: (containerSelector: string) => ({ containerSelector }),+ enableSpanKeys: (containerSelector: string, surface: TraceViewSurface) => ({ containerSelector, surface }),disableSpanKeys: true,highlightOperation: (operationKey: string | null,@@ -292,6 +348,14 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLogsetSpans: (_, { spans }) => spans,},],+ // Counts the traces shown, so the span tree can tell one trace from the next even when the next trace's+ // spans arrive before a render of the empty list.+ shownTraceCount: [+ 0,+ {+ showTrace: (count) => count + 1,+ },+ ],// The span the trace was opened on: it stays listed even inside a folded branch.pinnedSpanId: [null as string | null,@@ -329,6 +393,11 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLog{showTrace: () => new Set<string>(),showAllChildren: (shown, { spanId }) => new Set(shown).add(spanId),+ showFewerChildren: (shown, { spanId }) => {+ const next = new Set(shown)+ next.delete(spanId)+ return next+ },revealSpans: (shown, { reveal }) => new Set([...shown, ...reveal.fullChildListSpanIds]),},],@@ -347,6 +416,21 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLogrevealSpans: (opened, { reveal }) => new Set([...opened, ...reveal.chainIds]),},],+ // Runs fold by default too, so this holds the opened ones, by the id of their first span.+ openRunIds: [+ new Set<string>(),+ {+ showTrace: () => new Set<string>(),+ toggleRun: (opened, { spanId }) => {+ const next = new Set(opened)+ if (!next.delete(spanId)) {+ next.add(spanId)+ }+ return next+ },+ revealSpans: (opened, { reveal }) => new Set([...opened, ...reveal.runIds]),+ },+ ],// A tab the person picked sticks while they move between spans. Until they pick one, the// inspector chooses for the span in view.chosenInspectorTab: [@@ -385,18 +469,30 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLog},],spanRows: [- (s) => [s.spanTree, s.collapsedSpanIds, s.fullChildListSpanIds, s.openChainIds, s.pinnedSpanId],+ (s) => [+ s.spanTree,+ s.collapsedSpanIds,+ s.fullChildListSpanIds,+ s.openChainIds,+ s.foldedRunsEnabled,+ s.openRunIds,+ s.pinnedSpanId,+ ],(spanTree: TraceViewTree,collapsedSpanIds: Set<string>,fullChildListSpanIds: Set<string>,openChainIds: Set<string>,+ foldedRunsEnabled: boolean,+ openRunIds: Set<string>,pinnedSpanId: string | null): TraceDialogRow[] =>buildTraceDialogRows(spanTree.roots, {collapsedSpanIds,fullChildListSpanIds,openChainIds,+ foldRuns: foldedRunsEnabled,+ openRunIds,pinned: (pinnedSpanId && spanTree.nodesById.get(pinnedSpanId)) || null,}),],@@ -408,6 +504,12 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLogreturn node ? [node] : []}),],+ // The spans that have a row, or head a folded chain or run, so a selection can check in one lookup that it+ // has something on screen.+ visibleSpanIds: [+ (s) => [s.flatSpans],+ (flatSpans: SpanNode[]): Set<string> => new Set(flatSpans.map((node) => node.span.span_id)),+ ],chainStartIds: [(s) => [s.spanRows],(spanRows: TraceDialogRow[]): { folded: Set<string>; opened: Set<string> } => {@@ -423,6 +525,11 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLogreturn { folded, opened }},],+ foldedRunStartIds: [+ (s) => [s.spanRows],+ (spanRows: TraceDialogRow[]): Set<string> =>+ new Set(spanRows.flatMap((row) => (row.kind === 'run' ? [row.nodes[0].span.span_id] : []))),+ ],selectedSpan: [(s) => [s.spans, s.selectedSpanId, s.summary],(spans: Span[], selectedSpanId: string | null, summary: TraceViewSummary): Span | null =>@@ -449,6 +556,10 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLog(s) => [s.featureFlags],(featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.TRACING_TRACE_OPERATIONS_TAB],],+ foldedRunsEnabled: [+ (s) => [s.featureFlags],+ (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.TRACING_TRACE_FOLDED_RUNS],+ ],// 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: [@@ -514,8 +625,36 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLog}),],}),- listeners(({ values, actions, cache, selectors }) => ({- enableSpanKeys: ({ containerSelector }) => {+ sharedListeners(({ values, actions }) => ({+ // J, K and clicks select spans on screen. The URL, or back and forward, can select a span that a folded run+ // hides, and a later page can fold the selected span into a run with the spans it adds. Open those runs.+ // Only runs: chains and collapsed spans stay as the person left them. One action that only opens, so the+ // trace dialog does not count it as the person's own toggle. A cleared selection has nothing to open.+ revealSelectedSpan: () => {+ const spanId = values.selectedSpanId+ const target =+ spanId && values.foldedRunsEnabled && !values.visibleSpanIds.has(spanId)+ ? values.spanTree.nodesById.get(spanId)+ : undefined+ if (!target) {+ return+ }+ const { roots, nodesById } = values.spanTree+ const { runIds } = revealSpanInRows(roots, target, {+ collapsedSpanIds: values.collapsedSpanIds,+ fullChildListSpanIds: values.fullChildListSpanIds,+ openChainIds: values.openChainIds,+ foldRuns: values.foldedRunsEnabled,+ openRunIds: values.openRunIds,+ pinned: (values.pinnedSpanId && nodesById.get(values.pinnedSpanId)) || null,+ })+ if (runIds.length > 0) {+ actions.revealSpans({ collapsedSpanIds: [], fullChildListSpanIds: [], chainIds: [], runIds })+ }+ },+ })),+ listeners(({ values, actions, cache, selectors, sharedListeners }) => ({+ enableSpanKeys: ({ containerSelector, surface }) => {// 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.cache.disposables.add(() => {@@ -540,8 +679,8 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLogconst step = {j: actions.selectNextSpan,k: actions.selectPreviousSpan,- arrowleft: actions.collapseSelectedSpan,- arrowright: actions.expandSelectedSpan,+ arrowleft: () => actions.collapseSelectedSpan(surface),+ arrowright: () => actions.expandSelectedSpan(surface),}[event.key.toLowerCase()]if (step) {event.preventDefault()@@ -593,21 +732,33 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLogcollapsedSpanIds: values.collapsedSpanIds,fullChildListSpanIds: values.fullChildListSpanIds,openChainIds: values.openChainIds,+ foldRuns: values.foldedRunsEnabled,+ openRunIds: values.openRunIds,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) {+ if (+ reveal.collapsedSpanIds.length ++ reveal.fullChildListSpanIds.length ++ reveal.chainIds.length ++ reveal.runIds.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)- }- },+ selectSpan: [+ // 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.+ () => {+ if (values.missingParentSpanId && values.highlightedOperationKey) {+ actions.highlightOperation(null)+ }+ },+ sharedListeners.revealSelectedSpan,+ ],+ setSpans: sharedListeners.revealSelectedSpan,selectNextSpan: () => {actions.spanStepped()// A missing-parent row is selectable too, so step from it rather than from the root fallback.@@ -628,17 +779,29 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLog}},// Left collapses the selected span, or moves up to its parent once there is nothing to collapse.- collapseSelectedSpan: () => {+ collapseSelectedSpan: ({ surface }) => {const node = values.spanTree.nodesById.get(values.missingParentSpanId ?? values.selectedSpan?.span_id ?? '')if (!node) {return}actions.spanStepped()const spanId = node.span.span_id+ const spanRow = values.spanRows.find((row) => row.kind === 'span' && row.node === node)+ const openRunStart = spanRow?.kind === 'span' ? spanRow.openRunStart : undefinedif (values.chainStartIds.opened.has(spanId)) {actions.toggleChain(spanId)- } else if (node.children.length > 0 && !values.collapsedSpanIds.has(spanId)) {+ } else if (+ // A folded run already hides the spans under its first span, so Left moves on to the parent.+ node.children.length > 0 &&+ !values.collapsedSpanIds.has(spanId) &&+ !values.foldedRunStartIds.has(spanId)+ ) {actions.toggleSpanCollapsed(spanId)+ } else if (openRunStart) {+ // Any span of an opened run folds it once its own children are collapsed, the first span included,+ // so a person deep in a long run can close it from where they are. The fold leaves the selection on+ // the run's row.+ actions.toggleRun(openRunStart.span.span_id, 'key', surface)} else if (node.parent) {// The parent can sit inside a folded chain, which stands for it on screen.const shown = new Set(values.flatSpans)@@ -652,8 +815,14 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLog}},// Right expands the selected span, or steps into its first child once it is open.- expandSelectedSpan: () => {+ expandSelectedSpan: ({ surface }) => {const node = values.spanTree.nodesById.get(values.missingParentSpanId ?? values.selectedSpan?.span_id ?? '')+ // A folded run opens before the children check, because its first span can be a leaf.+ if (node && values.foldedRunStartIds.has(node.span.span_id)) {+ actions.spanStepped()+ actions.toggleRun(node.span.span_id, 'key', surface)+ return+ }if (!node || node.children.length === 0) {return}@@ -675,19 +844,69 @@ export const traceViewLogic: LogicWrapper<traceViewLogicType> = kea<traceViewLogtoggleChain: () => {actions.keepSelectionOnScreen()},+ showFewerChildren: () => {+ actions.keepSelectionOnScreen()+ },+ toggleRun: ({ spanId, method, surface }) => {+ if (method) {+ // Listeners run after the reducers, so the rows already show the toggled run: an opened run's first+ // span row carries the run's length, and a folded run is a run row.+ const row = values.spanRows.find((row) => rowSpanNode(row)?.span.span_id === spanId)+ const spanCount =+ row?.kind === 'run' ? row.nodes.length : row?.kind === 'span' ? row.openRunLength : undefined+ // pinned: analytics event name, so renaming it breaks the insights built on it+ posthog.capture('tracing trace run toggled', {+ action: values.openRunIds.has(spanId) ? 'open' : 'fold',+ span_count: spanCount ?? null,+ method,+ surface,+ })+ }+ actions.keepSelectionOnScreen()+ },+ // The span tree reports each change of the folded runs it shows. The event marks that a trace showed runs,+ // so it goes out once per trace, and later pages and toggles of the same trace send nothing.+ runsShown: ({ surface }) => {+ if (cache.runsShownSent) {+ return+ }+ const runLengths = values.spanRows.flatMap((row) => (row.kind === 'run' ? [row.nodes.length] : []))+ if (runLengths.length === 0) {+ return+ }+ cache.runsShownSent = true+ // pinned: analytics event name, so renaming it breaks the insights built on it+ posthog.capture('tracing trace runs shown', {+ run_count: runLengths.length,+ largest_run: runLengths.reduce((largest, length) => Math.max(largest, length), 0),+ surface,+ })+ },+ showTrace: () => {+ cache.runsShownSent = false+ },// The inspector must never show a span the list hides.keepSelectionOnScreen: () => {const selected = values.selectedSpanId ? values.spanTree.nodesById.get(values.selectedSpanId) : undefined- if (!selected) {+ const shown = new Set(values.flatSpans)+ if (!selected || shown.has(selected)) {return}- const shown = new Set(values.flatSpans)+ // A folded run has one row, which stands for its first span, so a span that the fold hides moves to that+ // span. J and K stop there too. Otherwise the selection moves up to the nearest span on screen.+ const runFirstSpans = new Map<SpanNode, SpanNode>()+ for (const row of values.spanRows) {+ if (row.kind === 'run') {+ row.nodes.forEach((member) => runFirstSpans.set(member, row.nodes[0]))+ }+ }let node: SpanNode | null = selected- while (node && !shown.has(node)) {+ while (node && !shown.has(node) && !runFirstSpans.has(node)) {node = node.parent}- if (node && node !== selected) {- actions.selectSpan(node.span.span_id)+ const target = node ? (runFirstSpans.get(node) ?? node) : null+ if (target && target !== selected) {+ actions.selectSpan(target.span.span_id)}},})),diff --git a/products/tracing/frontend/tracingViewerLogic.test.ts b/products/tracing/frontend/tracingViewerLogic.test.tsindex f16b8cda0c9c..09ff246620c5 100644--- a/products/tracing/frontend/tracingViewerLogic.test.ts+++ b/products/tracing/frontend/tracingViewerLogic.test.ts@@ -315,7 +315,7 @@ describe('tracingViewerLogic', () => {makeSpan({ uuid: 'CC01', span_id: 'CC01', trace_id: 'trace-y' }),makeSpan({ uuid: 'DD02', span_id: 'DD02', trace_id: 'trace-y' }),])- overlay.actions.enableSpanKeys('[data-attr="overlay"]')+ overlay.actions.enableSpanKeys('[data-attr="overlay"]', 'drawer')press()expect(overlay.values.selectedSpanId).toBe('DD02')diff --git a/products/tracing/frontend/tracingViewerLogic.ts b/products/tracing/frontend/tracingViewerLogic.tsindex 15ea4d6359e0..5d5eb8f054e1 100644--- a/products/tracing/frontend/tracingViewerLogic.ts+++ b/products/tracing/frontend/tracingViewerLogic.ts@@ -117,8 +117,12 @@ export interface tracingViewerLogicActions {disableSpanKeys: () => {value: true} // traceViewLogic- enableSpanKeys: (containerSelector: string) => {+ enableSpanKeys: (+ containerSelector: string,+ surface: import('./components/TraceView/traceViewLogic').TraceViewSurface+ ) => {containerSelector: string+ surface: import('./components/TraceView/traceViewLogic').TraceViewSurface} // traceViewLogicselectViewSpan: (spanId: string | null) => {spanId: string | null@@ -537,7 +541,7 @@ export const tracingViewerLogic = kea<tracingViewerLogicType>([},openTrace: ({ traceId, ts, spanId }) => {actions.showTrace(spanId, values.inspectorTab)- actions.enableSpanKeys(`[data-attr="${TRACE_DRAWER_DATA_ATTR}"]`)+ actions.enableSpanKeys(`[data-attr="${TRACE_DRAWER_DATA_ATTR}"]`, 'drawer')// pinned: analytics event and property names. The view persists across traces, so the view change event// alone cannot count how many traces people read as a call tree.posthog.capture('tracing trace opened', { view: values.traceViewMode })@@ -568,12 +572,12 @@ export const tracingViewerLogic = kea<tracingViewerLogicType>([},closeLogsViewerModal: () => {if (values.isTraceOpen) {- actions.enableSpanKeys(`[data-attr="${TRACE_DRAWER_DATA_ATTR}"]`)+ actions.enableSpanKeys(`[data-attr="${TRACE_DRAWER_DATA_ATTR}"]`, 'drawer')}},closeSessionPlayer: () => {if (values.isTraceOpen) {- actions.enableSpanKeys(`[data-attr="${TRACE_DRAWER_DATA_ATTR}"]`)+ actions.enableSpanKeys(`[data-attr="${TRACE_DRAWER_DATA_ATTR}"]`, 'drawer')}},selectInspectorTab: ({ tab }) => {