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): add per-span self-time and call-tree fan-out ratio (#63479)

Jon McCallumada0882826e0
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 65782658c6d2..ff64f0ee4186 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -40303,6 +40303,10 @@
"description": "Average nanoseconds from the parent span's start to this span's start. Zero for root spans. Used to order children left-to-right by typical start time in the flame graph.",
"type": "number"
},
+ "calls_per_parent_invocation": {
+ "description": "How many times this child runs per parent invocation (edge count / parent span count). Separates fan-out volume from per-call cost: a child can dominate total_duration_nano purely by running many times per parent. Null for root edges (no parent invocation to ratio against).",
+ "type": ["number", "null"]
+ },
"count": {
"$ref": "#/definitions/integer"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 6b1da432068c..afe2fc071cd7 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -3293,6 +3293,13 @@ export interface SpanTreeNode {
* flame graph.
*/
avg_start_offset_nano: number
+ /**
+ * How many times this child runs per parent invocation (edge count / parent span
+ * count). Separates fan-out volume from per-call cost: a child can dominate
+ * total_duration_nano purely by running many times per parent. Null for root edges
+ * (no parent invocation to ratio against).
+ */
+ calls_per_parent_invocation?: number | null
}
export interface TraceSpansTreeQuery extends DataNode<TraceSpansTreeQueryResponse> {
diff --git a/posthog/schema.py b/posthog/schema.py
index e61755f9ad87..20a5835c2e72 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -6656,6 +6656,15 @@ class SpanTreeNode(BaseModel):
" start time in the flame graph."
),
)
+ calls_per_parent_invocation: float | None = Field(
+ default=None,
+ description=(
+ "How many times this child runs per parent invocation (edge count / parent"
+ " span count). Separates fan-out volume from per-call cost: a child can"
+ " dominate total_duration_nano purely by running many times per parent."
+ " Null for root edges (no parent invocation to ratio against)."
+ ),
+ )
count: int
error_count: int
name: str
diff --git a/products/tracing/backend/aggregation_query_runner.py b/products/tracing/backend/aggregation_query_runner.py
index a30d948d9f8b..4affdaf4ec03 100644
--- a/products/tracing/backend/aggregation_query_runner.py
+++ b/products/tracing/backend/aggregation_query_runner.py
@@ -325,6 +325,28 @@ class TraceSpansAggregationQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunn
return response
+def _annotate_calls_per_parent_invocation(rows: list[SpanTreeNode]) -> None:
+ """Set each edge's child-calls-per-parent-invocation ratio, in place.
+
+ A parent's invocation count is the sum of edge counts where it appears as the child
+ (it may appear under several grandparents). Root edges have no parent invocation to
+ ratio against, so they stay None.
+
+ The denominator is reconstructed from the returned rows, so when the tree hits the
+ `_ROW_LIMIT` cap a parent's child edges can be split across the cut, understating the
+ denominator and overstating the ratio. That only happens with very high span-name
+ cardinality in one service; the prompt doc flags the ratio as approximate at the cap.
+ """
+ invocations: dict[tuple[str, str], int] = {}
+ for node in rows:
+ key = (node.service_name, node.name)
+ invocations[key] = invocations.get(key, 0) + node.count
+ for node in rows:
+ parent_total = invocations.get((node.parent_service, node.parent_name))
+ if parent_total:
+ node.calls_per_parent_invocation = node.count / parent_total
+
+
class TraceSpansTreeQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunner[TraceSpansTreeQueryResponse]):
query: TraceSpansTreeQuery
cached_response: CachedTraceSpansTreeQueryResponse
@@ -337,6 +359,9 @@ class TraceSpansTreeQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunner[Trac
def _calculate(self) -> TraceSpansTreeQueryResponse:
current_rows, previous_rows = self._run_with_compare()
+ _annotate_calls_per_parent_invocation(current_rows)
+ if previous_rows is not None:
+ _annotate_calls_per_parent_invocation(previous_rows)
return TraceSpansTreeQueryResponse(results=current_rows, compare=previous_rows)
def _build_query(self, query_date_range: QueryDateRange) -> ast.SelectQuery:
diff --git a/products/tracing/backend/facade/api.py b/products/tracing/backend/facade/api.py
index 0336fcace025..df35fc63d51c 100644
--- a/products/tracing/backend/facade/api.py
+++ b/products/tracing/backend/facade/api.py
@@ -37,6 +37,7 @@ from products.tracing.backend.count_query_runner import run_count_query as _run_
from products.tracing.backend.duration_histogram_query_runner import (
run_duration_histogram_query as _run_duration_histogram_query,
)
+from products.tracing.backend.self_time import annotate_self_time as _annotate_self_time
if TYPE_CHECKING:
from posthog.models import Team
@@ -107,3 +108,8 @@ def run_duration_histogram_query(
status_codes=status_codes,
filter_group=filter_group,
)
+
+
+def annotate_self_time(spans: list[dict]) -> None:
+ """Set `self_time_nano` on every span dict of a full trace, in place."""
+ _annotate_self_time(spans)
diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.py
index 23cbab027060..1062e9218698 100644
--- a/products/tracing/backend/presentation/views.py
+++ b/products/tracing/backend/presentation/views.py
@@ -40,7 +40,12 @@ from posthog.clickhouse.query_tagging import Feature, tag_queries
from posthog.event_usage import report_user_action
from posthog.hogql_queries.query_runner import ExecutionMode
-from ..facade.api import run_attribute_breakdown_query, run_count_query, run_duration_histogram_query
+from ..facade.api import (
+ annotate_self_time,
+ run_attribute_breakdown_query,
+ run_count_query,
+ run_duration_histogram_query,
+)
from ..has_spans_query_runner import team_has_spans
from ..logic import (
TraceSpansQueryRunner,
@@ -813,6 +818,11 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
response = runner.run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
assert isinstance(response, TraceSpansQueryResponse | CachedTraceSpansQueryResponse)
+ # Only this endpoint returns the (practically) full trace, so per-span self-time
+ # is computable here — query results elsewhere see partial traces.
+ if isinstance(response.results, list):
+ annotate_self_time(response.results)
+
return Response(
{"results": response.results},
status=status.HTTP_200_OK,
diff --git a/products/tracing/backend/self_time.py b/products/tracing/backend/self_time.py
new file mode 100644
index 000000000000..68592ef13c4a
--- /dev/null
+++ b/products/tracing/backend/self_time.py
@@ -0,0 +1,42 @@
+"""Per-span self-time annotation for full-trace payloads.
+
+Self-time is the part of a span's duration not covered by its children — computed as an
+interval union so overlapping or parallel children are only subtracted once. For a leaf
+it equals the span's own duration; for a parent it is the unaccounted gap ("where did
+the wall-clock actually go"), which is invisible from duration_nano alone.
+"""
+
+import datetime as dt
+from collections import defaultdict
+
+_MICROSECOND = dt.timedelta(microseconds=1)
+
+
+def annotate_self_time(spans: list[dict]) -> None:
+ """Set `self_time_nano` on every span dict, in place.
+
+ Expects the full span set of a trace (children grouped by `parent_span_id`);
+ `timestamp` / `end_time` must still be datetimes. On a truncated trace the values
+ overstate self-time for spans whose children were cut.
+ """
+ children_by_parent: dict[str, list[dict]] = defaultdict(list)
+ for span in spans:
+ children_by_parent[span["parent_span_id"]].append(span)
+
+ for span in spans:
+ start, end = span["timestamp"], span["end_time"]
+ intervals = sorted(
+ (max(child["timestamp"], start), min(child["end_time"], end))
+ for child in children_by_parent.get(span["span_id"], [])
+ if child["timestamp"] < end and child["end_time"] > start
+ )
+
+ covered_ns = 0
+ cursor = start
+ for child_start, child_end in intervals:
+ child_start = max(child_start, cursor)
+ if child_end > child_start:
+ covered_ns += ((child_end - child_start) // _MICROSECOND) * 1000
+ cursor = child_end
+
+ span["self_time_nano"] = max(span["duration_nano"] - covered_ns, 0)
diff --git a/products/tracing/backend/tests/test_aggregation_query_runner.py b/products/tracing/backend/tests/test_aggregation_query_runner.py
index 59fcedb1243a..3d0568e616e8 100644
--- a/products/tracing/backend/tests/test_aggregation_query_runner.py
+++ b/products/tracing/backend/tests/test_aggregation_query_runner.py
@@ -1,46 +1,25 @@
-import base64
import datetime as dt
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin
-
from parameterized import parameterized
from posthog.schema import DateRange
from posthog.clickhouse.client import sync_execute
-from posthog.clickhouse.query_tagging import tag_queries
-from posthog.clickhouse.traces.spans import TRACE_SPANS_DISTRIBUTED_TABLE_SQL, TRACE_SPANS_TABLE_SQL
from products.tracing.backend.logic import run_tree_query
+from products.tracing.backend.tests.test_keyset_pagination import DATE_FROM, DATE_TO, _b64, _TraceSpansTestBase
-DATE_FROM = "2026-06-02T07:00:00Z"
-DATE_TO = "2026-06-02T09:00:00Z"
# Child starts 40ms after its parent. In nanoseconds that's 40_000_000 — the unit the
# avg_start_offset_nano column claims to report.
CHILD_OFFSET_MS = 40
EXPECTED_OFFSET_NANO = CHILD_OFFSET_MS * 1_000_000
-def _b64(raw: bytes) -> str:
- return base64.b64encode(raw).decode("ascii")
-
-
-class TestTraceSpansTreeStartOffset(ClickhouseTestMixin, APIBaseTest):
- CLASS_DATA_LEVEL_SETUP = True
-
+class TestTraceSpansTreeStartOffset(_TraceSpansTestBase):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
- tag_queries(product="tracing", feature="query")
- sync_execute("DROP TABLE IF EXISTS trace_spans_distributed")
- sync_execute("DROP TABLE IF EXISTS trace_spans")
- sync_execute(TRACE_SPANS_TABLE_SQL())
- # is_root_span ships via a separate logs-cluster migration, not the Python DDL.
- sync_execute(
- "ALTER TABLE trace_spans ADD COLUMN IF NOT EXISTS "
- "is_root_span Bool MATERIALIZED (replaceAll(trimRight(parent_span_id, '='), 'A', '')) = ''"
- )
- sync_execute(TRACE_SPANS_DISTRIBUTED_TABLE_SQL())
+ cls._recreate_trace_spans_tables()
trace_id = _b64((1).to_bytes(16, "big"))
parent_span_id = _b64((1).to_bytes(8, "big"))
@@ -66,14 +45,6 @@ class TestTraceSpansTreeStartOffset(ClickhouseTestMixin, APIBaseTest):
"timestamp, end_time, observed_timestamp, status_code, service_name) VALUES " + ",".join(rows)
)
- @classmethod
- def tearDownClass(cls):
- 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()
-
@parameterized.expand(
[
# Pre-fix the child returned ~0.04 (seconds), not 40_000_000 (nanos).
@@ -90,3 +61,53 @@ class TestTraceSpansTreeStartOffset(ClickhouseTestMixin, APIBaseTest):
)
edge = next(node for node in response.results if node.name == edge_name)
self.assertEqual(edge.avg_start_offset_nano, expected_offset_nano)
+
+
+class TestTraceSpansTreeCallRatio(_TraceSpansTestBase):
+ @classmethod
+ def setUpTestData(cls):
+ super().setUpTestData()
+ cls._recreate_trace_spans_tables()
+
+ # Two traces, each: one entry-op root fanning out to three child-op spans. The
+ # (entry-op → child-op) edge counts 6 children over 2 parent invocations → ratio 3.
+ ts_str = dt.datetime(2026, 6, 2, 8, 0, 0).strftime("%Y-%m-%d %H:%M:%S.%f")
+ rows: list[str] = []
+ for trace_no in (1, 2):
+ trace_id = _b64(trace_no.to_bytes(16, "big"))
+ root_span_id = _b64((trace_no * 100).to_bytes(8, "big"))
+ rows.append(
+ f"('019e875a-0000-0000-{trace_no:04d}-000000000000', {cls.team.id}, '{trace_id}', "
+ f"'{root_span_id}', '', 'entry-op', 2, '{ts_str}', '{ts_str}', '{ts_str}', 0, 'web')"
+ )
+ for child_no in range(1, 4):
+ child_span_id = _b64((trace_no * 100 + child_no).to_bytes(8, "big"))
+ rows.append(
+ f"('019e875a-0000-0000-{trace_no:04d}-{child_no:012d}', {cls.team.id}, '{trace_id}', "
+ f"'{child_span_id}', '{root_span_id}', 'child-op', 2, '{ts_str}', '{ts_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)
+ )
+
+ def test_fan_out_edge_reports_calls_per_parent_invocation(self):
+ response = run_tree_query(
+ team=self.team,
+ date_range=DateRange(date_from=DATE_FROM, date_to=DATE_TO),
+ span_name="entry-op",
+ service_name="web",
+ )
+ child_edge = next(node for node in response.results if node.name == "child-op")
+ self.assertEqual(child_edge.count, 6)
+ self.assertEqual(child_edge.calls_per_parent_invocation, 3.0)
+
+ def test_root_edge_has_no_parent_invocation_ratio(self):
+ response = run_tree_query(
+ team=self.team,
+ date_range=DateRange(date_from=DATE_FROM, date_to=DATE_TO),
+ span_name="entry-op",
+ service_name="web",
+ )
+ root_edge = next(node for node in response.results if node.parent_name == "<ROOT>")
+ self.assertIsNone(root_edge.calls_per_parent_invocation)
diff --git a/products/tracing/backend/tests/test_self_time.py b/products/tracing/backend/tests/test_self_time.py
new file mode 100644
index 000000000000..7cb2eb4e062b
--- /dev/null
+++ b/products/tracing/backend/tests/test_self_time.py
@@ -0,0 +1,77 @@
+import datetime as dt
+
+from posthog.clickhouse.client import sync_execute
+
+from products.tracing.backend.tests.test_keyset_pagination import _b64, _TraceSpansTestBase
+
+MS = 1_000_000 # ns per ms
+BASE = dt.datetime(2026, 6, 2, 8, 0, 0)
+
+# Trace 1 — overlapping children: root spans 1s; child A covers 0-100ms, child B 50-150ms.
+# Their union is 150ms, so root self-time is 850ms (interval union, not a 200ms sum).
+# Trace 2 — parallel children: both cover 0-100ms exactly; union is 100ms, so root
+# self-time is 900ms (a sum would wrongly say 800ms).
+TRACES = {
+ 1: [
+ # (span_no, parent_no | None, start_offset_ms, duration_ms)
+ (1, None, 0, 1000),
+ (2, 1, 0, 100),
+ (3, 1, 50, 100),
+ ],
+ 2: [
+ (1, None, 0, 1000),
+ (2, 1, 0, 100),
+ (3, 1, 0, 100),
+ ],
+}
+
+
+class TestTraceSelfTime(_TraceSpansTestBase):
+ @classmethod
+ def setUpTestData(cls):
+ super().setUpTestData()
+ cls._recreate_trace_spans_tables()
+
+ rows: list[str] = []
+ for trace_no, spans in TRACES.items():
+ trace_id = _b64(trace_no.to_bytes(16, "big"))
+ for span_no, parent_no, start_offset_ms, duration_ms in spans:
+ span_id = _b64((trace_no * 100 + span_no).to_bytes(8, "big"))
+ parent = _b64((trace_no * 100 + parent_no).to_bytes(8, "big")) if parent_no else ""
+ start = BASE + dt.timedelta(milliseconds=start_offset_ms)
+ end = start + dt.timedelta(milliseconds=duration_ms)
+ rows.append(
+ f"('019e8759-0000-0000-{trace_no:04d}-{span_no:012d}', {cls.team.id}, '{trace_id}', "
+ f"'{span_id}', '{parent}', 'op-{span_no}', 2, "
+ f"'{start.strftime('%Y-%m-%d %H:%M:%S.%f')}', '{end.strftime('%Y-%m-%d %H:%M:%S.%f')}', "
+ f"'{start.strftime('%Y-%m-%d %H:%M:%S.%f')}', 0, 'web')"
+ )
+ sync_execute(
+ "INSERT INTO trace_spans (uuid, team_id, trace_id, span_id, parent_span_id, name, kind, "
+ "timestamp, end_time, observed_timestamp, status_code, service_name) VALUES " + ",".join(rows)
+ )
+
+ def _trace_spans(self, trace_no: int) -> dict[str, dict]:
+ trace_hex = trace_no.to_bytes(16, "big").hex()
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/tracing/spans/trace/{trace_hex}/",
+ {"dateRange": {"date_from": "2026-06-02T07:00:00Z", "date_to": "2026-06-02T09:00:00Z"}},
+ format="json",
+ )
+ self.assertEqual(response.status_code, 200, response.content)
+ return {span["name"]: span for span in response.json()["results"]}
+
+ def test_overlapping_children_cover_their_union_not_their_sum(self):
+ spans = self._trace_spans(1)
+ # Children 0-100ms and 50-150ms merge to 150ms covered → 850ms unaccounted in the root.
+ self.assertEqual(spans["op-1"]["self_time_nano"], 850 * MS)
+
+ def test_parallel_children_are_not_double_counted(self):
+ spans = self._trace_spans(2)
+ # Two children both spanning 0-100ms cover 100ms once → 900ms self-time.
+ self.assertEqual(spans["op-1"]["self_time_nano"], 900 * MS)
+
+ def test_leaf_self_time_is_its_own_duration(self):
+ spans = self._trace_spans(1)
+ self.assertEqual(spans["op-2"]["self_time_nano"], 100 * MS)
+ self.assertEqual(spans["op-3"]["self_time_nano"], 100 * MS)
diff --git a/products/tracing/mcp/prompts/apm-spans-tree.md b/products/tracing/mcp/prompts/apm-spans-tree.md
index c4fc3f26b0e3..cdfd780fe8a1 100644
--- a/products/tracing/mcp/prompts/apm-spans-tree.md
+++ b/products/tracing/mcp/prompts/apm-spans-tree.md
@@ -10,6 +10,7 @@ Returns rows with:
- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano` — duration stats in nanoseconds
- `error_count` — child spans with OTel status code `Error` (status_code = 2)
- `avg_start_offset_nano` — average nanoseconds from the parent span's start to this child's start
+- `calls_per_parent_invocation` — how many times this child runs per parent invocation (null for root edges). A child can top `total_duration_nano` purely by fan-out volume; divide by this to compare per-call cost
Rows are ordered by `total_duration_nano` DESC and capped at 5000.
@@ -136,5 +137,6 @@ Property filters applied to both windows. See the "Property filters" section.
- Root spans have `parent_name = "<ROOT>"` and `avg_start_offset_nano = 0`.
- Duration values are in nanoseconds.
- Results are ordered by `total_duration_nano` DESC and capped at 5000 rows.
+- `calls_per_parent_invocation` is derived from the returned rows. If results hit the 5000-row cap (only happens with very high span-name cardinality in one service), a parent's edges can be split across the cut and the ratio can read high — treat it as approximate when the row count is at the cap.
- For a flat per-operation aggregate without parent linkage, use `apm-spans-aggregate`.
- Use `apm-services-list`, `apm-attributes-list`, `apm-attribute-values-list` to discover values before filtering.
diff --git a/products/tracing/mcp/tools.yaml b/products/tracing/mcp/tools.yaml
index 6140ac2181e8..76c4b7761caa 100644
--- a/products/tracing/mcp/tools.yaml
+++ b/products/tracing/mcp/tools.yaml
@@ -176,9 +176,12 @@ tools:
title: Retrieve trace spans
description: >
Fetch all spans for a specific trace by its hex trace ID. Returns the full span tree for the trace including
- parent-child relationships, timing, status information, and each span's attributes map. Use this to inspect
- a specific trace in detail after discovering it via the query tool. Set excludeAttributes to true to drop
- the per-span attributes map (which can hold multi-KB values like db.statement) and keep the payload compact.
+ parent-child relationships, timing, status information, and each span's attributes map. Each span carries
+ self_time_nano — its duration not covered by child spans — so "where did the wall-clock go" is answered by
+ sorting on it: a large self_time_nano on a parent span is an uninstrumented gap, not time in any child. Use
+ this to inspect a specific trace in detail after discovering it via the query tool. Set excludeAttributes to
+ true to drop the per-span attributes map (which can hold multi-KB values like db.statement) and keep the
+ payload compact.
ui_app: trace-span-list
feature_flag: tracing
response:
diff --git a/products/tracing/skills/exploring-apm-traces/SKILL.md b/products/tracing/skills/exploring-apm-traces/SKILL.md
index bac8c4fe4de0..b430b4a69df3 100644
--- a/products/tracing/skills/exploring-apm-traces/SKILL.md
+++ b/products/tracing/skills/exploring-apm-traces/SKILL.md
@@ -97,9 +97,11 @@ To rebuild the tree:
### "Where is time going?"
-1. Run `print_summary.py` — it surfaces the top-5 slowest spans by `duration_nano`.
-2. For a noisy trace, run `print_timeline.py` and scan the indented durations — you can see whether time is dominated by one child span or fan-out across many.
-3. To dig into one slow span, `SPAN="<name>" python3 scripts/extract_span.py FILE`.
+1. Every span from `apm-trace-get` carries `self_time_nano` — duration not covered by children. Sort by it: the top span is where wall-clock actually went. A parent with large `self_time_nano` is an **uninstrumented gap** (the work happened inside it, not in any recorded child).
+2. Run `print_summary.py` — it surfaces the top-5 slowest spans by `duration_nano`.
+3. For a noisy trace, run `print_timeline.py` and scan the indented durations — you can see whether time is dominated by one child span or fan-out across many.
+4. To dig into one slow span, `SPAN="<name>" python3 scripts/extract_span.py FILE`.
+5. For aggregate "which child dominates" questions use `apm-spans-tree` and read `calls_per_parent_invocation` — it separates a child that's slow per call from one that merely runs 20× per parent.
### "Where did the error happen?"
diff --git a/products/tracing/skills/exploring-apm-traces/references/spans-and-fields.md b/products/tracing/skills/exploring-apm-traces/references/spans-and-fields.md
index 6ebcbe23316a..460d7581b9a5 100644
--- a/products/tracing/skills/exploring-apm-traces/references/spans-and-fields.md
+++ b/products/tracing/skills/exploring-apm-traces/references/spans-and-fields.md
@@ -4,22 +4,23 @@ Fields returned by `apm-trace-get` and `query-apm-spans`.
## Span fields
-| Field | Type | Description |
-| ---------------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `uuid` | string | Internal row UUID (rarely useful for analysis) |
-| `trace_id` | hex string | 32-char hex ID linking every span in one trace |
-| `span_id` | hex string | 16-char hex ID for this span |
-| `parent_span_id` | hex string | Parent span's hex ID. Zero-padded `"00000000…"` for root spans |
-| `name` | string | Operation name (e.g. `HTTP GET /api/users`, `db.query`) |
-| `kind` | int 0–5 | OpenTelemetry span kind (see enum below) |
-| `service_name` | string | Service that emitted the span |
-| `status_code` | int 0–2 | OpenTelemetry status (see enum below). `2` is the only error indicator |
-| `timestamp` | ISO 8601 | Start time |
-| `end_time` | ISO 8601 | End time |
-| `duration_nano` | int | Duration in **nanoseconds** (1s = 1_000_000_000) |
-| `is_root_span` | bool | Convenience flag for the trace entry — prefer this over comparing parent ID |
-| `matched_filter` | int 0/1 | `1` if this span matched the `query-apm-spans` filter; `0` if it only shares a trace with a match (root/prefetched sibling). Always present; only meaningful from `query-apm-spans` |
-| `attributes` | map | Span-level OTel attributes the span set, e.g. `http.method`, `db.statement`, `net.peer.name`. A string-keyed map |
+| Field | Type | Description |
+| ---------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `uuid` | string | Internal row UUID (rarely useful for analysis) |
+| `trace_id` | hex string | 32-char hex ID linking every span in one trace |
+| `span_id` | hex string | 16-char hex ID for this span |
+| `parent_span_id` | hex string | Parent span's hex ID. Zero-padded `"00000000…"` for root spans |
+| `name` | string | Operation name (e.g. `HTTP GET /api/users`, `db.query`) |
+| `kind` | int 0–5 | OpenTelemetry span kind (see enum below) |
+| `service_name` | string | Service that emitted the span |
+| `status_code` | int 0–2 | OpenTelemetry status (see enum below). `2` is the only error indicator |
+| `timestamp` | ISO 8601 | Start time |
+| `end_time` | ISO 8601 | End time |
+| `duration_nano` | int | Duration in **nanoseconds** (1s = 1_000_000_000) |
+| `is_root_span` | bool | Convenience flag for the trace entry — prefer this over comparing parent ID |
+| `matched_filter` | int 0/1 | `1` if this span matched the `query-apm-spans` filter; `0` if it only shares a trace with a match (root/prefetched sibling). Always present; only meaningful from `query-apm-spans` |
+| `attributes` | map | Span-level OTel attributes the span set, e.g. `http.method`, `db.statement`, `net.peer.name`. A string-keyed map |
+| `self_time_nano` | int | `apm-trace-get` only. Duration not covered by child spans (interval union — overlapping/parallel children counted once). Leaf: own duration. Parent: the unaccounted gap — sort by this to find where wall-clock actually went |
**Returned in the payload:** span-level `attributes` (above) — read them straight off the span.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 8d86d43bd836..e113cb40ecc8 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -521,7 +521,7 @@
"feature_flag": "tracing"
},
"apm-spans-tree": {
- "description": "Aggregate trace span statistics as a call tree — one row per `(parent_service, parent_name) → (service_name, name)` edge.\n\nRequires a `spanName` to bound the matched trace set (the `(trace_id, parent_span_id)` self-join is unsafe at high cardinality without it), and a `serviceName` to scope the returned tree to a single service. All traces that contain at least one span with the given name in the given service are included, and every span in those traces from that service is aggregated against its parent.\n\nReturns rows with:\n\n- `parent_service`, `parent_name` — the parent span identity (`parent_name` is `\"<ROOT>\"` for root spans)\n- `service_name`, `name` — the child span identity\n- `count` — number of spans matched for this `(parent, child)` edge\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano` — duration stats in nanoseconds\n- `error_count` — child spans with OTel status code `Error` (status_code = 2)\n- `avg_start_offset_nano` — average nanoseconds from the parent span's start to this child's start\n\nRows are ordered by `total_duration_nano` DESC and capped at 5000.\n\nUse to answer:\n\n- \"What does the `/checkout` flow actually call downstream?\"\n- \"Which child operation under `POST /orders` is the slowest?\"\n- \"Where is time spent inside `process_payment` — DB, external API, or something else?\"\n- \"Did the call tree under `/api/feed` change between last week and this week?\" (with `compareFilter`)\n\nFor a flat per-operation view (no parent linkage), use `apm-spans-aggregate` instead.\n\nAll parameters must be nested inside a `query` object.\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.\n- Set `compare_to: \"-7d\"` to compare against the window 7 days earlier (same length as the primary window).\n\n# Data narrowing\n\n## Property filters\n\n`query.filterGroup` narrows the matched span set. Same filter shape and operators as `apm-spans-aggregate` / `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values.\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`).\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.spanName (required)\n\nThe span name that anchors the matched trace set. Every trace containing at least one span with this name (in the given `serviceName`) is included.\n\nPick a high-level entry-point span (e.g. an HTTP route or job name). Generic names (`HTTP`, `GET`) match too many traces and produce noisy aggregates. Use `query-apm-spans` first if you need to discover concrete span names.\n\n## query.serviceName (required)\n\nThe service the tree should be scoped to. Applied to the spans CTE so the returned rows only contain spans from this service, even when the matched traces also touch other services. Use `apm-services-list` to discover service names.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Same shape as in `apm-spans-aggregate`.\n\n## query.serviceNames\n\nList of service names to filter the matched span set. Use `apm-services-list` to discover services.\n\n## query.filterGroup\n\nProperty filters applied to both windows. See the \"Property filters\" section.\n\n# Examples\n\n## Call tree under a specific operation in the last hour\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\"\n }\n}\n```\n\n## Call tree over the last day\n\n```json\n{\n \"query\": {\n \"spanName\": \"checkout_flow\",\n \"serviceName\": \"web-server\",\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Compare today's call tree vs last week\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\",\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Restrict to error-bearing traces\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\",\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }]\n }\n}\n```\n\n# Reminders\n\n- `spanName` and `serviceName` are both required. Bound `spanName` to a specific high-level span (avoid generic names like `HTTP`); set `serviceName` to the one service whose call-tree you want.\n- Root spans have `parent_name = \"<ROOT>\"` and `avg_start_offset_nano = 0`.\n- Duration values are in nanoseconds.\n- Results are ordered by `total_duration_nano` DESC and capped at 5000 rows.\n- For a flat per-operation aggregate without parent linkage, use `apm-spans-aggregate`.\n- Use `apm-services-list`, `apm-attributes-list`, `apm-attribute-values-list` to discover values before filtering.",
+ "description": "Aggregate trace span statistics as a call tree — one row per `(parent_service, parent_name) → (service_name, name)` edge.\n\nRequires a `spanName` to bound the matched trace set (the `(trace_id, parent_span_id)` self-join is unsafe at high cardinality without it), and a `serviceName` to scope the returned tree to a single service. All traces that contain at least one span with the given name in the given service are included, and every span in those traces from that service is aggregated against its parent.\n\nReturns rows with:\n\n- `parent_service`, `parent_name` — the parent span identity (`parent_name` is `\"<ROOT>\"` for root spans)\n- `service_name`, `name` — the child span identity\n- `count` — number of spans matched for this `(parent, child)` edge\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano` — duration stats in nanoseconds\n- `error_count` — child spans with OTel status code `Error` (status_code = 2)\n- `avg_start_offset_nano` — average nanoseconds from the parent span's start to this child's start\n- `calls_per_parent_invocation` — how many times this child runs per parent invocation (null for root edges). A child can top `total_duration_nano` purely by fan-out volume; divide by this to compare per-call cost\n\nRows are ordered by `total_duration_nano` DESC and capped at 5000.\n\nUse to answer:\n\n- \"What does the `/checkout` flow actually call downstream?\"\n- \"Which child operation under `POST /orders` is the slowest?\"\n- \"Where is time spent inside `process_payment` — DB, external API, or something else?\"\n- \"Did the call tree under `/api/feed` change between last week and this week?\" (with `compareFilter`)\n\nFor a flat per-operation view (no parent linkage), use `apm-spans-aggregate` instead.\n\nAll parameters must be nested inside a `query` object.\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.\n- Set `compare_to: \"-7d\"` to compare against the window 7 days earlier (same length as the primary window).\n\n# Data narrowing\n\n## Property filters\n\n`query.filterGroup` narrows the matched span set. Same filter shape and operators as `apm-spans-aggregate` / `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values.\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`).\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.spanName (required)\n\nThe span name that anchors the matched trace set. Every trace containing at least one span with this name (in the given `serviceName`) is included.\n\nPick a high-level entry-point span (e.g. an HTTP route or job name). Generic names (`HTTP`, `GET`) match too many traces and produce noisy aggregates. Use `query-apm-spans` first if you need to discover concrete span names.\n\n## query.serviceName (required)\n\nThe service the tree should be scoped to. Applied to the spans CTE so the returned rows only contain spans from this service, even when the matched traces also touch other services. Use `apm-services-list` to discover service names.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Same shape as in `apm-spans-aggregate`.\n\n## query.serviceNames\n\nList of service names to filter the matched span set. Use `apm-services-list` to discover services.\n\n## query.filterGroup\n\nProperty filters applied to both windows. See the \"Property filters\" section.\n\n# Examples\n\n## Call tree under a specific operation in the last hour\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\"\n }\n}\n```\n\n## Call tree over the last day\n\n```json\n{\n \"query\": {\n \"spanName\": \"checkout_flow\",\n \"serviceName\": \"web-server\",\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Compare today's call tree vs last week\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\",\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Restrict to error-bearing traces\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\",\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }]\n }\n}\n```\n\n# Reminders\n\n- `spanName` and `serviceName` are both required. Bound `spanName` to a specific high-level span (avoid generic names like `HTTP`); set `serviceName` to the one service whose call-tree you want.\n- Root spans have `parent_name = \"<ROOT>\"` and `avg_start_offset_nano = 0`.\n- Duration values are in nanoseconds.\n- Results are ordered by `total_duration_nano` DESC and capped at 5000 rows.\n- `calls_per_parent_invocation` is derived from the returned rows. If results hit the 5000-row cap (only happens with very high span-name cardinality in one service), a parent's edges can be split across the cut and the ratio can read high — treat it as approximate when the row count is at the cap.\n- For a flat per-operation aggregate without parent linkage, use `apm-spans-aggregate`.\n- Use `apm-services-list`, `apm-attributes-list`, `apm-attribute-values-list` to discover values before filtering.",
"category": "Tracing",
"feature": "tracing",
"summary": "Aggregate span call tree",
@@ -536,7 +536,7 @@
"feature_flag": "tracing"
},
"apm-trace-get": {
- "description": "Fetch all spans for a specific trace by its hex trace ID. Returns the full span tree for the trace including parent-child relationships, timing, status information, and each span's attributes map. Use this to inspect a specific trace in detail after discovering it via the query tool. Set excludeAttributes to true to drop the per-span attributes map (which can hold multi-KB values like db.statement) and keep the payload compact.",
+ "description": "Fetch all spans for a specific trace by its hex trace ID. Returns the full span tree for the trace including parent-child relationships, timing, status information, and each span's attributes map. Each span carries self_time_nano — its duration not covered by child spans — so \"where did the wall-clock go\" is answered by sorting on it: a large self_time_nano on a parent span is an uninstrumented gap, not time in any child. Use this to inspect a specific trace in detail after discovering it via the query tool. Set excludeAttributes to true to drop the per-span attributes map (which can hold multi-KB values like db.statement) and keep the payload compact.",
"category": "Tracing",
"feature": "tracing",
"summary": "Retrieve trace spans",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 8bb383fa3c5d..f54990f1f9a0 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -537,7 +537,7 @@
"feature_flag": "tracing"
},
"apm-spans-tree": {
- "description": "Aggregate trace span statistics as a call tree — one row per `(parent_service, parent_name) → (service_name, name)` edge.\n\nRequires a `spanName` to bound the matched trace set (the `(trace_id, parent_span_id)` self-join is unsafe at high cardinality without it), and a `serviceName` to scope the returned tree to a single service. All traces that contain at least one span with the given name in the given service are included, and every span in those traces from that service is aggregated against its parent.\n\nReturns rows with:\n\n- `parent_service`, `parent_name` — the parent span identity (`parent_name` is `\"<ROOT>\"` for root spans)\n- `service_name`, `name` — the child span identity\n- `count` — number of spans matched for this `(parent, child)` edge\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano` — duration stats in nanoseconds\n- `error_count` — child spans with OTel status code `Error` (status_code = 2)\n- `avg_start_offset_nano` — average nanoseconds from the parent span's start to this child's start\n\nRows are ordered by `total_duration_nano` DESC and capped at 5000.\n\nUse to answer:\n\n- \"What does the `/checkout` flow actually call downstream?\"\n- \"Which child operation under `POST /orders` is the slowest?\"\n- \"Where is time spent inside `process_payment` — DB, external API, or something else?\"\n- \"Did the call tree under `/api/feed` change between last week and this week?\" (with `compareFilter`)\n\nFor a flat per-operation view (no parent linkage), use `apm-spans-aggregate` instead.\n\nAll parameters must be nested inside a `query` object.\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.\n- Set `compare_to: \"-7d\"` to compare against the window 7 days earlier (same length as the primary window).\n\n# Data narrowing\n\n## Property filters\n\n`query.filterGroup` narrows the matched span set. Same filter shape and operators as `apm-spans-aggregate` / `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values.\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`).\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.spanName (required)\n\nThe span name that anchors the matched trace set. Every trace containing at least one span with this name (in the given `serviceName`) is included.\n\nPick a high-level entry-point span (e.g. an HTTP route or job name). Generic names (`HTTP`, `GET`) match too many traces and produce noisy aggregates. Use `query-apm-spans` first if you need to discover concrete span names.\n\n## query.serviceName (required)\n\nThe service the tree should be scoped to. Applied to the spans CTE so the returned rows only contain spans from this service, even when the matched traces also touch other services. Use `apm-services-list` to discover service names.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Same shape as in `apm-spans-aggregate`.\n\n## query.serviceNames\n\nList of service names to filter the matched span set. Use `apm-services-list` to discover services.\n\n## query.filterGroup\n\nProperty filters applied to both windows. See the \"Property filters\" section.\n\n# Examples\n\n## Call tree under a specific operation in the last hour\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\"\n }\n}\n```\n\n## Call tree over the last day\n\n```json\n{\n \"query\": {\n \"spanName\": \"checkout_flow\",\n \"serviceName\": \"web-server\",\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Compare today's call tree vs last week\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\",\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Restrict to error-bearing traces\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\",\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }]\n }\n}\n```\n\n# Reminders\n\n- `spanName` and `serviceName` are both required. Bound `spanName` to a specific high-level span (avoid generic names like `HTTP`); set `serviceName` to the one service whose call-tree you want.\n- Root spans have `parent_name = \"<ROOT>\"` and `avg_start_offset_nano = 0`.\n- Duration values are in nanoseconds.\n- Results are ordered by `total_duration_nano` DESC and capped at 5000 rows.\n- For a flat per-operation aggregate without parent linkage, use `apm-spans-aggregate`.\n- Use `apm-services-list`, `apm-attributes-list`, `apm-attribute-values-list` to discover values before filtering.",
+ "description": "Aggregate trace span statistics as a call tree — one row per `(parent_service, parent_name) → (service_name, name)` edge.\n\nRequires a `spanName` to bound the matched trace set (the `(trace_id, parent_span_id)` self-join is unsafe at high cardinality without it), and a `serviceName` to scope the returned tree to a single service. All traces that contain at least one span with the given name in the given service are included, and every span in those traces from that service is aggregated against its parent.\n\nReturns rows with:\n\n- `parent_service`, `parent_name` — the parent span identity (`parent_name` is `\"<ROOT>\"` for root spans)\n- `service_name`, `name` — the child span identity\n- `count` — number of spans matched for this `(parent, child)` edge\n- `total_duration_nano`, `avg_duration_nano`, `p50_duration_nano`, `p95_duration_nano` — duration stats in nanoseconds\n- `error_count` — child spans with OTel status code `Error` (status_code = 2)\n- `avg_start_offset_nano` — average nanoseconds from the parent span's start to this child's start\n- `calls_per_parent_invocation` — how many times this child runs per parent invocation (null for root edges). A child can top `total_duration_nano` purely by fan-out volume; divide by this to compare per-call cost\n\nRows are ordered by `total_duration_nano` DESC and capped at 5000.\n\nUse to answer:\n\n- \"What does the `/checkout` flow actually call downstream?\"\n- \"Which child operation under `POST /orders` is the slowest?\"\n- \"Where is time spent inside `process_payment` — DB, external API, or something else?\"\n- \"Did the call tree under `/api/feed` change between last week and this week?\" (with `compareFilter`)\n\nFor a flat per-operation view (no parent linkage), use `apm-spans-aggregate` instead.\n\nAll parameters must be nested inside a `query` object.\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.\n- Set `compare_to: \"-7d\"` to compare against the window 7 days earlier (same length as the primary window).\n\n# Data narrowing\n\n## Property filters\n\n`query.filterGroup` narrows the matched span set. Same filter shape and operators as `apm-spans-aggregate` / `query-apm-spans`:\n\n- `span` — built-in span fields (trace_id, span_id, duration, name, kind, status_code, is_root_span)\n- `span_attribute` — span-level attributes\n- `span_resource_attribute` — resource-level attributes\n\nUse `apm-attributes-list` and `apm-attribute-values-list` to discover available attribute keys/values.\n\n## Time period\n\nUse `query.dateRange` to control the time window. Default is the last hour (`-1h`).\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.spanName (required)\n\nThe span name that anchors the matched trace set. Every trace containing at least one span with this name (in the given `serviceName`) is included.\n\nPick a high-level entry-point span (e.g. an HTTP route or job name). Generic names (`HTTP`, `GET`) match too many traces and produce noisy aggregates. Use `query-apm-spans` first if you need to discover concrete span names.\n\n## query.serviceName (required)\n\nThe service the tree should be scoped to. Applied to the spans CTE so the returned rows only contain spans from this service, even when the matched traces also touch other services. Use `apm-services-list` to discover service names.\n\n## query.dateRange\n\nDate range for the primary window. Defaults to the last hour.\n\n- `date_from`: Start of the range. ISO 8601 or relative: `-1h`, `-6h`, `-1d`, `-7d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.compareFilter\n\nOptional comparison-window configuration. Same shape as in `apm-spans-aggregate`.\n\n## query.serviceNames\n\nList of service names to filter the matched span set. Use `apm-services-list` to discover services.\n\n## query.filterGroup\n\nProperty filters applied to both windows. See the \"Property filters\" section.\n\n# Examples\n\n## Call tree under a specific operation in the last hour\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\"\n }\n}\n```\n\n## Call tree over the last day\n\n```json\n{\n \"query\": {\n \"spanName\": \"checkout_flow\",\n \"serviceName\": \"web-server\",\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Compare today's call tree vs last week\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\",\n \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Restrict to error-bearing traces\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"serviceName\": \"web-server\",\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }]\n }\n}\n```\n\n# Reminders\n\n- `spanName` and `serviceName` are both required. Bound `spanName` to a specific high-level span (avoid generic names like `HTTP`); set `serviceName` to the one service whose call-tree you want.\n- Root spans have `parent_name = \"<ROOT>\"` and `avg_start_offset_nano = 0`.\n- Duration values are in nanoseconds.\n- Results are ordered by `total_duration_nano` DESC and capped at 5000 rows.\n- `calls_per_parent_invocation` is derived from the returned rows. If results hit the 5000-row cap (only happens with very high span-name cardinality in one service), a parent's edges can be split across the cut and the ratio can read high — treat it as approximate when the row count is at the cap.\n- For a flat per-operation aggregate without parent linkage, use `apm-spans-aggregate`.\n- Use `apm-services-list`, `apm-attributes-list`, `apm-attribute-values-list` to discover values before filtering.",
"category": "Tracing",
"feature": "tracing",
"summary": "Aggregate span call tree",
@@ -552,7 +552,7 @@
"feature_flag": "tracing"
},
"apm-trace-get": {
- "description": "Fetch all spans for a specific trace by its hex trace ID. Returns the full span tree for the trace including parent-child relationships, timing, status information, and each span's attributes map. Use this to inspect a specific trace in detail after discovering it via the query tool. Set excludeAttributes to true to drop the per-span attributes map (which can hold multi-KB values like db.statement) and keep the payload compact.",
+ "description": "Fetch all spans for a specific trace by its hex trace ID. Returns the full span tree for the trace including parent-child relationships, timing, status information, and each span's attributes map. Each span carries self_time_nano — its duration not covered by child spans — so \"where did the wall-clock go\" is answered by sorting on it: a large self_time_nano on a parent span is an uninstrumented gap, not time in any child. Use this to inspect a specific trace in detail after discovering it via the query tool. Set excludeAttributes to true to drop the per-span attributes map (which can hold multi-KB values like db.statement) and keep the payload compact.",
"category": "Tracing",
"feature": "tracing",
"summary": "Retrieve trace spans",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c61a5a192a1e..c0ca4c476c99 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -21356,6 +21356,8 @@ export namespace Schemas {
avg_duration_nano: number;
/** Average nanoseconds from the parent span's start to this span's start. Zero for root spans. Used to order children left-to-right by typical start time in the flame graph. */
avg_start_offset_nano: number;
+ /** How many times this child runs per parent invocation (edge count / parent span count). Separates fan-out volume from per-call cost: a child can dominate total_duration_nano purely by running many times per parent. Null for root edges (no parent invocation to ratio against). */
+ calls_per_parent_invocation?: number | null;
count: number;
error_count: number;
name: string;