Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(tracing): sort the span list from clickable column headers (#62697)

Jon McCallumd5682949c0f8
diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsx
index 29f8fc2559a5..9a6c9e1f0795 100644
--- a/products/tracing/frontend/TracingScene.tsx
+++ b/products/tracing/frontend/TracingScene.tsx
@@ -77,6 +77,7 @@ function TracingSceneContents(): JSX.Element {
fetchNextPage,
setVisibleRowRange,
toggleExpandSpan,
+ setSort,
} = useActions(tracingSceneLogic())
const { addProductIntent } = useActions(teamLogic)
const compareMode = filters.compareMode
@@ -179,6 +180,15 @@ function TracingSceneContents(): JSX.Element {
onVisibleRowRangeChange={setVisibleRowRange}
expandedSpanIds={expandedSpanIds}
onToggleExpand={toggleExpandSpan}
+ orderBy={filters.orderBy}
+ orderDirection={filters.orderDirection}
+ onSort={(column) =>
+ // Click an active column to flip direction; a new column starts at DESC.
+ setSort(
+ column,
+ column === filters.orderBy && filters.orderDirection === 'DESC' ? 'ASC' : 'DESC'
+ )
+ }
emptyState={
<div className="flex flex-col items-center gap-1">
<span>No spans found</span>
diff --git a/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.tsx b/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.tsx
index b6176c87244d..8b987948265d 100644
--- a/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.tsx
+++ b/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.tsx
@@ -6,9 +6,11 @@ import { LemonButton, LemonTag } from '@posthog/lemon-ui'
import { AutoSizer } from 'lib/components/AutoSizer'
import { SizeProps } from 'lib/components/AutoSizer/AutoSizer'
+import { SortingIndicator } from 'lib/lemon-ui/LemonTable/sorting'
import { cn } from 'lib/utils/css-classes'
import { formatDuration } from '../../TraceFlameChart'
+import type { TracingOrderBy, TracingOrderDirection } from '../../tracingFiltersLogic'
import { SPAN_KIND_LABELS, STATUS_CODE_LABELS } from '../../types'
import type { Span } from '../../types'
import { ExpandedSpanContent } from './ExpandedSpanContent'
@@ -41,7 +43,13 @@ function isRootSpan(span: Span): boolean {
return !span.parent_span_id
}
-interface VirtualizedSpanListProps {
+interface SortProps {
+ orderBy: TracingOrderBy
+ orderDirection: TracingOrderDirection
+ onSort: (column: TracingOrderBy) => void
+}
+
+interface VirtualizedSpanListProps extends SortProps {
dataSource: Span[]
loading: boolean
onRowClick: (span: Span) => void
@@ -73,7 +81,33 @@ function Cell({ width, children }: { width?: number; children: React.ReactNode }
)
}
-function SpanRowHeader(): JSX.Element {
+function SortableHeaderCell({
+ column,
+ label,
+ width,
+ orderBy,
+ orderDirection,
+ onSort,
+}: { column: TracingOrderBy; label: string; width: number } & SortProps): JSX.Element {
+ const active = orderBy === column
+ return (
+ <Cell width={width}>
+ <button
+ type="button"
+ className={cn('flex items-center cursor-pointer hover:text-default', active && 'text-default')}
+ onClick={() => onSort(column)}
+ data-attr={`tracing-sort-${column}`}
+ >
+ <span>{label}</span>
+ {/* Neutral icon when inactive (so the column reads as sortable), directional arrow
+ once active — order 1 = ASC, -1 = DESC, matching LemonTable's convention. */}
+ <SortingIndicator order={active ? (orderDirection === 'ASC' ? 1 : -1) : null} />
+ </button>
+ </Cell>
+ )
+}
+
+function SpanRowHeader({ orderBy, orderDirection, onSort }: SortProps): JSX.Element {
return (
<div
className="flex items-center border-b border-border bg-surface-secondary font-medium text-muted"
@@ -81,11 +115,25 @@ function SpanRowHeader(): JSX.Element {
style={{ height: HEADER_HEIGHT }}
>
<Cell width={COL_WIDTH.expand}> </Cell>
- <Cell width={COL_WIDTH.timestamp}>Timestamp</Cell>
+ <SortableHeaderCell
+ column="timestamp"
+ label="Timestamp"
+ width={COL_WIDTH.timestamp}
+ orderBy={orderBy}
+ orderDirection={orderDirection}
+ onSort={onSort}
+ />
<Cell>Name</Cell>
<Cell width={COL_WIDTH.service}>Service</Cell>
<Cell width={COL_WIDTH.kind}>Kind</Cell>
- <Cell width={COL_WIDTH.duration}>Duration</Cell>
+ <SortableHeaderCell
+ column="duration"
+ label="Duration"
+ width={COL_WIDTH.duration}
+ orderBy={orderBy}
+ orderDirection={orderDirection}
+ onSort={onSort}
+ />
<Cell width={COL_WIDTH.status}>Status</Cell>
<Cell width={COL_WIDTH.traceId}>Trace ID</Cell>
<Cell width={COL_WIDTH.actions}> </Cell>
@@ -210,6 +258,9 @@ export function VirtualizedSpanList({
hasMoreToLoad = false,
onLoadMore,
emptyState = 'No spans found',
+ orderBy,
+ orderDirection,
+ onSort,
}: 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)
@@ -271,7 +322,7 @@ export function VirtualizedSpanList({
<div className="overflow-x-auto" style={{ width, height }}>
{/* eslint-disable-next-line react/forbid-dom-props */}
<div style={{ width: rowWidth }}>
- <SpanRowHeader />
+ <SpanRowHeader orderBy={orderBy} orderDirection={orderDirection} onSort={onSort} />
<List<SpanRowProps>
style={{ height: height - HEADER_HEIGHT, width: rowWidth }}
overscanCount={10}
diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.ts
index e9b1ed4e4d61..96d01b09b0af 100644
--- a/products/tracing/frontend/tracingDataLogic.ts
+++ b/products/tracing/frontend/tracingDataLogic.ts
@@ -13,7 +13,7 @@ import { AggregatedSpanRow, SpanTreeNode } from '~/queries/schema/schema-general
import { PropertyGroupFilter } from '~/types'
import type { tracingDataLogicType } from './tracingDataLogicType'
-import { tracingFiltersLogic } from './tracingFiltersLogic'
+import { type TracingOrderBy, tracingFiltersLogic } from './tracingFiltersLogic'
import type { Span } from './types'
export interface SparklineRow {
@@ -59,7 +59,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
path(['products', 'tracing', 'frontend', 'tracingDataLogic']),
connect(() => ({
- values: [tracingFiltersLogic(), ['filters', 'utcDateRange', 'currentWindowMs', 'previousWindowMs']],
+ values: [tracingFiltersLogic(), ['filters', 'orderBy', 'utcDateRange', 'currentWindowMs', 'previousWindowMs']],
})),
actions({
@@ -195,6 +195,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
{
dateRange: values.utcDateRange,
orderBy: values.filters.orderBy,
+ orderDirection: values.filters.orderDirection,
serviceNames:
values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,
filterGroup: values.filters.filterGroup as PropertyGroupFilter,
@@ -210,23 +211,31 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
return response.results as Span[]
},
fetchNextPage: async () => {
- if (!values.nextCursor) {
+ if (!values.hasMoreToLoad) {
return values.spans
}
const controller = new AbortController()
actions.cancelInProgressSpans(controller)
+ // Duration ordering paginates by offset (it has no keyset cursor); timestamp
+ // ordering uses the `after` cursor. Offset is the count of traces already shown.
+ const pagination =
+ values.filters.orderBy === 'duration'
+ ? { offset: values.rootSpans.length }
+ : { after: values.nextCursor ?? undefined }
+
const response = await api.tracing.listSpans(
{
dateRange: values.utcDateRange,
orderBy: values.filters.orderBy,
+ orderDirection: values.filters.orderDirection,
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,
+ ...pagination,
},
controller.signal
)
@@ -437,13 +446,19 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
},
],
- // 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.
+ // Date range covered by the currently-visible (scrolled-into-view) rows, so the sparkline can
+ // highlight the window the list is showing (mirrors the logs viewer). Only meaningful when the
+ // list is time-ordered — under duration (or any non-timestamp) sort, consecutive rows aren't
+ // contiguous in time, so the highlight would be meaningless. Suppress it then; a
+ // duration-appropriate overlay is a follow-up (JON-36).
visibleRowDateRange: [
- (s) => [s.visibleRowRange, s.rootSpans],
- (visibleRowRange: VisibleRowRange | null, rootSpans: Span[]): VisibleSpanTimeRange | null => {
- if (!visibleRowRange || rootSpans.length === 0) {
+ (s) => [s.visibleRowRange, s.rootSpans, s.orderBy],
+ (
+ visibleRowRange: VisibleRowRange | null,
+ rootSpans: Span[],
+ orderBy: TracingOrderBy
+ ): VisibleSpanTimeRange | null => {
+ if (orderBy !== 'timestamp' || !visibleRowRange || rootSpans.length === 0) {
return null
}
const startIndex = Math.max(0, Math.min(visibleRowRange.startIndex, rootSpans.length - 1))
diff --git a/products/tracing/frontend/tracingFiltersLogic.ts b/products/tracing/frontend/tracingFiltersLogic.ts
index bed505d9767d..f4eab7df18fc 100644
--- a/products/tracing/frontend/tracingFiltersLogic.ts
+++ b/products/tracing/frontend/tracingFiltersLogic.ts
@@ -11,10 +11,12 @@ import type { tracingFiltersLogicType } from './tracingFiltersLogicType'
export const DEFAULT_DATE_RANGE: DateRange = { date_from: '-1h', date_to: null }
export const DEFAULT_SERVICE_NAMES: string[] = []
export const DEFAULT_ORDER_BY = 'timestamp' as const
+export const DEFAULT_ORDER_DIRECTION = 'DESC' as const
-// Column the list is ordered by. Direction (asc/desc) is a backend default (desc) until the sort
-// control lands (JON-34); timestamp+desc reproduces the previous "latest" behaviour.
+// Column the list is ordered by, and its direction. timestamp+DESC is "latest" (keyset paginated via
+// the `after` cursor); duration+DESC/ASC is slowest/fastest (offset paginated). See tracingDataLogic.
export type TracingOrderBy = 'timestamp' | 'duration'
+export type TracingOrderDirection = 'ASC' | 'DESC'
export interface OverlayWindow {
startMs: number
@@ -26,6 +28,7 @@ export interface TracingFilters {
serviceNames: string[]
filterGroup: UniversalFiltersGroup
orderBy: TracingOrderBy
+ orderDirection: TracingOrderDirection
compareMode: boolean
/** User-positioned overrides for the two compare windows. Null until the overlay is dragged. */
currentWindowOverride: OverlayWindow | null
@@ -39,7 +42,7 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([
setDateRange: (dateRange: DateRange) => ({ dateRange }),
setServiceNames: (serviceNames: string[]) => ({ serviceNames }),
setFilterGroup: (filterGroup: UniversalFiltersGroup) => ({ filterGroup }),
- setOrderBy: (orderBy: TracingOrderBy) => ({ orderBy }),
+ setSort: (orderBy: TracingOrderBy, orderDirection: TracingOrderDirection) => ({ orderBy, orderDirection }),
setCompareMode: (compareMode: boolean) => ({ compareMode }),
/**
* Persist the user-dragged overlay windows. Both must be supplied. Setting these
@@ -76,10 +79,17 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([
orderBy: [
DEFAULT_ORDER_BY as TracingOrderBy,
{
- setOrderBy: (_, { orderBy }) => orderBy,
+ setSort: (_, { orderBy }) => orderBy,
setFilters: (state, { filters }) => (filters.orderBy as TracingOrderBy) ?? state,
},
],
+ orderDirection: [
+ DEFAULT_ORDER_DIRECTION as TracingOrderDirection,
+ {
+ setSort: (_, { orderDirection }) => orderDirection,
+ setFilters: (state, { filters }) => (filters.orderDirection as TracingOrderDirection) ?? state,
+ },
+ ],
compareMode: [
false as boolean,
{
@@ -116,6 +126,7 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([
s.serviceNames,
s.filterGroup,
s.orderBy,
+ s.orderDirection,
s.compareMode,
s.currentWindowOverride,
s.previousWindowOverride,
@@ -125,6 +136,7 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([
serviceNames,
filterGroup,
orderBy,
+ orderDirection,
compareMode,
currentWindowOverride,
previousWindowOverride
@@ -133,6 +145,7 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([
serviceNames,
filterGroup,
orderBy,
+ orderDirection,
compareMode,
currentWindowOverride,
previousWindowOverride,
diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.ts
index edac9075b8dc..d665ad2fdd73 100644
--- a/products/tracing/frontend/tracingSceneLogic.ts
+++ b/products/tracing/frontend/tracingSceneLogic.ts
@@ -11,7 +11,13 @@ import { Params } from 'scenes/sceneTypes'
import { Breadcrumb } from '~/types'
import { PREFETCH_SPANS, tracingDataLogic } from './tracingDataLogic'
-import { DEFAULT_DATE_RANGE, DEFAULT_ORDER_BY, DEFAULT_SERVICE_NAMES, tracingFiltersLogic } from './tracingFiltersLogic'
+import {
+ DEFAULT_DATE_RANGE,
+ DEFAULT_ORDER_BY,
+ DEFAULT_ORDER_DIRECTION,
+ DEFAULT_SERVICE_NAMES,
+ tracingFiltersLogic,
+} from './tracingFiltersLogic'
import type { tracingSceneLogicType } from './tracingSceneLogicType'
import type { Span } from './types'
@@ -49,7 +55,7 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
'setDateRange',
'setServiceNames',
'setFilterGroup',
- 'setOrderBy',
+ 'setSort',
'setCompareMode',
'setOverlayWindows',
'setFilters',
@@ -156,7 +162,8 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
setDateRange: () => actions.handleFilterChange('date_range'),
setServiceNames: () => actions.handleFilterChange('service_names'),
setFilterGroup: () => actions.handleFilterChange('filter_group'),
- setOrderBy: () => actions.handleFilterChange('order_by'),
+ setSort: ({ orderBy, orderDirection }) =>
+ actions.handleFilterChange('sort', { column: orderBy, direction: orderDirection }),
setCompareMode: ({ compareMode }) => actions.handleFilterChange('compare_mode', { enabled: compareMode }),
setOverlayWindows: () => {
// Overlay drags only refetch the aggregation — the sparkline canvas range
@@ -231,6 +238,13 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
}
}
+ if (searchParams.orderDirection) {
+ if (searchParams.orderDirection !== values.filters.orderDirection) {
+ filtersFromUrl.orderDirection = searchParams.orderDirection
+ hasChanges = true
+ }
+ }
+
const compareFromUrl = searchParams.compare === 'true' || searchParams.compare === true
if (compareFromUrl !== values.filters.compareMode) {
filtersFromUrl.compareMode = compareFromUrl
@@ -261,6 +275,9 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
if (values.filters.orderBy !== DEFAULT_ORDER_BY) {
searchParams.orderBy = values.filters.orderBy
}
+ if (values.filters.orderDirection !== DEFAULT_ORDER_DIRECTION) {
+ searchParams.orderDirection = values.filters.orderDirection
+ }
if (values.filters.compareMode) {
searchParams.compare = 'true'
}