: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): virtualize spans list and flame chart (#60738)
Jon McCallum42bb7d98f9fd
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8a91697a0e70..264052c9d066 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3463,6 +3463,9 @@ importers:react:specifier: 18.3.1version: 18.3.1+ react-window:+ specifier: '*'products/user_interviews:dependencies:@@ -23027,8 +23030,8 @@ packages:resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==}engines: {node: '>= 10.0.0'}- resolution: {integrity: sha512-fFQ1O06CPO5T0bnvI3ug+wT7xoQ4XX9ELcjgZV2/ySQKmCAi+IVj6LmMtIrrSMyX5Ad3GQTEPop86d0uuXSLPw==}+ resolution: {integrity: sha512-g2Btv3iOmCRIW2VGXOjBAeXAEDk6IoftdXewS1+spkRp2OTCHJOJCp3dZoSSKPLyFBF5hwoekBJ7WSdvLNCn8Q==}resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==}@@ -46974,7 +46977,7 @@ snapshots:dependencies:react: 18.3.1- unlayer-types: 1.414.0+ unlayer-types: 1.415.0dependencies:@@ -49459,7 +49462,7 @@ snapshots:- [email protected]: {}+ [email protected]: {}diff --git a/products/tracing/frontend/TraceFlameChart.tsx b/products/tracing/frontend/TraceFlameChart.tsxindex 1f05415e46ed..1be056cb22f1 100644--- a/products/tracing/frontend/TraceFlameChart.tsx+++ b/products/tracing/frontend/TraceFlameChart.tsx@@ -1,9 +1,12 @@-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { CSSProperties, useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { List, useDynamicRowHeight } from 'react-window'import { IconWarning } from '@posthog/icons'import { LemonTag } from '@posthog/lemon-ui'import { getSeriesColor } from 'lib/colors'+import { AutoSizer } from 'lib/components/AutoSizer'+import { SizeProps } from 'lib/components/AutoSizer/AutoSizer'import { Tooltip } from 'lib/lemon-ui/Tooltip'import { SPAN_KIND_LABELS, STATUS_CODE_LABELS } from './types'@@ -141,6 +144,11 @@ const LABEL_COLUMN_WIDTH_STORAGE_KEY = 'tracing-trace-label-width'/** Hit area for the vertical splitter (centered on the label/timeline border). */const LABEL_SPLITTER_HIT_PX = 8const ROW_HEIGHT = 32+// Cap the windowed list viewport; taller traces scroll inside it instead of growing the modal.+const MAX_FLAME_HEIGHT = 600+// Rough extra room reserved when a span's detail panel is open, so a selection near the top of a+// short trace doesn't pop an unexpected scrollbar.+const SELECTED_DETAIL_RESERVE = 320function clampLabelColumnWidth(px: number): number {return Math.min(MAX_LABEL_COLUMN_WIDTH, Math.max(MIN_LABEL_COLUMN_WIDTH, Math.round(px)))@@ -276,6 +284,184 @@ function SpanDetailPanel({ span }: { span: Span }): JSX.Element {)}+interface FlameRowData {+ flatSpans: SpanNode[]+ traceStartUs: number+ traceDurationUs: number+ serviceColorMap: Map<string, number>+ ticks: number[]+ labelColumnWidth: number+ selectedSpanId: string | null+ onSelect: (spanId: string) => void+ dynamicRowHeight: ReturnType<typeof useDynamicRowHeight>+}++function FlameRow({+ node,+ traceStartUs,+ traceDurationUs,+ serviceColorMap,+ ticks,+ labelColumnWidth,+ selectedSpanId,+ onSelect,+}: Omit<FlameRowData, 'flatSpans' | 'dynamicRowHeight'> & { node: SpanNode }): JSX.Element {+ const { span } = node+ const spanStartUs = parseTimestampUs(span.timestamp)+ const spanDurationUs = span.duration_nano / 1_000+ const leftPct = traceDurationUs > 0 ? Math.max(((spanStartUs - traceStartUs) / traceDurationUs) * 100, 0) : 0+ const rawWidthPct = traceDurationUs > 0 ? (spanDurationUs / traceDurationUs) * 100 : 100+ const widthPct = Math.max(Math.min(rawWidthPct, 100 - leftPct), 0.3)++ const isError = span.status_code === 2+ const isUnmatched = !span.matched_filter+ const seriesIndex = serviceColorMap.get(span.service_name) ?? 0+ const seriesColor = isError ? ERROR_COLOR : getSeriesColor(seriesIndex)+ const barColor = isUnmatched ? 'var(--border)' : seriesColor+ const isSelected = selectedSpanId === span.uuid++ return (+ <div>+ <div+ className={`flex items-stretch cursor-pointer transition-colors ${+ isSelected ? 'bg-surface-primary-active' : 'hover:bg-surface-primary-hover'+ }`}+ // eslint-disable-next-line react/forbid-dom-props+ style={{ minHeight: ROW_HEIGHT }}+ role="button"+ tabIndex={0}+ aria-pressed={isSelected}+ onClick={() => onSelect(span.uuid)}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault()+ onSelect(span.uuid)+ }+ }}+ >+ {/* Label column */}+ <div+ className="shrink-0 flex items-center overflow-hidden border-r border-border px-2"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ width: labelColumnWidth }}+ >+ <TreeIndent node={node} />+ {isError && (+ <Tooltip title="This span has an error status">+ <IconWarning className="text-danger shrink-0 mr-1" fontSize={14} />+ </Tooltip>+ )}+ <Tooltip title={span.name}>+ <span+ className={`text-xs truncate ${isError ? 'text-danger font-semibold' : 'font-medium'} ${isUnmatched ? 'opacity-40' : ''}`}+ >+ {span.name}+ </span>+ </Tooltip>+ </div>++ {/* Timeline column */}+ <div+ className="relative grow self-center"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ height: ROW_HEIGHT - 8 }}+ >+ {/* Grid lines */}+ {ticks.map((tickUs) => {+ const pct = (tickUs / traceDurationUs) * 100+ return (+ <span+ key={tickUs}+ className="absolute top-0 bottom-0 border-l border-border"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ left: `${pct}%` }}+ />+ )+ })}++ {/* Span bar */}+ <Tooltip+ title={+ <span>+ <strong>{span.name}</strong>+ <br />+ {span.service_name} · {formatDuration(span.duration_nano)}+ {isError ? ' · Error' : ''}+ </span>+ }+ >+ <div+ className="absolute h-full flex items-center px-1.5 overflow-hidden"+ // eslint-disable-next-line react/forbid-dom-props+ style={{+ left: `${leftPct}%`,+ width: `${widthPct}%`,+ minWidth: 2,+ backgroundColor: `color-mix(in srgb, ${barColor} 20%, transparent)`,+ borderLeft: `1px solid ${barColor}`,+ }}+ >+ <span+ className={`text-[11px] truncate whitespace-nowrap flex items-center gap-1.5 ${isUnmatched ? 'opacity-40' : ''}`}+ >+ <span className="text-muted-alt font-medium">{span.service_name}</span>+ <span className="text-muted">{formatDuration(span.duration_nano)}</span>+ </span>+ </div>+ </Tooltip>+ </div>+ </div>++ {/* Detail panel */}+ {isSelected && <SpanDetailPanel span={span} />}+ </div>+ )+}++function FlameListRow({+ ariaAttributes,+ index,+ style,+ flatSpans,+ traceStartUs,+ traceDurationUs,+ serviceColorMap,+ ticks,+ labelColumnWidth,+ selectedSpanId,+ onSelect,+ dynamicRowHeight,+}: {+ ariaAttributes: { 'aria-posinset': number; 'aria-setsize': number; role: 'listitem' }+ index: number+ style: CSSProperties+} & FlameRowData): JSX.Element {+ const rowRef = useRef<HTMLDivElement>(null)+ const node = flatSpans[index]++ useEffect(() => {+ if (rowRef.current) {+ return dynamicRowHeight.observeRowElements([rowRef.current])+ }+ }, [dynamicRowHeight])++ return (+ // eslint-disable-next-line react/forbid-dom-props+ <div {...ariaAttributes} ref={rowRef} style={style} data-index={index} data-row-key={node.span.uuid}>+ <FlameRow+ node={node}+ traceStartUs={traceStartUs}+ traceDurationUs={traceDurationUs}+ serviceColorMap={serviceColorMap}+ ticks={ticks}+ labelColumnWidth={labelColumnWidth}+ selectedSpanId={selectedSpanId}+ onSelect={onSelect}+ />+ </div>+ )+}+export function TraceFlameChart({ spans }: TraceFlameChartProps): JSX.Element {const [selectedSpanId, setSelectedSpanId] = useState<string | null>(null)const [cursorPct, setCursorPct] = useState<number | null>(null)@@ -294,6 +480,11 @@ export function TraceFlameChart({ spans }: TraceFlameChartProps): JSX.Element {const serviceColorMap = useMemo(() => buildServiceColorMap(spans), [spans])const tree = useMemo(() => buildSpanTree(spans), [spans])const flatSpans = useMemo(() => flattenTree(tree), [tree])+ const dynamicRowHeight = useDynamicRowHeight({ defaultRowHeight: ROW_HEIGHT })++ const handleSelect = useCallback((spanId: string): void => {+ setSelectedSpanId((cur) => (cur === spanId ? null : spanId))+ }, [])const { traceStartUs, traceDurationUs } = useMemo(() => {if (spans.length === 0) {@@ -486,120 +677,36 @@ export function TraceFlameChart({ spans }: TraceFlameChartProps): JSX.Element {</div></div>- {/* Span rows */}- {flatSpans.map((node) => {- const { span } = node- const spanStartUs = parseTimestampUs(span.timestamp)- const spanDurationUs = span.duration_nano / 1_000- const leftPct =- traceDurationUs > 0 ? Math.max(((spanStartUs - traceStartUs) / traceDurationUs) * 100, 0) : 0- const rawWidthPct = traceDurationUs > 0 ? (spanDurationUs / traceDurationUs) * 100 : 100- const widthPct = Math.max(Math.min(rawWidthPct, 100 - leftPct), 0.3)-- const isError = span.status_code === 2- const isUnmatched = !span.matched_filter- const seriesIndex = serviceColorMap.get(span.service_name) ?? 0- const seriesColor = isError ? ERROR_COLOR : getSeriesColor(seriesIndex)- const barColor = isUnmatched ? 'var(--border)' : seriesColor- const isSelected = selectedSpanId === span.uuid-- return (- <div key={span.uuid}>- <div- className={`flex items-stretch cursor-pointer transition-colors ${- isSelected ? 'bg-surface-primary-active' : 'hover:bg-surface-primary-hover'- }`}- // eslint-disable-next-line react/forbid-dom-props- style={{ minHeight: ROW_HEIGHT }}- role="button"- tabIndex={0}- aria-pressed={isSelected}- onClick={() => setSelectedSpanId(isSelected ? null : span.uuid)}- onKeyDown={(e) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault()- setSelectedSpanId(isSelected ? null : span.uuid)- }- }}- >- {/* Label column */}- <div- className="shrink-0 flex items-center overflow-hidden border-r border-border px-2"- // eslint-disable-next-line react/forbid-dom-props- style={{ width: labelColumnWidth }}- >- <TreeIndent node={node} />- {isError && (- <Tooltip title="This span has an error status">- <IconWarning className="text-danger shrink-0 mr-1" fontSize={14} />- </Tooltip>- )}- <Tooltip title={span.name}>- <span- className={`text-xs truncate ${isError ? 'text-danger font-semibold' : 'font-medium'} ${isUnmatched ? 'opacity-40' : ''}`}- >- {span.name}- </span>- </Tooltip>- </div>-- {/* Timeline column */}- <div- className="relative grow self-center"- // eslint-disable-next-line react/forbid-dom-props- style={{ height: ROW_HEIGHT - 8 }}- >- {/* Grid lines */}- {ticks.map((tickUs) => {- const pct = (tickUs / traceDurationUs) * 100- return (- <span- key={tickUs}- className="absolute top-0 bottom-0 border-l border-border"- // eslint-disable-next-line react/forbid-dom-props- style={{ left: `${pct}%` }}- />- )- })}-- {/* Span bar */}- <Tooltip- title={- <span>- <strong>{span.name}</strong>- <br />- {span.service_name} · {formatDuration(span.duration_nano)}- {isError ? ' · Error' : ''}- </span>- }- >- <div- className="absolute h-full flex items-center px-1.5 overflow-hidden"- // eslint-disable-next-line react/forbid-dom-props- style={{- left: `${leftPct}%`,- width: `${widthPct}%`,- minWidth: 2,- backgroundColor: `color-mix(in srgb, ${barColor} 20%, transparent)`,- borderLeft: `1px solid ${barColor}`,- }}- >- <span- className={`text-[11px] truncate whitespace-nowrap flex items-center gap-1.5 ${isUnmatched ? 'opacity-40' : ''}`}- >- <span className="text-muted-alt font-medium">{span.service_name}</span>- <span className="text-muted">{formatDuration(span.duration_nano)}</span>- </span>- </div>- </Tooltip>- </div>- </div>-- {/* Detail panel */}- {isSelected && <SpanDetailPanel span={span} />}- </div>- )- })}+ {/* Span rows (virtualized) */}+ <AutoSizer+ disableHeight+ renderProp={({ width }: SizeProps) => (+ <List<FlameRowData>+ style={{+ height: Math.min(+ flatSpans.length * ROW_HEIGHT + (selectedSpanId ? SELECTED_DETAIL_RESERVE : 0),+ MAX_FLAME_HEIGHT+ ),+ width,+ }}+ overscanCount={10}+ rowCount={flatSpans.length}+ rowHeight={dynamicRowHeight}+ rowComponent={FlameListRow}+ rowProps={{+ flatSpans,+ traceStartUs,+ traceDurationUs,+ serviceColorMap,+ ticks,+ labelColumnWidth,+ selectedSpanId,+ onSelect: handleSelect,+ dynamicRowHeight,+ }}+ />+ )}+ />{/* Full-height splitter between label column and timeline */}<divdiff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsxindex 1a95fac858ae..f8a16258571d 100644--- a/products/tracing/frontend/TracingScene.tsx+++ b/products/tracing/frontend/TracingScene.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import posthog from 'posthog-js'-import { LemonBanner, LemonModal, LemonTable, LemonTableColumns, LemonTag } from '@posthog/lemon-ui'+import { LemonBanner, LemonModal } from '@posthog/lemon-ui'import { IconFeedback } from 'lib/lemon-ui/icons'import { SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'@@ -13,16 +13,16 @@ import { SceneDivider } from '~/layout/scenes/components/SceneDivider'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'+import { VirtualizedSpanList } from './components/VirtualizedSpanList/VirtualizedSpanList'import { TraceCompareFlame } from './TraceCompareFlame'import { TraceCompareTable } from './TraceCompareTable'-import { formatDuration, TraceFlameChart } from './TraceFlameChart'+import { TraceFlameChart } from './TraceFlameChart'import { tracingDataLogic } from './tracingDataLogic'import { TracingFilterBar } from './TracingFilterBar'import { tracingFiltersLogic } from './tracingFiltersLogic'import { tracingSceneLogic, TracingSceneLogicProps } from './tracingSceneLogic'import { TracingSparkline } from './TracingSparkline'import { TracingTabIdProvider, useTracingTabId } from './TracingTabContext'-import { SPAN_KIND_LABELS, STATUS_CODE_LABELS } from './types'import type { Span } from './types'const TRACING_FEEDBACK_SURVEY_ID = '019e6a26-4943-0000-24a0-dc46310f6b7c'@@ -33,63 +33,6 @@ export const scene: SceneExport<TracingSceneLogicProps> = {productKey: ProductKey.TRACING,}-function isRootSpan(span: Span): boolean {- return !span.parent_span_id-}--const columns: LemonTableColumns<Span> = [- {- title: 'Timestamp',- dataIndex: 'timestamp',- render: (_, span) => new Date(span.timestamp).toLocaleString(),- },- {- title: 'Name',- dataIndex: 'name',- render: (_, span) => (- <span className="flex items-center gap-2">- {span.name}- {isRootSpan(span) && (- <LemonTag type="highlight" size="small">- trace- </LemonTag>- )}- </span>- ),- },- {- title: 'Service',- dataIndex: 'service_name',- render: (_, span) => <LemonTag>{span.service_name}</LemonTag>,- },- {- title: 'Kind',- dataIndex: 'kind',- render: (_, span) => SPAN_KIND_LABELS[span.kind] ?? span.kind,- },- {- title: 'Duration',- dataIndex: 'duration_nano',- render: (_, span) => formatDuration(span.duration_nano),- },- {- title: 'Status',- dataIndex: 'status_code',- render: (_, span) => {- const status = STATUS_CODE_LABELS[span.status_code] ?? {- label: String(span.status_code),- type: 'default' as const,- }- return <LemonTag type={status.type}>{status.label}</LemonTag>- },- },- {- title: 'Trace ID',- dataIndex: 'trace_id',- render: (_, span) => <span className="font-mono text-xs">{span.trace_id.substring(0, 16)}...</span>,- },-]-export default function TracingScene(props: TracingSceneLogicProps = {}): JSX.Element {const sceneLogic = tracingSceneLogic(props)// Keep filters + data logic alive across tab switches by attaching them to the scene@@ -124,9 +67,19 @@ function TracingSceneContents(): JSX.Element {spanTree,spanTreeLoading,compareFlameSpanName,+ hasMoreToLoad,+ visibleRowDateRange,} = useValues(tracingSceneLogic({ tabId }))- const { openTraceModal, closeTraceModal, setDateRange, setOverlayWindows, openCompareFlame, closeCompareFlame } =- useActions(tracingSceneLogic({ tabId }))+ const {+ openTraceModal,+ closeTraceModal,+ setDateRange,+ setOverlayWindows,+ openCompareFlame,+ closeCompareFlame,+ fetchNextPage,+ setVisibleRowRange,+ } = useActions(tracingSceneLogic({ tabId }))const compareMode = filters.compareMode// Anchor the overlay's coordinate space to the *fetched* sparkline data so overlay@@ -147,7 +100,7 @@ function TracingSceneContents(): JSX.Element {: undefinedreturn (- <SceneContent>+ <SceneContent className="h-[calc(var(--scene-layout-rect-height,_100vh)_-_1rem)]"><SceneTitleSectionname="Tracing"description="Monitor and analyze distributed traces to understand service performance and debug issues."@@ -172,6 +125,7 @@ function TracingSceneContents(): JSX.Element {onDateRangeChange={setDateRange}displayTimezone="UTC"compare={compareConfig}+ visibleRowDateRange={visibleRowDateRange}/><SceneDivider /><TracingFilterBar />@@ -181,29 +135,28 @@ function TracingSceneContents(): JSX.Element {</div>)}{compareMode ? (- <TraceCompareTable- current={aggregation.current}- previous={aggregation.previous}- loading={aggregationLoading}- onRowClick={(row) => openCompareFlame(row.name, row.service_name)}- />+ <div className="flex flex-col flex-1 min-h-0 overflow-auto">+ <TraceCompareTable+ current={aggregation.current}+ previous={aggregation.previous}+ loading={aggregationLoading}+ onRowClick={(row) => openCompareFlame(row.name, row.service_name)}+ />+ </div>) : (- <LemonTable- columns={columns}+ <VirtualizedSpanListdataSource={rootSpans}loading={spansLoading}- rowKey="uuid"- emptyState="No spans found"- onRow={(span) => ({- onClick: () => {- // Clicking a row leaves the scrollable <main tabIndex="0"> as the active- // element; react-modal then scrolls it back into view when restoring focus- // on close. Blur so the restore target is <body>, which doesn't scroll.- ;(document.activeElement as HTMLElement | null)?.blur?.()- openTraceModal(span.trace_id)- },- className: 'cursor-pointer',- })}+ hasMoreToLoad={hasMoreToLoad}+ onLoadMore={fetchNextPage}+ onVisibleRowRangeChange={setVisibleRowRange}+ onRowClick={(span: Span) => {+ // Clicking a row leaves the scrollable <main tabIndex="0"> as the active+ // element; react-modal then scrolls it back into view when restoring focus+ // on close. Blur so the restore target is <body>, which doesn't scroll.+ ;(document.activeElement as HTMLElement | null)?.blur?.()+ openTraceModal(span.trace_id)+ }}/>)}<LemonModaldiff --git a/products/tracing/frontend/TracingSparkline.tsx b/products/tracing/frontend/TracingSparkline.tsxindex 4506c2d1ab04..79ba356c461e 100644--- a/products/tracing/frontend/TracingSparkline.tsx+++ b/products/tracing/frontend/TracingSparkline.tsx@@ -11,7 +11,7 @@ import { cn } from 'lib/utils/css-classes'import { DateRange } from '~/queries/schema/schema-general'import { SparklineCompareOverlay } from './SparklineCompareOverlay'-import type { TracingSparklineData } from './tracingDataLogic'+import type { TracingSparklineData, VisibleSpanTimeRange } from './tracingDataLogic'interface CompareConfig {fullStartMs: number@@ -27,6 +27,7 @@ interface TracingSparklineProps {onDateRangeChange: (dateRange: DateRange) => voiddisplayTimezone: stringcompare?: CompareConfig+ visibleRowDateRange?: VisibleSpanTimeRange | null}export function TracingSparkline({@@ -35,6 +36,7 @@ export function TracingSparkline({onDateRangeChange,displayTimezone,compare,+ visibleRowDateRange,}: TracingSparklineProps): JSX.Element | null {const [collapsed, setCollapsed] = useState(false)@@ -95,6 +97,37 @@ export function TracingSparkline({return sparklineData.dates.map((date: string) => dayjs(date).toISOString())}, [sparklineData.dates])+ // Map the visible-row date range onto bucket indices in `dates`. Buckets are anchored at+ // their start time; the date_to edge belongs to the bucket whose start is the last one+ // <= date_to. Suppressed in compare mode, where the list (and its window) isn't shown.+ const highlightedRange = useMemo(() => {+ if (compare || !visibleRowDateRange || sparklineData.dates.length === 0) {+ return null+ }+ const fromMs = dayjs(visibleRowDateRange.date_from).valueOf()+ const toMs = dayjs(visibleRowDateRange.date_to).valueOf()+ let startIndex = -1+ let endIndex = -1+ for (let i = 0; i < sparklineData.dates.length; i++) {+ const bucketMs = dayjs(sparklineData.dates[i]).valueOf()+ if (bucketMs <= fromMs) {+ startIndex = i+ }+ if (bucketMs <= toMs) {+ endIndex = i+ } else {+ break+ }+ }+ if (startIndex === -1) {+ startIndex = 0+ }+ if (endIndex === -1 || endIndex < startIndex) {+ return null+ }+ return { startIndex, endIndex }+ }, [compare, visibleRowDateRange, sparklineData.dates])+const onSelectionChange = useCallback((selection: { startIndex: number; endIndex: number }): void => {const dates = sparklineData.dates@@ -140,6 +173,7 @@ export function TracingSparkline({tooltipRowCutoff={100}hideZerosInTooltipsortTooltipByCount+ highlightedRange={highlightedRange}/>) : !sparklineLoading ? (<div className="h-full text-muted flex items-center justify-center">diff --git a/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.tsx b/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.tsxnew file mode 100644index 000000000000..c241269d3965--- /dev/null+++ b/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.tsx@@ -0,0 +1,221 @@+import { CSSProperties, useCallback, useMemo, useRef } from 'react'+import { List } from 'react-window'++import { LemonTag } from '@posthog/lemon-ui'++import { AutoSizer } from 'lib/components/AutoSizer'+import { SizeProps } from 'lib/components/AutoSizer/AutoSizer'+import { cn } from 'lib/utils/css-classes'++import { formatDuration } from '../../TraceFlameChart'+import { SPAN_KIND_LABELS, STATUS_CODE_LABELS } from '../../types'+import type { Span } from '../../types'++const ROW_HEIGHT = 36+const HEADER_HEIGHT = 32+// Minimum content width so the fixed columns keep a sensible size and the row scrolls+// horizontally (rather than collapsing the name column) on narrow viewports.+const MIN_ROW_WIDTH = 900+// Trigger the next page once the bottom of the rendered window is within this many rows of the end.+const LOAD_MORE_THRESHOLD = 10++// Fixed column widths (px). The name column flexes to fill the remaining space.+const COL_WIDTH = {+ timestamp: 190,+ service: 150,+ kind: 90,+ duration: 90,+ status: 80,+ traceId: 140,+} as const++function isRootSpan(span: Span): boolean {+ return !span.parent_span_id+}++interface VirtualizedSpanListProps {+ dataSource: Span[]+ loading: boolean+ onRowClick: (span: Span) => void+ onVisibleRowRangeChange: (startIndex: number, stopIndex: number) => void+ hasMoreToLoad?: boolean+ onLoadMore?: () => void+}++interface SpanRowProps {+ dataSource: Span[]+ onRowClick: (span: Span) => void+}++function Cell({ width, children }: { width?: number; children: React.ReactNode }): JSX.Element {+ return (+ <div+ className={cn('shrink-0 truncate px-2 text-xs', width === undefined && 'flex-1 min-w-0')}+ // eslint-disable-next-line react/forbid-dom-props+ style={width !== undefined ? { width } : undefined}+ >+ {children}+ </div>+ )+}++function SpanRowHeader(): JSX.Element {+ return (+ <div+ className="flex items-center border-b border-border bg-surface-secondary font-medium text-muted"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ height: HEADER_HEIGHT }}+ >+ <Cell width={COL_WIDTH.timestamp}>Timestamp</Cell>+ <Cell>Name</Cell>+ <Cell width={COL_WIDTH.service}>Service</Cell>+ <Cell width={COL_WIDTH.kind}>Kind</Cell>+ <Cell width={COL_WIDTH.duration}>Duration</Cell>+ <Cell width={COL_WIDTH.status}>Status</Cell>+ <Cell width={COL_WIDTH.traceId}>Trace ID</Cell>+ </div>+ )+}++function SpanRow({ span, onClick }: { span: Span; onClick: () => void }): JSX.Element {+ const status = STATUS_CODE_LABELS[span.status_code] ?? { label: String(span.status_code), type: 'default' as const }++ return (+ <div+ className="flex h-full items-center cursor-pointer border-b border-border hover:bg-surface-primary-hover"+ onClick={onClick}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault()+ onClick()+ }+ }}+ role="button"+ tabIndex={0}+ >+ <Cell width={COL_WIDTH.timestamp}>{new Date(span.timestamp).toLocaleString()}</Cell>+ <Cell>+ <span className="flex items-center gap-2 truncate">+ <span className="truncate">{span.name}</span>+ {isRootSpan(span) && (+ <LemonTag type="highlight" size="small">+ trace+ </LemonTag>+ )}+ </span>+ </Cell>+ <Cell width={COL_WIDTH.service}>+ <LemonTag>{span.service_name}</LemonTag>+ </Cell>+ <Cell width={COL_WIDTH.kind}>{SPAN_KIND_LABELS[span.kind] ?? span.kind}</Cell>+ <Cell width={COL_WIDTH.duration}>{formatDuration(span.duration_nano)}</Cell>+ <Cell width={COL_WIDTH.status}>+ <LemonTag type={status.type}>{status.label}</LemonTag>+ </Cell>+ <Cell width={COL_WIDTH.traceId}>+ <span className="font-mono">{span.trace_id.substring(0, 16)}...</span>+ </Cell>+ </div>+ )+}++function SpanListRow({+ ariaAttributes,+ index,+ style,+ dataSource,+ onRowClick,+}: {+ ariaAttributes: { 'aria-posinset': number; 'aria-setsize': number; role: 'listitem' }+ index: number+ style: CSSProperties+} & SpanRowProps): JSX.Element {+ const span = dataSource[index]+ return (+ // eslint-disable-next-line react/forbid-dom-props+ <div {...ariaAttributes} style={style} data-index={index} data-row-key={span.uuid}>+ <SpanRow span={span} onClick={() => onRowClick(span)} />+ </div>+ )+}++export function VirtualizedSpanList({+ dataSource,+ loading,+ onRowClick,+ onVisibleRowRangeChange,+ hasMoreToLoad = false,+ onLoadMore,+}: VirtualizedSpanListProps): JSX.Element {+ // Tracks the last range we dispatched so we don't fire on every overscan tick.+ const lastVisibleRangeRef = useRef<{ startIndex: number; stopIndex: number } | null>(null)++ const handleRowsRendered = useCallback(+ (+ visibleRows: { startIndex: number; stopIndex: number },+ allRows: { startIndex: number; stopIndex: number }+ ): void => {+ if (+ onLoadMore &&+ hasMoreToLoad &&+ !loading &&+ allRows.stopIndex >= dataSource.length - 1 - LOAD_MORE_THRESHOLD+ ) {+ onLoadMore()+ }++ const prev = lastVisibleRangeRef.current+ if (!prev || prev.startIndex !== visibleRows.startIndex || prev.stopIndex !== visibleRows.stopIndex) {+ lastVisibleRangeRef.current = { startIndex: visibleRows.startIndex, stopIndex: visibleRows.stopIndex }+ onVisibleRowRangeChange(visibleRows.startIndex, visibleRows.stopIndex)+ }+ },+ [dataSource.length, hasMoreToLoad, loading, onLoadMore, onVisibleRowRangeChange]+ )++ const rowProps = useMemo((): SpanRowProps => ({ dataSource, onRowClick }), [dataSource, onRowClick])++ if (dataSource.length === 0 && !loading) {+ return (+ <div className="flex items-center justify-center p-8 text-muted border rounded bg-bg-light">+ No spans found+ </div>+ )+ }++ return (+ <div+ className="flex flex-col flex-1 min-h-0 bg-bg-light border rounded overflow-hidden"+ data-attr="tracing-spans-table"+ >+ <AutoSizer+ renderProp={({ width, height }: SizeProps) => {+ if (!width || !height) {+ return null+ }+ const rowWidth = Math.max(width, MIN_ROW_WIDTH)+ return (+ // The viewport is fixed to the available box; the inner content can be wider+ // (MIN_ROW_WIDTH) so columns scroll horizontally and rows align with the header.+ // eslint-disable-next-line react/forbid-dom-props+ <div className="overflow-x-auto" style={{ width, height }}>+ {/* eslint-disable-next-line react/forbid-dom-props */}+ <div style={{ width: rowWidth }}>+ <SpanRowHeader />+ <List<SpanRowProps>+ style={{ height: height - HEADER_HEIGHT, width: rowWidth }}+ overscanCount={10}+ rowCount={dataSource.length}+ rowHeight={ROW_HEIGHT}+ rowComponent={SpanListRow}+ rowProps={rowProps}+ onRowsRendered={handleRowsRendered}+ />+ </div>+ </div>+ )+ }}+ />+ </div>+ )+}diff --git a/products/tracing/frontend/tracingDataLogic.test.ts b/products/tracing/frontend/tracingDataLogic.test.tsnew file mode 100644index 000000000000..c96a27f6f821--- /dev/null+++ b/products/tracing/frontend/tracingDataLogic.test.ts@@ -0,0 +1,127 @@+import { initKeaTests } from '~/test/init'++import { tracingDataLogic } from './tracingDataLogic'+import { tracingFiltersLogic } from './tracingFiltersLogic'+import type { Span } from './types'++const TEST_TAB = 'test-tab'++const createMockSpan = (uuid: string, timestamp: string): Span => ({+ uuid,+ trace_id: `trace-${uuid}`,+ span_id: uuid,+ parent_span_id: '',+ name: 'op',+ kind: 1,+ service_name: 'svc',+ status_code: 1,+ timestamp,+ end_time: timestamp,+ duration_nano: 1000,+ is_root_span: true,+ matched_filter: true,+})++const mockSpans: Span[] = [+ createMockSpan('span-1', '2024-01-01T00:00:00Z'),+ createMockSpan('span-2', '2024-01-01T01:00:00Z'),+ createMockSpan('span-3', '2024-01-01T02:00:00Z'),+ createMockSpan('span-4', '2024-01-01T03:00:00Z'),+]++function mountWithSpans(spans: Span[] = mockSpans): ReturnType<typeof tracingDataLogic.build> {+ tracingFiltersLogic({ tabId: TEST_TAB }).mount()+ const logic = tracingDataLogic({ tabId: TEST_TAB })+ logic.mount()+ if (spans.length > 0) {+ logic.actions.fetchSpansSuccess(spans)+ }+ return logic+}++describe('tracingDataLogic', () => {+ let logic: ReturnType<typeof tracingDataLogic.build>++ beforeEach(() => {+ initKeaTests()+ })++ afterEach(() => {+ logic?.unmount()+ })++ describe('visible row range tracking', () => {+ beforeEach(() => {+ logic = mountWithSpans()+ })++ it('defaults to null', () => {+ expect(logic.values.visibleRowRange).toBeNull()+ expect(logic.values.visibleRowDateRange).toBeNull()+ })++ it('records the visible row index range', () => {+ logic.actions.setVisibleRowRange(1, 2)+ expect(logic.values.visibleRowRange).toEqual({ startIndex: 1, stopIndex: 2 })+ })++ it.each([+ {+ name: 'ascending spans',+ reverse: false,+ range: [1, 2] as const,+ expected: { date_from: '2024-01-01T01:00:00.000Z', date_to: '2024-01-01T02:00:00.000Z' },+ },+ {+ // "Latest first" — startIndex points at a later timestamp than stopIndex.+ name: 'descending spans',+ reverse: true,+ range: [0, 1] as const,+ expected: { date_from: '2024-01-01T02:00:00.000Z', date_to: '2024-01-01T03:00:00.000Z' },+ },+ {+ name: 'single-row range',+ reverse: false,+ range: [2, 2] as const,+ expected: { date_from: '2024-01-01T02:00:00.000Z', date_to: '2024-01-01T02:00:00.000Z' },+ },+ ])('derives a date range ordered earliest-first ($name)', ({ reverse, range, expected }) => {+ if (reverse) {+ logic.actions.fetchSpansSuccess([...mockSpans].reverse())+ }+ logic.actions.setVisibleRowRange(range[0], range[1])+ expect(logic.values.visibleRowDateRange).toEqual(expected)+ })++ it('clamps indices that fall outside the loaded spans', () => {+ logic.actions.setVisibleRowRange(0, 999)+ expect(logic.values.visibleRowDateRange).toEqual({+ date_from: '2024-01-01T00:00:00.000Z',+ date_to: '2024-01-01T03:00:00.000Z',+ })+ })++ it('ignores non-root spans when deriving the range', () => {+ const withChild = [+ createMockSpan('root-1', '2024-01-01T00:00:00Z'),+ { ...createMockSpan('child-1', '2024-01-01T05:00:00Z'), parent_span_id: 'root-1', is_root_span: false },+ createMockSpan('root-2', '2024-01-01T01:00:00Z'),+ ]+ logic.actions.fetchSpansSuccess(withChild)+ // rootSpans = [root-1, root-2]; index 1 is root-2, never the child at 05:00.+ logic.actions.setVisibleRowRange(0, 1)+ expect(logic.values.visibleRowDateRange).toEqual({+ date_from: '2024-01-01T00:00:00.000Z',+ date_to: '2024-01-01T01:00:00.000Z',+ })+ })++ it('clears when spans are reset', () => {+ logic.actions.setVisibleRowRange(0, 2)+ expect(logic.values.visibleRowDateRange).not.toBeNull()+ logic.actions.clearSpans()+ expect(logic.values.visibleRowRange).toBeNull()+ expect(logic.values.visibleRowDateRange).toBeNull()+ })+ })+})diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.tsindex 7ed0798b4ef3..16f6e0bab4e3 100644--- a/products/tracing/frontend/tracingDataLogic.ts+++ b/products/tracing/frontend/tracingDataLogic.ts@@ -5,6 +5,7 @@ import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'import { dataColorVars } from 'lib/colors'+import { dayjs } from 'lib/dayjs'import { humanFriendlyDetailedTime } from 'lib/utils'import { AggregatedSpanRow, SpanTreeNode } from '~/queries/schema/schema-general'@@ -26,6 +27,16 @@ export interface TracingSparklineData {labels: string[]}+export interface VisibleRowRange {+ startIndex: number+ stopIndex: number+}++export interface VisibleSpanTimeRange {+ date_from: string+ date_to: string+}+const DEFAULT_PAGE_SIZE = 100export const PREFETCH_SPANS = 20const NEW_QUERY_STARTED_ERROR_MESSAGE = 'new query started' as const@@ -65,6 +76,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([setSpanTreeAbortController: (controller: AbortController | null) => ({ controller }),setHasMoreToLoad: (hasMore: boolean) => ({ hasMore }),setNextCursor: (cursor: string | null) => ({ cursor }),+ setVisibleRowRange: (startIndex: number, stopIndex: number) => ({ startIndex, stopIndex }),/*** Snapshot the resolved time windows used for the last aggregation fetch.* The drill-down flame query reads this snapshot instead of recomputing from@@ -161,6 +173,13 @@ export const tracingDataLogic = kea<tracingDataLogicType>([clearSpans: () => null,},],+ visibleRowRange: [+ null as VisibleRowRange | null,+ {+ setVisibleRowRange: (_, { startIndex, stopIndex }) => ({ startIndex, stopIndex }),+ clearSpans: () => null,+ },+ ],}),loaders(({ values, actions }) => ({@@ -205,6 +224,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([serviceNames:values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,filterGroup: values.filters.filterGroup as PropertyGroupFilter,+ prefetchSpans: PREFETCH_SPANS,limit: DEFAULT_PAGE_SIZE,after: values.nextCursor,},@@ -416,6 +436,32 @@ export const tracingDataLogic = kea<tracingDataLogicType>([return spans.filter((s) => s.is_root_span)},],++ // Date range covered by the currently-visible (scrolled-into-view) rows. Mirrors the+ // logs viewer so the sparkline can highlight the window the list is showing. Values are+ // always ordered date_from <= date_to regardless of the list's sort order.+ visibleRowDateRange: [+ (s) => [s.visibleRowRange, s.rootSpans],+ (visibleRowRange: VisibleRowRange | null, rootSpans: Span[]): VisibleSpanTimeRange | null => {+ if (!visibleRowRange || rootSpans.length === 0) {+ return null+ }+ const startIndex = Math.max(0, Math.min(visibleRowRange.startIndex, rootSpans.length - 1))+ const stopIndex = Math.max(0, Math.min(visibleRowRange.stopIndex, rootSpans.length - 1))+ const a = rootSpans[startIndex]?.timestamp+ const b = rootSpans[stopIndex]?.timestamp+ if (!a || !b) {+ return null+ }+ const ta = dayjs(a)+ const tb = dayjs(b)+ const [earlier, later] = ta.isBefore(tb) ? [ta, tb] : [tb, ta]+ return {+ date_from: earlier.toISOString(),+ date_to: later.toISOString(),+ }+ },+ ],}),listeners(({ actions, values }) => ({diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.tsindex 9fdbb622a4a0..a7210555d053 100644--- a/products/tracing/frontend/tracingSceneLogic.ts+++ b/products/tracing/frontend/tracingSceneLogic.ts@@ -43,13 +43,14 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>(['aggregationLoading','spanTree','spanTreeLoading',+ 'visibleRowDateRange',],tracingFiltersLogic({ tabId: p.tabId }),['filters', 'utcDateRange', 'sparklineWindowMs', 'currentWindowMs', 'previousWindowMs'],],actions: [tracingDataLogic({ tabId: p.tabId }),- ['runQuery', 'fetchNextPage', 'loadTraceSpans', 'fetchAggregation', 'fetchSpanTree'],+ ['runQuery', 'fetchNextPage', 'loadTraceSpans', 'fetchAggregation', 'fetchSpanTree', 'setVisibleRowRange'],tracingFiltersLogic({ tabId: p.tabId }),['setDateRange',diff --git a/products/tracing/package.json b/products/tracing/package.jsonindex ce923d96441b..bb9e6b8cd551 100644--- a/products/tracing/package.json+++ b/products/tracing/package.json@@ -14,6 +14,7 @@"@types/react": "*","clsx": "*","fast-deep-equal": "*",- "react": "*"+ "react": "*",+ "react-window": "*"}}