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): paginate trace waterfall with infinite scroll (#64251)

Frank Hamand0943897f64ff
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 24bf17b71489..d06bb2a0c72e 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -2897,8 +2897,9 @@ const api = {
serviceNames?: string[]
statusCodes?: number[]
filterGroup?: PropertyGroupFilter
+ offset?: number
}
- ): Promise<{ results: Record<string, any>[] }> {
+ ): Promise<{ results: Record<string, any>[]; hasMore: boolean; nextOffset?: number | null }> {
return new ApiRequest()
.tracingSpans()
.withAction(`trace/${traceId}`)
diff --git a/products/tracing/backend/logic.py b/products/tracing/backend/logic.py
index ecb2e00d8ca3..2cd80a517f83 100644
--- a/products/tracing/backend/logic.py
+++ b/products/tracing/backend/logic.py
@@ -622,6 +622,11 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra
# Root rows drive the displayed list order. Time sorts order them by timestamp; duration sorts
# by the per-trace duration window (constant within a trace, so spans of a trace stay grouped).
base_order = [parse_order_expr("is_root_span DESC"), parse_order_expr("matched_filter DESC")]
+ # The single-trace waterfall paginates *within* one trace: order its spans purely by start
+ # time so the per-trace `LIMIT BY` window is the first `prefetchSpans` spans by start time,
+ # and an `offset` pages through the rest (infinite scroll). The multi-trace list keeps its
+ # root/matched-first grouping so a trace's root and matching spans stay visible.
+ single_trace = self.query.traceId is not None
if by_duration:
query.order_by = [
*base_order,
@@ -629,12 +634,20 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra
parse_order_expr(f"trace_id {order_dir}"),
parse_order_expr("timestamp ASC"),
]
+ elif single_trace:
+ query.order_by = [
+ parse_order_expr(f"timestamp {order_dir}"),
+ parse_order_expr(f"span_id {order_dir}"),
+ ]
else:
query.order_by = [*base_order, parse_order_expr(f"timestamp {order_dir}")]
query.limit_by = ast.LimitByExpr(
n=ast.Constant(value=limit_by_n),
exprs=[ast.Field(chain=["trace_id"])],
+ # Within-trace offset paging — only meaningful for the single-trace waterfall (timestamp
+ # order). The paginator's own offset stays 0 in grouped mode, so these don't compound.
+ offset_value=ast.Constant(value=self.query.offset) if single_trace and self.query.offset else None,
)
return query
diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.py
index 5fb2a3293cad..8b6ed9d31ecd 100644
--- a/products/tracing/backend/presentation/views.py
+++ b/products/tracing/backend/presentation/views.py
@@ -224,6 +224,11 @@ class _TracingTraceRequestSerializer(serializers.Serializer):
default=False,
help_text="Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false.",
)
+ offset = serializers.IntegerField(
+ required=False,
+ min_value=0,
+ help_text="Pagination offset into the trace's spans (ordered by start time ascending). Each page returns up to 2000 spans; pass the response's `nextOffset` to load the next page. Defaults to 0.",
+ )
class _TracingServiceNamesQuerySerializer(serializers.Serializer):
@@ -542,6 +547,11 @@ class _SymbolStatsResponseSerializer(serializers.Serializer):
)
+# Spans returned per page by the single-trace `trace` endpoint. The waterfall fetches the first page
+# on open and pages through the rest via infinite scroll (offset pagination, earliest spans first).
+TRACE_SPANS_PAGE_SIZE = 2000
+
+
def _encode_after_cursor(timestamp: str, **secondary: str) -> str:
"""Encode a keyset `after` cursor as base64(json) of the boundary row's timestamp + secondary id.
@@ -1060,14 +1070,22 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
except (ValidationError, ValueError, ParseError):
filter_group = None
+ offset = max(int(query_data.get("offset") or 0), 0)
+
+ # The waterfall loads a trace one page at a time, earliest spans first, with infinite scroll
+ # fetching the next page. Order by start time ASC so a page is the first N spans by start
+ # time; fetch one extra to detect whether more pages remain.
spans_query = TraceSpansQuery(
dateRange=date_range,
traceId=trace_id,
serviceNames=query_data.get("serviceNames", None),
statusCodes=query_data.get("statusCodes", None),
filterGroup=filter_group,
- limit=1000,
- prefetchSpans=2000,
+ orderBy="timestamp",
+ orderDirection="ASC",
+ limit=1,
+ offset=offset,
+ prefetchSpans=TRACE_SPANS_PAGE_SIZE + 1,
rootSpans=False,
excludeAttributes=query_data.get("excludeAttributes", False),
)
@@ -1076,13 +1094,20 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
response = runner.run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
assert isinstance(response, TraceSpansQueryResponse | CachedTraceSpansQueryResponse)
- # Only this endpoint returns the (practically) full trace, so per-span self-time
- # is computable here — query results elsewhere see partial traces.
- if isinstance(response.results, list):
- annotate_self_time(response.results)
+ all_results = list(response.results) if isinstance(response.results, list) else []
+ has_more = len(all_results) > TRACE_SPANS_PAGE_SIZE
+ results = all_results[:TRACE_SPANS_PAGE_SIZE]
+
+ # Self-time needs a span's children present. On a paged (truncated) trace it overstates for
+ # spans whose children fall on a later page — an accepted bound, same as the prior 2000 cap.
+ annotate_self_time(results)
return Response(
- {"results": response.results},
+ {
+ "results": results,
+ "hasMore": has_more,
+ "nextOffset": offset + len(results) if has_more else None,
+ },
status=status.HTTP_200_OK,
)
diff --git a/products/tracing/backend/tests/test_trace_pagination.py b/products/tracing/backend/tests/test_trace_pagination.py
new file mode 100644
index 000000000000..0a0cc6933a17
--- /dev/null
+++ b/products/tracing/backend/tests/test_trace_pagination.py
@@ -0,0 +1,71 @@
+import datetime as dt
+
+from posthog.clickhouse.client import sync_execute
+
+from products.tracing.backend.presentation.views import TRACE_SPANS_PAGE_SIZE
+from products.tracing.backend.tests.test_keyset_pagination import _b64, _TraceSpansTestBase
+
+BASE = dt.datetime(2026, 6, 2, 8, 0, 0)
+SPAN_COUNT = TRACE_SPANS_PAGE_SIZE + 3 # spills past one page so paging actually kicks in
+
+
+class TestTracePagination(_TraceSpansTestBase):
+ @classmethod
+ def setUpTestData(cls):
+ super().setUpTestData()
+ cls._recreate_trace_spans_tables()
+
+ trace_id = _b64((1).to_bytes(16, "big"))
+ rows: list[str] = []
+ # span_no 1 is the root; the rest are children. Start time strictly increases with span_no so
+ # "first N by start time" is span_no 1..N — a deterministic ordering to assert against.
+ for span_no in range(1, SPAN_COUNT + 1):
+ span_id = _b64((100 + span_no).to_bytes(8, "big"))
+ parent = "" if span_no == 1 else _b64((101).to_bytes(8, "big"))
+ start = BASE + dt.timedelta(milliseconds=span_no)
+ end = start + dt.timedelta(milliseconds=1)
+ rows.append(
+ f"('019e8759-0000-0000-0001-{span_no:012d}', {cls.team.id}, '{trace_id}', "
+ f"'{span_id}', '{parent}', 'op-{span_no}', 2, "
+ f"'{start.strftime('%Y-%m-%d %H:%M:%S.%f')}', '{end.strftime('%Y-%m-%d %H:%M:%S.%f')}', "
+ f"'{start.strftime('%Y-%m-%d %H:%M:%S.%f')}', 0, 'web')"
+ )
+ sync_execute(
+ "INSERT INTO trace_spans (uuid, team_id, trace_id, span_id, parent_span_id, name, kind, "
+ "timestamp, end_time, observed_timestamp, status_code, service_name) VALUES " + ",".join(rows)
+ )
+
+ def _fetch_page(self, offset: int = 0) -> dict:
+ trace_hex = (1).to_bytes(16, "big").hex()
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/tracing/spans/trace/{trace_hex}/",
+ {
+ "dateRange": {"date_from": "2026-06-02T07:00:00Z", "date_to": "2026-06-02T09:00:00Z"},
+ "offset": offset,
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, 200, response.content)
+ return response.json()
+
+ def test_first_page_is_the_earliest_spans_by_start_time(self):
+ page = self._fetch_page()
+ names = [span["name"] for span in page["results"]]
+ self.assertEqual(len(names), TRACE_SPANS_PAGE_SIZE)
+ # The first page is exactly the earliest-starting spans (span_no 1..PAGE_SIZE), in order.
+ self.assertEqual(set(names), {f"op-{n}" for n in range(1, TRACE_SPANS_PAGE_SIZE + 1)})
+ self.assertTrue(page["hasMore"])
+ self.assertEqual(page["nextOffset"], TRACE_SPANS_PAGE_SIZE)
+
+ def test_second_page_returns_the_remainder_and_ends(self):
+ page = self._fetch_page(offset=TRACE_SPANS_PAGE_SIZE)
+ names = {span["name"] for span in page["results"]}
+ self.assertEqual(names, {f"op-{n}" for n in range(TRACE_SPANS_PAGE_SIZE + 1, SPAN_COUNT + 1)})
+ self.assertFalse(page["hasMore"])
+ self.assertIsNone(page["nextOffset"])
+
+ def test_pages_do_not_overlap(self):
+ first = {span["span_id"] for span in self._fetch_page()["results"]}
+ second = {span["span_id"] for span in self._fetch_page(offset=TRACE_SPANS_PAGE_SIZE)["results"]}
+ self.assertEqual(first & second, set())
+ self.assertEqual(len(first | second), SPAN_COUNT)
diff --git a/products/tracing/frontend/TraceWaterfallView.tsx b/products/tracing/frontend/TraceWaterfallView.tsx
index f24a7a359d0d..35b66bd51e74 100644
--- a/products/tracing/frontend/TraceWaterfallView.tsx
+++ b/products/tracing/frontend/TraceWaterfallView.tsx
@@ -2,6 +2,7 @@ import { CSSProperties, useCallback, useEffect, useMemo, useRef, useState } from
import { List, useDynamicRowHeight, useListRef } from 'react-window'
import { IconWarning } from '@posthog/icons'
+import { LemonButton, Spinner } from '@posthog/lemon-ui'
import { getSeriesColor } from 'lib/colors'
import { AutoSizer } from 'lib/components/AutoSizer'
@@ -15,6 +16,11 @@ interface TraceWaterfallViewProps {
/** Currently-selected span (controlled by the scene's URL-canonical state). */
selectedSpanId?: string | null
onSpanSelect?: (spanId: string | null) => void
+ /** The trace has more spans than are loaded — show the infinite-scroll affordance at the bottom. */
+ hasMore?: boolean
+ /** A next page of spans is being fetched. */
+ loadingMore?: boolean
+ onLoadMore?: () => void
}
interface SpanNode {
@@ -147,6 +153,8 @@ const LABEL_SPLITTER_HIT_PX = 8
const ROW_HEIGHT = 32
// Cap the windowed list viewport; taller traces scroll inside it instead of growing the modal.
const MAX_WATERFALL_HEIGHT = 600
+// Fetch the next page once the bottom of the rendered window is within this many rows of the end.
+const LOAD_MORE_THRESHOLD = 10
// Rough extra room reserved when a span's detail panel is open, so a selection near the top of a
// short trace doesn't pop an unexpected scrollbar.
@@ -433,6 +441,9 @@ export function TraceWaterfallView({
spans,
selectedSpanId = null,
onSpanSelect,
+ hasMore = false,
+ loadingMore = false,
+ onLoadMore,
}: TraceWaterfallViewProps): JSX.Element {
const [cursorPct, setCursorPct] = useState<number | null>(null)
const [labelColumnWidth, setLabelColumnWidth] = useState(
@@ -453,6 +464,24 @@ export function TraceWaterfallView({
const dynamicRowHeight = useDynamicRowHeight({ defaultRowHeight: ROW_HEIGHT })
const listRef = useListRef(null)
+ // Infinite scroll: fetch the next page once the rendered window nears the end of the loaded spans.
+ const handleRowsRendered = useCallback(
+ (
+ _visibleRows: { startIndex: number; stopIndex: number },
+ allRows: { startIndex: number; stopIndex: number }
+ ): void => {
+ if (
+ onLoadMore &&
+ hasMore &&
+ !loadingMore &&
+ allRows.stopIndex >= flatSpans.length - 1 - LOAD_MORE_THRESHOLD
+ ) {
+ onLoadMore()
+ }
+ },
+ [onLoadMore, hasMore, loadingMore, flatSpans.length]
+ )
+
// Deep links land with a span anchor — scroll it into view once the tree is built. The anchor
// is captured at mount (the drawer keys this component by trace, so it remounts per trace) so
// later selection changes from clicking don't recenter, and data refreshes (full-trace fetch
@@ -694,11 +723,29 @@ export function TraceWaterfallView({
onSelect: handleSelect,
dynamicRowHeight,
}}
+ onRowsRendered={handleRowsRendered}
listRef={listRef}
/>
)}
/>
+ {/* Infinite-scroll footer: a trace can exceed the per-page span cap, so page the rest in
+ as the user scrolls to the bottom. The button is a manual fallback to the auto-trigger. */}
+ {hasMore && (
+ <div className="flex items-center justify-center gap-2 py-2 text-xs text-muted border-t border-border">
+ {loadingMore ? (
+ <>
+ <Spinner />
+ <span>Loading more spans…</span>
+ </>
+ ) : (
+ <LemonButton size="xsmall" type="tertiary" onClick={() => onLoadMore?.()}>
+ Load more spans
+ </LemonButton>
+ )}
+ </div>
+ )}
+
{/* Full-height splitter between label column and timeline */}
<div
role="separator"
diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsx
index de591053a069..bf9fd89697b4 100644
--- a/products/tracing/frontend/TracingScene.tsx
+++ b/products/tracing/frontend/TracingScene.tsx
@@ -56,6 +56,8 @@ function TracingSceneContents(): JSX.Element {
totalSpansMatchingFilters,
openTraceSpans,
isLoadingFullTrace,
+ canLoadMoreTraceSpans,
+ traceSpansLoadingMore,
aggregation,
aggregationLoading,
filters,
@@ -81,6 +83,7 @@ function TracingSceneContents(): JSX.Element {
openCompareFlame,
closeCompareFlame,
fetchNextPage,
+ loadMoreTraceSpans,
setVisibleRowRange,
toggleExpandSpan,
setSort,
@@ -219,6 +222,9 @@ function TracingSceneContents(): JSX.Element {
ts={selectedTraceTs}
spans={openTraceSpans}
loading={isLoadingFullTrace}
+ hasMoreSpans={canLoadMoreTraceSpans}
+ loadingMoreSpans={traceSpansLoadingMore}
+ onLoadMoreSpans={loadMoreTraceSpans}
selectedSpanId={selectedSpanId}
onSelectSpan={selectSpan}
onClose={closeTrace}
diff --git a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx
index 80b95130aef8..d1b189b77ef2 100644
--- a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx
+++ b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx
@@ -34,6 +34,11 @@ export interface TraceDrawerProps {
ts: string | null
spans: Span[]
loading: 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). */
+ loadingMoreSpans?: boolean
+ onLoadMoreSpans?: () => void
selectedSpanId: string | null
onSelectSpan: (spanId: string | null) => void
onClose: () => void
@@ -49,6 +54,9 @@ export function TraceDrawer({
ts,
spans,
loading,
+ hasMoreSpans = false,
+ loadingMoreSpans = false,
+ onLoadMoreSpans,
selectedSpanId,
onSelectSpan,
onClose,
@@ -129,6 +137,9 @@ export function TraceDrawer({
spans={spans}
selectedSpanId={selectedSpanId}
onSpanSelect={onSelectSpan}
+ hasMore={hasMoreSpans}
+ loadingMore={loadingMoreSpans}
+ onLoadMore={onLoadMoreSpans}
/>
</div>
<div
diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.ts
index 730e90c5eee2..67b679a5d4cc 100644
--- a/products/tracing/frontend/generated/api.schemas.ts
+++ b/products/tracing/frontend/generated/api.schemas.ts
@@ -438,6 +438,11 @@ export interface _TracingTraceRequestApi {
dateRange?: _TracingDateRangeApi
/** Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false. */
excludeAttributes?: boolean
+ /**
+ * Pagination offset into the trace's spans (ordered by start time ascending). Each page returns up to 2000 spans; pass the response's `nextOffset` to load the next page. Defaults to 0.
+ * @minimum 0
+ */
+ offset?: number
}
export interface _TracingTreeQueryBodyApi {
diff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.ts
index b9fd26be4229..01c577b0135c 100644
--- a/products/tracing/frontend/generated/api.zod.ts
+++ b/products/tracing/frontend/generated/api.zod.ts
@@ -611,6 +611,7 @@ export const TracingSpansSymbolStatsCreateBody = /* @__PURE__ */ zod.object({
})
export const tracingSpansTraceCreateBodyExcludeAttributesDefault = false
+export const tracingSpansTraceCreateBodyOffsetMin = 0
export const TracingSpansTraceCreateBody = /* @__PURE__ */ zod.object({
dateRange: zod
@@ -634,6 +635,13 @@ export const TracingSpansTraceCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false.'
),
+ offset: zod
+ .number()
+ .min(tracingSpansTraceCreateBodyOffsetMin)
+ .optional()
+ .describe(
+ "Pagination offset into the trace's spans (ordered by start time ascending). Each page returns up to 2000 spans; pass the response's `nextOffset` to load the next page. Defaults to 0."
+ ),
})
export const tracingSpansTreeCreateBodyQueryOneCompareFilterOneCompareDefault = false
diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.ts
index f521ea767cf5..a54ec1cbd997 100644
--- a/products/tracing/frontend/tracingDataLogic.ts
+++ b/products/tracing/frontend/tracingDataLogic.ts
@@ -55,6 +55,23 @@ function isUserInitiatedError(error: unknown): boolean {
return error === NEW_QUERY_STARTED_ERROR_MESSAGE || errorStr.includes('abort')
}
+// A ts hint (from a shared/cold link) bounds the lookup tightly around the trace instead of the
+// scene's current date range — the table is time-keyed, so this is what keeps an id lookup from
+// scanning the whole window. Guard validity: a hand-edited/corrupted ts would otherwise make dayjs
+// throw on toISOString().
+function resolveTraceLookupRange(
+ ts: string | null | undefined,
+ utcDateRange: { date_from?: string | null; date_to?: string | null }
+): { date_from?: string | null; date_to?: string | null } {
+ if (ts && dayjs(ts).isValid()) {
+ return traceLookupDateRange(ts)
+ }
+ return {
+ date_from: utcDateRange.date_from ?? '-24h',
+ date_to: utcDateRange.date_to ?? undefined,
+ }
+}
+
function captureTracingResults(count: number, queryType: 'spans' | 'aggregation'): void {
if (count === 0) {
posthog.capture('tracing no results returned', { query_type: queryType })
@@ -73,6 +90,8 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
actions({
runQuery: true,
fetchNextPage: true,
+ loadMoreTraceSpans: true,
+ setTracePagination: (hasMore: boolean, nextOffset: number | null) => ({ hasMore, nextOffset }),
clearSpans: true,
cancelInProgressSpans: (controller: AbortController | null) => ({ controller }),
cancelInProgressSparkline: (controller: AbortController | null) => ({ controller }),
@@ -202,6 +221,46 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
clearSpans: () => null,
},
],
+ // Whether the open trace has more spans than the loaded pages (drives the waterfall's
+ // infinite scroll). Reset on every fresh trace open so a small trace can't inherit a
+ // previous trace's "load more" affordance.
+ traceSpansHasMore: [
+ false as boolean,
+ {
+ setTracePagination: (_, { hasMore }) => hasMore,
+ loadTraceSpans: () => false,
+ },
+ ],
+ // Offset to request for the next waterfall page (count of spans already loaded for the trace).
+ traceSpansNextOffset: [
+ 0 as number,
+ {
+ setTracePagination: (_, { nextOffset }) => nextOffset ?? 0,
+ loadTraceSpans: () => 0,
+ },
+ ],
+ // The trace + ts the loaded spans belong to, so `loadMoreTraceSpans` can refetch the next
+ // page with the same lookup window without re-deriving it from a since-shifted date range.
+ traceLoadContext: [
+ null as { traceId: string; ts?: string | null } | null,
+ {
+ loadTraceSpans: (_, { traceId, ts }) => ({ traceId, ts }),
+ clearSpans: () => null,
+ },
+ ],
+ // 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: [
+ false as boolean,
+ {
+ loadMoreTraceSpans: () => true,
+ loadMoreTraceSpansSuccess: () => false,
+ loadMoreTraceSpansFailure: () => false,
+ // A fresh trace fetch must show the full-trace overlay even if a stale load-more is
+ // still in flight.
+ loadTraceSpans: () => false,
+ },
+ ],
}),
loaders(({ values, actions }) => ({
@@ -273,24 +332,35 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
[] as Span[],
{
loadTraceSpans: async ({ traceId, ts }: { traceId: string; ts?: string | null }): Promise<Span[]> => {
- // A ts hint (from a shared/cold link) bounds the lookup tightly around the trace
- // instead of the scene's current date range — the table is time-keyed, so this is
- // what keeps an id lookup from scanning the whole window. Guard validity: a
- // hand-edited/corrupted ?ts= would otherwise make dayjs throw on toISOString().
- const dateRange =
- ts && dayjs(ts).isValid()
- ? traceLookupDateRange(ts)
- : {
- date_from: values.utcDateRange.date_from ?? '-24h',
- date_to: values.utcDateRange.date_to ?? undefined,
- }
const response = await api.tracing.getTrace(traceId, {
- dateRange,
+ dateRange: resolveTraceLookupRange(ts, values.utcDateRange),
serviceNames: values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,
filterGroup: values.filters.filterGroup as PropertyGroupFilter,
})
+ actions.setTracePagination(!!response.hasMore, response.nextOffset ?? null)
return response.results as Span[]
},
+ // Infinite scroll: page in the next batch of the open trace's spans (earliest first)
+ // and append. Guarded so a trailing scroll event after the last page is a no-op.
+ loadMoreTraceSpans: async (): Promise<Span[]> => {
+ if (!values.traceSpansHasMore || !values.traceLoadContext) {
+ return values.traceSpans
+ }
+ const { traceId, ts } = values.traceLoadContext
+ const response = await api.tracing.getTrace(traceId, {
+ dateRange: resolveTraceLookupRange(ts, values.utcDateRange),
+ serviceNames: values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,
+ filterGroup: values.filters.filterGroup as PropertyGroupFilter,
+ offset: values.traceSpansNextOffset,
+ })
+ // Bail if a new trace was opened mid-fetch — appending this stale page to the new
+ // trace's spans would corrupt the waterfall.
+ if (values.traceLoadContext?.traceId !== traceId) {
+ return values.traceSpans
+ }
+ actions.setTracePagination(!!response.hasMore, response.nextOffset ?? null)
+ return [...values.traceSpans, ...(response.results as Span[])]
+ },
},
],
spanTree: [
@@ -635,6 +705,11 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
lemonToast.error(`Failed to load call tree: ${error}`)
}
},
+ loadMoreTraceSpansFailure: ({ error }) => {
+ if (!isUserInitiatedError(error)) {
+ lemonToast.error(`Failed to load more spans: ${error}`)
+ }
+ },
})),
events(({ values }) => ({
diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.ts
index 7340fefd1747..abd6d55ec876 100644
--- a/products/tracing/frontend/tracingSceneLogic.ts
+++ b/products/tracing/frontend/tracingSceneLogic.ts
@@ -38,6 +38,8 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
'totalSpansMatchingFilters',
'traceSpans',
'traceSpansLoading',
+ 'traceSpansLoadingMore',
+ 'traceSpansHasMore',
'aggregation',
'aggregationLoading',
'spanTree',
@@ -53,7 +55,15 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
],
actions: [
tracingDataLogic(),
- ['runQuery', 'fetchNextPage', 'loadTraceSpans', 'fetchAggregation', 'fetchSpanTree', 'setVisibleRowRange'],
+ [
+ 'runQuery',
+ 'fetchNextPage',
+ 'loadTraceSpans',
+ 'loadMoreTraceSpans',
+ 'fetchAggregation',
+ 'fetchSpanTree',
+ 'setVisibleRowRange',
+ ],
tracingFiltersLogic(),
[
'setDateRange',
@@ -157,7 +167,22 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
return spans.filter((s) => s.trace_id === selectedTraceId)
},
],
- isLoadingFullTrace: [(s) => [s.traceSpansLoading], (traceSpansLoading: boolean): boolean => traceSpansLoading],
+ // 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[] => [
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a2ae28deb976..6ebfb5ee35c6 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -49007,6 +49007,11 @@ export namespace Schemas {
dateRange?: _TracingDateRange;
/** Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false. */
excludeAttributes?: boolean;
+ /**
+ * Pagination offset into the trace's spans (ordered by start time ascending). Each page returns up to 2000 spans; pass the response's `nextOffset` to load the next page. Defaults to 0.
+ * @minimum 0
+ */
+ offset?: number;
}
export interface _TracingTreeQueryBody {
diff --git a/services/mcp/src/generated/tracing/api.ts b/services/mcp/src/generated/tracing/api.ts
index b6982fc581ac..8d290975b125 100644
--- a/services/mcp/src/generated/tracing/api.ts
+++ b/services/mcp/src/generated/tracing/api.ts
@@ -675,6 +675,7 @@ export const TracingSpansTraceCreateParams = /* @__PURE__ */ zod.object({
})
export const tracingSpansTraceCreateBodyExcludeAttributesDefault = false
+export const tracingSpansTraceCreateBodyOffsetMin = 0
export const TracingSpansTraceCreateBody = /* @__PURE__ */ zod.object({
dateRange: zod
@@ -698,6 +699,13 @@ export const TracingSpansTraceCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false.'
),
+ offset: zod
+ .number()
+ .min(tracingSpansTraceCreateBodyOffsetMin)
+ .optional()
+ .describe(
+ "Pagination offset into the trace's spans (ordered by start time ascending). Each page returns up to 2000 spans; pass the response's `nextOffset` to load the next page. Defaults to 0."
+ ),
})
export const TracingSpansTreeCreateParams = /* @__PURE__ */ zod.object({
diff --git a/services/mcp/src/tools/generated/tracing.ts b/services/mcp/src/tools/generated/tracing.ts
index 99a6b6dd4623..f6199414d026 100644
--- a/services/mcp/src/tools/generated/tracing.ts
+++ b/services/mcp/src/tools/generated/tracing.ts
@@ -229,6 +229,9 @@ const apmTraceGet = (): ToolBase<typeof ApmTraceGetSchema, unknown> =>
if (params.excludeAttributes !== undefined) {
body['excludeAttributes'] = params.excludeAttributes
}
+ if (params.offset !== undefined) {
+ body['offset'] = params.offset
+ }
const result = await context.api.request<unknown>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/tracing/spans/trace/${encodeURIComponent(String(params.trace_id))}/`,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-trace-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-trace-get.json
index 120a831114dd..2409fad3870f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-trace-get.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-trace-get.json
@@ -34,6 +34,11 @@
"description": "Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false.",
"type": "boolean"
},
+ "offset": {
+ "description": "Pagination offset into the trace's spans (ordered by start time ascending). Each page returns up to 2000 spans; pass the response's `nextOffset` to load the next page. Defaults to 0.",
+ "minimum": 0,
+ "type": "number"
+ },
"trace_id": {
"pattern": "^[a-zA-Z0-9]+$",
"type": "string"