Skip to content

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

feat(tracing): add Traces/Spans view switcher (#64857)

Jon McCallum5ace04c4073f
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index dd645ba8426e..207c486ccebe 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -2939,6 +2939,9 @@ const api = {
after?: string
offset?: number
prefetchSpans?: number
+ // false (default) groups by trace_id and returns root spans; true returns every
+ // matching span (root and child) flat. See products/tracing/backend logic.py.
+ flatSpans?: boolean
},
signal?: AbortSignal
): Promise<{
@@ -2981,6 +2984,17 @@ const api = {
}> {
return new ApiRequest().tracingSpans().withAction('sparkline').create({ signal, data: { query } })
},
+ async count(
+ query: {
+ dateRange?: { date_from?: string | null; date_to?: string | null }
+ serviceNames?: string[]
+ statusCodes?: number[]
+ filterGroup?: PropertyGroupFilter
+ },
+ signal?: AbortSignal
+ ): Promise<{ count: number; traceCount: number }> {
+ return new ApiRequest().tracingSpans().withAction('count').create({ signal, data: { query } })
+ },
async durationHistogram(
query: {
dateRange?: { date_from?: string | null; date_to?: string | null }
diff --git a/products/tracing/backend/count_query_runner.py b/products/tracing/backend/count_query_runner.py
index 409f3b53e5e6..99ed3f5efd08 100644
--- a/products/tracing/backend/count_query_runner.py
+++ b/products/tracing/backend/count_query_runner.py
@@ -56,7 +56,8 @@ class TraceSpansCountQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunne
settings=self.settings,
)
count = response.results[0][0] if response.results else 0
- return TraceSpansQueryResponse(results={"count": count})
+ trace_count = response.results[0][1] if response.results else 0
+ return TraceSpansQueryResponse(results={"count": count, "traceCount": trace_count})
def to_query(self) -> ast.SelectQuery:
# where() bounds the window by time_bucket (day precision); add explicit half-open
@@ -73,8 +74,11 @@ class TraceSpansCountQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunne
),
]
)
+ # count() is every matching span (the "Spans" view's row count). The trace count must match the
+ # "Traces" view, which selects traces by root-span match (rootSpans defaults True → root_only in
+ # logic.py), so restrict the distinct-trace count to matching root spans — not any matching span.
query = parse_select(
- "SELECT count() FROM posthog.trace_spans WHERE {where}",
+ "SELECT count(), uniqExactIf(trace_id, is_root_span = 1) FROM posthog.trace_spans WHERE {where}",
placeholders={"where": where_with_timestamp},
)
assert isinstance(query, ast.SelectQuery)
diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.py
index 8b6ed9d31ecd..33d72508a5b1 100644
--- a/products/tracing/backend/presentation/views.py
+++ b/products/tracing/backend/presentation/views.py
@@ -446,6 +446,9 @@ class _TracingCountRequestSerializer(serializers.Serializer):
class _TracingCountResponseSerializer(serializers.Serializer):
count = serializers.IntegerField(help_text="Number of spans matching the filters.")
+ traceCount = serializers.IntegerField(
+ help_text="Number of distinct traces whose root span matches the filters — the trace count shown in the Traces view."
+ )
# Upper bound on symbols per request; each becomes a multiIf branch in the generated query.
diff --git a/products/tracing/backend/tests/test_count_query_runner.py b/products/tracing/backend/tests/test_count_query_runner.py
index 943f69aa9c42..5d2a68f65da5 100644
--- a/products/tracing/backend/tests/test_count_query_runner.py
+++ b/products/tracing/backend/tests/test_count_query_runner.py
@@ -89,7 +89,23 @@ class TestTraceSpansCount(ClickhouseTestMixin, APIBaseTest):
date_range=DateRange(date_from=DATE_FROM, date_to=DATE_TO),
service_names=service_names,
)
- self.assertEqual(response.results, {"count": expected_count})
+ self.assertEqual(response.results["count"], expected_count)
+
+ @parameterized.expand(
+ [
+ # count() is per-span; traceCount is distinct traces whose root matches. Unfiltered, every
+ # root matches, so count = 9 spans but traceCount = 3 traces.
+ ("unfiltered", None, NUM_TRACES * 3, NUM_TRACES),
+ ("no_match_returns_zero_for_both", ["does-not-exist"], 0, 0),
+ ]
+ )
+ def test_count_includes_distinct_trace_count(self, _name, service_names, expected_spans, expected_traces):
+ response = run_count_query(
+ team=self.team,
+ date_range=DateRange(date_from=DATE_FROM, date_to=DATE_TO),
+ service_names=service_names,
+ )
+ self.assertEqual(response.results, {"count": expected_spans, "traceCount": expected_traces})
def test_count_via_api_with_name_filter(self):
body = {
@@ -101,7 +117,21 @@ class TestTraceSpansCount(ClickhouseTestMixin, APIBaseTest):
res = self.client.post(f"/api/projects/{self.team.id}/tracing/spans/count/", body, format="json")
self.assertEqual(res.status_code, 200, res.content)
# One root span named process_query_model per trace.
- self.assertEqual(res.json(), {"count": NUM_TRACES})
+ self.assertEqual(res.json()["count"], NUM_TRACES)
+
+ def test_count_api_child_only_filter_matches_spans_but_no_trace_roots(self):
+ body = {
+ "query": {
+ "dateRange": {"date_from": DATE_FROM, "date_to": DATE_TO},
+ "filterGroup": [{"key": "is_root_span", "type": "span", "operator": "exact", "value": False}],
+ }
+ }
+ res = self.client.post(f"/api/projects/{self.team.id}/tracing/spans/count/", body, format="json")
+ self.assertEqual(res.status_code, 200, res.content)
+ # 2 child spans per trace = 6 matching spans, but no trace's ROOT matches (the filter excludes
+ # roots), so the Traces view shows 0 traces — traceCount must agree with that, not count traces
+ # by any matching span.
+ self.assertEqual(res.json(), {"count": NUM_TRACES * 2, "traceCount": 0})
@parameterized.expand(
[
@@ -130,4 +160,4 @@ class TestTraceSpansCount(ClickhouseTestMixin, APIBaseTest):
}
res = self.client.post(f"/api/projects/{self.team.id}/tracing/spans/count/", body, format="json")
self.assertEqual(res.status_code, 200, res.content)
- self.assertEqual(res.json(), {"count": expected_count})
+ self.assertEqual(res.json()["count"], expected_count)
diff --git a/products/tracing/frontend/TracingFilterBar.tsx b/products/tracing/frontend/TracingFilterBar.tsx
index bd584bed6f13..11c16f76f561 100644
--- a/products/tracing/frontend/TracingFilterBar.tsx
+++ b/products/tracing/frontend/TracingFilterBar.tsx
@@ -1,8 +1,16 @@
import { BindLogic, useActions, useValues } from 'kea'
import { useRef, useState } from 'react'
-import { IconChevronDown, IconMinusSquare, IconPlusSquare, IconRefresh } from '@posthog/icons'
-import { LemonButton, LemonCheckbox, LemonDropdown, LemonInput, LemonSwitch, LemonTag } from '@posthog/lemon-ui'
+import { IconChevronDown, IconList, IconListTree, IconMinusSquare, IconPlusSquare, IconRefresh } from '@posthog/icons'
+import {
+ LemonButton,
+ LemonCheckbox,
+ LemonDropdown,
+ LemonInput,
+ LemonSegmentedButton,
+ LemonSwitch,
+ LemonTag,
+} from '@posthog/lemon-ui'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'
@@ -28,7 +36,7 @@ import {
} from '~/types'
import { tracingDataLogic } from './tracingDataLogic'
-import { tracingFiltersLogic } from './tracingFiltersLogic'
+import { tracingFiltersLogic, type TracingViewMode } from './tracingFiltersLogic'
import { tracingServiceFilterLogic, TracingServiceFilterLogicProps } from './tracingServiceFilterLogic'
const taxonomicFilterLogicKey = 'tracing'
@@ -82,8 +90,9 @@ export function TracingFilterBar(): JSX.Element {
const { spansLoading } = useValues(tracingDataLogic())
const { runQuery } = useActions(tracingDataLogic())
const { filters, utcDateRange } = useValues(tracingFiltersLogic())
- const { setDateRange, setServiceNames, setFilterGroup, setCompareMode } = useActions(tracingFiltersLogic())
- const { dateRange, serviceNames, filterGroup, compareMode } = filters
+ const { setDateRange, setServiceNames, setFilterGroup, setViewMode, setCompareMode } =
+ useActions(tracingFiltersLogic())
+ const { dateRange, serviceNames, filterGroup, viewMode, compareMode } = filters
return (
<TracingFilterGroup filterGroup={filterGroup} onFilterGroupChange={setFilterGroup}>
@@ -145,6 +154,29 @@ export function TracingFilterBar(): JSX.Element {
}}
/>
</div>
+ {!compareMode && (
+ <LemonSegmentedButton<TracingViewMode>
+ size="small"
+ value={viewMode}
+ onChange={setViewMode}
+ options={[
+ {
+ value: 'traces',
+ label: 'Traces',
+ icon: <IconListTree />,
+ tooltip: 'Group matching spans by trace — one row per trace (its root span)',
+ 'data-attr': 'tracing-view-mode-traces',
+ },
+ {
+ value: 'spans',
+ label: 'Spans',
+ icon: <IconList />,
+ tooltip: 'Show every matching span individually, including child spans',
+ 'data-attr': 'tracing-view-mode-spans',
+ },
+ ]}
+ />
+ )}
<LemonSwitch
label="Compare"
checked={compareMode}
diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsx
index bf9fd89697b4..be52606c0afb 100644
--- a/products/tracing/frontend/TracingScene.tsx
+++ b/products/tracing/frontend/TracingScene.tsx
@@ -5,6 +5,7 @@ import { LemonBanner, LemonButton, LemonModal, Link } from '@posthog/lemon-ui'
import { IconFeedback } from 'lib/lemon-ui/icons'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { SceneExport } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
@@ -45,7 +46,7 @@ export default function TracingScene(): JSX.Element {
function TracingSceneContents(): JSX.Element {
const {
- rootSpans,
+ listRows,
spansLoading,
isTraceOpen,
selectedTraceId,
@@ -53,7 +54,7 @@ function TracingSceneContents(): JSX.Element {
selectedTraceTs,
sparklineData,
sparklineLoading,
- totalSpansMatchingFilters,
+ totalMatchingFilters,
openTraceSpans,
isLoadingFullTrace,
canLoadMoreTraceSpans,
@@ -168,9 +169,12 @@ function TracingSceneContents(): JSX.Element {
/>
<SceneDivider />
<TracingFilterBar />
- {!sparklineLoading && totalSpansMatchingFilters > 0 && (
+ {/* No loading guard: keep the last (view-mode-independent) count visible across reloads,
+ so a Traces/Spans switch doesn't flicker the label out and back in. */}
+ {!compareMode && totalMatchingFilters > 0 && (
<div className="text-xs text-muted px-1">
- {totalSpansMatchingFilters.toLocaleString()} spans matching filters
+ {humanFriendlyNumber(totalMatchingFilters)} {filters.viewMode === 'spans' ? 'spans' : 'traces'}{' '}
+ matching filters
</div>
)}
{compareMode ? (
@@ -182,7 +186,7 @@ function TracingSceneContents(): JSX.Element {
/>
) : (
<VirtualizedSpanList
- dataSource={rootSpans}
+ dataSource={listRows}
loading={spansLoading}
hasMoreToLoad={hasMoreToLoad}
onLoadMore={fetchNextPage}
@@ -211,7 +215,9 @@ function TracingSceneContents(): JSX.Element {
// 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?.()
- openTrace(span.trace_id, { ts: span.timestamp })
+ // Anchor the waterfall on the clicked span — in Spans mode this is often a
+ // child span, so without spanId the drawer would open unfocused at the root.
+ openTrace(span.trace_id, { spanId: span.span_id, ts: span.timestamp })
}}
/>
)}
diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.ts
index 67b679a5d4cc..c7481a6c0e06 100644
--- a/products/tracing/frontend/generated/api.schemas.ts
+++ b/products/tracing/frontend/generated/api.schemas.ts
@@ -219,6 +219,8 @@ export interface _TracingCountRequestApi {
export interface _TracingCountResponseApi {
/** Number of spans matching the filters. */
count: number
+ /** Number of distinct traces whose root span matches the filters — the trace count shown in the Traces view. */
+ traceCount: number
}
export interface _TracingTimeseriesQueryBodyApi {
diff --git a/products/tracing/frontend/tracingDataLogic.test.ts b/products/tracing/frontend/tracingDataLogic.test.ts
index 27a6d51315ec..dc43add42603 100644
--- a/products/tracing/frontend/tracingDataLogic.test.ts
+++ b/products/tracing/frontend/tracingDataLogic.test.ts
@@ -1,5 +1,9 @@
import posthog from 'posthog-js'
+import { lemonToast } from '@posthog/lemon-ui'
+
+import api from 'lib/api'
+
import { AggregatedSpanRow } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
@@ -124,7 +128,7 @@ describe('tracingDataLogic', () => {
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.
+ // listRows = [root-1, root-2] in traces mode; 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',
@@ -187,4 +191,104 @@ describe('tracingDataLogic', () => {
expect(captureSpy).toHaveBeenCalledWith(event, properties)
})
})
+
+ describe('view mode', () => {
+ const withChildSpans: Span[] = [
+ createMockSpan('root-1', '2024-01-01T00:00:00Z'),
+ { ...createMockSpan('child-1', '2024-01-01T00:00:01Z'), parent_span_id: 'root-1', is_root_span: false },
+ createMockSpan('root-2', '2024-01-01T01:00:00Z'),
+ ]
+
+ it('lists only root spans in traces mode (default)', () => {
+ logic = mountWithSpans(withChildSpans)
+ expect(logic.values.filters.viewMode).toBe('traces')
+ expect(logic.values.listRows.map((s) => s.uuid)).toEqual(['root-1', 'root-2'])
+ })
+
+ it('lists every span (root and child) in spans mode', () => {
+ logic = mountWithSpans(withChildSpans)
+ tracingFiltersLogic().actions.setViewMode('spans')
+ expect(logic.values.listRows.map((s) => s.uuid)).toEqual(['root-1', 'child-1', 'root-2'])
+ })
+
+ it('requests flat spans from the API when in spans mode', async () => {
+ const listSpansSpy = jest.spyOn(api.tracing, 'listSpans').mockResolvedValue({ results: [], hasMore: false })
+ logic = mountWithSpans([])
+ tracingFiltersLogic().actions.setViewMode('spans')
+ await logic.asyncActions.fetchSpans()
+ expect(listSpansSpy).toHaveBeenCalledWith(expect.objectContaining({ flatSpans: true }), expect.anything())
+ listSpansSpy.mockRestore()
+ })
+
+ it('requests grouped traces from the API in traces mode', async () => {
+ const listSpansSpy = jest.spyOn(api.tracing, 'listSpans').mockResolvedValue({ results: [], hasMore: false })
+ logic = mountWithSpans([])
+ await logic.asyncActions.fetchSpans()
+ expect(listSpansSpy).toHaveBeenCalledWith(expect.objectContaining({ flatSpans: false }), expect.anything())
+ listSpansSpy.mockRestore()
+ })
+
+ it('totalMatchingFilters reports trace count in traces mode and span count in spans mode', () => {
+ logic = mountWithSpans([])
+ logic.actions.fetchMatchingCountsSuccess({ count: 5000, traceCount: 100 })
+ expect(logic.values.totalMatchingFilters).toBe(100)
+ tracingFiltersLogic().actions.setViewMode('spans')
+ expect(logic.values.totalMatchingFilters).toBe(5000)
+ })
+ })
+
+ describe('matching counts', () => {
+ it('does not re-fetch the count when only the view mode changes', async () => {
+ const countSpy = jest.spyOn(api.tracing, 'count').mockResolvedValue({ count: 10, traceCount: 3 })
+ logic = mountWithSpans([])
+ await logic.asyncActions.fetchMatchingCounts()
+ tracingFiltersLogic().actions.setViewMode('spans')
+ await logic.asyncActions.fetchMatchingCounts()
+ // The count is view-mode-independent, so the second run reuses the cached result.
+ expect(countSpy).toHaveBeenCalledTimes(1)
+ countSpy.mockRestore()
+ })
+
+ it('re-fetches the count when the data scope changes', async () => {
+ const countSpy = jest.spyOn(api.tracing, 'count').mockResolvedValue({ count: 10, traceCount: 3 })
+ logic = mountWithSpans([])
+ await logic.asyncActions.fetchMatchingCounts()
+ tracingFiltersLogic().actions.setServiceNames(['api'])
+ await logic.asyncActions.fetchMatchingCounts()
+ expect(countSpy).toHaveBeenCalledTimes(2)
+ countSpy.mockRestore()
+ })
+
+ it('toasts on a real count failure', async () => {
+ const toastSpy = jest.spyOn(lemonToast, 'error').mockReturnValue(undefined as any)
+ jest.spyOn(api.tracing, 'count').mockRejectedValue(new Error('boom'))
+ logic = mountWithSpans([])
+ await logic.asyncActions.fetchMatchingCounts().catch(() => {})
+ expect(toastSpy).toHaveBeenCalled()
+ toastSpy.mockRestore()
+ })
+ })
+
+ describe('sparkline', () => {
+ it('does not re-fetch the sparkline when only the view mode changes', async () => {
+ const sparklineSpy = jest.spyOn(api.tracing, 'sparkline').mockResolvedValue({ results: [] })
+ logic = mountWithSpans([])
+ await logic.asyncActions.fetchSparkline()
+ tracingFiltersLogic().actions.setViewMode('spans')
+ await logic.asyncActions.fetchSparkline()
+ // The sparkline is view-mode-independent, so the second run reuses the cached result.
+ expect(sparklineSpy).toHaveBeenCalledTimes(1)
+ sparklineSpy.mockRestore()
+ })
+
+ it('re-fetches the sparkline when the data scope changes', async () => {
+ const sparklineSpy = jest.spyOn(api.tracing, 'sparkline').mockResolvedValue({ results: [] })
+ logic = mountWithSpans([])
+ await logic.asyncActions.fetchSparkline()
+ tracingFiltersLogic().actions.setServiceNames(['api'])
+ await logic.asyncActions.fetchSparkline()
+ expect(sparklineSpy).toHaveBeenCalledTimes(2)
+ sparklineSpy.mockRestore()
+ })
+ })
})
diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.ts
index e4c2e8196cb5..fc19c8f39476 100644
--- a/products/tracing/frontend/tracingDataLogic.ts
+++ b/products/tracing/frontend/tracingDataLogic.ts
@@ -95,11 +95,13 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
clearSpans: true,
cancelInProgressSpans: (controller: AbortController | null) => ({ controller }),
cancelInProgressSparkline: (controller: AbortController | null) => ({ controller }),
+ cancelInProgressMatchingCounts: (controller: AbortController | null) => ({ controller }),
cancelInProgressDurationHistogram: (controller: AbortController | null) => ({ controller }),
cancelInProgressAggregation: (controller: AbortController | null) => ({ controller }),
cancelInProgressSpanTree: (controller: AbortController | null) => ({ controller }),
setSpansAbortController: (controller: AbortController | null) => ({ controller }),
setSparklineAbortController: (controller: AbortController | null) => ({ controller }),
+ setMatchingCountsAbortController: (controller: AbortController | null) => ({ controller }),
setDurationHistogramAbortController: (controller: AbortController | null) => ({ controller }),
setAggregationAbortController: (controller: AbortController | null) => ({ controller }),
setSpanTreeAbortController: (controller: AbortController | null) => ({ controller }),
@@ -129,6 +131,10 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
null as AbortController | null,
{ setSparklineAbortController: (_, { controller }) => controller },
],
+ matchingCountsAbortController: [
+ null as AbortController | null,
+ { setMatchingCountsAbortController: (_, { controller }) => controller },
+ ],
durationHistogramAbortController: [
null as AbortController | null,
{ setDurationHistogramAbortController: (_, { controller }) => controller },
@@ -263,7 +269,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
],
}),
- loaders(({ values, actions }) => ({
+ loaders(({ values, actions, cache }) => ({
spans: [
[] as Span[],
{
@@ -281,6 +287,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,
filterGroup: values.filters.filterGroup as PropertyGroupFilter,
prefetchSpans: PREFETCH_SPANS,
+ flatSpans: values.filters.viewMode === 'spans',
limit: DEFAULT_PAGE_SIZE,
},
controller.signal
@@ -300,10 +307,10 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
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.
+ // ordering uses the `after` cursor. Offset is the count of rows already shown.
const pagination =
values.filters.orderBy === 'duration'
- ? { offset: values.rootSpans.length }
+ ? { offset: values.listRows.length }
: { after: values.nextCursor ?? undefined }
const response = await api.tracing.listSpans(
@@ -315,6 +322,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,
filterGroup: values.filters.filterGroup as PropertyGroupFilter,
prefetchSpans: PREFETCH_SPANS,
+ flatSpans: values.filters.viewMode === 'spans',
limit: DEFAULT_PAGE_SIZE,
...pagination,
},
@@ -473,6 +481,18 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
[] as SparklineRow[],
{
fetchSparkline: async () => {
+ // Like the count, the sparkline depends only on the data scope (date range,
+ // services, filters) — not on view mode, sort, or compare. Skip the re-fetch (and its
+ // spinner overlay) when a Traces/Spans toggle re-runs the query without changing scope.
+ const scopeKey = JSON.stringify([
+ values.utcDateRange,
+ values.filters.serviceNames,
+ values.filters.filterGroup,
+ ])
+ if (scopeKey === cache.sparklineScope) {
+ return values.rawSparklineData
+ }
+
const controller = new AbortController()
actions.cancelInProgressSparkline(controller)
@@ -487,10 +507,49 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
)
actions.setSparklineAbortController(null)
+ // Record the scope only after a successful fetch, so a failed/aborted request retries.
+ cache.sparklineScope = scopeKey
return response.results
},
},
],
+ matchingCounts: [
+ { count: 0, traceCount: 0 } as { count: number; traceCount: number },
+ {
+ fetchMatchingCounts: async () => {
+ // The count is view-mode-independent — it returns both span and trace counts in one
+ // response, and the label selects which to show. So a Traces/Spans (or sort/compare)
+ // toggle that re-runs the query must not re-hit the endpoint; only the data scope
+ // (date range, services, filters) changes the result. Skip the fetch when unchanged.
+ const scopeKey = JSON.stringify([
+ values.utcDateRange,
+ values.filters.serviceNames,
+ values.filters.filterGroup,
+ ])
+ if (scopeKey === cache.matchingCountsScope) {
+ return values.matchingCounts
+ }
+
+ const controller = new AbortController()
+ actions.cancelInProgressMatchingCounts(controller)
+
+ const response = await api.tracing.count(
+ {
+ dateRange: values.utcDateRange,
+ serviceNames:
+ values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,
+ filterGroup: values.filters.filterGroup as PropertyGroupFilter,
+ },
+ controller.signal
+ )
+
+ actions.setMatchingCountsAbortController(null)
+ // Record the scope only after a successful fetch, so a failed/aborted request retries.
+ cache.matchingCountsScope = scopeKey
+ return response
+ },
+ },
+ ],
rawDurationHistogram: [
[] as DurationHistogramRow[],
{
@@ -567,25 +626,31 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
return { data, labels, dates }
},
],
- totalSpansMatchingFilters: [
- (s) => [s.rawSparklineData],
- (rows: SparklineRow[]): number => rows.reduce((sum, item) => sum + item.count, 0),
+ // Total matching the filters, in the unit the list is showing: distinct traces in 'traces'
+ // mode, individual spans in 'spans' mode. Fed by the count endpoint, which returns both.
+ totalMatchingFilters: [
+ (s) => [s.matchingCounts, s.filters],
+ (matchingCounts: { count: number; traceCount: number }, filters: TracingFilters): number =>
+ filters.viewMode === 'spans' ? matchingCounts.count : matchingCounts.traceCount,
],
durationHistogramData: [
(s) => [s.rawDurationHistogram],
(rows: DurationHistogramRow[]): TracingDurationHistogramData => pivotDurationHistogram(rows, dataColorVars),
],
- rootSpans: [
- (s) => [s.spans],
- (spans: Span[]): Span[] => {
- return spans.filter((s) => s.is_root_span)
+ // The rows the list renders. 'traces' mode shows root spans only (one row per trace);
+ // 'spans' mode shows every matching span (root and child) flat. The fetch passes flatSpans
+ // to match, so in 'spans' mode the loaded spans are already the flat set.
+ listRows: [
+ (s) => [s.spans, s.filters],
+ (spans: Span[], filters: TracingFilters): Span[] => {
+ return filters.viewMode === 'spans' ? spans : spans.filter((s) => s.is_root_span)
},
],
// Memoized separately so visibleRowDurationRange (recomputed on every scroll tick) doesn't
- // re-allocate the durations array — this only changes when the loaded spans do.
- rootSpanDurations: [
- (s) => [s.rootSpans],
- (rootSpans: Span[]): number[] => rootSpans.map((span) => span.duration_nano),
+ // re-allocate the durations array — this only changes when the loaded rows do.
+ listRowDurations: [
+ (s) => [s.listRows],
+ (listRows: Span[]): number[] => listRows.map((span) => span.duration_nano),
],
// Single owner of the "show the duration histogram?" rule — the fetch decision, the
// highlight selector, and the scene's rendering all derive from this one place.
@@ -601,16 +666,16 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
// duration space, so the histogram can sweep a highlight across the distribution as the
// user scrolls (the same interaction the time sparkline has under timestamp sort).
visibleRowDurationRange: [
- (s) => [s.visibleRowRange, s.rootSpanDurations, s.isDurationMode],
+ (s) => [s.visibleRowRange, s.listRowDurations, s.isDurationMode],
(
visibleRowRange: VisibleRowRange | null,
- rootSpanDurations: number[],
+ listRowDurations: number[],
isDurationMode: boolean
): VisibleDurationRange | null => {
if (!isDurationMode) {
return null
}
- return visibleDurationRange(visibleRowRange, rootSpanDurations)
+ return visibleDurationRange(visibleRowRange, listRowDurations)
},
],
@@ -620,19 +685,19 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
// contiguous in time, so the highlight would be meaningless. Suppress it then; the duration
// histogram (visibleRowDurationRange above) covers the duration-sorted case.
visibleRowDateRange: [
- (s) => [s.visibleRowRange, s.rootSpans, s.orderBy],
+ (s) => [s.visibleRowRange, s.listRows, s.orderBy],
(
visibleRowRange: VisibleRowRange | null,
- rootSpans: Span[],
+ listRows: Span[],
orderBy: TracingOrderBy
): VisibleSpanTimeRange | null => {
- if (orderBy !== 'timestamp' || !visibleRowRange || rootSpans.length === 0) {
+ if (orderBy !== 'timestamp' || !visibleRowRange || listRows.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
+ const startIndex = Math.max(0, Math.min(visibleRowRange.startIndex, listRows.length - 1))
+ const stopIndex = Math.max(0, Math.min(visibleRowRange.stopIndex, listRows.length - 1))
+ const a = listRows[startIndex]?.timestamp
+ const b = listRows[stopIndex]?.timestamp
if (!a || !b) {
return null
}
@@ -650,10 +715,11 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
listeners(({ actions, values }) => ({
runQuery: () => {
actions.clearSpans()
- // The time sparkline is always fetched — it also feeds totalSpansMatchingFilters, and
- // keeps the chart warm when the user flips back to timestamp sort. Duration sort
- // additionally fetches the histogram that replaces it visually.
+ // The time sparkline is always fetched — it keeps the chart warm when the user flips back
+ // to timestamp sort. Duration sort additionally fetches the histogram that replaces it
+ // visually. The count endpoint feeds the "N traces/spans matching filters" label.
actions.fetchSparkline()
+ actions.fetchMatchingCounts()
if (values.isDurationMode) {
actions.fetchDurationHistogram()
}
@@ -675,6 +741,12 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
}
actions.setSparklineAbortController(controller)
},
+ cancelInProgressMatchingCounts: ({ controller }) => {
+ if (values.matchingCountsAbortController !== null) {
+ values.matchingCountsAbortController.abort(NEW_QUERY_STARTED_ERROR_MESSAGE)
+ }
+ actions.setMatchingCountsAbortController(controller)
+ },
cancelInProgressDurationHistogram: ({ controller }) => {
if (values.durationHistogramAbortController !== null) {
values.durationHistogramAbortController.abort(NEW_QUERY_STARTED_ERROR_MESSAGE)
@@ -694,7 +766,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
actions.setSpanTreeAbortController(controller)
},
fetchSpansSuccess: () => {
- captureTracingResults(values.rootSpans.length, 'spans')
+ captureTracingResults(values.listRows.length, 'spans')
},
fetchAggregationSuccess: ({ aggregation }) => {
captureTracingResults(aggregation.current.length, 'aggregation')
@@ -705,6 +777,11 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
posthog.capture('tracing query failed', { query_type: 'spans', error_message: String(error) })
}
},
+ fetchMatchingCountsFailure: ({ error }) => {
+ if (!isUserInitiatedError(error)) {
+ lemonToast.error(`Failed to load the matching count: ${error}`)
+ }
+ },
fetchAggregationFailure: ({ error }) => {
if (!isUserInitiatedError(error)) {
lemonToast.error(`Failed to load span aggregation: ${error}`)
@@ -730,6 +807,9 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
if (values.sparklineAbortController) {
values.sparklineAbortController.abort('unmounting component')
}
+ if (values.matchingCountsAbortController) {
+ values.matchingCountsAbortController.abort('unmounting component')
+ }
if (values.durationHistogramAbortController) {
values.durationHistogramAbortController.abort('unmounting component')
}
diff --git a/products/tracing/frontend/tracingFiltersLogic.test.ts b/products/tracing/frontend/tracingFiltersLogic.test.ts
new file mode 100644
index 000000000000..65041d23e99a
--- /dev/null
+++ b/products/tracing/frontend/tracingFiltersLogic.test.ts
@@ -0,0 +1,36 @@
+import { initKeaTests } from '~/test/init'
+
+import { tracingFiltersLogic } from './tracingFiltersLogic'
+
+describe('tracingFiltersLogic', () => {
+ let logic: ReturnType<typeof tracingFiltersLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ logic = tracingFiltersLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ describe('view mode', () => {
+ it('defaults to traces', () => {
+ expect(logic.values.viewMode).toBe('traces')
+ expect(logic.values.filters.viewMode).toBe('traces')
+ })
+
+ it('switches to spans', () => {
+ logic.actions.setViewMode('spans')
+ expect(logic.values.viewMode).toBe('spans')
+ expect(logic.values.filters.viewMode).toBe('spans')
+ })
+
+ it('switches back to traces', () => {
+ logic.actions.setViewMode('spans')
+ logic.actions.setViewMode('traces')
+ expect(logic.values.viewMode).toBe('traces')
+ })
+ })
+})
diff --git a/products/tracing/frontend/tracingFiltersLogic.ts b/products/tracing/frontend/tracingFiltersLogic.ts
index f4eab7df18fc..19192e4ff7fd 100644
--- a/products/tracing/frontend/tracingFiltersLogic.ts
+++ b/products/tracing/frontend/tracingFiltersLogic.ts
@@ -12,12 +12,17 @@ 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
+export const DEFAULT_VIEW_MODE = 'traces' as const
// 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'
+// 'traces' groups by trace_id and shows root spans only (one row per trace). 'spans' shows every
+// matching span (root and child) flat — backed by the query's flatSpans param. See tracingDataLogic.
+export type TracingViewMode = 'traces' | 'spans'
+
export interface OverlayWindow {
startMs: number
endMs: number
@@ -29,6 +34,7 @@ export interface TracingFilters {
filterGroup: UniversalFiltersGroup
orderBy: TracingOrderBy
orderDirection: TracingOrderDirection
+ viewMode: TracingViewMode
compareMode: boolean
/** User-positioned overrides for the two compare windows. Null until the overlay is dragged. */
currentWindowOverride: OverlayWindow | null
@@ -43,6 +49,7 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([
setServiceNames: (serviceNames: string[]) => ({ serviceNames }),
setFilterGroup: (filterGroup: UniversalFiltersGroup) => ({ filterGroup }),
setSort: (orderBy: TracingOrderBy, orderDirection: TracingOrderDirection) => ({ orderBy, orderDirection }),
+ setViewMode: (viewMode: TracingViewMode) => ({ viewMode }),
setCompareMode: (compareMode: boolean) => ({ compareMode }),
/**
* Persist the user-dragged overlay windows. Both must be supplied. Setting these
@@ -90,6 +97,13 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([
setFilters: (state, { filters }) => (filters.orderDirection as TracingOrderDirection) ?? state,
},
],
+ viewMode: [
+ DEFAULT_VIEW_MODE as TracingViewMode,
+ {
+ setViewMode: (_, { viewMode }) => viewMode,
+ setFilters: (state, { filters }) => filters.viewMode ?? state,
+ },
+ ],
compareMode: [
false as boolean,
{
@@ -127,6 +141,7 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([
s.filterGroup,
s.orderBy,
s.orderDirection,
+ s.viewMode,
s.compareMode,
s.currentWindowOverride,
s.previousWindowOverride,
@@ -137,6 +152,7 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([
filterGroup,
orderBy,
orderDirection,
+ viewMode,
compareMode,
currentWindowOverride,
previousWindowOverride
@@ -146,6 +162,7 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([
filterGroup,
orderBy,
orderDirection,
+ viewMode,
compareMode,
currentWindowOverride,
previousWindowOverride,
diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.ts
index abd6d55ec876..b94c43102e45 100644
--- a/products/tracing/frontend/tracingSceneLogic.ts
+++ b/products/tracing/frontend/tracingSceneLogic.ts
@@ -16,6 +16,7 @@ import {
DEFAULT_ORDER_BY,
DEFAULT_ORDER_DIRECTION,
DEFAULT_SERVICE_NAMES,
+ DEFAULT_VIEW_MODE,
tracingFiltersLogic,
} from './tracingFiltersLogic'
import type { tracingSceneLogicType } from './tracingSceneLogicType'
@@ -30,12 +31,12 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
[
'spans',
'spansLoading',
- 'rootSpans',
+ 'listRows',
'sparklineData',
'sparklineLoading',
'hasMoreToLoad',
'hasRunQuery',
- 'totalSpansMatchingFilters',
+ 'totalMatchingFilters',
'traceSpans',
'traceSpansLoading',
'traceSpansLoadingMore',
@@ -70,6 +71,7 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
'setServiceNames',
'setFilterGroup',
'setSort',
+ 'setViewMode',
'setCompareMode',
'setOverlayWindows',
'setFilters',
@@ -217,6 +219,7 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
setFilterGroup: () => actions.handleFilterChange('filter_group'),
setSort: ({ orderBy, orderDirection }) =>
actions.handleFilterChange('sort', { column: orderBy, direction: orderDirection }),
+ setViewMode: ({ viewMode }) => actions.handleFilterChange('view_mode', { mode: viewMode }),
setCompareMode: ({ compareMode }) => actions.handleFilterChange('compare_mode', { enabled: compareMode }),
setOverlayWindows: () => {
// Overlay drags only refetch the aggregation — the sparkline canvas range
@@ -304,6 +307,12 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
hasChanges = true
}
+ const viewModeFromUrl = searchParams.view === 'spans' ? 'spans' : DEFAULT_VIEW_MODE
+ if (viewModeFromUrl !== values.filters.viewMode) {
+ filtersFromUrl.viewMode = viewModeFromUrl
+ hasChanges = true
+ }
+
if (hasChanges) {
actions.setFilters(filtersFromUrl)
} else if (!values.hasRunQuery) {
@@ -368,6 +377,9 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
if (values.filters.compareMode) {
searchParams.compare = 'true'
}
+ if (values.filters.viewMode !== DEFAULT_VIEW_MODE) {
+ searchParams.view = values.filters.viewMode
+ }
actions.runQuery()
return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 23f3a4776919..ed57e2a4f4d5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -53460,6 +53460,8 @@ export namespace Schemas {
export interface _TracingCountResponse {
/** Number of spans matching the filters. */
count: number;
+ /** Number of distinct traces whose root span matches the filters — the trace count shown in the Traces view. */
+ traceCount: number;
}
/**