: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tracing): filter span tree view to the selected service (#58567)
Frank Hamandfb17a1a1b039
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 8eda38cf1091..a6bdc21cba16 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -2889,6 +2889,7 @@ const api = {async tree(query: {spanName: string+ serviceName: stringdateRange?: { date_from?: string | null; date_to?: string | null }serviceNames?: string[]filterGroup?: PropertyGroupFilterdiff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 4186e329dee1..863077337741 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -37986,6 +37986,10 @@"response": {"$ref": "#/definitions/TraceSpansTreeQueryResponse"},+ "serviceName": {+ "description": "Service name that scopes the returned tree. Applied to the spans CTE so the call-tree only contains spans from this service, even when matched traces span multiple services.",+ "type": "string"+ },"serviceNames": {"items": {"type": "string"@@ -38004,7 +38008,7 @@"type": "number"}},- "required": ["dateRange", "kind", "spanName"],+ "required": ["dateRange", "kind", "serviceName", "spanName"],"type": "object"},"TraceSpansTreeQueryResponse": {diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 52ef17ea5d09..9177706dfcf6 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -3128,6 +3128,12 @@ export interface TraceSpansTreeQuery extends DataNode<TraceSpansTreeQueryRespons* matched traces — at high name cardinality the query becomes unsafe to run.*/spanName: string+ /**+ * Service name that scopes the returned tree. Applied to the spans CTE so the+ * call-tree only contains spans from this service, even when matched traces+ * span multiple services.+ */+ serviceName: string/** Optional comparison window — when `compare` is true, the runner returns an extra `compare` result set. */compareFilter?: CompareFilterfilterGroup?: PropertyGroupFilterdiff --git a/posthog/schema.py b/posthog/schema.pyindex 421f4bebf796..84404e299eab 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -20374,6 +20374,14 @@ class TraceSpansTreeQuery(BaseModel):kind: Literal["TraceSpansTreeQuery"] = "TraceSpansTreeQuery"modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")response: TraceSpansTreeQueryResponse | None = None+ serviceName: str = Field(+ ...,+ description=(+ "Service name that scopes the returned tree. Applied to the spans CTE so"+ " the call-tree only contains spans from this service, even when matched"+ " traces span multiple services."+ ),+ )serviceNames: list[str] | None = NonespanName: str = Field(...,diff --git a/products/tracing/backend/aggregation_query_runner.py b/products/tracing/backend/aggregation_query_runner.pyindex 8d1581fc5e9c..619e6ba258dc 100644--- a/products/tracing/backend/aggregation_query_runner.py+++ b/products/tracing/backend/aggregation_query_runner.py@@ -339,7 +339,9 @@ class TraceSpansTreeQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunner[Tracdef _build_query(self, query_date_range: QueryDateRange) -> ast.SelectQuery:# The CTE has to widen the span-name filter so we can also fetch parent and# ancestor rows that match by trace_id but not by name; otherwise the LEFT JOIN- # can't recover the parent.+ # can't recover the parent. The service filter, however, is applied to the spans+ # CTE so the resulting tree is scoped to one service even when matched traces+ # span multiple services.query = parse_select("""WITH matched_traces AS (@@ -347,6 +349,7 @@ class TraceSpansTreeQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunner[TracFROM posthog.trace_spansWHERE {where}AND name = {span_name}+ AND service_name = {service_name}AND toStartOfDay(time_bucket) >= toStartOfDay({date_from})AND toStartOfDay(time_bucket) <= toStartOfDay({date_to})AND timestamp >= {date_from}@@ -358,6 +361,7 @@ class TraceSpansTreeQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunner[Tracduration_nano, status_code, timestampFROM posthog.trace_spansWHERE trace_id IN (SELECT trace_id FROM matched_traces)+ AND service_name = {service_name}AND toStartOfDay(time_bucket) >= toStartOfDay({date_from})AND toStartOfDay(time_bucket) <= toStartOfDay({date_to})AND timestamp >= {date_from}@@ -391,6 +395,7 @@ class TraceSpansTreeQueryRunner(_SpanAggregationMixin, AnalyticsQueryRunner[Tracplaceholders={"where": self._where_without_date_range(),"span_name": ast.Constant(value=self.query.spanName),+ "service_name": ast.Constant(value=self.query.serviceName),"limit": ast.Constant(value=_ROW_LIMIT),**query_date_range.to_placeholders(),},diff --git a/products/tracing/backend/logic.py b/products/tracing/backend/logic.pyindex d27026d4214d..919b52f16424 100644--- a/products/tracing/backend/logic.py+++ b/products/tracing/backend/logic.py@@ -686,6 +686,7 @@ def run_tree_query(team: "Team",date_range: DateRange,span_name: str,+ service_name: str,compare_filter: CompareFilter | None = None,filter_group: PropertyGroupFilter | None = None,service_names: list[str] | None = None,@@ -694,6 +695,7 @@ def run_tree_query(query = TraceSpansTreeQuery(dateRange=date_range,spanName=span_name,+ serviceName=service_name,compareFilter=compare_filter,filterGroup=filter_group,serviceNames=service_names,diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.pyindex 28f1e660458d..e560ca3199fc 100644--- a/products/tracing/backend/presentation/views.py+++ b/products/tracing/backend/presentation/views.py@@ -234,6 +234,14 @@ class _TracingTreeQueryBodySerializer(serializers.Serializer):"(trace_id, parent_span_id) self-join is unsafe without bounding the matched traces."),)+ serviceName = serializers.CharField(+ required=True,+ help_text=(+ "Service name that scopes the returned tree. Applied to the spans CTE so "+ "the call-tree only contains spans from this service, even when matched "+ "traces span multiple services."+ ),+ )dateRange = _TracingDateRangeSerializer(required=False,help_text="Date range for the primary window. Defaults to last hour.",@@ -426,6 +434,13 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)status=status.HTTP_400_BAD_REQUEST,)+ service_name = query_data.get("serviceName")+ if not service_name or not isinstance(service_name, str):+ return Response(+ {"detail": "`serviceName` is required for tree aggregation queries."},+ status=status.HTTP_400_BAD_REQUEST,+ )+date_range = self.get_model(query_data.get("dateRange", {"date_from": "-1h"}), DateRange)try:@@ -449,6 +464,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)team=self.team,date_range=date_range,span_name=span_name,+ service_name=service_name,compare_filter=compare_filter,filter_group=filter_group,service_names=query_data.get("serviceNames", None),diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsxindex 802ed457cd9a..b9ee75d7beff 100644--- a/products/tracing/frontend/TracingScene.tsx+++ b/products/tracing/frontend/TracingScene.tsx@@ -170,7 +170,7 @@ function TracingSceneContents(): JSX.Element {current={aggregation.current}previous={aggregation.previous}loading={aggregationLoading}- onRowClick={(row) => openCompareFlame(row.name)}+ onRowClick={(row) => openCompareFlame(row.name, row.service_name)}/>) : (<LemonTablediff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.tsindex af1b3d29d291..0fd23e755d2a 100644--- a/products/tracing/frontend/generated/api.schemas.ts+++ b/products/tracing/frontend/generated/api.schemas.ts@@ -164,6 +164,8 @@ export interface _TracingTraceRequestApi {export interface _TracingTreeQueryBodyApi {/** Span name to scope the matched trace set. Required because the (trace_id, parent_span_id) self-join is unsafe without bounding the matched traces. */spanName: string+ /** Service name that scopes the returned tree. Applied to the spans CTE so the call-tree only contains spans from this service, even when matched traces span multiple services. */+ serviceName: string/** Date range for the primary window. Defaults to last hour. */dateRange?: _TracingDateRangeApi/** Optional comparison-window configuration. When omitted, only the primary window is returned. */diff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.tsindex 652ceb120882..89c75a0d2c50 100644--- a/products/tracing/frontend/generated/api.zod.ts+++ b/products/tracing/frontend/generated/api.zod.ts@@ -310,6 +310,11 @@ export const TracingSpansTreeCreateBody = /* @__PURE__ */ zod.object({.describe('Span name to scope the matched trace set. Required because the (trace_id, parent_span_id) self-join is unsafe without bounding the matched traces.'),+ serviceName: zod+ .string()+ .describe(+ 'Service name that scopes the returned tree. Applied to the spans CTE so the call-tree only contains spans from this service, even when matched traces span multiple services.'+ ),dateRange: zod.object({date_from: zoddiff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.tsindex 274bf39c6be5..7ed0798b4ef3 100644--- a/products/tracing/frontend/tracingDataLogic.ts+++ b/products/tracing/frontend/tracingDataLogic.ts@@ -241,7 +241,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([previous: null as SpanTreeNode[] | null,},{- fetchSpanTree: async (params: { spanName: string }) => {+ fetchSpanTree: async (params: { spanName: string; serviceName: string }) => {// Abort any in-flight tree fetch so rapid row-clicks can't deliver a stale// response that overwrites the newer one — matches the pattern used by// fetchSpans / fetchSparkline / fetchAggregation.@@ -260,6 +260,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([const response = await api.tracing.tree({spanName: params.spanName,+ serviceName: params.serviceName,dateRange: {date_from: new Date(currentStartMs).toISOString(),date_to: new Date(currentEndMs).toISOString(),diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.tsindex 753ffde56443..9fdbb622a4a0 100644--- a/products/tracing/frontend/tracingSceneLogic.ts+++ b/products/tracing/frontend/tracingSceneLogic.ts@@ -66,7 +66,7 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([actions({openTraceModal: (traceId: string) => ({ traceId }),closeTraceModal: true,- openCompareFlame: (spanName: string) => ({ spanName }),+ openCompareFlame: (spanName: string, serviceName: string) => ({ spanName, serviceName }),closeCompareFlame: true,syncUrlAndRunQuery: true,}),@@ -86,6 +86,13 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([closeCompareFlame: () => null,},],+ compareFlameServiceName: [+ null as string | null,+ {+ openCompareFlame: (_, { serviceName }) => serviceName,+ closeCompareFlame: () => null,+ },+ ],}),selectors({@@ -126,8 +133,8 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([actions.loadTraceSpans(traceId)}},- openCompareFlame: ({ spanName }) => {- actions.fetchSpanTree({ spanName })+ openCompareFlame: ({ spanName, serviceName }) => {+ actions.fetchSpanTree({ spanName, serviceName })},setDateRange: () => {actions.syncUrlAndRunQuery()@@ -149,8 +156,11 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([// stays fixed while the user moves windows around within it. If the compare-flame// modal is open we also refetch its tree so it doesn't display stale windows.actions.fetchAggregation()- if (values.compareFlameSpanName) {- actions.fetchSpanTree({ spanName: values.compareFlameSpanName })+ if (values.compareFlameSpanName && values.compareFlameServiceName) {+ actions.fetchSpanTree({+ spanName: values.compareFlameSpanName,+ serviceName: values.compareFlameServiceName,+ })}},setFilters: () => {diff --git a/products/tracing/mcp/prompts/apm-spans-tree.md b/products/tracing/mcp/prompts/apm-spans-tree.mdindex bbde3baac6df..ab95045d3810 100644--- a/products/tracing/mcp/prompts/apm-spans-tree.md+++ b/products/tracing/mcp/prompts/apm-spans-tree.md@@ -1,6 +1,6 @@Aggregate trace span statistics as a call tree — one row per `(parent_service, parent_name) → (service_name, name)` edge.-Requires a `spanName` to bound the matched trace set (the `(trace_id, parent_span_id)` self-join is unsafe at high cardinality without it). All traces that contain at least one span with the given name are included, and every span in those traces is aggregated against its parent.+Requires 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.Returns rows with:@@ -53,10 +53,14 @@ All parameters go inside `query`.## query.spanName (required)-The span name that anchors the matched trace set. Every trace containing at least one span with this name is included, and every span in those traces is aggregated.+The span name that anchors the matched trace set. Every trace containing at least one span with this name (in the given `serviceName`) is included.Pick 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.+## query.serviceName (required)++The 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.+## query.dateRangeDate range for the primary window. Defaults to the last hour.@@ -83,7 +87,8 @@ Property filters applied to both windows. See the "Property filters" section.```json{"query": {- "spanName": "POST /api/orders"+ "spanName": "POST /api/orders",+ "serviceName": "web-server"}}```@@ -94,6 +99,7 @@ Property filters applied to both windows. See the "Property filters" section.{"query": {"spanName": "checkout_flow",+ "serviceName": "web-server","dateRange": { "date_from": "-1d" }}}@@ -105,29 +111,20 @@ Property filters applied to both windows. See the "Property filters" section.{"query": {"spanName": "POST /api/orders",+ "serviceName": "web-server","dateRange": { "date_from": "-1d" },"compareFilter": { "compare": true, "compare_to": "-7d" }}}```-## Scope to a single service--```json-{- "query": {- "spanName": "render_dashboard",- "serviceNames": ["web-server"]- }-}-```-## Restrict to error-bearing traces```json{"query": {"spanName": "POST /api/orders",+ "serviceName": "web-server","filterGroup": [{ "key": "status_code", "operator": "exact", "type": "span", "value": 2 }]}}@@ -135,7 +132,7 @@ Property filters applied to both windows. See the "Property filters" section.# Reminders-- `spanName` is required. Bound to a specific high-level span; avoid generic names like `HTTP`.+- `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.- 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.diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 5cc75c591535..55a41dee140a 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -349,7 +349,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). All traces that contain at least one span with the given name are included, and every span in those traces 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)\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 is included, and every span in those traces is aggregated.\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.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 }\n}\n```\n\n## Call tree over the last day\n\n```json\n{\n \"query\": {\n \"spanName\": \"checkout_flow\",\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 \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Scope to a single service\n\n```json\n{\n \"query\": {\n \"spanName\": \"render_dashboard\",\n \"serviceNames\": [\"web-server\"]\n }\n}\n```\n\n## Restrict to error-bearing traces\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }]\n }\n}\n```\n\n# Reminders\n\n- `spanName` is required. Bound to a specific high-level span; avoid generic names like `HTTP`.\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\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)\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.","category": "Tracing","feature": "tracing","summary": "Aggregate span call tree",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex d222660e9a92..9c96de146f1c 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -366,7 +366,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). All traces that contain at least one span with the given name are included, and every span in those traces 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)\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 is included, and every span in those traces is aggregated.\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.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 }\n}\n```\n\n## Call tree over the last day\n\n```json\n{\n \"query\": {\n \"spanName\": \"checkout_flow\",\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 \"dateRange\": { \"date_from\": \"-1d\" },\n \"compareFilter\": { \"compare\": true, \"compare_to\": \"-7d\" }\n }\n}\n```\n\n## Scope to a single service\n\n```json\n{\n \"query\": {\n \"spanName\": \"render_dashboard\",\n \"serviceNames\": [\"web-server\"]\n }\n}\n```\n\n## Restrict to error-bearing traces\n\n```json\n{\n \"query\": {\n \"spanName\": \"POST /api/orders\",\n \"filterGroup\": [{ \"key\": \"status_code\", \"operator\": \"exact\", \"type\": \"span\", \"value\": 2 }]\n }\n}\n```\n\n# Reminders\n\n- `spanName` is required. Bound to a specific high-level span; avoid generic names like `HTTP`.\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\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)\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.","category": "Tracing","feature": "tracing","summary": "Aggregate span call tree",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c461875313ab..cbe549585bd8 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -18326,6 +18326,8 @@ export namespace Schemas {/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;response?: TraceSpansTreeQueryResponse | null;+ /** Service name that scopes the returned tree. Applied to the spans CTE so the call-tree only contains spans from this service, even when matched traces span multiple services. */+ serviceName: string;serviceNames?: string[] | null;/** Span name to scope the matched trace set. Required because the `(trace_id, parent_span_id)` self-join is prohibitive without bounding the matched traces — at high name cardinality the query becomes unsafe to run. */spanName: string;@@ -36390,6 +36392,8 @@ export namespace Schemas {export interface _TracingTreeQueryBody {/** Span name to scope the matched trace set. Required because the (trace_id, parent_span_id) self-join is unsafe without bounding the matched traces. */spanName: string;+ /** Service name that scopes the returned tree. Applied to the spans CTE so the call-tree only contains spans from this service, even when matched traces span multiple services. */+ serviceName: string;/** Date range for the primary window. Defaults to last hour. */dateRange?: _TracingDateRange;/** Optional comparison-window configuration. When omitted, only the primary window is returned. */diff --git a/services/mcp/src/generated/tracing/api.ts b/services/mcp/src/generated/tracing/api.tsindex 79091b51d374..73a0382d359f 100644--- a/services/mcp/src/generated/tracing/api.ts+++ b/services/mcp/src/generated/tracing/api.ts@@ -299,6 +299,11 @@ export const TracingSpansTreeCreateBody = /* @__PURE__ */ zod.object({.describe('Span name to scope the matched trace set. Required because the (trace_id, parent_span_id) self-join is unsafe without bounding the matched traces.'),+ serviceName: zod+ .string()+ .describe(+ 'Service name that scopes the returned tree. Applied to the spans CTE so the call-tree only contains spans from this service, even when matched traces span multiple services.'+ ),dateRange: zod.object({date_from: zoddiff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/apm-spans-tree.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/apm-spans-tree.jsonindex 10334a686369..2ffc36e1459b 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/apm-spans-tree.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/apm-spans-tree.json@@ -93,6 +93,10 @@},"type": "array"},+ "serviceName": {+ "description": "Service name that scopes the returned tree. Applied to the spans CTE so the call-tree only contains spans from this service, even when matched traces span multiple services.",+ "type": "string"+ },"serviceNames": {"description": "Filter by service names.","items": {@@ -105,7 +109,7 @@"type": "string"}},- "required": ["spanName"],+ "required": ["spanName", "serviceName"],"type": "object"}},