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): order span list by duration via offset paging (#62651)

Jon McCallum6d8ccbf84a76
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 12489e4018f7..5b147ad5b884 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -2863,9 +2863,11 @@ const api = {
serviceNames?: string[]
statusCodes?: number[]
filterGroup?: PropertyGroupFilter
- orderBy?: 'latest' | 'earliest'
+ orderBy?: 'timestamp' | 'duration'
+ orderDirection?: 'ASC' | 'DESC'
limit?: number
after?: string
+ offset?: number
prefetchSpans?: number
},
signal?: AbortSignal
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 4d03ebb10546..219fc9bcd3ca 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -41424,6 +41424,11 @@
},
"type": "object"
},
+ "TraceOrderColumn": {
+ "description": "Columns the trace list can be ordered by (allowlisted — fed straight into `ORDER BY`).",
+ "enum": ["timestamp", "duration"],
+ "type": "string"
+ },
"TraceQuery": {
"additionalProperties": false,
"properties": {
@@ -41659,7 +41664,13 @@
"$ref": "#/definitions/integer"
},
"orderBy": {
- "$ref": "#/definitions/LogsOrderBy"
+ "$ref": "#/definitions/TraceOrderColumn",
+ "description": "Column to order by. Defaults to timestamp. `timestamp` paginates via keyset cursor (`after`); other columns via `offset`."
+ },
+ "orderDirection": {
+ "description": "Order direction. Defaults to DESC.",
+ "enum": ["ASC", "DESC"],
+ "type": "string"
},
"prefetchSpans": {
"$ref": "#/definitions/integer",
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index e38bbc2fe375..49d6119553c2 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -3056,6 +3056,9 @@ export type LogsSparklineBreakdownBy = 'severity' | 'service'
/** @title LogsOrderBy */
export type LogsOrderBy = 'latest' | 'earliest'
+/** Columns the trace list can be ordered by (allowlisted — fed straight into `ORDER BY`). */
+export type TraceOrderColumn = 'timestamp' | 'duration'
+
/**
* Filter criteria for a logs alert configuration. Subset of LogsViewerFilters
* (excludes dateRange). At least one of `severityLevels`, `serviceNames`, or
@@ -3195,7 +3198,10 @@ export interface TraceSpansQuery extends DataNode<TraceSpansQueryResponse> {
dateRange: DateRange
limit?: integer
offset?: integer
- orderBy?: LogsOrderBy
+ /** Column to order by. Defaults to timestamp. `timestamp` paginates via keyset cursor (`after`); other columns via `offset`. */
+ orderBy?: TraceOrderColumn
+ /** Order direction. Defaults to DESC. */
+ orderDirection?: 'ASC' | 'DESC'
filterGroup?: PropertyGroupFilter
serviceNames?: string[]
statusCodes?: integer[]
diff --git a/posthog/schema.py b/posthog/schema.py
index d013271e8954..3692e621d3cd 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -5233,6 +5233,11 @@ class TraceNeighborsQueryResponse(BaseModel):
)
+class TraceOrderColumn(StrEnum):
+ TIMESTAMP = "timestamp"
+ DURATION = "duration"
+
+
class DetailedResultsAggregationType(StrEnum):
TOTAL = "total"
AVERAGE = "average"
@@ -24494,7 +24499,14 @@ class TraceSpansQuery(BaseModel):
limit: int | None = None
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
offset: int | None = None
- orderBy: LogsOrderBy | None = None
+ orderBy: TraceOrderColumn | None = Field(
+ default=None,
+ description=(
+ "Column to order by. Defaults to timestamp. `timestamp` paginates via"
+ " keyset cursor (`after`); other columns via `offset`."
+ ),
+ )
+ orderDirection: OrderDirection2 | None = Field(default=None, description="Order direction. Defaults to DESC.")
prefetchSpans: int | None = Field(
default=None,
description=("Prefetch up to this many spans per trace and include them in results"),
diff --git a/products/tracing/backend/logic.py b/products/tracing/backend/logic.py
index 5799b7e3d6b6..71fbc9bcb938 100644
--- a/products/tracing/backend/logic.py
+++ b/products/tracing/backend/logic.py
@@ -359,6 +359,9 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra
"trace_start": (result[13] or result[8]).replace(tzinfo=ZoneInfo("UTC")),
# OTel span attributes the user set, as a key-value map.
"attributes": result[14],
+ # Per-trace duration key (max matching-span duration); the offset-pagination key for
+ # the slowest/fastest sorts. Falls back to this row's own duration.
+ "trace_duration": result[15] if result[15] is not None else result[10],
}
results.append(row)
@@ -369,6 +372,11 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra
assert isinstance(response, TraceSpansQueryResponse | CachedTraceSpansQueryResponse)
return response
+ @property
+ def _by_duration(self) -> bool:
+ """Ordering by duration paginates via offset; ordering by timestamp via the time keyset."""
+ return self.query.orderBy == "duration"
+
def _parse_after_cursor(self) -> tuple[dt.datetime, str] | None:
"""Decode the opaque `after` cursor into (trace_start_ts, trace_id_base64).
@@ -387,16 +395,17 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra
return cursor_ts, cursor_trace_id_b64
def to_query(self) -> ast.SelectQuery:
- order_dir = "ASC" if self.query.orderBy == "earliest" else "DESC"
+ by_duration = self._by_duration
+ order_dir = "ASC" if self.query.orderDirection == "ASC" else "DESC"
limit_by_n = self.query.prefetchSpans or 1
- # The list paginates by trace, ordered by each trace's start time (its earliest span, i.e.
- # the root). We GROUP BY trace_id so the keyset cursor lands on a stable per-trace key —
- # `LIMIT 1 BY trace_id` can't keyset cleanly because a multi-span trace straddling the
- # cursor would be re-selected via its other spans.
- cursor = self._parse_after_cursor()
- op = ">" if self.query.orderBy == "earliest" else "<"
- ts_op = ">=" if self.query.orderBy == "earliest" else "<="
+ # The list paginates by trace. We GROUP BY trace_id so the page key lands on a stable
+ # per-trace value — `LIMIT 1 BY trace_id` can't paginate cleanly because a multi-span trace
+ # straddling the boundary would be re-selected via its other spans. Time sorts order by each
+ # trace's start time (`min(timestamp)`) and keyset on it; duration sorts order by trace
+ # duration (`max(duration_nano)`) and offset-paginate (the time index can't prune a duration
+ # order, so keyset would pay its cost for none of its benefit).
+ sort_key_sql = "max(duration_nano)" if by_duration else "min(timestamp)"
# rootSpans is opt-in and gated on `is True` (not truthiness): the frontend never sends it
# (None), so its prefetch-driven waterfall is untouched. An explicit True narrows the
@@ -408,26 +417,31 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra
subquery_where_exprs: list[ast.Expr] = [self.where()]
if root_only:
subquery_where_exprs.append(parse_expr("is_root_span = 1"))
+
having_expr: ast.Expr | None = None
- if cursor is not None:
- cursor_ts, cursor_trace_id = cursor
- # Coarse day bound on time_bucket lets ClickHouse prune parts via the primary index.
- # Pin both sides to UTC for the same reason as the where() date bound: the cursor
- # constant prints UTC-pinned, so an unpinned toStartOfDay would truncate on the
- # session-tz day grid and drop same-day rows under a non-UTC session.
- subquery_where_exprs.append(
- parse_expr(
- f"toStartOfDay(time_bucket, 'UTC') {ts_op} toStartOfDay({{cursor_ts}}, 'UTC')",
- placeholders={"cursor_ts": ast.Constant(value=cursor_ts)},
+ if not by_duration:
+ cursor = self._parse_after_cursor()
+ op = ">" if order_dir == "ASC" else "<"
+ ts_op = ">=" if order_dir == "ASC" else "<="
+ if cursor is not None:
+ cursor_ts, cursor_trace_id = cursor
+ # Coarse day bound on time_bucket lets ClickHouse prune parts via the primary index.
+ # Pin both sides to UTC for the same reason as the where() date bound: the cursor
+ # constant prints UTC-pinned, so an unpinned toStartOfDay would truncate on the
+ # session-tz day grid and drop same-day rows under a non-UTC session.
+ subquery_where_exprs.append(
+ parse_expr(
+ f"toStartOfDay(time_bucket, 'UTC') {ts_op} toStartOfDay({{cursor_ts}}, 'UTC')",
+ placeholders={"cursor_ts": ast.Constant(value=cursor_ts)},
+ )
+ )
+ having_expr = parse_expr(
+ f"(min(timestamp), trace_id) {op} ({{cursor_ts}}, {{cursor_trace_id}})",
+ placeholders={
+ "cursor_ts": ast.Constant(value=cursor_ts),
+ "cursor_trace_id": ast.Constant(value=cursor_trace_id),
+ },
)
- )
- having_expr = parse_expr(
- f"(min(timestamp), trace_id) {op} ({{cursor_ts}}, {{cursor_trace_id}})",
- placeholders={
- "cursor_ts": ast.Constant(value=cursor_ts),
- "cursor_trace_id": ast.Constant(value=cursor_trace_id),
- },
- )
subquery_where = (
subquery_where_exprs[0] if len(subquery_where_exprs) == 1 else ast.And(exprs=subquery_where_exprs)
@@ -450,18 +464,25 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra
assert isinstance(trace_id_query, ast.SelectQuery)
trace_id_query.order_by = [
- parse_order_expr(f"min(timestamp) {order_dir}"),
+ parse_order_expr(f"{sort_key_sql} {order_dir}"),
parse_order_expr(f"trace_id {order_dir}"),
]
if having_expr is not None:
trace_id_query.having = having_expr
+ if by_duration and self.query.offset:
+ trace_id_query.offset = ast.Constant(value=self.query.offset)
+
+ # `trace_start` / `trace_duration` are the per-trace keys the view paginates and re-sorts on.
+ # They MUST aggregate over the same rows the trace-selection subquery grouped, or the keys
+ # diverge from the set the subquery picked — e.g. under root_only the subquery orders traces
+ # by `max(duration_nano)` over root spans, so a window over *all* spans would rank a trace by
+ # a long child the subquery never considered, corrupting the order and offset page boundaries.
+ # Scope the key windows to match the subquery (cursor/time bounds are deliberately excluded —
+ # the key is a property of the whole trace, not of the current page).
+ key_predicate: ast.Expr = self.where()
+ if root_only:
+ key_predicate = ast.And(exprs=[self.where(), parse_expr("is_root_span = 1")])
- # `trace_start` is the per-trace pagination key — the earliest timestamp among the spans
- # matching the filters, i.e. exactly what the subquery's `min(timestamp)` HAVING/ORDER BY
- # uses. Computing it here as a window over the (untruncated) span set lets the view read the
- # SQL key directly instead of re-deriving min() over the prefetched spans, which is wrong
- # for a trace whose earliest span isn't in the prefetched slice (e.g. a rootless trace with
- # prefetchSpans > 1 and orderBy="latest").
query = parse_select(
"""
SELECT
@@ -479,13 +500,14 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra
is_root_span,
{where} as matched_filter,
min(if({where_for_start}, timestamp, NULL)) OVER (PARTITION BY trace_id) as trace_start,
- {attributes}
+ {attributes},
+ max(if({where_for_start}, duration_nano, NULL)) OVER (PARTITION BY trace_id) as trace_duration
FROM posthog.trace_spans
WHERE {filters} AND trace_id IN ({trace_id_query}) LIMIT {limit}
""",
placeholders={
"where": self.where(),
- "where_for_start": self.where(),
+ "where_for_start": key_predicate,
"trace_id_query": trace_id_query,
"limit": ast.Constant(value=(self.query.limit or 1) * limit_by_n),
"filters": ast.Placeholder(expr=ast.Field(chain=["filters"])),
@@ -497,11 +519,18 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra
)
assert isinstance(query, ast.SelectQuery)
- query.order_by = [
- parse_order_expr("is_root_span DESC"),
- parse_order_expr("matched_filter DESC"),
- parse_order_expr(f"timestamp {order_dir}"),
- ]
+ # 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")]
+ if by_duration:
+ query.order_by = [
+ *base_order,
+ parse_order_expr(f"trace_duration {order_dir}"),
+ parse_order_expr(f"trace_id {order_dir}"),
+ parse_order_expr("timestamp ASC"),
+ ]
+ 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),
diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.py
index c39b24a11eff..e3ed9cfc87c9 100644
--- a/products/tracing/backend/presentation/views.py
+++ b/products/tracing/backend/presentation/views.py
@@ -12,7 +12,6 @@ No business logic here - that belongs in logic.py via the facade.
import json
import base64
-import datetime as dt
from drf_spectacular.utils import extend_schema
from pydantic import ValidationError
@@ -111,9 +110,17 @@ class _TracingQueryBodySerializer(serializers.Serializer):
help_text="Filter by HTTP status codes.",
)
orderBy = serializers.ChoiceField(
- choices=["latest", "earliest"],
+ choices=["timestamp", "duration"],
required=False,
- help_text="Order results by timestamp. Defaults to latest.",
+ help_text=(
+ "Column to order by. Defaults to timestamp. Ordering by timestamp paginates via the keyset "
+ "cursor ('after'); ordering by duration paginates via 'offset'."
+ ),
+ )
+ orderDirection = serializers.ChoiceField(
+ choices=["ASC", "DESC"],
+ required=False,
+ help_text="Order direction. Defaults to DESC (e.g. timestamp+DESC = newest first, duration+DESC = slowest first).",
)
filterGroup = serializers.ListField(
child=_SpanPropertyFilterSerializer(),
@@ -132,7 +139,12 @@ class _TracingQueryBodySerializer(serializers.Serializer):
)
after = serializers.CharField(
required=False,
- help_text="Pagination cursor from previous response.",
+ help_text="Keyset pagination cursor from a previous timestamp-ordered response.",
+ )
+ offset = serializers.IntegerField(
+ required=False,
+ min_value=0,
+ help_text="Pagination offset, used when ordering by a column (e.g. duration). Defaults to 0.",
)
rootSpans = serializers.BooleanField(
required=False,
@@ -372,9 +384,13 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
date_range = self.get_model(query_data.get("dateRange", {"date_from": "-1h"}), DateRange)
order_by = query_data.get("orderBy")
- if order_by not in ("earliest", "latest"):
- order_by = "latest"
+ if order_by not in ("timestamp", "duration"):
+ order_by = "timestamp"
+ order_direction = query_data.get("orderDirection")
+ if order_direction not in ("ASC", "DESC"):
+ order_direction = "DESC"
+ offset = query_data.get("offset") or 0
requested_limit = min(query_data.get("limit", 100), 1000)
prefetch_spans = query_data.get("prefetchSpans", None)
if prefetch_spans is not None:
@@ -391,9 +407,11 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
serviceNames=query_data.get("serviceNames", None),
statusCodes=query_data.get("statusCodes", None),
orderBy=order_by,
+ orderDirection=order_direction,
filterGroup=filter_group,
traceId=query_data.get("traceId", None),
limit=requested_limit + 1,
+ offset=offset,
after=after_cursor,
rootSpans=query_data.get("rootSpans", True),
prefetchSpans=prefetch_spans,
@@ -405,25 +423,29 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
assert isinstance(response, TraceSpansQueryResponse | CachedTraceSpansQueryResponse)
all_results = list(response.results)
- # Paginate at the trace level. The runner fetched up to requested_limit + 1 traces ordered
- # by start time; decide hasMore on the trace count, drop the spans of the overflow trace,
- # and emit a cursor pointing at the last kept trace. `trace_start` is the SQL pagination key
- # carried on every span row (see TraceSpansQueryRunner.to_query) — read it directly rather
- # than re-deriving min() over the prefetched spans, which can disagree with the SQL key.
- earliest_first = order_by == "earliest"
- trace_start: dict[str, dt.datetime] = {span["trace_id"]: span["trace_start"] for span in all_results}
+ # Paginate at the trace level. The runner fetched up to requested_limit + 1 traces; decide
+ # hasMore on the trace count and drop the spans of the overflow trace. Ordering by timestamp
+ # emits a keyset cursor pointing at the last kept trace; ordering by duration paginates via
+ # `offset` instead, so no cursor is emitted. The per-trace sort key (`trace_start` /
+ # `trace_duration`) is carried on every span row (see TraceSpansQueryRunner.to_query) — read it
+ # directly rather than re-deriving over the prefetched spans, which can disagree with the SQL key.
+ by_duration = order_by == "duration"
+ descending = order_direction == "DESC"
+ sort_key = "trace_duration" if by_duration else "trace_start"
+ trace_keys: dict[str, object] = {span["trace_id"]: span[sort_key] for span in all_results}
ordered_traces = sorted(
- trace_start.items(),
+ trace_keys.items(),
key=lambda item: (item[1], base64.b64encode(bytes.fromhex(item[0])).decode("ascii")),
- reverse=not earliest_first,
+ reverse=descending,
)
has_more = len(ordered_traces) > requested_limit
kept_trace_ids = {tid for tid, _ in ordered_traces[:requested_limit]}
results = [span for span in all_results if span["trace_id"] in kept_trace_ids]
+ # Duration ordering paginates via `offset`; only the timestamp keyset emits an `after` cursor.
next_cursor = None
- if has_more:
+ if has_more and not by_duration:
boundary_trace_id, boundary_ts = ordered_traces[requested_limit - 1]
next_cursor = base64.b64encode(
json.dumps({"timestamp": boundary_ts.isoformat(), "trace_id": boundary_trace_id}).encode("utf-8")
@@ -440,7 +462,8 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
"service_names_count": len(query_data.get("serviceNames") or []),
"status_codes_count": len(query_data.get("statusCodes") or []),
"order_by": order_by,
- "is_paginated": bool(after_cursor),
+ "order_direction": order_direction,
+ "is_paginated": bool(after_cursor) or bool(offset),
},
team=self.team,
request=request,
diff --git a/products/tracing/backend/tests/test_exclude_attributes.py b/products/tracing/backend/tests/test_exclude_attributes.py
index 892361daf297..83f1be672704 100644
--- a/products/tracing/backend/tests/test_exclude_attributes.py
+++ b/products/tracing/backend/tests/test_exclude_attributes.py
@@ -60,7 +60,7 @@ class TestExcludeAttributes(ClickhouseTestMixin, APIBaseTest):
def _run(self, *, exclude: bool) -> list[dict]:
query = TraceSpansQuery(
dateRange=DateRange(date_from=DATE_FROM, date_to=DATE_TO),
- orderBy="latest",
+ orderBy="timestamp",
limit=100,
excludeAttributes=exclude,
)
diff --git a/products/tracing/backend/tests/test_keyset_pagination.py b/products/tracing/backend/tests/test_keyset_pagination.py
index 2401d4991fe8..d7e40120f854 100644
--- a/products/tracing/backend/tests/test_keyset_pagination.py
+++ b/products/tracing/backend/tests/test_keyset_pagination.py
@@ -18,27 +18,20 @@ from posthog.clickhouse.traces.spans import TRACE_SPANS_DISTRIBUTED_TABLE_SQL, T
from products.tracing.backend.logic import TraceSpansQueryRunner
-# 150 same-day root traces (i=0..149), timestamps increasing with i, newest-first ordering.
-# The 100th newest is i=50, so page 2 (after that cursor) should yield i=0..49 = 50 distinct traces.
-TOTAL_TRACES = 150
-PAGE_SIZE = 100
-CURSOR_INDEX = 50
DATE_FROM = "2026-06-02T07:00:00Z"
DATE_TO = "2026-06-02T09:00:00Z"
-CURSOR_TS_ISO = "2026-06-02T08:00:50+00:00"
-CURSOR_TRACE_ID_HEX = format(CURSOR_INDEX, "032x")
def _b64(raw: bytes) -> str:
return base64.b64encode(raw).decode("ascii")
-class TestTraceSpansKeysetPaginationTimezone(ClickhouseTestMixin, APIBaseTest):
+class _TraceSpansTestBase(ClickhouseTestMixin, APIBaseTest):
+ # Shared trace_spans table management + query execution. Not collected (no `Test` prefix, no tests).
CLASS_DATA_LEVEL_SETUP = True
@classmethod
- def setUpTestData(cls):
- super().setUpTestData()
+ def _recreate_trace_spans_tables(cls) -> None:
tag_queries(product="tracing", feature="query")
sync_execute("DROP TABLE IF EXISTS trace_spans_distributed")
sync_execute("DROP TABLE IF EXISTS trace_spans")
@@ -50,6 +43,64 @@ class TestTraceSpansKeysetPaginationTimezone(ClickhouseTestMixin, APIBaseTest):
)
sync_execute(TRACE_SPANS_DISTRIBUTED_TABLE_SQL())
+ @classmethod
+ def tearDownClass(cls):
+ # Restore the standard Python DDL so a later test class in the same process doesn't inherit
+ # this class's modified schema. Drop the distributed table first (it depends on the base).
+ sync_execute("DROP TABLE IF EXISTS trace_spans_distributed")
+ sync_execute("DROP TABLE IF EXISTS trace_spans")
+ sync_execute(TRACE_SPANS_TABLE_SQL())
+ sync_execute(TRACE_SPANS_DISTRIBUTED_TABLE_SQL())
+ super().tearDownClass()
+
+ def _execute(self, query: TraceSpansQuery, *, session_timezone: str | None = None) -> list:
+ runner = TraceSpansQueryRunner(query, self.team)
+ sql, context = HogQLQueryExecutor(
+ query_type="TraceSpansQuery",
+ query=runner.to_query(),
+ modifiers=runner.modifiers,
+ team=self.team,
+ workload=Workload.LOGS,
+ timings=runner.timings,
+ limit_context=LimitContext.QUERY,
+ ).generate_clickhouse_sql()
+ settings = {"session_timezone": session_timezone} if session_timezone else None
+ return sync_execute(sql, context.values, workload=Workload.LOGS, settings=settings)
+
+ def _ordered_trace_indices(self, *, order_direction: str, limit: int, offset: int = 0) -> list[int]:
+ # Distinct trace ids in row order, recovered as the integer trace index from the hex id (col 1).
+ query = TraceSpansQuery(
+ dateRange=DateRange(date_from=DATE_FROM, date_to=DATE_TO),
+ orderBy="duration",
+ orderDirection=order_direction,
+ limit=limit,
+ offset=offset,
+ rootSpans=True,
+ prefetchSpans=20,
+ )
+ ordered: list[int] = []
+ for row in self._execute(query):
+ idx = int(row[1], 16)
+ if idx not in ordered:
+ ordered.append(idx)
+ return ordered
+
+
+# 150 same-day root traces (i=0..149), timestamps increasing with i, newest-first ordering.
+# The 100th newest is i=50, so page 2 (after that cursor) should yield i=0..49 = 50 distinct traces.
+TOTAL_TRACES = 150
+PAGE_SIZE = 100
+CURSOR_INDEX = 50
+CURSOR_TS_ISO = "2026-06-02T08:00:50+00:00"
+CURSOR_TRACE_ID_HEX = format(CURSOR_INDEX, "032x")
+
+
+class TestTraceSpansKeysetPaginationTimezone(_TraceSpansTestBase):
+ @classmethod
+ def setUpTestData(cls):
+ super().setUpTestData()
+ cls._recreate_trace_spans_tables()
+
rows = []
base = dt.datetime(2026, 6, 2, 8, 0, 0)
for i in range(TOTAL_TRACES):
@@ -66,16 +117,6 @@ class TestTraceSpansKeysetPaginationTimezone(ClickhouseTestMixin, APIBaseTest):
"timestamp, end_time, observed_timestamp, status_code, service_name) VALUES " + ",".join(rows)
)
- @classmethod
- def tearDownClass(cls):
- # Restore the standard Python DDL so a later test class in the same process doesn't inherit
- # this class's modified schema. Drop the distributed table first (it depends on the base).
- sync_execute("DROP TABLE IF EXISTS trace_spans_distributed")
- sync_execute("DROP TABLE IF EXISTS trace_spans")
- sync_execute(TRACE_SPANS_TABLE_SQL())
- sync_execute(TRACE_SPANS_DISTRIBUTED_TABLE_SQL())
- super().tearDownClass()
-
def _cursor(self) -> str:
return base64.b64encode(
json.dumps({"timestamp": CURSOR_TS_ISO, "trace_id": CURSOR_TRACE_ID_HEX}).encode("utf-8")
@@ -84,26 +125,14 @@ class TestTraceSpansKeysetPaginationTimezone(ClickhouseTestMixin, APIBaseTest):
def _distinct_trace_count(self, *, after: str | None, limit: int, session_timezone: str) -> int:
query = TraceSpansQuery(
dateRange=DateRange(date_from=DATE_FROM, date_to=DATE_TO),
- orderBy="latest",
+ orderBy="timestamp",
+ orderDirection="DESC",
limit=limit,
after=after,
rootSpans=True,
prefetchSpans=20,
)
- runner = TraceSpansQueryRunner(query, self.team)
- sql, context = HogQLQueryExecutor(
- query_type="TraceSpansQuery",
- query=runner.to_query(),
- modifiers=runner.modifiers,
- team=self.team,
- workload=Workload.LOGS,
- timings=runner.timings,
- limit_context=LimitContext.QUERY,
- ).generate_clickhouse_sql()
- results = sync_execute(
- sql, context.values, workload=Workload.LOGS, settings={"session_timezone": session_timezone}
- )
- return len({row[1] for row in results}) # col 1 = hex(trace_id)
+ return len({row[1] for row in self._execute(query, session_timezone=session_timezone)}) # col 1 = hex(trace_id)
# The regression: a non-UTC session truncated time_bucket on a different day grid and emptied
# page 2. Both pages must return identical counts under UTC and a non-UTC session. Page 2 passes
@@ -121,3 +150,152 @@ class TestTraceSpansKeysetPaginationTimezone(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(
self._distinct_trace_count(after=after, limit=limit, session_timezone=session_timezone), expected
)
+
+
+# 20 traces (i=0..19), one root span each, duration = (i+1)s — so duration strictly increases with i.
+DURATION_TRACES = 20
+
+
+class TestTraceSpansDurationOrdering(_TraceSpansTestBase):
+ @classmethod
+ def setUpTestData(cls):
+ super().setUpTestData()
+ cls._recreate_trace_spans_tables()
+
+ rows = []
+ base = dt.datetime(2026, 6, 2, 8, 0, 0)
+ ts_str = base.strftime("%Y-%m-%d %H:%M:%S.%f")
+ for i in range(DURATION_TRACES):
+ end = base + dt.timedelta(seconds=i + 1) # duration = (i+1)s, distinct and non-zero
+ end_str = end.strftime("%Y-%m-%d %H:%M:%S.%f")
+ rows.append(
+ "("
+ f"'019e8754-0000-0000-0000-{i:012d}', {cls.team.id}, '{_b64(i.to_bytes(16, 'big'))}', "
+ f"'{_b64(i.to_bytes(8, 'big'))}', '', 'GET /api', 2, '{ts_str}', '{end_str}', '{ts_str}', 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)
+ )
+
+ @parameterized.expand(
+ [
+ # Duration increases with i: DESC ranks highest index first, ASC lowest first.
+ ("slowest_desc", "DESC", list(range(DURATION_TRACES - 1, -1, -1))),
+ ("fastest_asc", "ASC", list(range(DURATION_TRACES))),
+ ]
+ )
+ def test_orders_by_duration(self, _name, order_direction, expected):
+ self.assertEqual(self._ordered_trace_indices(order_direction=order_direction, limit=DURATION_TRACES), expected)
+
+ def test_offset_paginates_the_duration_sort(self):
+ page_size = 5
+ page1 = self._ordered_trace_indices(order_direction="DESC", limit=page_size, offset=0)
+ page2 = self._ordered_trace_indices(order_direction="DESC", limit=page_size, offset=page_size)
+ self.assertEqual(page1, [19, 18, 17, 16, 15])
+ self.assertEqual(page2, [14, 13, 12, 11, 10])
+
+ def _api_page(self, *, limit: int, offset: int) -> tuple[list[int], bool, str | None]:
+ # Hits the real endpoint so the VIEW's pagination (limit+1 over-fetch, hasMore, keep-top-N,
+ # offset) is exercised end-to-end — the runner-level tests above don't cover that layer.
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/tracing/spans/query/",
+ {
+ "query": {
+ "dateRange": {"date_from": DATE_FROM, "date_to": DATE_TO},
+ "orderBy": "duration",
+ "orderDirection": "DESC",
+ "limit": limit,
+ "offset": offset,
+ "rootSpans": True,
+ "prefetchSpans": 20,
+ }
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, 200, response.content)
+ body = response.json()
+ ordered: list[int] = []
+ for span in body["results"]:
+ idx = int(span["trace_id"], 16)
+ if idx not in ordered:
+ ordered.append(idx)
+ return ordered, body["hasMore"], body.get("nextCursor")
+
+ def test_offset_pagination_covers_every_trace_exactly_once(self):
+ # Walk the whole list the way the frontend does — advance offset by the running trace count
+ # (frontend sends `offset: rootSpans.length`) until hasMore is false — and prove every trace
+ # appears exactly once, slowest-first, with no overlap or gap across page boundaries.
+ # page_size = 7 deliberately doesn't divide 20 evenly, to stress the ragged final page.
+ page_size = 7
+ seen: list[int] = []
+ page_count = 0
+ has_more = True
+ first_cursor: str | None = "unset"
+ while has_more:
+ page, has_more, cursor = self._api_page(limit=page_size, offset=len(seen))
+ if page_count == 0:
+ first_cursor = cursor
+ self.assertGreater(len(page), 0, "a non-final page must never come back empty")
+ seen.extend(page)
+ page_count += 1
+ self.assertLess(page_count, DURATION_TRACES, "pagination did not terminate")
+
+ # Exact equality proves all three at once: full coverage (no drops), no duplicates (no
+ # overlap), and correct slowest-first order across every page boundary.
+ self.assertEqual(seen, list(range(DURATION_TRACES - 1, -1, -1)))
+ self.assertEqual(len(seen), len(set(seen))) # explicit no-overlap assertion
+ self.assertEqual(page_count, 3) # 7 + 7 + 6
+ self.assertIsNone(first_cursor) # duration ordering paginates by offset, not a keyset cursor
+
+
+# Each trace has a root span + one child. Trace 1's child (50s) dwarfs its root (5s), so the
+# whole-trace max duration disagrees with the root-span duration. With rootSpans=True the list
+# displays the root span, so slowest/fastest must rank by ROOT duration, not the longest child.
+ROOT_DURATIONS = [10, 5, 8] # seconds, per trace i=0,1,2 → root order desc = [0, 2, 1]
+CHILD_DURATIONS = [1, 50, 2] # trace 1's child is the longest span anywhere
+
+
+class TestTraceSpansDurationRootScope(_TraceSpansTestBase):
+ @classmethod
+ def setUpTestData(cls):
+ super().setUpTestData()
+ cls._recreate_trace_spans_tables()
+
+ base = dt.datetime(2026, 6, 2, 8, 0, 0)
+ ts_str = base.strftime("%Y-%m-%d %H:%M:%S.%f")
+ rows: list[str] = []
+ for i in range(3):
+ trace_id = _b64(i.to_bytes(16, "big"))
+ # Non-zero span ids so the child's parent_span_id never base64-encodes to all-'A'
+ # (which the is_root_span expression would misread as a root).
+ root_span_id = _b64((1000 + i * 2).to_bytes(8, "big"))
+ child_span_id = _b64((1001 + i * 2).to_bytes(8, "big"))
+ root_end = (base + dt.timedelta(seconds=ROOT_DURATIONS[i])).strftime("%Y-%m-%d %H:%M:%S.%f")
+ child_end = (base + dt.timedelta(seconds=CHILD_DURATIONS[i])).strftime("%Y-%m-%d %H:%M:%S.%f")
+ # Root span: empty parent_span_id → is_root_span = 1.
+ rows.append(
+ f"('019e8755-0000-0000-0000-{len(rows):012d}', {cls.team.id}, '{trace_id}', '{root_span_id}', '', "
+ f"'GET /api', 2, '{ts_str}', '{root_end}', '{ts_str}', 0, 'web')"
+ )
+ # Child span: parent_span_id = root → is_root_span = 0.
+ rows.append(
+ f"('019e8755-0000-0000-0000-{len(rows):012d}', {cls.team.id}, '{trace_id}', '{child_span_id}', "
+ f"'{root_span_id}', 'db query', 2, '{ts_str}', '{child_end}', '{ts_str}', 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)
+ )
+
+ @parameterized.expand(
+ [
+ # Root durations [10, 5, 8] → DESC = [0, 2, 1], ASC = [1, 2, 0]. Trace 1's 50s child must
+ # NOT change the rank (that would be ranking by whole-trace max, not the displayed root).
+ ("slowest_by_root", "DESC", [0, 2, 1]),
+ ("fastest_by_root", "ASC", [1, 2, 0]),
+ ]
+ )
+ def test_ranks_by_root_span_duration(self, _name, order_direction, expected):
+ self.assertEqual(self._ordered_trace_indices(order_direction=order_direction, limit=10), expected)
diff --git a/products/tracing/backend/tests/test_root_spans_filter.py b/products/tracing/backend/tests/test_root_spans_filter.py
index da010f512173..0a2358749bd1 100644
--- a/products/tracing/backend/tests/test_root_spans_filter.py
+++ b/products/tracing/backend/tests/test_root_spans_filter.py
@@ -85,7 +85,7 @@ class TestRootSpansFilter(ClickhouseTestMixin, APIBaseTest):
def _run(self, *, root_spans: bool | None, prefetch: int, service_names: list[str] | None = None) -> list[dict]:
query = TraceSpansQuery(
dateRange=DateRange(date_from=DATE_FROM, date_to=DATE_TO),
- orderBy="latest",
+ orderBy="timestamp",
limit=100,
rootSpans=root_spans,
prefetchSpans=prefetch,
diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.ts
index 2d713a72276f..c1f71c0872b5 100644
--- a/products/tracing/frontend/generated/api.schemas.ts
+++ b/products/tracing/frontend/generated/api.schemas.ts
@@ -141,14 +141,26 @@ export interface _HasSpansResponseApi {
}
/**
- * * `latest` - latest
- * * `earliest` - earliest
+ * * `timestamp` - timestamp
+ * * `duration` - duration
*/
-export type OrderByEnumApi = (typeof OrderByEnumApi)[keyof typeof OrderByEnumApi]
+export type _TracingQueryBodyOrderByEnumApi =
+ (typeof _TracingQueryBodyOrderByEnumApi)[keyof typeof _TracingQueryBodyOrderByEnumApi]
-export const OrderByEnumApi = {
- Latest: 'latest',
- Earliest: 'earliest',
+export const _TracingQueryBodyOrderByEnumApi = {
+ Timestamp: 'timestamp',
+ Duration: 'duration',
+} as const
+
+/**
+ * * `ASC` - ASC
+ * * `DESC` - DESC
+ */
+export type OrderDirectionEnumApi = (typeof OrderDirectionEnumApi)[keyof typeof OrderDirectionEnumApi]
+
+export const OrderDirectionEnumApi = {
+ Asc: 'ASC',
+ Desc: 'DESC',
} as const
export interface _TracingQueryBodyApi {
@@ -158,19 +170,29 @@ export interface _TracingQueryBodyApi {
serviceNames?: string[]
/** Filter by HTTP status codes. */
statusCodes?: number[]
- /** Order results by timestamp. Defaults to latest.
+ /** Column to order by. Defaults to timestamp. Ordering by timestamp paginates via the keyset cursor ('after'); ordering by duration paginates via 'offset'.
*
- * * `latest` - latest
- * * `earliest` - earliest */
- orderBy?: OrderByEnumApi
+ * * `timestamp` - timestamp
+ * * `duration` - duration */
+ orderBy?: _TracingQueryBodyOrderByEnumApi
+ /** Order direction. Defaults to DESC (e.g. timestamp+DESC = newest first, duration+DESC = slowest first).
+ *
+ * * `ASC` - ASC
+ * * `DESC` - DESC */
+ orderDirection?: OrderDirectionEnumApi
/** Property filters for the query. */
filterGroup?: _SpanPropertyFilterApi[]
/** Filter to a specific trace ID (hex string). */
traceId?: string
/** Max results (1-1000). Defaults to 100. */
limit?: number
- /** Pagination cursor from previous response. */
+ /** Keyset pagination cursor from a previous timestamp-ordered response. */
after?: string
+ /**
+ * Pagination offset, used when ordering by a column (e.g. duration). Defaults to 0.
+ * @minimum 0
+ */
+ offset?: number
/** Filter to root spans only. Defaults to true. */
rootSpans?: boolean
/** Number of child spans to prefetch per trace (1-100). */
diff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.ts
index 7dc81595795a..2c4743af7471 100644
--- a/products/tracing/frontend/generated/api.zod.ts
+++ b/products/tracing/frontend/generated/api.zod.ts
@@ -172,6 +172,8 @@ export const TracingSpansCountCreateBody = /* @__PURE__ */ zod.object({
export const tracingSpansQueryCreateBodyQueryOneFilterGroupDefault = []
export const tracingSpansQueryCreateBodyQueryOneLimitDefault = 100
+export const tracingSpansQueryCreateBodyQueryOneOffsetMin = 0
+
export const tracingSpansQueryCreateBodyQueryOneRootSpansDefault = true
export const tracingSpansQueryCreateBodyQueryOneExcludeAttributesDefault = false
@@ -196,11 +198,18 @@ export const TracingSpansQueryCreateBody = /* @__PURE__ */ zod.object({
serviceNames: zod.array(zod.string()).optional().describe('Filter by service names.'),
statusCodes: zod.array(zod.number()).optional().describe('Filter by HTTP status codes.'),
orderBy: zod
- .enum(['latest', 'earliest'])
- .describe('\* `latest` - latest\n\* `earliest` - earliest')
+ .enum(['timestamp', 'duration'])
+ .describe('\* `timestamp` - timestamp\n\* `duration` - duration')
+ .optional()
+ .describe(
+ "Column to order by. Defaults to timestamp. Ordering by timestamp paginates via the keyset cursor ('after'); ordering by duration paginates via 'offset'.\n\n\* `timestamp` - timestamp\n\* `duration` - duration"
+ ),
+ orderDirection: zod
+ .enum(['ASC', 'DESC'])
+ .describe('\* `ASC` - ASC\n\* `DESC` - DESC')
.optional()
.describe(
- 'Order results by timestamp. Defaults to latest.\n\n\* `latest` - latest\n\* `earliest` - earliest'
+ 'Order direction. Defaults to DESC (e.g. timestamp+DESC = newest first, duration+DESC = slowest first).\n\n\* `ASC` - ASC\n\* `DESC` - DESC'
),
filterGroup: zod
.array(
@@ -252,7 +261,15 @@ export const TracingSpansQueryCreateBody = /* @__PURE__ */ zod.object({
.number()
.default(tracingSpansQueryCreateBodyQueryOneLimitDefault)
.describe('Max results (1-1000). Defaults to 100.'),
- after: zod.string().optional().describe('Pagination cursor from previous response.'),
+ after: zod
+ .string()
+ .optional()
+ .describe('Keyset pagination cursor from a previous timestamp-ordered response.'),
+ offset: zod
+ .number()
+ .min(tracingSpansQueryCreateBodyQueryOneOffsetMin)
+ .optional()
+ .describe('Pagination offset, used when ordering by a column (e.g. duration). Defaults to 0.'),
rootSpans: zod
.boolean()
.default(tracingSpansQueryCreateBodyQueryOneRootSpansDefault)
@@ -268,6 +285,8 @@ export const TracingSpansQueryCreateBody = /* @__PURE__ */ zod.object({
export const tracingSpansSparklineCreateBodyQueryOneFilterGroupDefault = []
export const tracingSpansSparklineCreateBodyQueryOneLimitDefault = 100
+export const tracingSpansSparklineCreateBodyQueryOneOffsetMin = 0
+
export const tracingSpansSparklineCreateBodyQueryOneRootSpansDefault = true
export const tracingSpansSparklineCreateBodyQueryOneExcludeAttributesDefault = false
@@ -292,11 +311,18 @@ export const TracingSpansSparklineCreateBody = /* @__PURE__ */ zod.object({
serviceNames: zod.array(zod.string()).optional().describe('Filter by service names.'),
statusCodes: zod.array(zod.number()).optional().describe('Filter by HTTP status codes.'),
orderBy: zod
- .enum(['latest', 'earliest'])
- .describe('\* `latest` - latest\n\* `earliest` - earliest')
+ .enum(['timestamp', 'duration'])
+ .describe('\* `timestamp` - timestamp\n\* `duration` - duration')
+ .optional()
+ .describe(
+ "Column to order by. Defaults to timestamp. Ordering by timestamp paginates via the keyset cursor ('after'); ordering by duration paginates via 'offset'.\n\n\* `timestamp` - timestamp\n\* `duration` - duration"
+ ),
+ orderDirection: zod
+ .enum(['ASC', 'DESC'])
+ .describe('\* `ASC` - ASC\n\* `DESC` - DESC')
.optional()
.describe(
- 'Order results by timestamp. Defaults to latest.\n\n\* `latest` - latest\n\* `earliest` - earliest'
+ 'Order direction. Defaults to DESC (e.g. timestamp+DESC = newest first, duration+DESC = slowest first).\n\n\* `ASC` - ASC\n\* `DESC` - DESC'
),
filterGroup: zod
.array(
@@ -348,7 +374,15 @@ export const TracingSpansSparklineCreateBody = /* @__PURE__ */ zod.object({
.number()
.default(tracingSpansSparklineCreateBodyQueryOneLimitDefault)
.describe('Max results (1-1000). Defaults to 100.'),
- after: zod.string().optional().describe('Pagination cursor from previous response.'),
+ after: zod
+ .string()
+ .optional()
+ .describe('Keyset pagination cursor from a previous timestamp-ordered response.'),
+ offset: zod
+ .number()
+ .min(tracingSpansSparklineCreateBodyQueryOneOffsetMin)
+ .optional()
+ .describe('Pagination offset, used when ordering by a column (e.g. duration). Defaults to 0.'),
rootSpans: zod
.boolean()
.default(tracingSpansSparklineCreateBodyQueryOneRootSpansDefault)
diff --git a/products/tracing/frontend/tracingFiltersLogic.ts b/products/tracing/frontend/tracingFiltersLogic.ts
index 672f8f627a59..bed505d9767d 100644
--- a/products/tracing/frontend/tracingFiltersLogic.ts
+++ b/products/tracing/frontend/tracingFiltersLogic.ts
@@ -10,9 +10,11 @@ import type { tracingFiltersLogicType } from './tracingFiltersLogicType'
export const DEFAULT_DATE_RANGE: DateRange = { date_from: '-1h', date_to: null }
export const DEFAULT_SERVICE_NAMES: string[] = []
-export const DEFAULT_ORDER_BY = 'latest' as const
+export const DEFAULT_ORDER_BY = 'timestamp' as const
-export type TracingOrderBy = 'latest' | 'earliest'
+// Column the list is ordered by. Direction (asc/desc) is a backend default (desc) until the sort
+// control lands (JON-34); timestamp+desc reproduces the previous "latest" behaviour.
+export type TracingOrderBy = 'timestamp' | 'duration'
export interface OverlayWindow {
startMs: number
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3b7d709a4879..2788dac389d5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -20862,6 +20862,14 @@ export namespace Schemas {
version?: number | null;
}
+ export type TraceOrderColumn = typeof TraceOrderColumn[keyof typeof TraceOrderColumn];
+
+
+ export const TraceOrderColumn = {
+ Timestamp: 'timestamp',
+ Duration: 'duration',
+ } as const;
+
export interface TraceSpansQueryResponse {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -20899,7 +20907,10 @@ export namespace Schemas {
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
offset?: number | null;
- orderBy?: LogsOrderBy | null;
+ /** Column to order by. Defaults to timestamp. `timestamp` paginates via keyset cursor (`after`); other columns via `offset`. */
+ orderBy?: TraceOrderColumn | null;
+ /** Order direction. Defaults to DESC. */
+ orderDirection?: OrderDirection2 | null;
/** Prefetch up to this many spans per trace and include them in results */
prefetchSpans?: number | null;
response?: TraceSpansQueryResponse | null;
@@ -42673,6 +42684,18 @@ export namespace Schemas {
count: number;
}
+ /**
+ * * `timestamp` - timestamp
+ * * `duration` - duration
+ */
+ export type _TracingQueryBodyOrderByEnum = typeof _TracingQueryBodyOrderByEnum[keyof typeof _TracingQueryBodyOrderByEnum];
+
+
+ export const _TracingQueryBodyOrderByEnum = {
+ Timestamp: 'timestamp',
+ Duration: 'duration',
+ } as const;
+
export interface _TracingQueryBody {
/** Date range for the query. Defaults to last hour. */
dateRange?: _TracingDateRange;
@@ -42680,19 +42703,29 @@ export namespace Schemas {
serviceNames?: string[];
/** Filter by HTTP status codes. */
statusCodes?: number[];
- /** Order results by timestamp. Defaults to latest.
+ /** Column to order by. Defaults to timestamp. Ordering by timestamp paginates via the keyset cursor ('after'); ordering by duration paginates via 'offset'.
*
- * * `latest` - latest
- * * `earliest` - earliest */
- orderBy?: OrderByEnum;
+ * * `timestamp` - timestamp
+ * * `duration` - duration */
+ orderBy?: _TracingQueryBodyOrderByEnum;
+ /** Order direction. Defaults to DESC (e.g. timestamp+DESC = newest first, duration+DESC = slowest first).
+ *
+ * * `ASC` - ASC
+ * * `DESC` - DESC */
+ orderDirection?: OrderDirectionEnum;
/** Property filters for the query. */
filterGroup?: _SpanPropertyFilter[];
/** Filter to a specific trace ID (hex string). */
traceId?: string;
/** Max results (1-1000). Defaults to 100. */
limit?: number;
- /** Pagination cursor from previous response. */
+ /** Keyset pagination cursor from a previous timestamp-ordered response. */
after?: string;
+ /**
+ * Pagination offset, used when ordering by a column (e.g. duration). Defaults to 0.
+ * @minimum 0
+ */
+ offset?: number;
/** Filter to root spans only. Defaults to true. */
rootSpans?: boolean;
/** Number of child spans to prefetch per trace (1-100). */
diff --git a/services/mcp/src/generated/tracing/api.ts b/services/mcp/src/generated/tracing/api.ts
index 4955e148d548..6f766a6c85e8 100644
--- a/services/mcp/src/generated/tracing/api.ts
+++ b/services/mcp/src/generated/tracing/api.ts
@@ -228,6 +228,8 @@ export const TracingSpansQueryCreateParams = /* @__PURE__ */ zod.object({
export const tracingSpansQueryCreateBodyQueryOneFilterGroupDefault = []
export const tracingSpansQueryCreateBodyQueryOneLimitDefault = 100
+export const tracingSpansQueryCreateBodyQueryOneOffsetMin = 0
+
export const tracingSpansQueryCreateBodyQueryOneRootSpansDefault = true
export const tracingSpansQueryCreateBodyQueryOneExcludeAttributesDefault = false
@@ -252,11 +254,18 @@ export const TracingSpansQueryCreateBody = /* @__PURE__ */ zod.object({
serviceNames: zod.array(zod.string()).optional().describe('Filter by service names.'),
statusCodes: zod.array(zod.number()).optional().describe('Filter by HTTP status codes.'),
orderBy: zod
- .enum(['latest', 'earliest'])
- .describe('* `latest` - latest\n* `earliest` - earliest')
+ .enum(['timestamp', 'duration'])
+ .describe('* `timestamp` - timestamp\n* `duration` - duration')
+ .optional()
+ .describe(
+ "Column to order by. Defaults to timestamp. Ordering by timestamp paginates via the keyset cursor ('after'); ordering by duration paginates via 'offset'.\n\n* `timestamp` - timestamp\n* `duration` - duration"
+ ),
+ orderDirection: zod
+ .enum(['ASC', 'DESC'])
+ .describe('* `ASC` - ASC\n* `DESC` - DESC')
.optional()
.describe(
- 'Order results by timestamp. Defaults to latest.\n\n* `latest` - latest\n* `earliest` - earliest'
+ 'Order direction. Defaults to DESC (e.g. timestamp+DESC = newest first, duration+DESC = slowest first).\n\n* `ASC` - ASC\n* `DESC` - DESC'
),
filterGroup: zod
.array(
@@ -308,7 +317,15 @@ export const TracingSpansQueryCreateBody = /* @__PURE__ */ zod.object({
.number()
.default(tracingSpansQueryCreateBodyQueryOneLimitDefault)
.describe('Max results (1-1000). Defaults to 100.'),
- after: zod.string().optional().describe('Pagination cursor from previous response.'),
+ after: zod
+ .string()
+ .optional()
+ .describe('Keyset pagination cursor from a previous timestamp-ordered response.'),
+ offset: zod
+ .number()
+ .min(tracingSpansQueryCreateBodyQueryOneOffsetMin)
+ .optional()
+ .describe('Pagination offset, used when ordering by a column (e.g. duration). Defaults to 0.'),
rootSpans: zod
.boolean()
.default(tracingSpansQueryCreateBodyQueryOneRootSpansDefault)
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-apm-spans.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-apm-spans.json
index f7b6b35f7856..03e60e19db25 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-apm-spans.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-apm-spans.json
@@ -5,7 +5,7 @@
"description": "The tracing spans query to execute.",
"properties": {
"after": {
- "description": "Pagination cursor from previous response.",
+ "description": "Keyset pagination cursor from a previous timestamp-ordered response.",
"type": "string"
},
"dateRange": {
@@ -85,9 +85,19 @@
"description": "Max results (1-1000). Defaults to 100.",
"type": "number"
},
+ "offset": {
+ "description": "Pagination offset, used when ordering by a column (e.g. duration). Defaults to 0.",
+ "minimum": 0,
+ "type": "number"
+ },
"orderBy": {
- "description": "Order results by timestamp. Defaults to latest.\n\n* `latest` - latest\n* `earliest` - earliest",
- "enum": ["latest", "earliest"],
+ "description": "Column to order by. Defaults to timestamp. Ordering by timestamp paginates via the keyset cursor ('after'); ordering by duration paginates via 'offset'.\n\n* `timestamp` - timestamp\n* `duration` - duration",
+ "enum": ["timestamp", "duration"],
+ "type": "string"
+ },
+ "orderDirection": {
+ "description": "Order direction. Defaults to DESC (e.g. timestamp+DESC = newest first, duration+DESC = slowest first).\n\n* `ASC` - ASC\n* `DESC` - DESC",
+ "enum": ["ASC", "DESC"],
"type": "string"
},
"prefetchSpans": {