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): split viewer UI state out of tracingSceneLogic (#69890)

Jon McCallum3426a260df6c
diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsx
index 6b72da0b5134..0ed5dff2cce4 100644
--- a/products/tracing/frontend/TracingScene.tsx
+++ b/products/tracing/frontend/TracingScene.tsx
@@ -32,6 +32,7 @@ import { TracingFilterBar } from './TracingFilterBar'
import { TRACING_SCENE_VIEWER_ID, tracingFiltersLogic } from './tracingFiltersLogic'
import { tracingSceneLogic } from './tracingSceneLogic'
import { TracingSparkline } from './TracingSparkline'
+import { tracingViewerLogic } from './tracingViewerLogic'
import type { Span } from './types'
const TRACING_FEEDBACK_SURVEY_ID = '019e6a26-4943-0000-24a0-dc46310f6b7c'
@@ -45,9 +46,10 @@ export const scene: SceneExport = {
export default function TracingScene(): JSX.Element {
const sceneLogic = tracingSceneLogic()
- // Keep filters + data logic alive across React unmounts by attaching them to the scene root.
+ // Keep filters + data + viewer logic alive across React unmounts by attaching them to the scene root.
useAttachedLogic(tracingFiltersLogic({ id: TRACING_SCENE_VIEWER_ID }), sceneLogic)
useAttachedLogic(tracingDataLogic({ id: TRACING_SCENE_VIEWER_ID }), sceneLogic)
+ useAttachedLogic(tracingViewerLogic({ id: TRACING_SCENE_VIEWER_ID }), sceneLogic)
// Bind the scene's keyed instances so nested components (filter bar, sparkline, ...)
// resolve them from context — the same components work inside an embedded viewer
@@ -55,7 +57,9 @@ export default function TracingScene(): JSX.Element {
return (
<BindLogic logic={tracingFiltersLogic} props={{ id: TRACING_SCENE_VIEWER_ID }}>
<BindLogic logic={tracingDataLogic} props={{ id: TRACING_SCENE_VIEWER_ID }}>
- <TracingSceneContents />
+ <BindLogic logic={tracingViewerLogic} props={{ id: TRACING_SCENE_VIEWER_ID }}>
+ <TracingSceneContents />
+ </BindLogic>
</BindLogic>
</BindLogic>
)
diff --git a/products/tracing/frontend/tracingDataLogic.test.ts b/products/tracing/frontend/tracingDataLogic.test.ts
index c12303445d39..ad31e7ce8314 100644
--- a/products/tracing/frontend/tracingDataLogic.test.ts
+++ b/products/tracing/frontend/tracingDataLogic.test.ts
@@ -1,3 +1,4 @@
+import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
@@ -208,8 +209,11 @@ describe('tracingDataLogic', () => {
})
it('lists every span (root and child) in spans mode', () => {
- logic = mountWithSpans(withChildSpans)
+ logic = mountWithSpans([])
+ // Set the mode first: a view-mode change re-runs the query (clearing loaded spans),
+ // so inject the fixture after the toggle.
tracingFiltersLogic().actions.setViewMode('spans')
+ logic.actions.fetchSpansSuccess(withChildSpans)
expect(logic.values.listRows.map((s) => s.uuid)).toEqual(['root-1', 'child-1', 'root-2'])
})
@@ -269,8 +273,11 @@ describe('tracingDataLogic', () => {
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()
+ // A scope change re-runs the query itself (no URL round trip), which must re-hit
+ // the endpoint rather than reuse the memoized count for the old scope.
+ await expectLogic(logic, () => {
+ tracingFiltersLogic().actions.setServiceNames(['api'])
+ }).toDispatchActions(['fetchMatchingCountsSuccess'])
expect(countSpy).toHaveBeenCalledTimes(2)
countSpy.mockRestore()
})
@@ -291,10 +298,11 @@ describe('tracingDataLogic', () => {
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 counts root spans in 'traces' mode and all spans in 'spans' mode, so a
- // view-mode toggle changes its scope and must re-fetch.
+ // view-mode toggle changes its scope and the auto re-query must re-fetch it.
+ await expectLogic(logic, () => {
+ tracingFiltersLogic().actions.setViewMode('spans')
+ }).toDispatchActions(['fetchSparklineSuccess'])
expect(sparklineSpy).toHaveBeenCalledTimes(2)
sparklineSpy.mockRestore()
})
@@ -303,14 +311,54 @@ describe('tracingDataLogic', () => {
const sparklineSpy = jest.spyOn(api.tracing, 'sparkline').mockResolvedValue({ results: [] })
logic = mountWithSpans([])
await logic.asyncActions.fetchSparkline()
- tracingFiltersLogic().actions.setServiceNames(['api'])
- await logic.asyncActions.fetchSparkline()
+ await expectLogic(logic, () => {
+ tracingFiltersLogic().actions.setServiceNames(['api'])
+ }).toDispatchActions(['fetchSparklineSuccess'])
expect(sparklineSpy).toHaveBeenCalledTimes(2)
sparklineSpy.mockRestore()
})
})
describe('keyed instances', () => {
+ it('re-runs the query when its filters change, with no URL involvement', async () => {
+ // The embed-critical wiring: filter changes must re-query inside the keyed stack.
+ // Before the scene/viewer split, the re-query was a side effect of the scene's URL
+ // write, so an embedded instance (no URL sync) would never refresh.
+ const listSpansSpy = jest.spyOn(api.tracing, 'listSpans').mockResolvedValue({ results: [], hasMore: false })
+ const isolatedFilters = tracingFiltersLogic({ id: 'isolated-requery' })
+ const isolatedData = tracingDataLogic({ id: 'isolated-requery' })
+ isolatedFilters.mount()
+ isolatedData.mount()
+ try {
+ await expectLogic(isolatedData, () => {
+ isolatedFilters.actions.setDateRange({ date_from: '-24h', date_to: null })
+ }).toDispatchActions(['handleFilterChange', 'runQuery', 'fetchSpansSuccess'])
+ expect(listSpansSpy).toHaveBeenCalled()
+ } finally {
+ isolatedData.unmount()
+ isolatedFilters.unmount()
+ listSpansSpy.mockRestore()
+ }
+ })
+
+ it('runs the first query on mount when autoLoad is set', async () => {
+ // Embedded viewers have no urlToAction to kick off the first fetch — autoLoad is
+ // their only entry point. Dropping it leaves embeds permanently empty.
+ const listSpansSpy = jest.spyOn(api.tracing, 'listSpans').mockResolvedValue({ results: [], hasMore: false })
+ tracingFiltersLogic({ id: 'auto-load' }).mount()
+ const autoData = tracingDataLogic({ id: 'auto-load', autoLoad: true })
+ try {
+ await expectLogic(autoData, () => {
+ autoData.mount()
+ }).toDispatchActions(['runQuery', 'fetchSpansSuccess'])
+ expect(listSpansSpy).toHaveBeenCalled()
+ } finally {
+ autoData.unmount()
+ tracingFiltersLogic({ id: 'auto-load' }).unmount()
+ listSpansSpy.mockRestore()
+ }
+ })
+
it('reads filters from its own instance, not the scene default', () => {
const isolatedFilters = tracingFiltersLogic({ id: 'isolated' })
const isolatedData = tracingDataLogic({ id: 'isolated' })
diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.ts
index 67cf1b039200..70346f0e7a1f 100644
--- a/products/tracing/frontend/tracingDataLogic.ts
+++ b/products/tracing/frontend/tracingDataLogic.ts
@@ -1,4 +1,4 @@
-import { actions, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { actions, afterMount, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import posthog from 'posthog-js'
@@ -87,10 +87,14 @@ function captureTracingResults(count: number, queryType: 'spans' | 'aggregation'
export interface TracingDataLogicProps {
id: string
+ // Run the first query on mount. Embedded viewers set this; the /tracing scene leaves it
+ // off because its first query is driven by urlToAction (which may first restore filters
+ // from the URL). Mirrors the LogsViewer `autoLoad` prop.
+ autoLoad?: boolean
}
export const tracingDataLogic = kea<tracingDataLogicType>([
- props({ id: TRACING_SCENE_VIEWER_ID } as TracingDataLogicProps),
+ props({ id: TRACING_SCENE_VIEWER_ID, autoLoad: false } as TracingDataLogicProps),
key((props) => props.id),
path((key) => ['products', 'tracing', 'frontend', 'tracingDataLogic', key]),
@@ -109,9 +113,26 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
'timeComparison',
],
],
+ actions: [
+ tracingFiltersLogic({ id }),
+ [
+ 'setDateRange',
+ 'setServiceNames',
+ 'setFilterGroup',
+ 'setSort',
+ 'setViewMode',
+ 'setComparison',
+ 'updateComparisonWindows',
+ 'setFilters',
+ ],
+ ],
})),
actions({
+ // Analytics + re-query on a user filter interaction. Dispatched by the filter-action
+ // listeners below; the scene logic additionally listens to this to sync the URL.
+ // Mirrors the logs viewer's handleQueryChange.
+ handleFilterChange: (filterType: string, extraProps?: Record<string, unknown>) => ({ filterType, extraProps }),
runQuery: true,
fetchNextPage: true,
loadMoreTraceSpans: true,
@@ -754,6 +775,28 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
}),
listeners(({ actions, values }) => ({
+ handleFilterChange: ({ filterType, extraProps }) => {
+ posthog.capture('tracing filter changed', { filter_type: filterType, ...extraProps })
+ actions.runQuery()
+ },
+ setDateRange: () => actions.handleFilterChange('date_range'),
+ setServiceNames: () => actions.handleFilterChange('service_names'),
+ setFilterGroup: () => actions.handleFilterChange('filter_group'),
+ setSort: ({ orderBy, orderDirection }) =>
+ actions.handleFilterChange('sort', { column: orderBy, direction: orderDirection }),
+ setViewMode: ({ viewMode }) => actions.handleFilterChange('view_mode', { mode: viewMode }),
+ setComparison: ({ comparison }) =>
+ actions.handleFilterChange('comparison', {
+ enabled: comparison !== null,
+ mode: comparison?.mode ?? null,
+ preset: comparison?.mode === 'time' ? comparison.preset : null,
+ }),
+ // Bulk restores (URL params, saved views) re-query without an interaction capture.
+ setFilters: () => actions.runQuery(),
+ // Overlay drags only refetch the aggregation — the sparkline canvas range stays fixed
+ // while the user moves windows around within it. The compare-flame refetch (viewer UI
+ // state) lives in tracingViewerLogic.
+ updateComparisonWindows: () => actions.fetchAggregation(),
runQuery: () => {
actions.clearSpans()
// The time sparkline is always fetched — it keeps the chart warm when the user flips back
@@ -862,4 +905,10 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
}
},
})),
+
+ afterMount(({ actions, props: logicProps, values }) => {
+ if (logicProps.autoLoad && !values.hasRunQuery) {
+ actions.runQuery()
+ }
+ }),
])
diff --git a/products/tracing/frontend/tracingSceneLogic.test.ts b/products/tracing/frontend/tracingSceneLogic.test.ts
index 0efc02835abd..2273ad2aafe8 100644
--- a/products/tracing/frontend/tracingSceneLogic.test.ts
+++ b/products/tracing/frontend/tracingSceneLogic.test.ts
@@ -98,4 +98,31 @@ describe('tracingSceneLogic', () => {
)
resumeKeaLoadersErrors()
})
+
+ // Same denominator guard for the bulk-restore path (back/forward, saved views): setFilters routes
+ // through the data logic's runQuery, which fires a windowed aggregate while comparing. Without the
+ // scene's full-range refetch the operations table would divide by the narrow compare sub-window.
+ it('keeps the operations aggregate on the full range when filters are restored while comparing', async () => {
+ silenceKeaLoadersErrors()
+ const filtersLogic = mountAt({ comparison: JSON.stringify({ mode: 'time', preset: 'custom' }) })
+ expect(filtersLogic.values.compareActive).toBe(true)
+
+ const aggregateSpy = jest.spyOn(api.tracing, 'aggregate')
+ logic.actions.setActiveTracingTab('operations')
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ aggregateSpy.mockClear()
+
+ // Restore a different filter set the way back/forward navigation does.
+ router.actions.push('/tracing', {
+ comparison: JSON.stringify({ mode: 'time', preset: 'custom' }),
+ serviceNames: 'svc-a',
+ })
+ await new Promise((resolve) => setTimeout(resolve, 0))
+
+ expect(aggregateSpy).toHaveBeenLastCalledWith(
+ expect.objectContaining({ compareFilter: expect.objectContaining({ compare: false }) }),
+ expect.anything()
+ )
+ resumeKeaLoadersErrors()
+ })
})
diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.ts
index e14e1f52102f..a2e7b303d885 100644
--- a/products/tracing/frontend/tracingSceneLogic.ts
+++ b/products/tracing/frontend/tracingSceneLogic.ts
@@ -1,7 +1,6 @@
import equal from 'fast-deep-equal'
import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { router, urlToAction } from 'kea-router'
-import posthog from 'posthog-js'
import { DEFAULT_UNIVERSAL_GROUP_FILTER } from 'lib/components/UniversalFilters/universalFiltersLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
@@ -10,7 +9,7 @@ import { Params } from 'scenes/sceneTypes'
import { Breadcrumb } from '~/types'
-import { PREFETCH_SPANS, tracingDataLogic } from './tracingDataLogic'
+import { tracingDataLogic } from './tracingDataLogic'
import {
DEFAULT_CUSTOM_COMPARISON,
DEFAULT_DATE_RANGE,
@@ -25,12 +24,15 @@ import {
tracingFiltersLogic,
} from './tracingFiltersLogic'
import type { tracingSceneLogicType } from './tracingSceneLogicType'
-import type { Span } from './types'
+import { tracingViewerLogic } from './tracingViewerLogic'
export const tracingSceneLogic = kea<tracingSceneLogicType>([
path(['products', 'tracing', 'frontend', 'tracingSceneLogic']),
- // The scene binds to the viewer-default instances of the keyed filter/data logics.
+ // The scene binds to the viewer-default instances of the keyed filter/data/viewer logics.
+ // It owns ALL URL sync — the keyed logics are URL-free so they can be embedded anywhere;
+ // this logic translates URL params to their actions and their actions back to URL writes.
+ // Mirrors the logsSceneLogic / logsViewerLogic boundary.
connect(() => ({
values: [
tracingDataLogic({ id: TRACING_SCENE_VIEWER_ID }),
@@ -59,6 +61,18 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
],
tracingFiltersLogic({ id: TRACING_SCENE_VIEWER_ID }),
['filters', 'utcDateRange', 'sparklineWindowMs', 'currentWindowMs', 'previousWindowMs', 'compareActive'],
+ tracingViewerLogic({ id: TRACING_SCENE_VIEWER_ID }),
+ [
+ 'selectedTraceId',
+ 'selectedSpanId',
+ 'selectedTraceTs',
+ 'isTraceOpen',
+ 'openTraceSpans',
+ 'isLoadingFullTrace',
+ 'canLoadMoreTraceSpans',
+ 'compareFlameSpanName',
+ 'compareFlameServiceName',
+ ],
],
actions: [
tracingDataLogic({ id: TRACING_SCENE_VIEWER_ID }),
@@ -70,6 +84,7 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
'fetchAggregation',
'fetchSpanTree',
'setVisibleRowRange',
+ 'handleFilterChange',
],
tracingFiltersLogic({ id: TRACING_SCENE_VIEWER_ID }),
[
@@ -82,63 +97,17 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
'updateComparisonWindows',
'setFilters',
],
+ tracingViewerLogic({ id: TRACING_SCENE_VIEWER_ID }),
+ ['openTrace', 'selectSpan', 'closeTrace', 'openCompareFlame', 'closeCompareFlame'],
],
})),
actions({
- openTrace: (traceId: string, options?: { spanId?: string | null; ts?: string | null }) => ({
- traceId,
- spanId: options?.spanId ?? null,
- ts: options?.ts ?? null,
- }),
- selectSpan: (spanId: string | null) => ({ spanId }),
- closeTrace: true,
- openCompareFlame: (spanName: string, serviceName: string) => ({ spanName, serviceName }),
- closeCompareFlame: true,
- syncUrlAndRunQuery: true,
- handleFilterChange: (filterType: string, extraProps?: Record<string, unknown>) => ({ filterType, extraProps }),
+ syncUrl: true,
setActiveTracingTab: (tab: 'traces' | 'operations') => ({ tab }),
}),
reducers({
- selectedTraceId: [
- null as string | null,
- {
- openTrace: (_, { traceId }) => traceId,
- closeTrace: () => null,
- },
- ],
- selectedSpanId: [
- null as string | null,
- {
- openTrace: (_, { spanId }) => spanId,
- selectSpan: (_, { spanId }) => spanId,
- closeTrace: () => null,
- },
- ],
- // Timestamp hint for the open trace — echoed into copy-links so cold loads can bound the
- // ClickHouse lookup (the spans table is time-keyed; OTel ids embed no timestamp).
- selectedTraceTs: [
- null as string | null,
- {
- openTrace: (_, { ts }) => ts,
- closeTrace: () => null,
- },
- ],
- compareFlameSpanName: [
- null as string | null,
- {
- openCompareFlame: (_, { spanName }) => spanName,
- closeCompareFlame: () => null,
- },
- ],
- compareFlameServiceName: [
- null as string | null,
- {
- openCompareFlame: (_, { serviceName }) => serviceName,
- closeCompareFlame: () => null,
- },
- ],
activeTracingTab: [
'traces' as 'traces' | 'operations',
{
@@ -148,39 +117,6 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
}),
selectors({
- isTraceOpen: [
- (s) => [s.selectedTraceId],
- (selectedTraceId: string | null): boolean => selectedTraceId !== null,
- ],
- openTraceSpans: [
- (s) => [s.selectedTraceId, s.spans, s.traceSpans],
- (selectedTraceId: string | null, spans: Span[], traceSpans: Span[]): Span[] => {
- if (!selectedTraceId) {
- return []
- }
- const filteredTraceSpans = traceSpans.filter((s) => s.trace_id === selectedTraceId)
- if (filteredTraceSpans.length > 0) {
- return filteredTraceSpans
- }
- return spans.filter((s) => s.trace_id === selectedTraceId)
- },
- ],
- // The drawer's full-trace overlay should only show on the initial fetch — paging in more
- // spans (loadMoreTraceSpans) keeps the waterfall visible with its own bottom spinner.
- isLoadingFullTrace: [
- (s) => [s.traceSpansLoading, s.traceSpansLoadingMore],
- (traceSpansLoading: boolean, traceSpansLoadingMore: boolean): boolean =>
- traceSpansLoading && !traceSpansLoadingMore,
- ],
- // Only offer "load more" when the full-fetched spans for the open trace are what's displayed
- // — never for the small prefetch fallback, which is already the trace's complete span set.
- canLoadMoreTraceSpans: [
- (s) => [s.traceSpansHasMore, s.traceSpans, s.selectedTraceId],
- (traceSpansHasMore: boolean, traceSpans: Span[], selectedTraceId: string | null): boolean =>
- traceSpansHasMore &&
- !!selectedTraceId &&
- traceSpans.some((span: Span) => span.trace_id === selectedTraceId),
- ],
breadcrumbs: [
() => [],
(): Breadcrumb[] => [
@@ -194,60 +130,33 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
}),
listeners(({ actions, values }) => ({
- openTrace: ({ traceId, ts }) => {
- posthog.capture('tracing trace opened')
- const prefetchedSpans = values.spans.filter((s: Span) => s.trace_id === traceId)
- // Zero prefetched spans = the trace isn't in the loaded list (cold link) — fetch it by
- // id. A full prefetch batch (>= PREFETCH_SPANS) may be truncated — fetch the rest.
- if (prefetchedSpans.length === 0 || prefetchedSpans.length >= PREFETCH_SPANS) {
- actions.loadTraceSpans({ traceId, ts })
- }
- },
- openCompareFlame: ({ spanName, serviceName }) => {
- actions.fetchSpanTree({ spanName, serviceName })
- },
- handleFilterChange: ({ filterType, extraProps }) => {
- posthog.capture('tracing filter changed', { filter_type: filterType, ...extraProps })
- actions.syncUrlAndRunQuery()
+ // The keyed data logic already captured the interaction and re-ran the query;
+ // the scene's jobs are the URL write and scene-tab side effects.
+ handleFilterChange: () => {
+ actions.syncUrl()
// Keep the Operations aggregate in sync with filters/date while that tab is active.
// Full range: the Operations view always covers the whole selected range, even while
// a (traces-tab) comparison is active.
//
- // This MUST stay after syncUrlAndRunQuery. When a comparison is active, that call
- // synchronously runs runQuery, whose listener fires a windowed fetchAggregation();
- // every fetchAggregation aborts the previous one, so the last dispatched wins. Keeping
- // the full-range fetch last makes it beat the windowed one deterministically —
+ // This MUST run after the data logic's handleFilterChange listener. When a comparison
+ // is active, that listener synchronously runs runQuery, whose listener fires a windowed
+ // fetchAggregation(); every fetchAggregation aborts the previous one, so the last
+ // dispatched wins. The data logic mounts before this scene logic, so its listener runs
+ // first and the full-range fetch here beats the windowed one deterministically —
// otherwise the Operations table would divide by the narrow compare sub-window.
if (values.activeTracingTab === 'operations') {
actions.fetchAggregation({ fullRange: true })
}
},
- setDateRange: () => actions.handleFilterChange('date_range'),
- setServiceNames: () => actions.handleFilterChange('service_names'),
- setFilterGroup: () => actions.handleFilterChange('filter_group'),
- setSort: ({ orderBy, orderDirection }) =>
- actions.handleFilterChange('sort', { column: orderBy, direction: orderDirection }),
- setViewMode: ({ viewMode }) => actions.handleFilterChange('view_mode', { mode: viewMode }),
- setComparison: ({ comparison }) =>
- actions.handleFilterChange('comparison', {
- enabled: comparison !== null,
- mode: comparison?.mode ?? null,
- preset: comparison?.mode === 'time' ? comparison.preset : null,
- }),
- updateComparisonWindows: () => {
- // Overlay drags only refetch the aggregation — the sparkline canvas range
- // stays fixed while the user moves windows around within it. If the compare-flame
- // modal is open we also refetch its tree so it doesn't display stale windows.
- actions.fetchAggregation()
- if (values.compareFlameSpanName && values.compareFlameServiceName) {
- actions.fetchSpanTree({
- spanName: values.compareFlameSpanName,
- serviceName: values.compareFlameServiceName,
- })
- }
- },
setFilters: () => {
- actions.syncUrlAndRunQuery()
+ actions.syncUrl()
+ // Bulk restores (URL params, back/forward) route through the data logic's setFilters
+ // listener → runQuery, which fires a windowed fetchAggregation when a comparison is
+ // active. Mirror handleFilterChange so the Operations tab keeps its full-range aggregate
+ // instead of the narrow compare sub-window (same mount-order guarantee applies).
+ if (values.activeTracingTab === 'operations') {
+ actions.fetchAggregation({ fullRange: true })
+ }
},
setActiveTracingTab: ({ tab }) => {
if (tab === 'operations') {
@@ -379,7 +288,7 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
},
})),
- trackedActionToUrl(({ values, actions }) => {
+ trackedActionToUrl(({ values }) => {
// The drawer params (trace/span/ts) live alongside the filter params. They're written by
// their own handlers below (which must NOT re-run the list query), and preserved by
// buildUrl so a filter change doesn't silently strip an open drawer from the URL.
@@ -423,7 +332,6 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
searchParams.view = values.filters.viewMode
}
- actions.runQuery()
return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]
}
@@ -441,7 +349,7 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
}
return {
- syncUrlAndRunQuery: () => buildUrl(),
+ syncUrl: () => buildUrl(),
openTrace: () => drawerUrl(false),
selectSpan: () => drawerUrl(true),
closeTrace: () => drawerUrl(false),
diff --git a/products/tracing/frontend/tracingViewerLogic.test.ts b/products/tracing/frontend/tracingViewerLogic.test.ts
new file mode 100644
index 000000000000..ba0b667d4f73
--- /dev/null
+++ b/products/tracing/frontend/tracingViewerLogic.test.ts
@@ -0,0 +1,62 @@
+import api from 'lib/api'
+
+import { initKeaTests } from '~/test/init'
+
+import { PREFETCH_SPANS, tracingDataLogic } from './tracingDataLogic'
+import { tracingViewerLogic } from './tracingViewerLogic'
+import type { Span } from './types'
+
+const createMockSpan = (uuid: string, traceId: string): Span => ({
+ uuid,
+ trace_id: traceId,
+ span_id: uuid,
+ parent_span_id: '',
+ name: 'op',
+ kind: 1,
+ service_name: 'svc',
+ status_code: 1,
+ timestamp: '2024-01-01T00:00:00Z',
+ end_time: '2024-01-01T00:00:00Z',
+ duration_nano: 1000,
+ is_root_span: true,
+ matched_filter: true,
+ attributes: {},
+ resource_attributes: {},
+})
+
+describe('tracingViewerLogic', () => {
+ let logic: ReturnType<typeof tracingViewerLogic.build>
+ let getTraceSpy: jest.SpyInstance
+
+ beforeEach(() => {
+ initKeaTests()
+ getTraceSpy = jest
+ .spyOn(api.tracing, 'getTrace')
+ .mockResolvedValue({ results: [], hasMore: false, nextOffset: null })
+ logic = tracingViewerLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ getTraceSpy.mockRestore()
+ })
+
+ // The prefetch decision drives whether opening a trace refetches it by id: a partial
+ // prefetch batch is the trace's complete span set (no fetch), while a cold link (zero
+ // loaded spans) or a possibly-truncated full batch must fetch. Getting this wrong either
+ // refetches every drawer open or shows truncated waterfalls on cold links.
+ it.each([
+ ['no loaded spans (cold link)', 0, true],
+ ['a partial prefetch batch', 2, false],
+ ['a possibly-truncated full batch', PREFETCH_SPANS, true],
+ ])('openTrace with %s %s', (_name, spanCount, shouldFetch) => {
+ const spans = Array.from({ length: spanCount }, (_, i) => createMockSpan(`span-${i}`, 'trace-x'))
+ tracingDataLogic().actions.fetchSpansSuccess(spans)
+
+ logic.actions.openTrace('trace-x', { ts: '2024-01-01T00:00:00Z' })
+
+ expect(logic.values.selectedTraceId).toBe('trace-x')
+ expect(getTraceSpy.mock.calls.length > 0).toBe(shouldFetch)
+ })
+})
diff --git a/products/tracing/frontend/tracingViewerLogic.ts b/products/tracing/frontend/tracingViewerLogic.ts
new file mode 100644
index 000000000000..acff01519805
--- /dev/null
+++ b/products/tracing/frontend/tracingViewerLogic.ts
@@ -0,0 +1,147 @@
+import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import posthog from 'posthog-js'
+
+import { PREFETCH_SPANS, tracingDataLogic } from './tracingDataLogic'
+import { TRACING_SCENE_VIEWER_ID, tracingFiltersLogic } from './tracingFiltersLogic'
+import type { tracingViewerLogicType } from './tracingViewerLogicType'
+import type { Span } from './types'
+
+export interface TracingViewerLogicProps {
+ id: string
+}
+
+// Per-instance viewer UI state: the trace drawer and the compare-flame modal. URL-free by
+// design — the /tracing scene logic reads and writes this instance's state to sync the URL;
+// an embedded viewer just never wires it up. Mirrors the logsViewerLogic boundary.
+export const tracingViewerLogic = kea<tracingViewerLogicType>([
+ props({ id: TRACING_SCENE_VIEWER_ID } as TracingViewerLogicProps),
+ key((props) => props.id),
+ path((key) => ['products', 'tracing', 'frontend', 'tracingViewerLogic', key]),
+
+ connect(({ id }: TracingViewerLogicProps) => ({
+ values: [
+ tracingDataLogic({ id }),
+ ['spans', 'traceSpans', 'traceSpansLoading', 'traceSpansLoadingMore', 'traceSpansHasMore'],
+ ],
+ actions: [
+ tracingDataLogic({ id }),
+ ['loadTraceSpans', 'fetchSpanTree', 'fetchAggregation'],
+ tracingFiltersLogic({ id }),
+ ['updateComparisonWindows'],
+ ],
+ })),
+
+ actions({
+ openTrace: (traceId: string, options?: { spanId?: string | null; ts?: string | null }) => ({
+ traceId,
+ spanId: options?.spanId ?? null,
+ ts: options?.ts ?? null,
+ }),
+ selectSpan: (spanId: string | null) => ({ spanId }),
+ closeTrace: true,
+ openCompareFlame: (spanName: string, serviceName: string) => ({ spanName, serviceName }),
+ closeCompareFlame: true,
+ }),
+
+ reducers({
+ selectedTraceId: [
+ null as string | null,
+ {
+ openTrace: (_, { traceId }) => traceId,
+ closeTrace: () => null,
+ },
+ ],
+ selectedSpanId: [
+ null as string | null,
+ {
+ openTrace: (_, { spanId }) => spanId,
+ selectSpan: (_, { spanId }) => spanId,
+ closeTrace: () => null,
+ },
+ ],
+ // Timestamp hint for the open trace — echoed into copy-links so cold loads can bound the
+ // ClickHouse lookup (the spans table is time-keyed; OTel ids embed no timestamp).
+ selectedTraceTs: [
+ null as string | null,
+ {
+ openTrace: (_, { ts }) => ts,
+ closeTrace: () => null,
+ },
+ ],
+ compareFlameSpanName: [
+ null as string | null,
+ {
+ openCompareFlame: (_, { spanName }) => spanName,
+ closeCompareFlame: () => null,
+ },
+ ],
+ compareFlameServiceName: [
+ null as string | null,
+ {
+ openCompareFlame: (_, { serviceName }) => serviceName,
+ closeCompareFlame: () => null,
+ },
+ ],
+ }),
+
+ selectors({
+ isTraceOpen: [
+ (s) => [s.selectedTraceId],
+ (selectedTraceId: string | null): boolean => selectedTraceId !== null,
+ ],
+ openTraceSpans: [
+ (s) => [s.selectedTraceId, s.spans, s.traceSpans],
+ (selectedTraceId: string | null, spans: Span[], traceSpans: Span[]): Span[] => {
+ if (!selectedTraceId) {
+ return []
+ }
+ const filteredTraceSpans = traceSpans.filter((s) => s.trace_id === selectedTraceId)
+ if (filteredTraceSpans.length > 0) {
+ return filteredTraceSpans
+ }
+ return spans.filter((s) => s.trace_id === selectedTraceId)
+ },
+ ],
+ // The drawer's full-trace overlay should only show on the initial fetch — paging in more
+ // spans (loadMoreTraceSpans) keeps the waterfall visible with its own bottom spinner.
+ isLoadingFullTrace: [
+ (s) => [s.traceSpansLoading, s.traceSpansLoadingMore],
+ (traceSpansLoading: boolean, traceSpansLoadingMore: boolean): boolean =>
+ traceSpansLoading && !traceSpansLoadingMore,
+ ],
+ // Only offer "load more" when the full-fetched spans for the open trace are what's displayed
+ // — never for the small prefetch fallback, which is already the trace's complete span set.
+ canLoadMoreTraceSpans: [
+ (s) => [s.traceSpansHasMore, s.traceSpans, s.selectedTraceId],
+ (traceSpansHasMore: boolean, traceSpans: Span[], selectedTraceId: string | null): boolean =>
+ traceSpansHasMore &&
+ !!selectedTraceId &&
+ traceSpans.some((span: Span) => span.trace_id === selectedTraceId),
+ ],
+ }),
+
+ listeners(({ actions, values }) => ({
+ openTrace: ({ traceId, ts }) => {
+ posthog.capture('tracing trace opened')
+ const prefetchedSpans = values.spans.filter((s: Span) => s.trace_id === traceId)
+ // Zero prefetched spans = the trace isn't in the loaded list (cold link) — fetch it by
+ // id. A full prefetch batch (>= PREFETCH_SPANS) may be truncated — fetch the rest.
+ if (prefetchedSpans.length === 0 || prefetchedSpans.length >= PREFETCH_SPANS) {
+ actions.loadTraceSpans({ traceId, ts })
+ }
+ },
+ openCompareFlame: ({ spanName, serviceName }) => {
+ actions.fetchSpanTree({ spanName, serviceName })
+ },
+ updateComparisonWindows: () => {
+ // The aggregation refetch on an overlay drag lives in tracingDataLogic; here we only
+ // refresh the compare-flame modal (viewer UI) so it doesn't display stale windows.
+ if (values.compareFlameSpanName && values.compareFlameServiceName) {
+ actions.fetchSpanTree({
+ spanName: values.compareFlameSpanName,
+ serviceName: values.compareFlameServiceName,
+ })
+ }
+ },
+ })),
+])