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): show health status per endpoint (#125557)

Jon McCallum4a7505016c75
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 1e19436df6c0..22b3f5276209 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -2898,6 +2898,7 @@ const api = {
offset?: number
includeImpact?: boolean
groupByEndpoint?: boolean
+ includeHealth?: boolean
},
signal?: AbortSignal
): Promise<{
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index a6e640c560a8..7d21d4c22e5e 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -1443,6 +1443,14 @@
"error_count": {
"$ref": "#/definitions/integer"
},
+ "health_reason": {
+ "description": "Short reason for `health_status`, such as `error rate 0.2% → 4.1%`. Empty when the status is `ok`.",
+ "type": "string"
+ },
+ "health_status": {
+ "$ref": "#/definitions/SpanHealthStatus",
+ "description": "Set only when the query asked for `includeHealth`. Same statuses as the service health check."
+ },
"name": {
"type": "string"
},
@@ -53483,6 +53491,10 @@
"required": ["startLine", "endLine"],
"type": "object"
},
+ "SpanHealthStatus": {
+ "enum": ["silent", "regressed", "degraded", "new", "recovered", "improved", "ok"],
+ "type": "string"
+ },
"SpanPropertyFilter": {
"additionalProperties": false,
"properties": {
@@ -55321,6 +55333,10 @@
"description": "Group HTTP server spans by `METHOD route` in place of the span name. Spans without a route keep their name. Spans that are not HTTP server spans are left out.",
"type": "boolean"
},
+ "includeHealth": {
+ "description": "Classify each row against the comparison window, or the previous period when `compareFilter` is off. Fills `health_status` and `health_reason`. Runs a second window query.",
+ "type": "boolean"
+ },
"includeImpact": {
"description": "Also aggregate sessions and people per operation. Off by default: it reads the attribute maps.",
"type": "boolean"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 6e3db686c653..d7be2c9b9417 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -5323,6 +5323,8 @@ export interface TraceSpansQueryResponse extends AnalyticsQueryResponseBase {
export type CachedTraceSpansQueryResponse = CachedQueryResponse<TraceSpansQueryResponse>
+export type SpanHealthStatus = 'silent' | 'regressed' | 'degraded' | 'new' | 'recovered' | 'improved' | 'ok'
+
/** One aggregated span row keyed by `(service_name, name)`. Used by the delta-table view. */
export interface AggregatedSpanRow {
service_name: string
@@ -5340,6 +5342,10 @@ export interface AggregatedSpanRow {
users?: integer
spans_with_session_id?: integer
spans_with_distinct_id?: integer
+ /** Set only when the query asked for `includeHealth`. Same statuses as the service health check. */
+ health_status?: SpanHealthStatus
+ /** Short reason for `health_status`, such as `error rate 0.2% → 4.1%`. Empty when the status is `ok`. */
+ health_reason?: string
}
export interface TraceSpansAggregationQuery extends DataNode<TraceSpansAggregationQueryResponse> {
@@ -5356,6 +5362,11 @@ export interface TraceSpansAggregationQuery extends DataNode<TraceSpansAggregati
* Spans that are not HTTP server spans are left out.
*/
groupByEndpoint?: boolean
+ /**
+ * Classify each row against the comparison window, or the previous period when `compareFilter` is off.
+ * Fills `health_status` and `health_reason`. Runs a second window query.
+ */
+ includeHealth?: boolean
}
export interface TraceSpansAggregationQueryResponse extends AnalyticsQueryResponseBase {
diff --git a/posthog/schema.py b/posthog/schema.py
index 0ee346791a8b..54135d61e68b 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -299,6 +299,7 @@ from posthog.schema_enums import (
SnapshotSource as SnapshotSource,
SortDirection as SortDirection,
SourceType as SourceType,
+ SpanHealthStatus as SpanHealthStatus,
SpanPropertyFilterType as SpanPropertyFilterType,
StartHandling as StartHandling,
Status as Status,
@@ -3787,6 +3788,16 @@ class AggregatedSpanRow(BaseModel):
avg_duration_nano: float
count: int
error_count: int
+ health_reason: str | None = Field(
+ default=None,
+ description=(
+ "Short reason for `health_status`, such as `error rate 0.2% → 4.1%`. Empty when the status is `ok`."
+ ),
+ )
+ health_status: SpanHealthStatus | None = Field(
+ default=None,
+ description=("Set only when the query asked for `includeHealth`. Same statuses as the service health check."),
+ )
name: str
p50_duration_nano: float
p95_duration_nano: float
@@ -31592,6 +31603,14 @@ class TraceSpansAggregationQuery(BaseModel):
" left out."
),
)
+ includeHealth: bool | None = Field(
+ default=None,
+ description=(
+ "Classify each row against the comparison window, or the previous period"
+ " when `compareFilter` is off. Fills `health_status` and `health_reason`."
+ " Runs a second window query."
+ ),
+ )
includeImpact: bool | None = Field(
default=None,
description=("Also aggregate sessions and people per operation. Off by default: it reads the attribute maps."),
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index ca198d4efdd7..2d6943366901 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -3025,6 +3025,16 @@ class SnapchatAdsDefaultSources(StrEnum):
SNAPCHAT = "snapchat"
+class SpanHealthStatus(StrEnum):
+ SILENT = "silent"
+ REGRESSED = "regressed"
+ DEGRADED = "degraded"
+ NEW = "new"
+ RECOVERED = "recovered"
+ IMPROVED = "improved"
+ OK = "ok"
+
+
class SpanPropertyFilterType(StrEnum):
SPAN = "span"
SPAN_ATTRIBUTE = "span_attribute"
diff --git a/products/tracing/backend/aggregation_query_runner.py b/products/tracing/backend/aggregation_query_runner.py
index 12d5d0ce2ddc..c3263edb9095 100644
--- a/products/tracing/backend/aggregation_query_runner.py
+++ b/products/tracing/backend/aggregation_query_runner.py
@@ -16,8 +16,6 @@ windows in parallel when set.
"""
import datetime as dt
-import contextvars
-from concurrent.futures import ThreadPoolExecutor
from functools import cached_property
from typing import TYPE_CHECKING, cast
from zoneinfo import ZoneInfo
@@ -30,6 +28,7 @@ from posthog.schema import (
HogQLQueryModifiers,
IntervalType,
PropertyGroupsMode,
+ SpanHealthStatus,
SpanPropertyFilter,
SpanPropertyFilterType,
SpanTreeNode,
@@ -49,6 +48,7 @@ from posthog.hogql.timings import HogQLTimings
from posthog.clickhouse.client.connection import Workload
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
+from posthog.hogql_queries.utils.caller_context import map_in_caller_context
from posthog.hogql_queries.utils.query_compare_to_date_range import QueryCompareToDateRange
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPreviousPeriodDateRange
@@ -63,6 +63,7 @@ from .logic import (
with_span_attribute_type_suffix,
)
from .models import TracingIdentityAttributeKeys
+from .service_health_query_runner import ServiceWindowStats, classify_service
from .span_identity import identity_value_expr, str_attr_field
if TYPE_CHECKING:
@@ -172,28 +173,19 @@ class _SpanAggregationMixin:
if compare_range is None:
return self._run_period(self.query_date_range, self.timings), None
- # Copy contextvars to worker threads so query tags (product/feature) set by the
- # viewset propagate. ThreadPoolExecutor does not inherit contextvars by default.
- primary_ctx = contextvars.copy_context()
- compare_ctx = contextvars.copy_context()
# HogQLTimings is not thread safe, so each worker gets its own clone.
- primary_timings = self.timings.clone_for_subquery(0)
- compare_timings = self.timings.clone_for_subquery(1)
+ windows = [
+ (self.query_date_range, self.timings.clone_for_subquery(0)),
+ (compare_range, self.timings.clone_for_subquery(1)),
+ ]
- def run_primary() -> list:
- return primary_ctx.run(self._run_period, self.query_date_range, primary_timings)
+ def run_window(window: tuple[QueryDateRange, HogQLTimings]) -> list:
+ return self._run_period(*window)
- def run_compare() -> list:
- return compare_ctx.run(self._run_period, compare_range, compare_timings)
-
- with ThreadPoolExecutor(max_workers=2) as pool:
- current_future = pool.submit(run_primary)
- previous_future = pool.submit(run_compare)
- results = current_future.result(), previous_future.result()
-
- self.timings.timings.update(primary_timings.timings)
- self.timings.timings.update(compare_timings.timings)
- return results
+ current, previous = map_in_caller_context(run_window, windows, thread_name_prefix="tracing_aggregation")
+ for _, timings in windows:
+ self.timings.timings.update(timings.timings)
+ return current, previous
def _run_period(self, query_date_range: QueryDateRange, timings: HogQLTimings) -> list:
query = self._build_query(query_date_range)
@@ -266,15 +258,63 @@ class TraceSpansAggregationQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunn
self._limit = _ROW_LIMIT if limit is None else max(1, min(limit, _ROW_LIMIT))
self._offset = max(0, offset)
self._identity_keys = identity_keys
+ self._baseline_keys: list[tuple[str, str]] | None = None
def get_cache_payload(self) -> dict:
# Runner arguments, not query fields, so the base payload cannot see them.
return {**super().get_cache_payload(), "limit": self._limit, "offset": self._offset}
+ def _compare_query_date_range(self) -> QueryDateRange | None:
+ compare_range = super()._compare_query_date_range()
+ if compare_range is None and self.query.includeHealth:
+ # Health needs a baseline, so without a comparison it uses the previous period.
+ return QueryPreviousPeriodDateRange(
+ date_range=self.query.dateRange,
+ team=self.team,
+ interval=IntervalType.MINUTE,
+ timezone_info=ZoneInfo("UTC"),
+ now=dt.datetime.now(),
+ )
+ return compare_range
+
+ def _run_with_compare(self) -> tuple[list, list | None]:
+ if not self.query.includeHealth:
+ return super()._run_with_compare()
+ compare_range = self._compare_query_date_range()
+ assert compare_range is not None
+ # Sequential: the baseline reads only the current page's rows, because their rank in the baseline can differ.
+ current_rows = self._run_period(self.query_date_range, self.timings)
+ if not current_rows:
+ return current_rows, []
+ self._baseline_keys = [(row.service_name, row.name) for row in current_rows]
+ return current_rows, self._run_period(compare_range, self.timings)
+
def _calculate(self) -> TraceSpansAggregationQueryResponse:
current_rows, previous_rows = self._run_with_compare()
+ if self.query.includeHealth:
+ self._classify(current_rows, previous_rows or [])
+ if not (self.query.compareFilter and self.query.compareFilter.compare):
+ previous_rows = None
return TraceSpansAggregationQueryResponse(results=current_rows, compare=previous_rows)
+ def _classify(self, current_rows: list[AggregatedSpanRow], baseline_rows: list[AggregatedSpanRow]) -> None:
+ # shortcut: rows carry no last-seen time, so silent never fires. Add a last_seen column if per-endpoint
+ # silence detection is needed.
+ baseline = {(row.service_name, row.name): row for row in baseline_rows}
+ window_from = self.query_date_range.date_from()
+ window_to = min(self.query_date_range.date_to(), dt.datetime.now(tz=ZoneInfo("UTC")))
+ for row in current_rows:
+ before = baseline.get((row.service_name, row.name))
+ status, reason = classify_service(
+ current=_window_stats(row, window_to),
+ baseline=_window_stats(before, window_to) if before else None,
+ has_baseline=True,
+ window_from=window_from,
+ window_to=window_to,
+ )
+ row.health_status = SpanHealthStatus(status.value)
+ row.health_reason = reason
+
def _build_query(self, query_date_range: QueryDateRange) -> ast.SelectQuery:
# Single table scan plus hash aggregate. Cheap enough to run unscoped.
where = self._where_without_date_range()
@@ -282,11 +322,29 @@ class TraceSpansAggregationQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunn
if self.query.groupByEndpoint:
where = ast.And(exprs=[where, _endpoint_scope_expr()])
group_name = _endpoint_name_expr()
+ limit, offset = self._limit, self._offset
+ if self._baseline_keys is not None and query_date_range is not self.query_date_range:
+ keys = ast.Tuple(
+ exprs=[
+ ast.Tuple(exprs=[ast.Constant(value=service), ast.Constant(value=name)])
+ for service, name in self._baseline_keys
+ ]
+ )
+ where = ast.And(
+ exprs=[
+ where,
+ parse_expr(
+ "tuple(service_name, {group_name}) IN {keys}",
+ placeholders={"keys": keys, "group_name": group_name},
+ ),
+ ]
+ )
+ limit, offset = len(self._baseline_keys), 0
placeholders: dict[str, ast.Expr] = {
"where": where,
"group_name": group_name,
- "limit": ast.Constant(value=self._limit),
- "offset": ast.Constant(value=self._offset),
+ "limit": ast.Constant(value=limit),
+ "offset": ast.Constant(value=offset),
**query_date_range.to_placeholders(),
}
# Appended rather than always present, because reading the attribute maps is the
@@ -359,6 +417,17 @@ class TraceSpansAggregationQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunn
return response
+def _window_stats(row: AggregatedSpanRow, last_seen: dt.datetime) -> ServiceWindowStats:
+ return ServiceWindowStats(
+ requests=row.count,
+ errors=row.error_count,
+ p50_ms=row.p50_duration_nano / 1e6,
+ p95_ms=row.p95_duration_nano / 1e6,
+ p99_ms=row.p99_duration_nano / 1e6,
+ last_seen=last_seen,
+ )
+
+
def _http_method_expr() -> ast.Expr:
# OTel renamed `http.method` to `http.request.method`; SDKs in the wild send either.
return parse_expr(
diff --git a/products/tracing/backend/logic.py b/products/tracing/backend/logic.py
index 3b332adad16f..8ed44dbdd6b5 100644
--- a/products/tracing/backend/logic.py
+++ b/products/tracing/backend/logic.py
@@ -1420,6 +1420,7 @@ def run_aggregation_query(
offset: int = 0,
include_impact: bool = False,
group_by_endpoint: bool = False,
+ include_health: bool = False,
) -> TraceSpansAggregationQueryResponse | CachedTraceSpansAggregationQueryResponse:
"""Facade-friendly entry point for running a flat span aggregation query."""
# The runners import `translate_span_filter` from this module, so a module-level import here is circular.
@@ -1436,6 +1437,7 @@ def run_aggregation_query(
serviceNames=service_names,
includeImpact=include_impact,
groupByEndpoint=group_by_endpoint,
+ includeHealth=include_health,
)
runner = TraceSpansAggregationQueryRunner(
query,
diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.py
index 1224a4172a21..82ae52990bca 100644
--- a/products/tracing/backend/presentation/views.py
+++ b/products/tracing/backend/presentation/views.py
@@ -72,6 +72,7 @@ from ..facade.api import (
run_symbol_stats_query,
service_health_byte_cap_message,
)
+from ..facade.enums import ServiceHealthStatus
from ..has_spans_query_runner import team_has_spans
from ..logic import (
_ROW_LIMIT,
@@ -631,6 +632,15 @@ class _TracingAggregationQueryBodySerializer(serializers.Serializer):
"that are not HTTP server spans are left out."
),
)
+ includeHealth = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text=(
+ "Also return `health_status` and `health_reason` per row, comparing each row with the same row in the "
+ "comparison window, or in the previous period when `compareFilter` is off. Uses the same statuses and "
+ "thresholds as the service health check. Costs a second window query."
+ ),
+ )
class _TracingAggregationRequestSerializer(serializers.Serializer):
@@ -676,6 +686,19 @@ class _AggregatedSpanRowSerializer(serializers.Serializer):
"attribute keys. Null unless the query set `includeImpact`."
),
)
+ health_status = serializers.ChoiceField(
+ choices=ServiceHealthStatus.choices,
+ allow_null=True,
+ help_text=(
+ "How this group compares with its baseline: regressed (error rate or p95 jumped), degraded (high error "
+ "rate), new (no spans in the baseline), recovered, improved, or ok. Null unless the query set "
+ "`includeHealth`."
+ ),
+ )
+ health_reason = serializers.CharField(
+ allow_null=True,
+ help_text="Short reason for `health_status`, such as `error rate 0.2% → 4.1%`. Empty when the status is ok.",
+ )
class _TracingAggregationResponseSerializer(serializers.Serializer):
@@ -1717,6 +1740,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
filter_group = None
compare_filter = self._parse_compare_filter(query_data)
+ include_health = self._parse_bool(query_data.get("includeHealth"))
# Bound the payload: default to a conservative page so agent/MCP callers don't pull the
# full high-cardinality tail. Callers opt into more via `limit`/`offset`.
@@ -1735,6 +1759,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
offset=offset,
include_impact=bool(query_data.get("includeImpact")),
group_by_endpoint=self._parse_bool(query_data.get("groupByEndpoint")),
+ include_health=include_health,
)
results = list(response.results)
@@ -1743,6 +1768,10 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
# `None` when no comparison was requested, `[]` when it ran but matched no spans — keep them
# distinct so an empty baseline isn't reported as "comparison ignored".
compare_rows = list(response.compare)[:limit] if response.compare is not None else None
+ if include_health and response.compare is not None:
+ # Health baselines follow the result keys, not their own ranking, so match them by key.
+ visible = {(row.service_name, row.name) for row in results}
+ compare_rows = [row for row in response.compare if (row.service_name, row.name) in visible]
self._report_usage(
request,
@@ -1757,6 +1786,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
"service_names_count": len(query_data.get("serviceNames") or []),
"include_impact": bool(query_data.get("includeImpact")),
"group_by_endpoint": bool(query_data.get("groupByEndpoint")),
+ "include_health": bool(query_data.get("includeHealth")),
},
)
diff --git a/products/tracing/backend/tests/test_aggregation_query_runner.py b/products/tracing/backend/tests/test_aggregation_query_runner.py
index 4c41ebe1b390..c1418e779335 100644
--- a/products/tracing/backend/tests/test_aggregation_query_runner.py
+++ b/products/tracing/backend/tests/test_aggregation_query_runner.py
@@ -314,3 +314,90 @@ class TestTraceSpansAggregationGroupByEndpoint(_TraceSpansTestBase):
group_by_endpoint=group_by_endpoint,
)
self.assertEqual({(row.name, row.count) for row in response.results}, expected)
+
+
+class TestTraceSpansAggregationHealth(_TraceSpansTestBase):
+ SERVICE = "api"
+ # (name, hour inside the query window or its previous period, span count, error count)
+ GROUPS = [
+ ("GET /orders", 6, 100, 0),
+ ("GET /orders", 8, 100, 10),
+ ("GET /items", 6, 100, 0),
+ ("GET /items", 8, 100, 0),
+ ("GET /new", 8, 5, 0),
+ # Ranks first in the baseline and last in the current window.
+ ("GET /legacy", 6, 300, 0),
+ ("GET /legacy", 8, 1, 0),
+ ]
+
+ @classmethod
+ def setUpTestData(cls):
+ super().setUpTestData()
+ cls._recreate_trace_spans_tables()
+
+ values: list[str] = []
+ for name, hour, count, errors in cls.GROUPS:
+ for j in range(count):
+ i = len(values)
+ ts = dt.datetime(2026, 6, 2, hour, 0, 0) + dt.timedelta(seconds=j)
+ ts_str = ts.strftime("%Y-%m-%d %H:%M:%S.%f")
+ end_str = (ts + dt.timedelta(milliseconds=10)).strftime("%Y-%m-%d %H:%M:%S.%f")
+ status = 2 if j >= count - errors else 0
+ values.append(
+ f"('019e8763-0000-0000-0000-{i:012d}', {cls.team.id}, '{_b64(i.to_bytes(16, 'big'))}', "
+ f"'{_b64((1000 + i).to_bytes(8, 'big'))}', '', '{name}', 2, '{ts_str}', '{end_str}', "
+ f"'{ts_str}', {status}, '{cls.SERVICE}')"
+ )
+ 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(values)
+ )
+
+ def test_classifies_each_row_against_the_previous_period(self):
+ response = run_aggregation_query(
+ team=self.team,
+ date_range=DateRange(date_from=DATE_FROM, date_to=DATE_TO),
+ include_health=True,
+ )
+ statuses = {row.name: row.health_status for row in response.results}
+ self.assertEqual(
+ {name: statuses[name] for name in ("GET /orders", "GET /items", "GET /new")},
+ {"GET /orders": "regressed", "GET /items": "ok", "GET /new": "new"},
+ )
+ self.assertIsNone(response.compare)
+
+ def test_api_compare_rows_follow_the_visible_page(self):
+ # The view over-fetches one row for has_more, so the baseline also holds the row it drops.
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/tracing/spans/aggregate/",
+ {
+ "query": {
+ "dateRange": {"date_from": DATE_FROM, "date_to": DATE_TO},
+ "compareFilter": {"compare": True},
+ "includeHealth": True,
+ "limit": 1,
+ "offset": 2,
+ }
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, 200, response.content)
+ data = response.json()
+ self.assertEqual([row["name"] for row in data["results"]], ["GET /new"])
+ self.assertEqual(data["compare"], [])
+
+ @parameterized.expand(
+ [("previous_period", None, None), ("compare_filter", CompareFilter(compare=True), ["GET /legacy"])]
+ )
+ def test_a_paged_row_keeps_its_baseline(self, _name, compare_filter, expected_compare):
+ response = run_aggregation_query(
+ team=self.team,
+ date_range=DateRange(date_from=DATE_FROM, date_to=DATE_TO),
+ compare_filter=compare_filter,
+ include_health=True,
+ limit=1,
+ offset=3,
+ )
+ self.assertEqual([row.name for row in response.results], ["GET /legacy"])
+ self.assertNotEqual(response.results[0].health_status, "new")
+ self.assertEqual(None if response.compare is None else [row.name for row in response.compare], expected_compare)
diff --git a/products/tracing/frontend/OperationsTable.tsx b/products/tracing/frontend/OperationsTable.tsx
index 3b4f0220d585..058fae2e5fa9 100644
--- a/products/tracing/frontend/OperationsTable.tsx
+++ b/products/tracing/frontend/OperationsTable.tsx
@@ -1,8 +1,10 @@
import { useMemo } from 'react'
+import { LemonTag, LemonTagType, Tooltip } from '@posthog/lemon-ui'
+
import { humanFriendlyNumber } from 'lib/utils/numbers'
-import { AggregatedSpanRow } from '~/queries/schema/schema-general'
+import { AggregatedSpanRow, SpanHealthStatus } from '~/queries/schema/schema-general'
import { formatIdentityCoverage } from './identityCoverage'
import { formatDuration } from './TraceWaterfallView'
@@ -56,6 +58,22 @@ const impactCell =
)
}
+// Listed worst first, so the Health column sorts unhealthy rows to the top.
+const HEALTH_META: Record<SpanHealthStatus, { label: string; tagType: LemonTagType }> = {
+ silent: { label: 'Silent', tagType: 'danger' },
+ regressed: { label: 'Regressed', tagType: 'danger' },
+ degraded: { label: 'Degraded', tagType: 'warning' },
+ new: { label: 'New', tagType: 'highlight' },
+ recovered: { label: 'Recovered', tagType: 'success' },
+ improved: { label: 'Improved', tagType: 'success' },
+ ok: { label: 'OK', tagType: 'muted' },
+}
+const HEALTH_ORDER = Object.keys(HEALTH_META) as SpanHealthStatus[]
+
+function healthRank(row: AggregatedSpanRow): number {
+ return row.health_status ? HEALTH_ORDER.indexOf(row.health_status) : HEALTH_ORDER.length
+}
+
function buildColumns(
windowMs: number,
showImpact: boolean,
@@ -90,7 +108,33 @@ function buildColumns(
]
: []
+ const healthColumns: VirtualizedTableColumn<AggregatedSpanRow>[] = groupedByEndpoint
+ ? [
+ {
+ key: 'health',
+ title: 'Health',
+ width: 110,
+ tooltip: 'Compared with the previous period of the same length.',
+ sorter: (a, b) => healthRank(b) - healthRank(a),
+ render: (row) => {
+ if (!row.health_status) {
+ return null
+ }
+ const { label, tagType } = HEALTH_META[row.health_status]
+ return (
+ <Tooltip title={row.health_reason || undefined}>
+ <LemonTag type={tagType} size="small">
+ {label}
+ </LemonTag>
+ </Tooltip>
+ )
+ },
+ },
+ ]
+ : []
+
return [
+ ...healthColumns,
{
key: 'service_name',
title: 'Service',
@@ -218,6 +262,8 @@ export function OperationsTable({
)
return (
<VirtualizedTable<AggregatedSpanRow>
+ // Remounts on a mode switch, so each mode starts from its own default sort.
+ key={groupedByEndpoint ? 'endpoints' : 'operations'}
// pinned: identifies stored column widths — renaming resets everyone's widths
tableKey="operations"
columns={columns}
@@ -225,7 +271,7 @@ export function OperationsTable({
loading={loading}
rowKey={operationRowKey}
onRowClick={onRowClick}
- defaultSort={{ columnKey: 'total_time', order: -1 }}
+ defaultSort={{ columnKey: groupedByEndpoint ? 'health' : 'total_time', order: -1 }}
emptyLabel={
groupedByEndpoint
? 'No HTTP server spans found for these filters'
diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.ts
index 94c34ca37d2a..27aa6b1034f5 100644
--- a/products/tracing/frontend/generated/api.schemas.ts
+++ b/products/tracing/frontend/generated/api.schemas.ts
@@ -249,6 +249,8 @@ export interface _TracingAggregationQueryBodyApi {
includeImpact?: boolean
/** Group HTTP server spans by `METHOD route` (from `http.route`) in place of the span name, so raw paths like `/users/1` and `/users/2` fold into one row. Spans without a route keep their span name. Spans that are not HTTP server spans are left out. */
groupByEndpoint?: boolean
+ /** Also return `health_status` and `health_reason` per row, comparing each row with the same row in the comparison window, or in the previous period when `compareFilter` is off. Uses the same statuses and thresholds as the service health check. Costs a second window query. */
+ includeHealth?: boolean
}
export interface _TracingAggregationRequestApi {
@@ -256,6 +258,27 @@ export interface _TracingAggregationRequestApi {
query: _TracingAggregationQueryBodyApi
}
+/**
+ * * `silent` - Silent
+ * * `regressed` - Regressed
+ * * `degraded` - Degraded
+ * * `new` - New
+ * * `recovered` - Recovered
+ * * `improved` - Improved
+ * * `ok` - Ok
+ */
+export type ServiceHealthStatusEnumApi = (typeof ServiceHealthStatusEnumApi)[keyof typeof ServiceHealthStatusEnumApi]
+
+export const ServiceHealthStatusEnumApi = {
+ Silent: 'silent',
+ Regressed: 'regressed',
+ Degraded: 'degraded',
+ New: 'new',
+ Recovered: 'recovered',
+ Improved: 'improved',
+ Ok: 'ok',
+} as const
+
export interface _AggregatedSpanRowApi {
/** Service that emitted the spans in this group. */
service_name: string
@@ -297,6 +320,21 @@ export interface _AggregatedSpanRowApi {
* @nullable
*/
spans_with_distinct_id: number | null
+ /** How this group compares with its baseline: regressed (error rate or p95 jumped), degraded (high error rate), new (no spans in the baseline), recovered, improved, or ok. Null unless the query set `includeHealth`.
+ *
+ * * `silent` - Silent
+ * * `regressed` - Regressed
+ * * `degraded` - Degraded
+ * * `new` - New
+ * * `recovered` - Recovered
+ * * `improved` - Improved
+ * * `ok` - Ok */
+ health_status: ServiceHealthStatusEnumApi | null
+ /**
+ * Short reason for `health_status`, such as `error rate 0.2% → 4.1%`. Empty when the status is ok.
+ * @nullable
+ */
+ health_reason: string | null
}
export interface _TracingAggregationResponseApi {
@@ -883,27 +921,6 @@ export interface _ServiceHealthSummaryApi {
improved: number
}
-/**
- * * `silent` - Silent
- * * `regressed` - Regressed
- * * `degraded` - Degraded
- * * `new` - New
- * * `recovered` - Recovered
- * * `improved` - Improved
- * * `ok` - Ok
- */
-export type ServiceHealthStatusEnumApi = (typeof ServiceHealthStatusEnumApi)[keyof typeof ServiceHealthStatusEnumApi]
-
-export const ServiceHealthStatusEnumApi = {
- Silent: 'silent',
- Regressed: 'regressed',
- Degraded: 'degraded',
- New: 'new',
- Recovered: 'recovered',
- Improved: 'improved',
- Ok: 'ok',
-} as const
-
export interface _ServiceHealthRowApi {
/** Service name. */
service: string
diff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.ts
index c84b0d8a1372..43faa04acc33 100644
--- a/products/tracing/frontend/generated/api.zod.ts
+++ b/products/tracing/frontend/generated/api.zod.ts
@@ -175,6 +175,7 @@ export const tracingSpansAggregateCreateBodyQueryOneOffsetMin = 0
export const tracingSpansAggregateCreateBodyQueryOneIncludeImpactDefault = false
export const tracingSpansAggregateCreateBodyQueryOneGroupByEndpointDefault = false
+export const tracingSpansAggregateCreateBodyQueryOneIncludeHealthDefault = false
export const TracingSpansAggregateCreateBody = /* @__PURE__ */ zod.object({
query: zod
@@ -290,6 +291,12 @@ export const TracingSpansAggregateCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Group HTTP server spans by `METHOD route` (from `http.route`) in place of the span name, so raw paths like `\/users\/1` and `\/users\/2` fold into one row. Spans without a route keep their span name. Spans that are not HTTP server spans are left out.'
),
+ includeHealth: zod
+ .boolean()
+ .default(tracingSpansAggregateCreateBodyQueryOneIncludeHealthDefault)
+ .describe(
+ 'Also return `health_status` and `health_reason` per row, comparing each row with the same row in the comparison window, or in the previous period when `compareFilter` is off. Uses the same statuses and thresholds as the service health check. Costs a second window query.'
+ ),
})
.describe('The span aggregation query to execute.'),
})
diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.ts
index f99b1f2fde43..8616cab52a53 100644
--- a/products/tracing/frontend/tracingDataLogic.ts
+++ b/products/tracing/frontend/tracingDataLogic.ts
@@ -1131,6 +1131,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
actions.cancelInProgressAggregation(controller)
const fullRange = options?.fullRange ?? false
+ const groupByEndpoint = options?.groupByEndpoint || undefined
const currentWindow = fullRange ? values.sparklineWindowMs : values.currentWindowMs
const compare = !fullRange && values.timeComparison !== null
@@ -1171,7 +1172,8 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
// Only the Operations table renders the Sessions and Users columns, and
// the aggregates read attribute maps the rest of the query never touches.
includeImpact: fullRange && !!values.featureFlags[FEATURE_FLAGS.TRACING_IMPACT_STRIP],
- groupByEndpoint: options?.groupByEndpoint || undefined,
+ groupByEndpoint,
+ includeHealth: groupByEndpoint,
},
controller.signal
)
diff --git a/products/tracing/frontend/tracingSceneLogic.test.ts b/products/tracing/frontend/tracingSceneLogic.test.ts
index 8c22effa2320..83ea4342136f 100644
--- a/products/tracing/frontend/tracingSceneLogic.test.ts
+++ b/products/tracing/frontend/tracingSceneLogic.test.ts
@@ -151,7 +151,10 @@ describe('tracingSceneLogic', () => {
featureFlagLogic.actions.setFeatureFlags([], { [flag]: true })
mountAt({ view })
expect(logic.values.activeTracingTab).toBe(view)
- expect(aggregate).toHaveBeenLastCalledWith(expect.objectContaining({ groupByEndpoint }), expect.anything())
+ expect(aggregate).toHaveBeenLastCalledWith(
+ expect.objectContaining({ groupByEndpoint, includeHealth: groupByEndpoint }),
+ expect.anything()
+ )
})
it.each(['operations', 'endpoints'])('ignores ?view=%s when its flag is off', (view) => {
diff --git a/products/tracing/mcp/prompts/apm-spans-aggregate.md b/products/tracing/mcp/prompts/apm-spans-aggregate.md
index f7cbc8ebdf4e..8c5d274e9d4f 100644
--- a/products/tracing/mcp/prompts/apm-spans-aggregate.md
+++ b/products/tracing/mcp/prompts/apm-spans-aggregate.md
@@ -98,6 +98,18 @@ Set to `true` to get per-endpoint health for HTTP servers. Rows then group by `M
- A span without `http.route` keeps its span name as the row key.
- Use it when span names are raw paths (`/users/1`, `/users/2`) or a bare method (`GET`), which split or merge routes.
+## query.includeHealth
+
+Set to `true` to get `health_status` and `health_reason` on every row. Each row is compared with the same row in the `compareFilter` window, or in the previous period of the same length when `compareFilter` is off.
+
+- `regressed`: the error rate or p95 jumped against the baseline.
+- `degraded`: the error rate is high, with no clear jump.
+- `new`: the row has no spans in the baseline.
+- `recovered` and `improved`: the error rate or p95 went down.
+- `ok`: none of the above.
+
+It runs a second window query for the routes on the current page. Without `compareFilter`, the response `compare` stays null. With `compareFilter`, `compare` holds the baseline rows for those same routes.
+
# Examples
## Top operations by total time in the last hour
@@ -161,12 +173,13 @@ Returns `results` for the last hour and `compare` for the hour before. Diff `tot
"query": {
"serviceNames": ["api-gateway"],
"groupByEndpoint": true,
+ "includeHealth": true,
"dateRange": { "date_from": "-1d" }
}
}
```
-Each row is one route. Compare `error_count / count` and `p95_duration_nano` across rows to find unhealthy endpoints.
+Each row is one route. Start with the rows whose `health_status` is `regressed` or `degraded`, and read `health_reason` for the cause.
## Aggregate within one service
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 577eecf9d37e..a8d6c834ff46 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1242,7 +1242,7 @@
"feature_flag": "tracing"
},
"apm-spans-aggregate": {
- "description": "Aggregate trace span statistics grouped by `(service_name, name)` over a date window.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nReturns one row per `(service_name, name)` pair with the following metrics:\n\n- `count` — number of spans matched\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano`, `p99_duration_nano`, `p999_duration_nano` — duration stats in nanoseconds (1 second = 1,000,000,000 ns). `p999_duration_nano` is the 99.9th percentile and is only meaningful for `(service, name)` groups with enough spans; on low-volume operations it collapses to the max\n- `error_count` — spans with OTel status code `Error` (status_code = 2)\n\nRows are ordered by `total_duration_nano` DESC. By default only the top 100 rows are returned — this keeps the response small, which matters because high span-name cardinality (e.g. untemplated URL paths) can otherwise produce an enormous payload. The top rows already surface the heaviest operations. When more rows genuinely exist the response sets `has_more: true` and `next_offset`; page through with `offset`, or raise `limit` (hard max 5000). Prefer narrowing with `serviceNames`/`filterGroup` over pulling a large page.\n\nUse to answer:\n\n- \"Which services/operations consume the most time?\"\n- \"What's the p95 or p99 latency of `GET /users`?\"\n- \"How many errors did the checkout service emit in the last day?\"\n- \"Did `POST /orders` get slower this week vs last week?\" (with `compareFilter`)\n\nFor per-call-tree breakdowns (parent → child relationships), use `apm-spans-tree` instead. For time-bucketed trends (\"when did it change?\"), use `apm-spans-sparkline` instead — `compareFilter` only contrasts two static windows.\n\n# Comparison window\n\nSet `query.compareFilter.compare: true` to also fetch a comparison window. The response then includes a `compare` array of the same shape as `results`.\n\n- Omit `compare_to` (or set null) to compare against the immediately previous period of equal length (e.g. `dateRange: -1d` → compares vs the day before).\n- Set `compare_to: \"-7d\"` to compare against the window 7 days earlier (same length as the primary window).\n\nWhen `compare` is true, `compare` is always an array — empty (`[]`) if the comparison window matched no spans (for example an operation that didn't exist yet), not null. `compare` is `null` only when no comparison was requested. So an empty array is a real answer (\"nothing in the prior window\"), not a failure.\n\n# Data narrowing\n\n## Property filters\n\nUse `query.filterGroup` to narrow results to spans matching specific attributes. Only include filters that are essential to the user's question.\n\nFilter `type` values:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). A `duration` filter value is in milliseconds (1 second = `1000`).\n- `span_attribute` — span-level attributes (e.g. \"http.method\", \"http.status_code\")\n- `span_resource_attribute` — resource-level attributes (e.g. k8s labels, deployment info)\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values before guessing.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nAn attribute filter (`span_attribute` or `span_resource_attribute`) matches only spans that have the attribute, also for negated operators such as `is_not` and `not_icontains`. To find spans without the attribute, use `is_not_set`.\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`). Examples: `-1h`, `-6h`, `-1d`, `-7d`.\n\n# Parameters\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Omit when you only need the primary window.\n\n- `compare` (boolean): set to true to enable comparison.\n- `compare_to` (string, optional): relative offset for the comparison window (e.g. `-1d`, `-7d`). Defaults to the immediately previous period of equal length.\n\n## query.serviceNames\n\nList of service names to restrict the aggregation to. Use `apm-services-list` to discover available services.\n\n## query.filterGroup\n\nA flat list of property filters applied to both the primary and comparison windows. See the \"Property filters\" section.\n\n## query.limit\n\nMax rows to return, ordered by `total_duration_nano` DESC. Defaults to 100; hard max 5000. Keep this small — a high value on high-cardinality span names returns a very large response. Narrow with `serviceNames`/`filterGroup` instead of raising it when you can.\n\n## query.offset\n\nRow offset for pagination. Combine with `limit` and the `next_offset` from a previous response to page through results beyond the first page.\n\n## query.groupByEndpoint\n\nSet to `true` to get per-endpoint health for HTTP servers. Rows then group by `METHOD route` (for example `GET /users/{id}`) from the `http.route` attribute, in place of the span name.\n\n- Only HTTP server spans (span kind server with an HTTP method) are counted. Queue consumers, workflow activities and client spans are left out.\n- A span without `http.route` keeps its span name as the row key.\n- Use it when span names are raw paths (`/users/1`, `/users/2`) or a bare method (`GET`), which split or merge routes.\n\n# Examples\n\n## Top operations by total time in the last hour\n\n```json\n{\n \"query\": {}\n}\n```\n\n## p95 latency by operation in the last day\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\nInspect the `p95_duration_nano` field on each result.\n\n## Compare this hour vs the previous hour\n\n```json\n{\n \"query\": {\n \"compareFilter\": { \"compare\": true }\n }\n}\n```\n\nReturns `results` for the last hour and `compare` for the hour before. Diff `total_duration_nano`, `avg_duration_nano`, etc. to find regressions.\n\n## Compare today vs same time last week\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Aggregate only error spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Endpoint health for one service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"groupByEndpoint\": true,\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\nEach row is one route. Compare `error_count / count` and `p95_duration_nano` across rows to find unhealthy endpoints.\n\n## Aggregate within one service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n# Reminders\n\n- Duration values in results are in nanoseconds. Divide by 1,000,000 for ms, 1,000,000,000 for seconds. A `duration` filter value is in milliseconds.\n- Results are ordered by `total_duration_nano` DESC and default to the top 100 rows. Check `has_more`/`next_offset` to page; raise `limit` (max 5000) only when you truly need the long tail.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attribute keys/values before filtering.\n- Use `apm-services-list` to discover services before filtering by service name.\n- For parent → child breakdowns, use `apm-spans-tree` instead.",
+ "description": "Aggregate trace span statistics grouped by `(service_name, name)` over a date window.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nReturns one row per `(service_name, name)` pair with the following metrics:\n\n- `count` — number of spans matched\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano`, `p99_duration_nano`, `p999_duration_nano` — duration stats in nanoseconds (1 second = 1,000,000,000 ns). `p999_duration_nano` is the 99.9th percentile and is only meaningful for `(service, name)` groups with enough spans; on low-volume operations it collapses to the max\n- `error_count` — spans with OTel status code `Error` (status_code = 2)\n\nRows are ordered by `total_duration_nano` DESC. By default only the top 100 rows are returned — this keeps the response small, which matters because high span-name cardinality (e.g. untemplated URL paths) can otherwise produce an enormous payload. The top rows already surface the heaviest operations. When more rows genuinely exist the response sets `has_more: true` and `next_offset`; page through with `offset`, or raise `limit` (hard max 5000). Prefer narrowing with `serviceNames`/`filterGroup` over pulling a large page.\n\nUse to answer:\n\n- \"Which services/operations consume the most time?\"\n- \"What's the p95 or p99 latency of `GET /users`?\"\n- \"How many errors did the checkout service emit in the last day?\"\n- \"Did `POST /orders` get slower this week vs last week?\" (with `compareFilter`)\n\nFor per-call-tree breakdowns (parent → child relationships), use `apm-spans-tree` instead. For time-bucketed trends (\"when did it change?\"), use `apm-spans-sparkline` instead — `compareFilter` only contrasts two static windows.\n\n# Comparison window\n\nSet `query.compareFilter.compare: true` to also fetch a comparison window. The response then includes a `compare` array of the same shape as `results`.\n\n- Omit `compare_to` (or set null) to compare against the immediately previous period of equal length (e.g. `dateRange: -1d` → compares vs the day before).\n- Set `compare_to: \"-7d\"` to compare against the window 7 days earlier (same length as the primary window).\n\nWhen `compare` is true, `compare` is always an array — empty (`[]`) if the comparison window matched no spans (for example an operation that didn't exist yet), not null. `compare` is `null` only when no comparison was requested. So an empty array is a real answer (\"nothing in the prior window\"), not a failure.\n\n# Data narrowing\n\n## Property filters\n\nUse `query.filterGroup` to narrow results to spans matching specific attributes. Only include filters that are essential to the user's question.\n\nFilter `type` values:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). A `duration` filter value is in milliseconds (1 second = `1000`).\n- `span_attribute` — span-level attributes (e.g. \"http.method\", \"http.status_code\")\n- `span_resource_attribute` — resource-level attributes (e.g. k8s labels, deployment info)\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values before guessing.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nAn attribute filter (`span_attribute` or `span_resource_attribute`) matches only spans that have the attribute, also for negated operators such as `is_not` and `not_icontains`. To find spans without the attribute, use `is_not_set`.\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`). Examples: `-1h`, `-6h`, `-1d`, `-7d`.\n\n# Parameters\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Omit when you only need the primary window.\n\n- `compare` (boolean): set to true to enable comparison.\n- `compare_to` (string, optional): relative offset for the comparison window (e.g. `-1d`, `-7d`). Defaults to the immediately previous period of equal length.\n\n## query.serviceNames\n\nList of service names to restrict the aggregation to. Use `apm-services-list` to discover available services.\n\n## query.filterGroup\n\nA flat list of property filters applied to both the primary and comparison windows. See the \"Property filters\" section.\n\n## query.limit\n\nMax rows to return, ordered by `total_duration_nano` DESC. Defaults to 100; hard max 5000. Keep this small — a high value on high-cardinality span names returns a very large response. Narrow with `serviceNames`/`filterGroup` instead of raising it when you can.\n\n## query.offset\n\nRow offset for pagination. Combine with `limit` and the `next_offset` from a previous response to page through results beyond the first page.\n\n## query.groupByEndpoint\n\nSet to `true` to get per-endpoint health for HTTP servers. Rows then group by `METHOD route` (for example `GET /users/{id}`) from the `http.route` attribute, in place of the span name.\n\n- Only HTTP server spans (span kind server with an HTTP method) are counted. Queue consumers, workflow activities and client spans are left out.\n- A span without `http.route` keeps its span name as the row key.\n- Use it when span names are raw paths (`/users/1`, `/users/2`) or a bare method (`GET`), which split or merge routes.\n\n## query.includeHealth\n\nSet to `true` to get `health_status` and `health_reason` on every row. Each row is compared with the same row in the `compareFilter` window, or in the previous period of the same length when `compareFilter` is off.\n\n- `regressed`: the error rate or p95 jumped against the baseline.\n- `degraded`: the error rate is high, with no clear jump.\n- `new`: the row has no spans in the baseline.\n- `recovered` and `improved`: the error rate or p95 went down.\n- `ok`: none of the above.\n\nIt runs a second window query for the routes on the current page. Without `compareFilter`, the response `compare` stays null. With `compareFilter`, `compare` holds the baseline rows for those same routes.\n\n# Examples\n\n## Top operations by total time in the last hour\n\n```json\n{\n \"query\": {}\n}\n```\n\n## p95 latency by operation in the last day\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\nInspect the `p95_duration_nano` field on each result.\n\n## Compare this hour vs the previous hour\n\n```json\n{\n \"query\": {\n \"compareFilter\": { \"compare\": true }\n }\n}\n```\n\nReturns `results` for the last hour and `compare` for the hour before. Diff `total_duration_nano`, `avg_duration_nano`, etc. to find regressions.\n\n## Compare today vs same time last week\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Aggregate only error spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Endpoint health for one service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"groupByEndpoint\": true,\n \"includeHealth\": true,\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\nEach row is one route. Start with the rows whose `health_status` is `regressed` or `degraded`, and read `health_reason` for the cause.\n\n## Aggregate within one service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n# Reminders\n\n- Duration values in results are in nanoseconds. Divide by 1,000,000 for ms, 1,000,000,000 for seconds. A `duration` filter value is in milliseconds.\n- Results are ordered by `total_duration_nano` DESC and default to the top 100 rows. Check `has_more`/`next_offset` to page; raise `limit` (max 5000) only when you truly need the long tail.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attribute keys/values before filtering.\n- Use `apm-services-list` to discover services before filtering by service name.\n- For parent → child breakdowns, use `apm-spans-tree` instead.",
"category": "Tracing",
"feature": "tracing",
"summary": "Aggregate span statistics",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 9ffffc576288..8948c8445204 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1257,7 +1257,7 @@
"feature_flag": "tracing"
},
"apm-spans-aggregate": {
- "description": "Aggregate trace span statistics grouped by `(service_name, name)` over a date window.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nReturns one row per `(service_name, name)` pair with the following metrics:\n\n- `count` — number of spans matched\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano`, `p99_duration_nano`, `p999_duration_nano` — duration stats in nanoseconds (1 second = 1,000,000,000 ns). `p999_duration_nano` is the 99.9th percentile and is only meaningful for `(service, name)` groups with enough spans; on low-volume operations it collapses to the max\n- `error_count` — spans with OTel status code `Error` (status_code = 2)\n\nRows are ordered by `total_duration_nano` DESC. By default only the top 100 rows are returned — this keeps the response small, which matters because high span-name cardinality (e.g. untemplated URL paths) can otherwise produce an enormous payload. The top rows already surface the heaviest operations. When more rows genuinely exist the response sets `has_more: true` and `next_offset`; page through with `offset`, or raise `limit` (hard max 5000). Prefer narrowing with `serviceNames`/`filterGroup` over pulling a large page.\n\nUse to answer:\n\n- \"Which services/operations consume the most time?\"\n- \"What's the p95 or p99 latency of `GET /users`?\"\n- \"How many errors did the checkout service emit in the last day?\"\n- \"Did `POST /orders` get slower this week vs last week?\" (with `compareFilter`)\n\nFor per-call-tree breakdowns (parent → child relationships), use `apm-spans-tree` instead. For time-bucketed trends (\"when did it change?\"), use `apm-spans-sparkline` instead — `compareFilter` only contrasts two static windows.\n\n# Comparison window\n\nSet `query.compareFilter.compare: true` to also fetch a comparison window. The response then includes a `compare` array of the same shape as `results`.\n\n- Omit `compare_to` (or set null) to compare against the immediately previous period of equal length (e.g. `dateRange: -1d` → compares vs the day before).\n- Set `compare_to: \"-7d\"` to compare against the window 7 days earlier (same length as the primary window).\n\nWhen `compare` is true, `compare` is always an array — empty (`[]`) if the comparison window matched no spans (for example an operation that didn't exist yet), not null. `compare` is `null` only when no comparison was requested. So an empty array is a real answer (\"nothing in the prior window\"), not a failure.\n\n# Data narrowing\n\n## Property filters\n\nUse `query.filterGroup` to narrow results to spans matching specific attributes. Only include filters that are essential to the user's question.\n\nFilter `type` values:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). A `duration` filter value is in milliseconds (1 second = `1000`).\n- `span_attribute` — span-level attributes (e.g. \"http.method\", \"http.status_code\")\n- `span_resource_attribute` — resource-level attributes (e.g. k8s labels, deployment info)\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values before guessing.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nAn attribute filter (`span_attribute` or `span_resource_attribute`) matches only spans that have the attribute, also for negated operators such as `is_not` and `not_icontains`. To find spans without the attribute, use `is_not_set`.\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`). Examples: `-1h`, `-6h`, `-1d`, `-7d`.\n\n# Parameters\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Omit when you only need the primary window.\n\n- `compare` (boolean): set to true to enable comparison.\n- `compare_to` (string, optional): relative offset for the comparison window (e.g. `-1d`, `-7d`). Defaults to the immediately previous period of equal length.\n\n## query.serviceNames\n\nList of service names to restrict the aggregation to. Use `apm-services-list` to discover available services.\n\n## query.filterGroup\n\nA flat list of property filters applied to both the primary and comparison windows. See the \"Property filters\" section.\n\n## query.limit\n\nMax rows to return, ordered by `total_duration_nano` DESC. Defaults to 100; hard max 5000. Keep this small — a high value on high-cardinality span names returns a very large response. Narrow with `serviceNames`/`filterGroup` instead of raising it when you can.\n\n## query.offset\n\nRow offset for pagination. Combine with `limit` and the `next_offset` from a previous response to page through results beyond the first page.\n\n## query.groupByEndpoint\n\nSet to `true` to get per-endpoint health for HTTP servers. Rows then group by `METHOD route` (for example `GET /users/{id}`) from the `http.route` attribute, in place of the span name.\n\n- Only HTTP server spans (span kind server with an HTTP method) are counted. Queue consumers, workflow activities and client spans are left out.\n- A span without `http.route` keeps its span name as the row key.\n- Use it when span names are raw paths (`/users/1`, `/users/2`) or a bare method (`GET`), which split or merge routes.\n\n# Examples\n\n## Top operations by total time in the last hour\n\n```json\n{\n \"query\": {}\n}\n```\n\n## p95 latency by operation in the last day\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\nInspect the `p95_duration_nano` field on each result.\n\n## Compare this hour vs the previous hour\n\n```json\n{\n \"query\": {\n \"compareFilter\": { \"compare\": true }\n }\n}\n```\n\nReturns `results` for the last hour and `compare` for the hour before. Diff `total_duration_nano`, `avg_duration_nano`, etc. to find regressions.\n\n## Compare today vs same time last week\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Aggregate only error spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Endpoint health for one service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"groupByEndpoint\": true,\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\nEach row is one route. Compare `error_count / count` and `p95_duration_nano` across rows to find unhealthy endpoints.\n\n## Aggregate within one service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n# Reminders\n\n- Duration values in results are in nanoseconds. Divide by 1,000,000 for ms, 1,000,000,000 for seconds. A `duration` filter value is in milliseconds.\n- Results are ordered by `total_duration_nano` DESC and default to the top 100 rows. Check `has_more`/`next_offset` to page; raise `limit` (max 5000) only when you truly need the long tail.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attribute keys/values before filtering.\n- Use `apm-services-list` to discover services before filtering by service name.\n- For parent → child breakdowns, use `apm-spans-tree` instead.",
+ "description": "Aggregate trace span statistics grouped by `(service_name, name)` over a date window.\n\nAll parameters go inside `query` — top-level fields are rejected:\n\n```json\n{ \"query\": { \"serviceNames\": [\"api\"], \"dateRange\": { \"date_from\": \"-1h\" } } }\n```\n\nReturns one row per `(service_name, name)` pair with the following metrics:\n\n- `count` — number of spans matched\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano`, `p99_duration_nano`, `p999_duration_nano` — duration stats in nanoseconds (1 second = 1,000,000,000 ns). `p999_duration_nano` is the 99.9th percentile and is only meaningful for `(service, name)` groups with enough spans; on low-volume operations it collapses to the max\n- `error_count` — spans with OTel status code `Error` (status_code = 2)\n\nRows are ordered by `total_duration_nano` DESC. By default only the top 100 rows are returned — this keeps the response small, which matters because high span-name cardinality (e.g. untemplated URL paths) can otherwise produce an enormous payload. The top rows already surface the heaviest operations. When more rows genuinely exist the response sets `has_more: true` and `next_offset`; page through with `offset`, or raise `limit` (hard max 5000). Prefer narrowing with `serviceNames`/`filterGroup` over pulling a large page.\n\nUse to answer:\n\n- \"Which services/operations consume the most time?\"\n- \"What's the p95 or p99 latency of `GET /users`?\"\n- \"How many errors did the checkout service emit in the last day?\"\n- \"Did `POST /orders` get slower this week vs last week?\" (with `compareFilter`)\n\nFor per-call-tree breakdowns (parent → child relationships), use `apm-spans-tree` instead. For time-bucketed trends (\"when did it change?\"), use `apm-spans-sparkline` instead — `compareFilter` only contrasts two static windows.\n\n# Comparison window\n\nSet `query.compareFilter.compare: true` to also fetch a comparison window. The response then includes a `compare` array of the same shape as `results`.\n\n- Omit `compare_to` (or set null) to compare against the immediately previous period of equal length (e.g. `dateRange: -1d` → compares vs the day before).\n- Set `compare_to: \"-7d\"` to compare against the window 7 days earlier (same length as the primary window).\n\nWhen `compare` is true, `compare` is always an array — empty (`[]`) if the comparison window matched no spans (for example an operation that didn't exist yet), not null. `compare` is `null` only when no comparison was requested. So an empty array is a real answer (\"nothing in the prior window\"), not a failure.\n\n# Data narrowing\n\n## Property filters\n\nUse `query.filterGroup` to narrow results to spans matching specific attributes. Only include filters that are essential to the user's question.\n\nFilter `type` values:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). A `duration` filter value is in milliseconds (1 second = `1000`).\n- `span_attribute` — span-level attributes (e.g. \"http.method\", \"http.status_code\")\n- `span_resource_attribute` — resource-level attributes (e.g. k8s labels, deployment info)\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values before guessing.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nAn attribute filter (`span_attribute` or `span_resource_attribute`) matches only spans that have the attribute, also for negated operators such as `is_not` and `not_icontains`. To find spans without the attribute, use `is_not_set`.\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`). Examples: `-1h`, `-6h`, `-1d`, `-7d`.\n\n# Parameters\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Omit when you only need the primary window.\n\n- `compare` (boolean): set to true to enable comparison.\n- `compare_to` (string, optional): relative offset for the comparison window (e.g. `-1d`, `-7d`). Defaults to the immediately previous period of equal length.\n\n## query.serviceNames\n\nList of service names to restrict the aggregation to. Use `apm-services-list` to discover available services.\n\n## query.filterGroup\n\nA flat list of property filters applied to both the primary and comparison windows. See the \"Property filters\" section.\n\n## query.limit\n\nMax rows to return, ordered by `total_duration_nano` DESC. Defaults to 100; hard max 5000. Keep this small — a high value on high-cardinality span names returns a very large response. Narrow with `serviceNames`/`filterGroup` instead of raising it when you can.\n\n## query.offset\n\nRow offset for pagination. Combine with `limit` and the `next_offset` from a previous response to page through results beyond the first page.\n\n## query.groupByEndpoint\n\nSet to `true` to get per-endpoint health for HTTP servers. Rows then group by `METHOD route` (for example `GET /users/{id}`) from the `http.route` attribute, in place of the span name.\n\n- Only HTTP server spans (span kind server with an HTTP method) are counted. Queue consumers, workflow activities and client spans are left out.\n- A span without `http.route` keeps its span name as the row key.\n- Use it when span names are raw paths (`/users/1`, `/users/2`) or a bare method (`GET`), which split or merge routes.\n\n## query.includeHealth\n\nSet to `true` to get `health_status` and `health_reason` on every row. Each row is compared with the same row in the `compareFilter` window, or in the previous period of the same length when `compareFilter` is off.\n\n- `regressed`: the error rate or p95 jumped against the baseline.\n- `degraded`: the error rate is high, with no clear jump.\n- `new`: the row has no spans in the baseline.\n- `recovered` and `improved`: the error rate or p95 went down.\n- `ok`: none of the above.\n\nIt runs a second window query for the routes on the current page. Without `compareFilter`, the response `compare` stays null. With `compareFilter`, `compare` holds the baseline rows for those same routes.\n\n# Examples\n\n## Top operations by total time in the last hour\n\n```json\n{\n \"query\": {}\n}\n```\n\n## p95 latency by operation in the last day\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\nInspect the `p95_duration_nano` field on each result.\n\n## Compare this hour vs the previous hour\n\n```json\n{\n \"query\": {\n \"compareFilter\": { \"compare\": true }\n }\n}\n```\n\nReturns `results` for the last hour and `compare` for the hour before. Diff `total_duration_nano`, `avg_duration_nano`, etc. to find regressions.\n\n## Compare today vs same time last week\n\n```json\n{\n \"query\": {\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Aggregate only error spans\n\n```json\n{\n \"query\": {\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Endpoint health for one service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"groupByEndpoint\": true,\n \"includeHealth\": true,\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\nEach row is one route. Start with the rows whose `health_status` is `regressed` or `degraded`, and read `health_reason` for the cause.\n\n## Aggregate within one service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n# Reminders\n\n- Duration values in results are in nanoseconds. Divide by 1,000,000 for ms, 1,000,000,000 for seconds. A `duration` filter value is in milliseconds.\n- Results are ordered by `total_duration_nano` DESC and default to the top 100 rows. Check `has_more`/`next_offset` to page; raise `limit` (max 5000) only when you truly need the long tail.\n- Use `apm-attributes-list` and `apm-attribute-values-list` to discover attribute keys/values before filtering.\n- Use `apm-services-list` to discover services before filtering by service name.\n- For parent → child breakdowns, use `apm-spans-tree` instead.",
"category": "Tracing",
"feature": "tracing",
"summary": "Aggregate span statistics",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index bb3681f0e9dc..d6022c127fd1 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -12239,10 +12239,27 @@ export namespace Schemas {
models: AgentModelOption[];
}
+ export type SpanHealthStatus = typeof SpanHealthStatus[keyof typeof SpanHealthStatus];
+
+
+ export const SpanHealthStatus = {
+ Silent: 'silent',
+ Regressed: 'regressed',
+ Degraded: 'degraded',
+ New: 'new',
+ Recovered: 'recovered',
+ Improved: 'improved',
+ Ok: 'ok',
+ } as const;
+
export interface AggregatedSpanRow {
avg_duration_nano: number;
count: number;
error_count: number;
+ /** Short reason for `health_status`, such as `error rate 0.2% → 4.1%`. Empty when the status is `ok`. */
+ health_reason?: string | null;
+ /** Set only when the query asked for `includeHealth`. Same statuses as the service health check. */
+ health_status?: SpanHealthStatus | null;
name: string;
p50_duration_nano: number;
p95_duration_nano: number;
@@ -62339,6 +62356,8 @@ export namespace Schemas {
filterGroup?: PropertyGroupFilter | null;
/** Group HTTP server spans by `METHOD route` in place of the span name. Spans without a route keep their name. Spans that are not HTTP server spans are left out. */
groupByEndpoint?: boolean | null;
+ /** Classify each row against the comparison window, or the previous period when `compareFilter` is off. Fills `health_status` and `health_reason`. Runs a second window query. */
+ includeHealth?: boolean | null;
/** Also aggregate sessions and people per operation. Off by default: it reads the attribute maps. */
includeImpact?: boolean | null;
kind?: 'TraceSpansAggregationQuery';
@@ -125361,6 +125380,21 @@ export namespace Schemas {
* @nullable
*/
spans_with_distinct_id: number | null;
+ /** How this group compares with its baseline: regressed (error rate or p95 jumped), degraded (high error rate), new (no spans in the baseline), recovered, improved, or ok. Null unless the query set `includeHealth`.
+ *
+ * * `silent` - Silent
+ * * `regressed` - Regressed
+ * * `degraded` - Degraded
+ * * `new` - New
+ * * `recovered` - Recovered
+ * * `improved` - Improved
+ * * `ok` - Ok */
+ health_status: ServiceHealthStatusEnum | null;
+ /**
+ * Short reason for `health_status`, such as `error rate 0.2% → 4.1%`. Empty when the status is ok.
+ * @nullable
+ */
+ health_reason: string | null;
}
export interface _CompareFilter {
@@ -127308,6 +127342,8 @@ export namespace Schemas {
includeImpact?: boolean;
/** Group HTTP server spans by `METHOD route` (from `http.route`) in place of the span name, so raw paths like `/users/1` and `/users/2` fold into one row. Spans without a route keep their span name. Spans that are not HTTP server spans are left out. */
groupByEndpoint?: boolean;
+ /** Also return `health_status` and `health_reason` per row, comparing each row with the same row in the comparison window, or in the previous period when `compareFilter` is off. Uses the same statuses and thresholds as the service health check. Costs a second window query. */
+ includeHealth?: boolean;
}
export interface _TracingAggregationRequest {
diff --git a/services/mcp/src/generated/tracing/api.ts b/services/mcp/src/generated/tracing/api.ts
index a332838fd08c..0f4ae969a66a 100644
--- a/services/mcp/src/generated/tracing/api.ts
+++ b/services/mcp/src/generated/tracing/api.ts
@@ -24,6 +24,7 @@ export const tracingSpansAggregateCreateBodyQueryOneOffsetMin = 0
export const tracingSpansAggregateCreateBodyQueryOneIncludeImpactDefault = false
export const tracingSpansAggregateCreateBodyQueryOneGroupByEndpointDefault = false
+export const tracingSpansAggregateCreateBodyQueryOneIncludeHealthDefault = false
export const TracingSpansAggregateCreateBody = () => zod.object({
query: zod
@@ -139,6 +140,12 @@ export const TracingSpansAggregateCreateBody = () => zod.object({
.describe(
'Group HTTP server spans by `METHOD route` (from `http.route`) in place of the span name, so raw paths like `\/users\/1` and `\/users\/2` fold into one row. Spans without a route keep their span name. Spans that are not HTTP server spans are left out.'
),
+ includeHealth: zod
+ .boolean()
+ .default(tracingSpansAggregateCreateBodyQueryOneIncludeHealthDefault)
+ .describe(
+ 'Also return `health_status` and `health_reason` per row, comparing each row with the same row in the comparison window, or in the previous period when `compareFilter` is off. Uses the same statuses and thresholds as the service health check. Costs a second window query.'
+ ),
})
.describe('The span aggregation query to execute.'),
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-aggregate.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-aggregate.json
index cead78dd5995..a1c2cdc2a1fa 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-aggregate.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-spans-aggregate.json
@@ -102,6 +102,11 @@
"description": "Group HTTP server spans by `METHOD route` (from `http.route`) in place of the span name, so raw paths like `/users/1` and `/users/2` fold into one row. Spans without a route keep their span name. Spans that are not HTTP server spans are left out.",
"type": "boolean"
},
+ "includeHealth": {
+ "default": false,
+ "description": "Also return `health_status` and `health_reason` per row, comparing each row with the same row in the comparison window, or in the previous period when `compareFilter` is off. Uses the same statuses and thresholds as the service health check. Costs a second window query.",
+ "type": "boolean"
+ },
"includeImpact": {
"default": false,
"description": "Also return the sessions and people behind each operation. Off by default because it reads the span and resource attribute maps, which the rest of the aggregation never touches.",