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): explain a trace with no spans (#116835)

Paul D'Ambra2fb1c691d652
diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsx
index 72e5482930ff..41baf3c01eea 100644
--- a/products/tracing/frontend/TracingScene.tsx
+++ b/products/tracing/frontend/TracingScene.tsx
@@ -103,6 +103,7 @@ function TracingSceneContents(): JSX.Element {
isLoadingFullTrace,
canLoadMoreTraceSpans,
traceSpansLoadingMore,
+ selectedTraceLoadFailed,
aggregation,
aggregationLoading,
filters,
@@ -125,6 +126,7 @@ function TracingSceneContents(): JSX.Element {
sceneTabsEnabled,
activeSceneTab,
} = useValues(tracingSceneLogic())
+ const { traceLoadFiltersActive } = useValues(tracingDataLogic)
const { featureFlags } = useValues(featureFlagLogic)
const {
openTrace,
@@ -137,6 +139,7 @@ function TracingSceneContents(): JSX.Element {
fetchNextPage,
fetchSpans,
fetchSparkline,
+ loadTraceSpans,
loadMoreTraceSpans,
setVisibleRowRange,
selectInspectorTab,
@@ -362,6 +365,13 @@ function TracingSceneContents(): JSX.Element {
errorsScope={errorsScope}
onSelectInspectorTab={selectInspectorTab}
loading={isLoadingFullTrace}
+ loadFailed={selectedTraceLoadFailed}
+ filtersActive={traceLoadFiltersActive}
+ onRetry={
+ selectedTraceId
+ ? () => loadTraceSpans({ traceId: selectedTraceId, ts: selectedTraceTs })
+ : undefined
+ }
hasMoreSpans={canLoadMoreTraceSpans}
loadingMoreSpans={traceSpansLoadingMore}
onLoadMoreSpans={loadMoreTraceSpans}
diff --git a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.test.tsx b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.test.tsx
new file mode 100644
index 000000000000..df41c70706a5
--- /dev/null
+++ b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.test.tsx
@@ -0,0 +1,157 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { Provider } from 'kea'
+import posthog from 'posthog-js'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import { tracingSpansTraceAiEventsRetrieve } from 'products/tracing/frontend/generated/api'
+
+import { makeSpan } from '../../__mocks__/span'
+import { EMPTY_TRACE_IDENTITY } from '../../traceIdentity'
+import { TraceDrawer, type TraceDrawerProps } from './TraceDrawer'
+
+jest.mock('products/tracing/frontend/generated/api', () => ({
+ tracingSpansTraceAiEventsRetrieve: jest.fn(),
+}))
+
+const mockAiEventsRetrieve = tracingSpansTraceAiEventsRetrieve as jest.MockedFunction<
+ typeof tracingSpansTraceAiEventsRetrieve
+>
+
+describe('TraceDrawer', () => {
+ let captureSpy: jest.SpyInstance
+
+ beforeEach(() => {
+ initKeaTests()
+ mockAiEventsRetrieve.mockReset()
+ mockAiEventsRetrieve.mockResolvedValue({ results: [], has_more: false, limit: 500 })
+ captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)
+ })
+ afterEach(() => {
+ cleanup()
+ captureSpy.mockRestore()
+ })
+
+ const renderDrawer = (props: Partial<TraceDrawerProps>): void => {
+ render(
+ <Provider>
+ <TraceDrawer
+ isOpen
+ traceId="abc123"
+ ts={null}
+ spans={[]}
+ identity={EMPTY_TRACE_IDENTITY}
+ sessionId={null}
+ showErrorsTab={false}
+ inspectorTab="attributes"
+ errorsScope={null}
+ onSelectInspectorTab={jest.fn()}
+ loading={false}
+ loadFailed={false}
+ filtersActive={false}
+ selectedSpanId={null}
+ onSelectSpan={jest.fn()}
+ onClose={jest.fn()}
+ {...props}
+ />
+ </Provider>
+ )
+ }
+
+ const unavailableCaptures = (): unknown[][] =>
+ captureSpy.mock.calls.filter(([event]) => event === 'tracing trace unavailable')
+
+ // A trace with no spans yet is still loading, so the notice and its capture must wait for the result.
+ it.each([
+ { loading: false, showsNotice: true },
+ { loading: true, showsNotice: false },
+ ])('with no spans and loading=$loading, shows the unavailable notice: $showsNotice', ({ loading, showsNotice }) => {
+ renderDrawer({ loading, filtersActive: true })
+
+ expect(screen.queryByText('Trace unavailable') !== null).toBe(showsNotice)
+ expect(unavailableCaptures()).toEqual(
+ showsNotice ? [['tracing trace unavailable', { filters_active: true }]] : []
+ )
+ })
+
+ // A failed fetch must read as an error, not as "this trace has no spans" — the two share the
+ // same empty `spans` array but mean opposite things to the user.
+ it('shows a retryable error instead of the unavailable notice when the trace failed to load', () => {
+ const onRetry = jest.fn()
+ renderDrawer({ loading: false, loadFailed: true, onRetry })
+
+ expect(screen.queryByText("Couldn't load trace")).not.toBeNull()
+ expect(screen.queryByText('Trace unavailable')).toBeNull()
+
+ screen.getByText('Try again').click()
+ expect(onRetry).toHaveBeenCalledTimes(1)
+ })
+
+ it.each([
+ { failedLoad: 'spans', loadFailed: true, aiEventsFail: false, spanRetries: 1, aiEventsFetches: 0 },
+ { failedLoad: 'AI events', loadFailed: false, aiEventsFail: true, spanRetries: 0, aiEventsFetches: 2 },
+ ])(
+ 'keeps the waterfall and shows a compact warning when the $failedLoad load fails but spans exist',
+ async ({ loadFailed, aiEventsFail, spanRetries, aiEventsFetches }) => {
+ if (aiEventsFail) {
+ mockAiEventsRetrieve.mockRejectedValueOnce(new Error('boom'))
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TRACING_AI_EVENTS]: true })
+ }
+ const onRetry = jest.fn()
+ renderDrawer({
+ loading: false,
+ loadFailed,
+ onRetry,
+ spans: [makeSpan({ trace_id: 'abc123', span_id: 'span-1', is_root_span: true })],
+ })
+
+ expect(
+ await screen.findByText("Couldn't load the full trace. Showing the spans loaded so far.")
+ ).toBeInTheDocument()
+ expect(screen.queryByText("Couldn't load trace")).toBeNull()
+ expect(screen.getAllByText('GET /checkout').length).toBeGreaterThan(0)
+
+ // LemonBanner renders its action twice (one per responsive breakpoint), both wired to the
+ // same handler, so any one of them firing once is the behavior under test.
+ screen.getAllByText('Try again')[0].click()
+ expect(onRetry).toHaveBeenCalledTimes(spanRetries)
+ expect(mockAiEventsRetrieve).toHaveBeenCalledTimes(aiEventsFetches)
+ }
+ )
+
+ // The spans fetch and the AI events fetch resolve independently, so a spans result that is empty
+ // must not read as "trace unavailable" while AI events for the same trace are still in flight.
+ it('waits for AI events to finish loading before showing the unavailable notice', () => {
+ mockAiEventsRetrieve.mockReturnValue(new Promise(() => {}))
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TRACING_AI_EVENTS]: true })
+
+ renderDrawer({ loading: false })
+
+ expect(screen.queryByText('Trace unavailable')).toBeNull()
+ expect(unavailableCaptures()).toEqual([])
+ })
+
+ it('shows a retryable error when the AI events fetch fails and there are no spans', async () => {
+ mockAiEventsRetrieve.mockRejectedValueOnce(new Error('boom'))
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TRACING_AI_EVENTS]: true })
+ const onRetry = jest.fn()
+
+ renderDrawer({ loading: false, onRetry })
+
+ expect(await screen.findByText("Couldn't load trace")).toBeInTheDocument()
+ expect(screen.queryByText('Trace unavailable')).toBeNull()
+ expect(unavailableCaptures()).toEqual([])
+
+ screen.getByText('Try again').click()
+ expect(mockAiEventsRetrieve).toHaveBeenCalledTimes(2)
+ expect(onRetry).not.toHaveBeenCalled()
+ })
+})
diff --git a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx
index 80009d20a185..eeee6bb840f6 100644
--- a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx
+++ b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx
@@ -1,7 +1,7 @@
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
import { useMemo, useRef } from 'react'
-import { LemonButton, LemonTabs, LemonTag, SpinnerOverlay } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonTabs, LemonTag, SpinnerOverlay } from '@posthog/lemon-ui'
import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
import { JSONViewer } from 'lib/components/JSONViewer'
@@ -33,6 +33,8 @@ import { TraceAiEventsCapNotice } from './TraceAiEventsCapNotice'
import { traceAiEventsLogic } from './traceAiEventsLogic'
import { TraceErrorsTab } from './TraceErrorsTab'
import { TraceIdentityChips } from './TraceIdentityChips'
+import { TraceLoadErrorNotice } from './TraceLoadErrorNotice'
+import { TraceUnavailableNotice } from './TraceUnavailableNotice'
// Below this the inspector's content (the attribute KVP tables) stops being readable; clamp so a
// drag can't crush it. The max is a flex `max-w` so a too-wide drag can't starve the waterfall.
@@ -56,6 +58,12 @@ export interface TraceDrawerProps {
errorsScope: ErrorScope | null
onSelectInspectorTab: (tab: SpanInspectorTab) => void
loading: boolean
+ /** The last full-trace fetch failed (network, 4xx, 5xx) — shows a retryable error instead of the empty-trace notice. */
+ loadFailed: boolean
+ /** Re-fetches the open trace. Omit to hide the retry button (e.g. no clean reload path). */
+ onRetry?: () => void
+ /** List filters scoped the last trace lookup, so an empty trace may be filtered out rather than never sent. */
+ filtersActive: boolean
/** The open trace has more spans than the loaded pages — drives the waterfall's infinite scroll. */
hasMoreSpans?: boolean
/** A next page of spans is being fetched (shows a bottom spinner without the full overlay). */
@@ -82,6 +90,9 @@ export function TraceDrawer({
errorsScope,
onSelectInspectorTab,
loading,
+ loadFailed,
+ onRetry,
+ filtersActive,
hasMoreSpans = false,
loadingMoreSpans = false,
onLoadMoreSpans,
@@ -89,7 +100,20 @@ export function TraceDrawer({
onSelectSpan,
onClose,
}: TraceDrawerProps): JSX.Element | null {
- const { aiEvents, hasMoreAiEvents, aiEventsLimit } = useValues(traceAiEventsLogic({ traceId }))
+ const { aiEvents, hasMoreAiEvents, aiEventsLimit, aiEventsResponseLoading, aiEventsLoadFailed } = useValues(
+ traceAiEventsLogic({ traceId })
+ )
+ const { loadAiEvents } = useActions(traceAiEventsLogic({ traceId }))
+ const anyLoadFailed = loadFailed || aiEventsLoadFailed
+ const canRetry = (loadFailed && !!onRetry) || aiEventsLoadFailed
+ const retryFailedLoads = (): void => {
+ if (loadFailed) {
+ onRetry?.()
+ }
+ if (aiEventsLoadFailed) {
+ loadAiEvents()
+ }
+ }
// The waterfall and the inspector read one list, so an AI row selects and inspects like a span.
const spans = useMemo(() => {
const aiEventSpans = buildAiEventSpans(aiEvents, realSpans)
@@ -182,126 +206,152 @@ export function TraceDrawer({
}
>
<TraceIdentityChips identity={identity} timestamp={rootSpan?.timestamp ?? ts} />
- <div className="relative min-h-32 flex gap-4 items-start">
- {loading && <SpinnerOverlay />}
- <div className="flex-1 min-w-0">
- <TraceAiEventsCapNotice aiEvents={aiEvents} hasMore={hasMoreAiEvents} limit={aiEventsLimit} />
- {/* Keyed by trace so a new trace resets selection + scroll state. */}
- <TraceWaterfallView
- key={traceId ?? ''}
- spans={spans}
- selectedSpanId={selectedSpanId}
- onSpanSelect={onSelectSpan}
- hasMore={hasMoreSpans}
- loadingMore={loadingMoreSpans}
- onLoadMore={onLoadMoreSpans}
- />
- </div>
- <div
- ref={inspectorRef}
- className={cn(
- 'relative shrink-0 border-l border-border pl-4 max-w-[70%]',
- inspectorWidth == null && 'w-2/5'
- )}
- // eslint-disable-next-line react/forbid-dom-props
- style={
- inspectorWidth != null ? { width: Math.max(MIN_INSPECTOR_WIDTH, inspectorWidth) } : undefined
- }
- data-attr="tracing-span-inspector"
- >
- <Resizer {...inspectorResizerProps} />
- {missingParentSpanId ? (
- <MissingParentSpanNotice traceId={traceId ?? ''} parentSpanId={missingParentSpanId} />
- ) : inspectedSpan ? (
- <>
- <SpanSummaryHeader span={inspectedSpan} serviceColorMap={serviceColorMap} />
- <LemonTabs
- activeKey={activeInspectorTab}
- onChange={onSelectInspectorTab}
- data-attr="tracing-inspector-tabs"
- tabs={[
- {
- key: 'attributes',
- label: 'Attributes',
- // The summary header carries the headline facts, so the tab
- // shows only the user attributes (no duplicate details table).
- content: <ExpandedSpanContent span={inspectedSpan} showDetails={false} />,
- },
- // Conditional (LemonTabs ignores falsy entries): only DB spans have a query.
- queryText
- ? {
- key: 'query',
- label: 'Query',
- content: (
- <CodeSnippet
- language={Language.SQL}
- wrap
- maxLinesWithoutExpansion={40}
- >
- {queryText}
- </CodeSnippet>
- ),
- }
- : null,
- {
- key: 'logs',
- label: 'Logs',
- // Keyed by trace, not span: a new trace remounts to reset the scope toggle
- // back to whole-trace, while selecting another span within the same trace
- // re-queries in place (the embedded viewer and memoized pinned filter handle
- // it) so we don't churn its logics or lose scroll.
- content: <SpanLogsTab key={inspectedSpan.trace_id} span={inspectedSpan} />,
- },
- // Conditional on its own flag. The tab is session-scoped, so it
- // stays available on a trace that resolved no session and
- // explains there what is missing.
- showErrorsTab
- ? {
- key: 'errors',
- label: 'Errors',
- content: (
- <TraceErrorsTab
- key={inspectedSpan.span_id}
- traceId={inspectedSpan.trace_id}
- // A synthetic AI row has no OTel span id, so it scopes to the trace.
- spanId={
- isAiEventSpan(inspectedSpan) ? null : inspectedSpan.span_id
- }
- timestamp={rootSpan?.timestamp ?? inspectedSpan.timestamp ?? ts}
- sessionId={sessionId}
- initialScope={errorsScope}
- resolving={loading}
- />
- ),
- }
- : null,
- // Conditional: needs the metrics product (flag + access) and its own flag.
- showMetricsTab
- ? {
- key: 'metrics',
- label: 'Metrics',
- // Keyed by trace like the Logs tab: a new trace remounts to reset
- // the scope toggle; selecting another span re-renders in place.
- content: (
- <SpanMetricsTab key={inspectedSpan.trace_id} span={inspectedSpan} />
- ),
- }
- : null,
- {
- key: 'raw',
- label: 'Raw',
- // Interactive tree, matching the logs viewer's raw view (LogDetailsModal)
- // for cross-pane consistency. The span as the frontend holds it.
- content: <JSONViewer src={inspectedSpan} collapsed={2} sortKeys />,
- },
- ]}
- />
- </>
- ) : (
- <div className="text-muted p-4">No spans in this trace</div>
- )}
+ {/* A failed refetch only replaces the waterfall when there are no spans to fall back on. */}
+ {traceId && !loading && anyLoadFailed && spans.length === 0 ? (
+ <TraceLoadErrorNotice onRetry={canRetry ? retryFailedLoads : undefined} />
+ ) : traceId && !loading && !aiEventsResponseLoading && spans.length === 0 ? (
+ <TraceUnavailableNotice traceId={traceId} filtersActive={filtersActive} />
+ ) : (
+ <div className="relative min-h-32 flex gap-4 items-start">
+ {(loading || (aiEventsResponseLoading && spans.length === 0)) && <SpinnerOverlay />}
+ <div className="flex-1 min-w-0">
+ {anyLoadFailed && (
+ <LemonBanner
+ type="warning"
+ className="mb-2"
+ action={canRetry ? { children: 'Try again', onClick: retryFailedLoads } : undefined}
+ data-attr="tracing-trace-load-error-banner"
+ >
+ Couldn't load the full trace. Showing the spans loaded so far.
+ </LemonBanner>
+ )}
+ <TraceAiEventsCapNotice aiEvents={aiEvents} hasMore={hasMoreAiEvents} limit={aiEventsLimit} />
+ {/* Keyed by trace so a new trace resets selection + scroll state. */}
+ <TraceWaterfallView
+ key={traceId ?? ''}
+ spans={spans}
+ selectedSpanId={selectedSpanId}
+ onSpanSelect={onSelectSpan}
+ hasMore={hasMoreSpans}
+ loadingMore={loadingMoreSpans}
+ onLoadMore={onLoadMoreSpans}
+ />
+ </div>
+ <div
+ ref={inspectorRef}
+ className={cn(
+ 'relative shrink-0 border-l border-border pl-4 max-w-[70%]',
+ inspectorWidth == null && 'w-2/5'
+ )}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={
+ inspectorWidth != null
+ ? { width: Math.max(MIN_INSPECTOR_WIDTH, inspectorWidth) }
+ : undefined
+ }
+ data-attr="tracing-span-inspector"
+ >
+ <Resizer {...inspectorResizerProps} />
+ {missingParentSpanId ? (
+ <MissingParentSpanNotice traceId={traceId ?? ''} parentSpanId={missingParentSpanId} />
+ ) : inspectedSpan ? (
+ <>
+ <SpanSummaryHeader span={inspectedSpan} serviceColorMap={serviceColorMap} />
+ <LemonTabs
+ activeKey={activeInspectorTab}
+ onChange={onSelectInspectorTab}
+ data-attr="tracing-inspector-tabs"
+ tabs={[
+ {
+ key: 'attributes',
+ label: 'Attributes',
+ // The summary header carries the headline facts, so the tab
+ // shows only the user attributes (no duplicate details table).
+ content: <ExpandedSpanContent span={inspectedSpan} showDetails={false} />,
+ },
+ // Conditional (LemonTabs ignores falsy entries): only DB spans have a query.
+ queryText
+ ? {
+ key: 'query',
+ label: 'Query',
+ content: (
+ <CodeSnippet
+ language={Language.SQL}
+ wrap
+ maxLinesWithoutExpansion={40}
+ >
+ {queryText}
+ </CodeSnippet>
+ ),
+ }
+ : null,
+ {
+ key: 'logs',
+ label: 'Logs',
+ // Keyed by trace, not span: a new trace remounts to reset the scope toggle
+ // back to whole-trace, while selecting another span within the same trace
+ // re-queries in place (the embedded viewer and memoized pinned filter handle
+ // it) so we don't churn its logics or lose scroll.
+ content: <SpanLogsTab key={inspectedSpan.trace_id} span={inspectedSpan} />,
+ },
+ // Conditional on its own flag. The tab is session-scoped, so it
+ // stays available on a trace that resolved no session and
+ // explains there what is missing.
+ showErrorsTab
+ ? {
+ key: 'errors',
+ label: 'Errors',
+ content: (
+ <TraceErrorsTab
+ key={inspectedSpan.span_id}
+ traceId={inspectedSpan.trace_id}
+ // A synthetic AI row has no OTel span id, so it scopes to the trace.
+ spanId={
+ isAiEventSpan(inspectedSpan)
+ ? null
+ : inspectedSpan.span_id
+ }
+ timestamp={
+ rootSpan?.timestamp ?? inspectedSpan.timestamp ?? ts
+ }
+ sessionId={sessionId}
+ initialScope={errorsScope}
+ resolving={loading}
+ />
+ ),
+ }
+ : null,
+ // Conditional: needs the metrics product (flag + access) and its own flag.
+ showMetricsTab
+ ? {
+ key: 'metrics',
+ label: 'Metrics',
+ // Keyed by trace like the Logs tab: a new trace remounts to reset
+ // the scope toggle; selecting another span re-renders in place.
+ content: (
+ <SpanMetricsTab
+ key={inspectedSpan.trace_id}
+ span={inspectedSpan}
+ />
+ ),
+ }
+ : null,
+ {
+ key: 'raw',
+ label: 'Raw',
+ // Interactive tree, matching the logs viewer's raw view (LogDetailsModal)
+ // for cross-pane consistency. The span as the frontend holds it.
+ content: <JSONViewer src={inspectedSpan} collapsed={2} sortKeys />,
+ },
+ ]}
+ />
+ </>
+ ) : (
+ <div className="text-muted p-4">No spans in this trace</div>
+ )}
+ </div>
</div>
- </div>
+ )}
</LemonDrawer>
)
}
diff --git a/products/tracing/frontend/components/TraceDrawer/TraceLoadErrorNotice.tsx b/products/tracing/frontend/components/TraceDrawer/TraceLoadErrorNotice.tsx
new file mode 100644
index 000000000000..2101bdf139e3
--- /dev/null
+++ b/products/tracing/frontend/components/TraceDrawer/TraceLoadErrorNotice.tsx
@@ -0,0 +1,24 @@
+import { LemonButton } from '@posthog/lemon-ui'
+
+// A failed fetch must read differently from a successful one that found nothing (TraceUnavailableNotice) —
+// otherwise a network error looks like proof the trace was never sent.
+export function TraceLoadErrorNotice({ onRetry }: { onRetry?: () => void }): JSX.Element {
+ return (
+ <div className="flex flex-col gap-1.5 p-4" data-attr="tracing-trace-load-error-notice">
+ <span className="font-semibold">Couldn't load trace</span>
+ <p className="m-0">PostHog couldn't load this trace.</p>
+ {onRetry && (
+ <div>
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={onRetry}
+ data-attr="tracing-trace-load-error-retry"
+ >
+ Try again
+ </LemonButton>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/tracing/frontend/components/TraceDrawer/TraceUnavailableNotice.tsx b/products/tracing/frontend/components/TraceDrawer/TraceUnavailableNotice.tsx
new file mode 100644
index 000000000000..3382c0729a8b
--- /dev/null
+++ b/products/tracing/frontend/components/TraceDrawer/TraceUnavailableNotice.tsx
@@ -0,0 +1,39 @@
+import posthog from 'posthog-js'
+
+import { Link } from '@posthog/lemon-ui'
+
+import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
+
+import { TRACING_DOCS_URL } from '../../traceLinks'
+import { CopyableId } from './SpanSummaryHeader'
+
+// Other products link here by trace ID alone, so an empty result must not read as "this request never ran".
+export function TraceUnavailableNotice({
+ traceId,
+ filtersActive,
+}: {
+ traceId: string
+ filtersActive: boolean
+}): JSX.Element {
+ // Captured on show, not on the span lookup, because AI events can still fill or fail the trace after that.
+ useOnMountEffect(() => {
+ posthog.capture('tracing trace unavailable', { filters_active: filtersActive })
+ })
+
+ return (
+ <div className="flex flex-col gap-1.5 p-4" data-attr="tracing-trace-unavailable-notice">
+ <span className="font-semibold">Trace unavailable</span>
+ <p className="m-0">
+ PostHog has no spans for this trace that match your current filters. The service may not send spans to
+ PostHog, sampling may have dropped them, active filters may be excluding them, or they may be older than
+ your retention period. New spans can take a few minutes to appear.
+ </p>
+ <div className="flex items-center gap-x-3 gap-y-1 flex-wrap text-xs text-muted">
+ <CopyableId label="Trace ID" value={traceId} />
+ <Link to={TRACING_DOCS_URL} target="_blank" data-attr="tracing-trace-unavailable-docs">
+ Send traces to PostHog
+ </Link>
+ </div>
+ </div>
+ )
+}
diff --git a/products/tracing/frontend/components/TraceDrawer/traceAiEventsLogic.ts b/products/tracing/frontend/components/TraceDrawer/traceAiEventsLogic.ts
index 8f2cc0981330..babedf57b8b3 100644
--- a/products/tracing/frontend/components/TraceDrawer/traceAiEventsLogic.ts
+++ b/products/tracing/frontend/components/TraceDrawer/traceAiEventsLogic.ts
@@ -1,4 +1,4 @@
-import { MakeLogicType, connect, kea, key, path, props, selectors } from 'kea'
+import { MakeLogicType, connect, kea, key, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
@@ -22,6 +22,7 @@ export interface traceAiEventsLogicValues {
aiEvents: TraceAiEvent[]
aiEventsEnabled: boolean
aiEventsLimit: number
+ aiEventsLoadFailed: boolean
aiEventsResponse: _TracingTraceAiEventsResponseApi
aiEventsResponseLoading: boolean
hasMoreAiEvents: boolean
@@ -92,6 +93,17 @@ export const traceAiEventsLogic = kea<traceAiEventsLogicType>([
},
})),
+ reducers({
+ aiEventsLoadFailed: [
+ false as boolean,
+ {
+ loadAiEvents: () => false,
+ loadAiEventsSuccess: () => false,
+ loadAiEventsFailure: () => true,
+ },
+ ],
+ }),
+
selectors({
aiEventsEnabled: [
(s) => [s.featureFlags],
diff --git a/products/tracing/frontend/tracingDataLogic.test.ts b/products/tracing/frontend/tracingDataLogic.test.ts
index e7eb13b8ad88..f1c3d69ccc69 100644
--- a/products/tracing/frontend/tracingDataLogic.test.ts
+++ b/products/tracing/frontend/tracingDataLogic.test.ts
@@ -197,7 +197,32 @@ describe('tracingDataLogic', () => {
},
])('captures the right event for $name', ({ dispatch, event, properties }) => {
dispatch(logic)
- expect(captureSpy).toHaveBeenCalledWith(event, properties)
+ expect(captureSpy).toHaveBeenCalledWith(event, ...(properties ? [properties] : []))
+ })
+
+ it('records that a service name filter scoped the trace lookup', () => {
+ logic.actions.setServiceNames(['checkout-api'])
+ logic.actions.loadTraceSpans({ traceId: 'trace-x' })
+ expect(logic.values.traceLoadFiltersActive).toBe(true)
+ })
+
+ // Filters changing mid-flight must not rescope or relabel a request made under the old filters.
+ it('keeps the filters active at request time through the widened lookup', async () => {
+ type TraceResponse = Awaited<ReturnType<typeof api.tracing.getTrace>>
+ const empty: TraceResponse = { results: [], hasMore: false, nextOffset: null }
+ let releaseBoundedLookup: (response: TraceResponse) => void = () => {}
+ const getTraceSpy = jest
+ .spyOn(api.tracing, 'getTrace')
+ .mockImplementationOnce(() => new Promise((resolve) => (releaseBoundedLookup = resolve)))
+ .mockResolvedValueOnce(empty)
+
+ logic.actions.loadTraceSpans({ traceId: 'trace-x', ts: '2024-01-01T00:00:00Z' })
+ logic.actions.setServiceNames(['checkout-api'])
+ releaseBoundedLookup(empty)
+ await expectLogic(logic).toDispatchActions(['loadTraceSpansSuccess'])
+
+ expect(getTraceSpy.mock.calls.map(([, params]) => params?.serviceNames)).toEqual([undefined, undefined])
+ expect(logic.values.traceLoadFiltersActive).toBe(false)
})
})
@@ -472,6 +497,45 @@ describe('tracingDataLogic', () => {
expect(logic.values.spansError).toBeNull()
})
+
+ it('flags a failed trace load and clears the flag once the next trace load starts', () => {
+ logic = mountWithSpans([])
+ logic.actions.loadTraceSpansFailure('boom')
+ expect(logic.values.traceSpansLoadFailed).toBe(true)
+
+ // Reopening a trace (even a different one) must not inherit the previous failure.
+ logic.actions.loadTraceSpans({ traceId: 'trace-1' })
+ expect(logic.values.traceSpansLoadFailed).toBe(false)
+ })
+
+ it('does not flag a failure when a superseded trace load rejects after the newer one resolved', async () => {
+ const flushPromises = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))
+ let rejectA: (error: Error) => void = () => {}
+ let resolveB: (value: { results: Span[]; hasMore: boolean; nextOffset: number | null }) => void = () => {}
+ const apiSpy = jest
+ .spyOn(api.tracing, 'getTrace')
+ .mockImplementationOnce(() => new Promise((_resolve, reject) => (rejectA = reject)))
+ .mockImplementationOnce(() => new Promise((resolve) => (resolveB = resolve)))
+ logic = mountWithSpans([])
+
+ logic.actions.loadTraceSpans({ traceId: 'trace-a' })
+ logic.actions.loadTraceSpans({ traceId: 'trace-b' })
+
+ const bSpans = [createMockSpan('span-b', '2024-01-01T04:00:00Z')]
+ resolveB({ results: bSpans, hasMore: false, nextOffset: null })
+ await flushPromises()
+
+ expect(logic.values.traceSpans).toEqual(bSpans)
+ expect(logic.values.traceSpansLoadFailed).toBe(false)
+
+ // trace A's late rejection must not mark trace B's spans as failed.
+ rejectA(new Error('boom'))
+ await flushPromises()
+
+ expect(logic.values.traceSpansLoadFailed).toBe(false)
+ expect(logic.values.traceSpans).toEqual(bSpans)
+ apiSpy.mockRestore()
+ })
})
describe('cancelled requests', () => {
diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.ts
index 9d7135305a20..4855eb678d19 100644
--- a/products/tracing/frontend/tracingDataLogic.ts
+++ b/products/tracing/frontend/tracingDataLogic.ts
@@ -19,6 +19,7 @@ import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { dataColorVars } from 'lib/colors'
+import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'
import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
@@ -61,6 +62,12 @@ import {
import type { OverlayWindow, TimeComparison, TracingOrderDirection, TracingViewMode } from './tracingFiltersLogic'
import type { Span } from './types'
+// The default filter group editor state nests an empty AND group inside an outer AND group, so a
+// plain `values.length` check reads the default as "filters active". Walk for a real leaf condition.
+function hasFilterConditions(group: UniversalFiltersGroup): boolean {
+ return group.values.some((value) => (isUniversalGroupFilterLike(value) ? hasFilterConditions(value) : true))
+}
+
export interface SparklineRow {
time: string
service: string
@@ -185,8 +192,10 @@ export interface tracingDataLogicValues {
traceId: string
ts?: string | null
} | null
+ traceLoadFiltersActive: boolean
traceSpans: Span[]
traceSpansHasMore: boolean
+ traceSpansLoadFailed: boolean
traceSpansLoading: boolean
traceSpansLoadingMore: boolean
traceSpansNextOffset: number
@@ -585,6 +594,9 @@ export interface tracingDataLogicActions {
setSparklineAbortController: (controller: AbortController | null) => {
controller: AbortController | null
}
+ setTraceLoadFiltersActive: (filtersActive: boolean) => {
+ filtersActive: boolean
+ }
setTracePagination: (
hasMore: boolean,
nextOffset: number | null
@@ -599,6 +611,9 @@ export interface tracingDataLogicActions {
startIndex: number
stopIndex: number
}
+ widenTraceLookup: () => {
+ value: true
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -696,6 +711,8 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
fetchNextPage: true,
loadMoreTraceSpans: true,
setTracePagination: (hasMore: boolean, nextOffset: number | null) => ({ hasMore, nextOffset }),
+ setTraceLoadFiltersActive: (filtersActive: boolean) => ({ filtersActive }),
+ widenTraceLookup: true,
clearSpans: true,
cancelInProgressSpans: (controller: AbortController | null) => ({ controller }),
cancelInProgressSparkline: (controller: AbortController | null) => ({ controller }),
@@ -856,6 +873,17 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
loadTraceSpans: () => false,
},
],
+ // Whether the last full-trace fetch failed, so the drawer can show a retryable error state
+ // instead of reading a failed request as a trace that genuinely has no spans.
+ traceSpansLoadFailed: [
+ false as boolean,
+ {
+ loadTraceSpans: () => false,
+ loadTraceSpansSuccess: () => false,
+ loadTraceSpansFailure: () => true,
+ clearSpans: () => false,
+ },
+ ],
// Offset to request for the next waterfall page (count of spans already loaded for the trace).
traceSpansNextOffset: [
0 as number,
@@ -870,9 +898,19 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
null as { traceId: string; ts?: string | null } | null,
{
loadTraceSpans: (_, { traceId, ts }) => ({ traceId, ts }),
+ widenTraceLookup: (state) => (state ? { ...state, ts: null } : state),
clearSpans: () => null,
},
],
+ // The same filters that scope the span list also scope the single-trace lookup, so an empty
+ // trace can mean "filtered out" rather than "never sent". Set when the lookup starts, because
+ // the filters can change while it is in flight.
+ traceLoadFiltersActive: [
+ false as boolean,
+ {
+ setTraceLoadFiltersActive: (_, { filtersActive }) => filtersActive,
+ },
+ ],
// Separate from the loader's own `traceSpansLoading` so paging in more spans shows a small
// bottom spinner rather than the drawer's full-trace overlay (see `isLoadingFullTrace`).
traceSpansLoadingMore: [
@@ -960,12 +998,39 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
traceSpans: [
[] as Span[],
{
- loadTraceSpans: async ({ traceId, ts }: { traceId: string; ts?: string | null }): Promise<Span[]> => {
- const response = await api.tracing.getTrace(traceId, {
- dateRange: resolveTraceLookupRange(ts),
- serviceNames: values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,
- filterGroup: values.queryFilterGroup as PropertyGroupFilter,
- })
+ loadTraceSpans: async (
+ { traceId, ts }: { traceId: string; ts?: string | null },
+ breakpoint
+ ): Promise<Span[]> => {
+ // Filters can change while the request is in flight; both lookups must use these.
+ const serviceNames =
+ values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined
+ const filterGroup = values.queryFilterGroup
+ actions.setTraceLoadFiltersActive(!!serviceNames || hasFilterConditions(filterGroup))
+ const lookUpTrace = (
+ dateRange: { date_from: string; date_to: string } | undefined
+ ): ReturnType<typeof api.tracing.getTrace> =>
+ api.tracing.getTrace(traceId, {
+ dateRange,
+ serviceNames,
+ filterGroup: filterGroup as PropertyGroupFilter,
+ })
+ const boundedRange = resolveTraceLookupRange(ts)
+ let response: Awaited<ReturnType<typeof api.tracing.getTrace>>
+ try {
+ response = await lookUpTrace(boundedRange)
+ // The ts hint can sit hours from the spans (e.g. an exception late in a long job).
+ if (boundedRange && response.results.length === 0) {
+ breakpoint()
+ actions.widenTraceLookup()
+ response = await lookUpTrace(undefined)
+ }
+ } catch (error) {
+ // A superseded request's failure must not mark the newer trace as failed.
+ breakpoint()
+ throw error
+ }
+ breakpoint()
actions.setTracePagination(!!response.hasMore, response.nextOffset ?? null)
return response.results as Span[]
},
diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.ts
index b407b882f6d9..e462783b51b1 100644
--- a/products/tracing/frontend/tracingSceneLogic.ts
+++ b/products/tracing/frontend/tracingSceneLogic.ts
@@ -117,6 +117,7 @@ export interface tracingSceneLogicValues {
openTraceSpans: Span[] // tracingViewerLogic
selectedSpanId: string | null // tracingViewerLogic
selectedTraceId: string | null // tracingViewerLogic
+ selectedTraceLoadFailed: boolean // tracingViewerLogic
selectedTraceTs: string | null // tracingViewerLogic
sessionErrorBadgesEnabled: boolean // tracingViewerLogic
traceIdentity: TraceIdentity // tracingViewerLogic
@@ -365,6 +366,7 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
'canLoadMoreTraceSpans',
'compareFlameSpanName',
'compareFlameServiceName',
+ 'selectedTraceLoadFailed',
],
],
actions: [
diff --git a/products/tracing/frontend/tracingViewerLogic.test.ts b/products/tracing/frontend/tracingViewerLogic.test.ts
index f0f33ba2ff15..3bd2bc6fa28a 100644
--- a/products/tracing/frontend/tracingViewerLogic.test.ts
+++ b/products/tracing/frontend/tracingViewerLogic.test.ts
@@ -58,19 +58,55 @@ describe('tracingViewerLogic', () => {
expect(getTraceSpy.mock.calls.length > 0).toBe(shouldFetch)
})
+ it("does not carry a previous trace's load failure into a trace opened from a complete prefetch", () => {
+ logic.actions.openTrace('trace-a', { ts: '2024-01-01T00:00:00Z' })
+ tracingDataLogic().actions.loadTraceSpansFailure('boom')
+ expect(logic.values.traceSpansLoadFailed).toBe(true)
+
+ const spans = [makeSpan({ uuid: 'span-0', span_id: 'span-0', trace_id: 'trace-b', is_root_span: true })]
+ tracingDataLogic().actions.fetchSpansSuccess(spans)
+ logic.actions.openTrace('trace-b', { ts: '2024-01-01T00:00:00Z' })
+
+ expect(logic.values.selectedTraceId).toBe('trace-b')
+ expect(logic.values.traceSpansLoadFailed).toBe(true)
+ expect(logic.values.selectedTraceLoadFailed).toBe(false)
+ })
+
+ // A full fetch can fail, then a later list refresh prefetch the same trace complete (root span,
+ // under the cap). Reopening it skips the fetch and must not read the earlier attempt's failure.
+ it("does not carry a trace's own previous load failure into its reopen from a complete prefetch", () => {
+ logic.actions.openTrace('trace-a', { ts: '2024-01-01T00:00:00Z' })
+ tracingDataLogic().actions.loadTraceSpansFailure('boom')
+ expect(logic.values.selectedTraceLoadFailed).toBe(true)
+ logic.actions.closeTrace()
+
+ const spans = [makeSpan({ uuid: 'span-0', span_id: 'span-0', trace_id: 'trace-a', is_root_span: true })]
+ tracingDataLogic().actions.fetchSpansSuccess(spans)
+ logic.actions.openTrace('trace-a', { ts: '2024-01-01T00:00:00Z' })
+
+ expect(logic.values.selectedTraceId).toBe('trace-a')
+ expect(getTraceSpy).toHaveBeenCalledTimes(1)
+ expect(logic.values.selectedTraceLoadFailed).toBe(false)
+ })
+
// Without a ts hint the lookup must not fall back to a date window, or a trace older than that
- // window never loads. With a hint, the lookup stays bounded to the hint's narrow window.
+ // window never loads. With a hint, the lookup stays bounded to the hint's narrow window, and
+ // retries by id alone when the hint sits too far from the spans to find any.
+ const hintWindow = { date_from: '2023-12-31T23:00:00.000Z', date_to: '2024-01-01T01:00:00.000Z' }
it.each([
- [
- 'a ts hint',
- '2024-01-01T00:00:00Z',
- { date_from: '2023-12-31T23:00:00.000Z', date_to: '2024-01-01T01:00:00.000Z' },
- ],
- ['no ts hint', undefined, undefined],
- ])('openTrace with %s sends the matching date range', async (_name, ts, dateRange) => {
+ ['a ts hint that finds spans', '2024-01-01T00:00:00Z', true, [hintWindow], 1],
+ ['a ts hint that finds no spans', '2024-01-01T00:00:00Z', false, [hintWindow, undefined], 1],
+ ['no ts hint', undefined, false, [undefined], 0],
+ ])('openTrace with %s sends the matching date ranges', async (_name, ts, firstFindsSpans, dateRanges, loaded) => {
+ const span = makeSpan({ uuid: 'span-0', span_id: 'span-0', trace_id: 'trace-x', is_root_span: true })
+ getTraceSpy
+ .mockResolvedValueOnce({ results: firstFindsSpans ? [span] : [], hasMore: false, nextOffset: null })
+ .mockResolvedValueOnce({ results: [span], hasMore: false, nextOffset: null })
+
await expectLogic(logic, () => logic.actions.openTrace('trace-x', { ts })).toFinishAllListeners()
- expect(getTraceSpy.mock.calls[0][1].dateRange).toEqual(dateRange)
+ expect(getTraceSpy.mock.calls.map(([, params]) => params.dateRange)).toEqual(dateRanges)
+ expect(tracingDataLogic().values.traceSpans).toHaveLength(loaded)
})
describe('identity resolution', () => {
diff --git a/products/tracing/frontend/tracingViewerLogic.ts b/products/tracing/frontend/tracingViewerLogic.ts
index e131efb992a8..5de4b1fa5718 100644
--- a/products/tracing/frontend/tracingViewerLogic.ts
+++ b/products/tracing/frontend/tracingViewerLogic.ts
@@ -19,6 +19,15 @@ export interface TracingViewerLogicProps {
id: string
}
+// Mirrors the prefetch check in the `openTrace` listener: a batch with the trace's root span,
+// under the cap, is already the trace's complete span set, so a fetch for it would be skipped.
+// Also used by `selectedTraceLoadFailed` to tell a stale failure (from an earlier, differently
+// shaped prefetch) apart from one that still describes what's about to be fetched.
+function isCompletePrefetch(spans: Span[], traceId: string): boolean {
+ const prefetchedSpans = spans.filter((s) => s.trace_id === traceId)
+ return prefetchedSpans.some((s) => s.is_root_span) && prefetchedSpans.length < PREFETCH_SPANS
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tracingViewerLogicValues {
configuredDistinctIdKeys: string[] | undefined // tracingCorrelationConfigLogic
@@ -26,8 +35,10 @@ export interface tracingViewerLogicValues {
correlationLinksEnabled: boolean // tracingCorrelationConfigLogic
sessionErrorBadgesEnabled: boolean // tracingCorrelationConfigLogic
spans: Span[] // tracingDataLogic
+ traceLoadContext: { traceId: string; ts?: string | null } | null // tracingDataLogic
traceSpans: Span[] // tracingDataLogic
traceSpansHasMore: boolean // tracingDataLogic
+ traceSpansLoadFailed: boolean // tracingDataLogic
traceSpansLoading: boolean // tracingDataLogic
traceSpansLoadingMore: boolean // tracingDataLogic
hasDeferredFilterRefresh: boolean // tracingFiltersLogic
@@ -41,6 +52,7 @@ export interface tracingViewerLogicValues {
openTraceSpans: Span[]
selectedSpanId: string | null
selectedTraceId: string | null
+ selectedTraceLoadFailed: boolean
selectedTraceTs: string | null
traceIdentity: TraceIdentity
traceSessionId: string | null
@@ -124,6 +136,12 @@ export interface tracingViewerLogicMeta {
traceSpans: Span[],
selectedTraceId: string | null
) => boolean
+ selectedTraceLoadFailed: (
+ traceSpansLoadFailed: boolean,
+ traceLoadContext: { traceId: string; ts?: string | null } | null,
+ selectedTraceId: string | null,
+ spans: Span[]
+ ) => boolean
traceIdentity: (
openTraceSpans: Span[],
canLoadMoreTraceSpans: boolean,
@@ -160,7 +178,15 @@ export const tracingViewerLogic = kea<tracingViewerLogicType>([
connect(({ id }: TracingViewerLogicProps) => ({
values: [
tracingDataLogic({ id }),
- ['spans', 'traceSpans', 'traceSpansLoading', 'traceSpansLoadingMore', 'traceSpansHasMore'],
+ [
+ 'spans',
+ 'traceSpans',
+ 'traceSpansLoading',
+ 'traceSpansLoadingMore',
+ 'traceSpansHasMore',
+ 'traceSpansLoadFailed',
+ 'traceLoadContext',
+ ],
tracingFiltersLogic({ id }),
['hasDeferredFilterRefresh'],
tracingCorrelationConfigLogic,
@@ -299,6 +325,21 @@ export const tracingViewerLogic = kea<tracingViewerLogicType>([
!!selectedTraceId &&
traceSpans.some((span: Span) => span.trace_id === selectedTraceId),
],
+ // openTrace skips the fetch for a complete prefetch, so the raw flag can belong to a previous
+ // attempt at this same trace (one a later, now-complete prefetch has since superseded).
+ selectedTraceLoadFailed: [
+ (s) => [s.traceSpansLoadFailed, s.traceLoadContext, s.selectedTraceId, s.spans],
+ (
+ traceSpansLoadFailed: boolean,
+ traceLoadContext: { traceId: string; ts?: string | null } | null,
+ selectedTraceId: string | null,
+ spans: Span[]
+ ): boolean =>
+ traceSpansLoadFailed &&
+ traceLoadContext?.traceId === selectedTraceId &&
+ !!selectedTraceId &&
+ !isCompletePrefetch(spans, selectedTraceId),
+ ],
// The person and session the open trace belongs to.
traceIdentity: [
(s) => [
@@ -384,12 +425,10 @@ export const tracingViewerLogic = kea<tracingViewerLogicType>([
},
openTrace: ({ traceId, ts }) => {
posthog.capture('tracing trace opened')
- const prefetchedSpans = values.spans.filter((s: Span) => s.trace_id === traceId)
// Fetch the trace by id when the prefetch can be incomplete. A batch with no root span is a
// cold link (no spans loaded) or an orphan trace, whose prefetch holds only the spans that
// matched the list. A full prefetch batch (>= PREFETCH_SPANS) may be truncated.
- const hasRootSpan = prefetchedSpans.some((s: Span) => s.is_root_span)
- if (!hasRootSpan || prefetchedSpans.length >= PREFETCH_SPANS) {
+ if (!isCompletePrefetch(values.spans, traceId)) {
actions.loadTraceSpans({ traceId, ts })
}
},