: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
fix(tracing): harden operation scene request lifecycle (#71497)
Jon McCallum3a154d1bc297
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex ebbc679afc46..b4041da724fa 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -2901,6 +2901,8 @@ const api = {// 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+ // true omits the per-span attribute maps — use when only scalar span fields are read.+ excludeAttributes?: boolean},signal?: AbortSignal): Promise<{@@ -2918,12 +2920,14 @@ const api = {statusCodes?: number[]filterGroup?: PropertyGroupFilteroffset?: number- }+ },+ signal?: AbortSignal): Promise<{ results: Record<string, any>[]; hasMore: boolean; nextOffset?: number | null }> {return new ApiRequest().tracingSpans().withAction(`trace/${traceId}`).create({+ signal,data: {...query,dateRange: query?.dateRange ?? { date_from: '-24h' },diff --git a/products/tracing/frontend/OperationHistogram.tsx b/products/tracing/frontend/OperationHistogram.tsxindex ff8d9a145e36..834f39491b07 100644--- a/products/tracing/frontend/OperationHistogram.tsx+++ b/products/tracing/frontend/OperationHistogram.tsx@@ -19,6 +19,8 @@ interface OperationHistogramProps {selection: DurationRange | nullonSelect: (selection: DurationRange) => voidonClear: () => void+ /** Clearing the selection refetches samples — disable the button while that's in flight. */+ samplesLoading?: boolean}export function OperationHistogram({@@ -27,6 +29,7 @@ export function OperationHistogram({selection,onSelect,onClear,+ samplesLoading = false,}: OperationHistogramProps): JSX.Element {const onSelectionChange = useCallback(({ startIndex, endIndex }: { startIndex: number; endIndex: number }): void => {@@ -69,7 +72,12 @@ export function OperationHistogram({<span className="text-xs font-mono">{formatBucketLabel(selection.minNs)} – {formatBucketLabel(selection.maxNs)}</span>- <LemonButton size="xsmall" type="tertiary" onClick={onClear}>+ <LemonButton+ size="xsmall"+ type="tertiary"+ onClick={onClear}+ disabledReason={samplesLoading ? 'Loading samples…' : undefined}+ >Clear</LemonButton></>diff --git a/products/tracing/frontend/TracingOperationScene.tsx b/products/tracing/frontend/TracingOperationScene.tsxindex 62183fbba26d..dd496e648205 100644--- a/products/tracing/frontend/TracingOperationScene.tsx+++ b/products/tracing/frontend/TracingOperationScene.tsx@@ -58,11 +58,11 @@ export function TracingOperationScene(): JSX.Element {} = useValues(tracingOperationSceneLogic)const { setDateRange, setDurationSelection, setSampleIndex, selectSpan } = useActions(tracingOperationSceneLogic)- if (!spanName) {+ if (!spanName || !serviceName) {return (<SceneContent><div className="flex flex-col items-center gap-1 py-16">- <span>This link is missing an operation name.</span>+ <span>This link is missing an operation or service name.</span><Link to={urls.tracing()}>Back to tracing</Link></div></SceneContent>@@ -105,6 +105,7 @@ export function TracingOperationScene(): JSX.Element {selection={durationSelection}onSelect={setDurationSelection}onClear={() => setDurationSelection(null)}+ samplesLoading={samplesLoading}/><SceneDivider />{samples.length === 0 && samplesLoading ? (diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.tsindex 93bf96d56b4b..c3b30964f08d 100644--- a/products/tracing/frontend/tracingDataLogic.ts+++ b/products/tracing/frontend/tracingDataLogic.ts@@ -68,9 +68,9 @@ export interface VisibleSpanTimeRange {const DEFAULT_PAGE_SIZE = 100export const PREFETCH_SPANS = 20-const NEW_QUERY_STARTED_ERROR_MESSAGE = 'new query started' as const+export const NEW_QUERY_STARTED_ERROR_MESSAGE = 'new query started' as const-function isUserInitiatedError(error: unknown): boolean {+export function isUserInitiatedError(error: unknown): boolean {const errorStr = String(error).toLowerCase()return error === NEW_QUERY_STARTED_ERROR_MESSAGE || errorStr.includes('abort')}diff --git a/products/tracing/frontend/tracingOperationSceneLogic.test.ts b/products/tracing/frontend/tracingOperationSceneLogic.test.tsindex 3e80f14ea5dd..056ad581fff9 100644--- a/products/tracing/frontend/tracingOperationSceneLogic.test.ts+++ b/products/tracing/frontend/tracingOperationSceneLogic.test.ts@@ -80,7 +80,8 @@ describe('tracingOperationSceneLogic', () => {},],},- })+ }),+ expect.anything())})@@ -91,7 +92,7 @@ describe('tracingOperationSceneLogic', () => {expect(logic.values.sampleTraceSpansLoading).toBe(true)await logic.asyncActions.fetchSampleTrace({ sample: logic.values.currentSample! })- expect(getTraceSpy).toHaveBeenLastCalledWith('trace-2', expect.anything())+ expect(getTraceSpy).toHaveBeenLastCalledWith('trace-2', expect.anything(), expect.anything())expect(logic.values.selectedSpanId).toBe('span-2')})@@ -99,4 +100,43 @@ describe('tracingOperationSceneLogic', () => {router.actions.push('/tracing/operation', { sample: '-1' })expect(logic.values.sampleIndex).toBe(0)})++ // A trace longer than the ±1h lookup window can share a trace_id with the loaded waterfall yet+ // omit spans that fell outside it — reuse must be gated on the span actually being present.+ it.each([+ { desc: 'refetches when the loaded trace lacks the paged-to span', loaded: ['span-a'], expectLoading: true },+ {+ desc: 'reuses the loaded trace when it already contains the paged-to span',+ loaded: ['span-a', 'span-b'],+ expectLoading: false,+ },+ ])('paging within a shared trace $desc', async ({ loaded, expectLoading }) => {+ const sameTrace = (spanId: string): Span => ({+ ...createMockSample(1),+ span_id: spanId,+ trace_id: 'trace-long',+ })+ logic.actions.fetchSamplesSuccess([sameTrace('span-a'), sameTrace('span-b')])+ logic.actions.fetchSampleTraceSuccess(loaded.map(sameTrace))++ logic.actions.setSampleIndex(1)+ expect(logic.values.sampleTraceSpansLoading).toBe(expectLoading)++ // Settle any in-flight fetch so it can't resolve after the test ends.+ await logic.asyncActions.fetchSampleTrace({ sample: logic.values.currentSample! })+ })++ it('recovers a retained sample when a failed refetch is left with a stale index', async () => {+ logic.actions.fetchSamplesSuccess([1, 2].map(createMockSample))+ // Browser navigation can move the index past the retained set while a refetch is in flight.+ logic.actions.setSampleIndex(5)+ getTraceSpy.mockClear()++ logic.actions.fetchSamplesFailure('network down')+ // The stale index clamps back into the retained set so the waterfall reloads, not stays blank.+ expect(logic.values.sampleIndex).toBe(0)++ await logic.asyncActions.fetchSampleTrace({ sample: logic.values.currentSample! })+ expect(getTraceSpy).toHaveBeenCalledWith('trace-1', expect.anything(), expect.anything())+ })})diff --git a/products/tracing/frontend/tracingOperationSceneLogic.ts b/products/tracing/frontend/tracingOperationSceneLogic.tsindex bb333beda7dd..fa2befd4f4c5 100644--- a/products/tracing/frontend/tracingOperationSceneLogic.ts+++ b/products/tracing/frontend/tracingOperationSceneLogic.ts@@ -12,6 +12,7 @@ import { AggregatedSpanRow, DateRange } from '~/queries/schema/schema-general'import { type DurationHistogramRow, pivotDurationHistogram, type TracingDurationHistogramData } from './durationBuckets'import { type DurationRange, operationFilterGroup } from './operationFilters'import { traceLookupDateRange } from './traceLinks'+import { isUserInitiatedError, NEW_QUERY_STARTED_ERROR_MESSAGE } from './tracingDataLogic'import { DEFAULT_DATE_RANGE } from './tracingFiltersLogic'import type { Span } from './types'@@ -119,6 +120,9 @@ export interface tracingOperationSceneLogicActions {operationStats: AggregatedSpanRow | nullpayload?: void}+ loadCurrentSampleTrace: () => {+ value: true+ }selectSpan: (spanId: string | null) => {spanId: string | null}@@ -154,6 +158,22 @@ export type tracingOperationSceneLogicType = MakeLogicType<tracingOperationSceneLogicMeta>+// One tracked AbortController per loader: re-issuing a fetch aborts the superseded request+// (not just discards its result), and unmount aborts whatever is still in flight.+function trackedSignal(cache: Record<string, any>, key: string): AbortSignal {+ let controller!: AbortController+ cache.disposables.add(+ () => {+ controller = new AbortController()+ return () => controller.abort(NEW_QUERY_STARTED_ERROR_MESSAGE)+ },+ key,+ // In-flight requests must survive tab switches — only supersession or unmount aborts.+ { pauseOnPageHidden: false }+ )+ return controller.signal+}+export const tracingOperationSceneLogic = kea<tracingOperationSceneLogicType>([props({} as TracingOperationSceneLogicProps),key(({ serviceName, spanName }) => `${serviceName}//${spanName}`),@@ -165,22 +185,26 @@ export const tracingOperationSceneLogic = kea<tracingOperationSceneLogicType>([setSampleIndex: (index: number) => ({ index }),selectSpan: (spanId: string | null) => ({ spanId }),setSamplesHaveMore: (hasMore: boolean) => ({ hasMore }),+ loadCurrentSampleTrace: true,}),- loaders(({ props, values, actions }) => ({+ loaders(({ props, values, actions, cache }) => ({rawHistogram: [[] as DurationHistogramRow[],{fetchHistogram: async (_: void, breakpoint) => {- await breakpoint(100)- const response = await api.tracing.durationHistogram({- dateRange: values.dateRange,- serviceNames: [props.serviceName],- filterGroup: operationFilterGroup(props.spanName, null),- // Span-level: operations are often child spans, and the samples query- // below is span-level too — both must count the same population.- rootSpans: false,- })+ await breakpoint(10) // coalesce same-tick dispatches (URL restore + afterMount)+ const response = await api.tracing.durationHistogram(+ {+ dateRange: values.dateRange,+ serviceNames: [props.serviceName],+ filterGroup: operationFilterGroup(props.spanName, null),+ // Span-level: operations are often child spans, and the samples query+ // below is span-level too — both must count the same population.+ rootSpans: false,+ },+ trackedSignal(cache, 'fetchHistogram')+ )breakpoint()return response.results},@@ -190,16 +214,22 @@ export const tracingOperationSceneLogic = kea<tracingOperationSceneLogicType>([[] as Span[],{fetchSamples: async (_: void, breakpoint) => {- await breakpoint(100)- const response = await api.tracing.listSpans({- dateRange: values.dateRange,- orderBy: 'timestamp',- orderDirection: 'DESC',- serviceNames: [props.serviceName],- filterGroup: operationFilterGroup(props.spanName, values.durationSelection),- flatSpans: true,- limit: SAMPLE_LIMIT,- })+ await breakpoint(10) // coalesce same-tick dispatches (URL restore + afterMount)+ const response = await api.tracing.listSpans(+ {+ dateRange: values.dateRange,+ orderBy: 'timestamp',+ orderDirection: 'DESC',+ serviceNames: [props.serviceName],+ filterGroup: operationFilterGroup(props.spanName, values.durationSelection),+ flatSpans: true,+ limit: SAMPLE_LIMIT,+ // Samples only feed the pager header (5 scalar fields); the waterfall+ // loads the full trace separately, so skip the heavy attribute maps.+ excludeAttributes: true,+ },+ trackedSignal(cache, 'fetchSamples')+ )breakpoint()actions.setSamplesHaveMore(!!response.hasMore)return response.results as Span[]@@ -210,12 +240,15 @@ export const tracingOperationSceneLogic = kea<tracingOperationSceneLogicType>([null as AggregatedSpanRow | null,{fetchStats: async (_: void, breakpoint) => {- await breakpoint(100)- const response = await api.tracing.aggregate({- dateRange: values.dateRange,- serviceNames: [props.serviceName],- filterGroup: operationFilterGroup(props.spanName, null),- })+ await breakpoint(10) // coalesce same-tick dispatches (URL restore + afterMount)+ const response = await api.tracing.aggregate(+ {+ dateRange: values.dateRange,+ serviceNames: [props.serviceName],+ filterGroup: operationFilterGroup(props.spanName, null),+ },+ trackedSignal(cache, 'fetchStats')+ )breakpoint()return response.results.find((row) => row.name === props.spanName) ?? null},@@ -225,10 +258,14 @@ export const tracingOperationSceneLogic = kea<tracingOperationSceneLogicType>([[] as Span[],{fetchSampleTrace: async ({ sample }: { sample: Span }, breakpoint) => {- await breakpoint(100)- const response = await api.tracing.getTrace(sample.trace_id, {- dateRange: traceLookupDateRange(sample.timestamp),- })+ await breakpoint(100) // debounce rapid pager clicks+ const response = await api.tracing.getTrace(+ sample.trace_id,+ {+ dateRange: traceLookupDateRange(sample.timestamp),+ },+ trackedSignal(cache, 'fetchSampleTrace')+ )breakpoint()return response.results as Span[]},@@ -275,6 +312,21 @@ export const tracingOperationSceneLogic = kea<tracingOperationSceneLogicType>([actions.fetchSamples()actions.fetchStats()},+ loadCurrentSampleTrace: () => {+ const sample = values.currentSample+ if (!sample) {+ return+ }+ // Adjacent samples often share a trace (a child operation hit N times per request) —+ // re-anchor on the already-loaded trace instead of refetching it, but only when that+ // trace actually contains this span: a trace longer than the ±1h lookup window can+ // share a trace_id yet omit spans that fell outside the window of the earlier fetch.+ if (values.sampleTraceSpans.some((span) => span.span_id === sample.span_id)) {+ actions.selectSpan(sample.span_id)+ return+ }+ actions.fetchSampleTrace({ sample })+ },fetchSamplesSuccess: ({ samples }) => {if (samples.length === 0) {actions.selectSpan(null)@@ -285,14 +337,15 @@ export const tracingOperationSceneLogic = kea<tracingOperationSceneLogicType>([actions.setSampleIndex(0)return}- if (values.currentSample) {- actions.fetchSampleTrace({ sample: values.currentSample })- }+ actions.loadCurrentSampleTrace()},setSampleIndex: () => {- if (values.currentSample) {- actions.fetchSampleTrace({ sample: values.currentSample })+ // While samples are (re)loading, the index points into the outgoing result set;+ // fetchSamplesSuccess (or fetchSamplesFailure) loads the trace for the resolved index.+ if (values.samplesLoading) {+ return}+ actions.loadCurrentSampleTrace()},fetchSampleTraceSuccess: () => {// Anchor the waterfall on the operation's own span — for child operations the@@ -300,16 +353,34 @@ export const tracingOperationSceneLogic = kea<tracingOperationSceneLogicType>([actions.selectSpan(values.currentSample?.span_id ?? null)},fetchHistogramFailure: ({ error }) => {- lemonToast.error(`Failed to load latency distribution: ${error}`)+ if (!isUserInitiatedError(error)) {+ lemonToast.error(`Failed to load latency distribution: ${error}`)+ }},fetchSamplesFailure: ({ error }) => {+ if (isUserInitiatedError(error)) {+ return+ }lemonToast.error(`Failed to load sample traces: ${error}`)+ // The failed refetch already blanked the waterfall (see the sampleTraceSpans reducer);+ // reload the trace for the retained samples so the scene stays usable. A stale index+ // (e.g. restored from the URL mid-load) can point past the retained set, resolving to+ // no current sample — clamp it back to 0 first, mirroring fetchSamplesSuccess.+ if (values.sampleIndex >= values.samples.length) {+ actions.setSampleIndex(0)+ return+ }+ actions.loadCurrentSampleTrace()},fetchStatsFailure: ({ error }) => {- lemonToast.error(`Failed to load operation stats: ${error}`)+ if (!isUserInitiatedError(error)) {+ lemonToast.error(`Failed to load operation stats: ${error}`)+ }},fetchSampleTraceFailure: ({ error }) => {- lemonToast.error(`Failed to load trace: ${error}`)+ if (!isUserInitiatedError(error)) {+ lemonToast.error(`Failed to load trace: ${error}`)+ }},})),@@ -350,13 +421,15 @@ export const tracingOperationSceneLogic = kea<tracingOperationSceneLogicType>([},})),- afterMount(({ actions, values }) => {+ afterMount(({ actions, props }) => {+ // A malformed link renders the scene's missing-params fallback; don't query for it.+ if (!props.spanName || !props.serviceName) {+ return+ }+ // URL restore may have dispatched these already in this same tick — the loaders'+ // leading breakpoint coalesces the duplicates into one request each.actions.fetchHistogram()actions.fetchStats()- // A deep link restores the selection via urlToAction, whose listener already fetches- // samples — only fetch directly when mounting without one.- if (!values.durationSelection) {- actions.fetchSamples()- }+ actions.fetchSamples()}),])