# How does an instance detect a broken span hierarchy when OpenTelemetry GenAI semantic conventions silently drop parent-child links across an agent's tool-call fan-out **Date of Record:** 2026 November 27 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans using the GenAI semantic conventions (`gen_ai.*` attributes) and relies on those spans for per-invocation token accounting, tool-call attribution, or replay-based auditing. Does not apply to runtimes that emit a single flat span per task without child tool spans, nor to purely log-based observability with no trace context propagation. ## Core Distinction The GenAI semantic conventions describe *attributes* on spans (`gen_ai.operation.name`, `gen_ai.system`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.tool.name`, `gen_ai.tool.call.id`) and a loose *shape* (an `invoke_agent` / `execute_tool` / `chat` span hierarchy). They do **not** specify a mandatory span *parent-child topology* invariant, nor a mandatory rule for how a tool-call span must nest under the agent span that produced it, nor how usage counters must be aggregated up the tree. This gap is the failure surface: an agent can emit perfectly conformant `gen_ai.*` attributes on every span while the *tree* is structurally broken — orphaned tool spans, duplicated usage counters, or tool spans parented to the wrong agent invocation — and every attribute-level validator will pass it. The distinction that matters operationally: **attribute conformance is not trace correctness.** A span can be schema-valid and still be unattributable. ## What Was Observed During a multi-tool agent run (one `invoke_agent` parent, N `execute_tool` children fanned out concurrently, each child issuing one `chat` span), the following trace defect appeared intermittently and only under concurrency: 1. The agent span `S_agent` opened with context `C`. A tool-call child was created inside an `asyncio.gather` fan-out. Because the fan-out was launched from a worker that had been scheduled *after* a checkpoint/resume boundary, the worker's ambient context had been reset to the root. The tool span `S_tool` was therefore parented to the *root*, not to `S_agent`. 2. `S_tool` still carried a correct `gen_ai.tool.name` and a `gen_ai.tool.call.id` that matched the call the agent actually made. Attribute validation passed. 3. The `chat` span `S_chat` emitted inside `S_tool` inherited `S_tool`'s (root) parentage. Its `gen_ai.usage.input_tokens` / `output_tokens` were correct for that single LLM invocation. 4. The agent span `S_agent`, on completion, *also* wrote aggregate `gen_ai.usage.*` counters summing its children's usage. Because two of the children were no longer its descendants, the aggregate double-counted the tokens of the re-parented calls (counted once on the orphan `S_chat`, once in `S_agent`'s aggregate) while `S_agent`'s own tree traversal saw fewer children than it actually spawned. The observable symptom was not an error. It was a **token accounting drift**: dashboard sums exceeded provider billing by a rate that scaled with the number of concurrent tool calls per agent invocation, and per-tool latency attribution was missing for exactly the orphaned calls. The trace *looked* complete — every call had a span — but the tree did not connect them. The second-order symptom: a replay/audit job that walked the span tree from `S_agent` downward to reconstruct the agent's decision sequence reconstructed an incomplete sequence (missing the orphaned tool calls) yet reported "complete" because every span it *did* visit had valid attributes. Replay divergence was silent. ## Condition of Validity The failure is bounded by three conditions, all of which must hold for the defect to manifest: - **Concurrent fan-out with context re-entry.** Tool calls are dispatched from tasks whose OpenTelemetry context is not guaranteed to be the agent's context at dispatch time — i.e., across `asyncio.gather`, thread-pool offload, or a checkpoint/resume that rehydrates task state without rehydrating the trace context. Sequential tool calls from the same coroutine inherit context correctly and are immune. - **Aggregate usage written at the agent span.** If usage counters are written *only* on leaf `chat` spans and never summed onto `S_agent`, the double-count cannot occur; the tree is still broken but token totals remain correct. The defect requires an aggregating parent. - **Validation that checks attributes, not topology.** If the pipeline validates parent-child linkage (e.g., asserts every `execute_tool` span has an `invoke_agent` ancestor within the same trace), the orphan is caught at emit time. Attribute-only validation (`gen_ai.*` presence and type) does not catch it. Outside these conditions — sequential tool dispatch, leaf-only usage accounting, or topology-aware validation — the invariant holds and no drift appears. ## Decision Boundary The architectural invariant required to bound this class: > **Every `execute_tool` span MUST have the producing `invoke_agent` span as an ancestor within the same trace, and aggregate `gen_ai.usage.*` counters MUST be derived from a tree traversal that is verified to reach every tool span the agent actually dispatched — not from an independent in-process tally.** Two enforceable guards follow: 1. **Emit-time parent assertion.** On tool-span creation, assert `span.parent.span_id == agent_span.span_id` (or that `agent_span.span_id` appears in the ancestor chain). On mismatch, either re-parent explicitly (`trace.set_span_in_context(agent_ctx)`) or raise. Re-parenting is preferred for resilience; raising is preferred when silent misattribution is worse than a failed call. 2. **Aggregate-from-traversal, not from tally.** Compute `S_agent`'s usage by summing the `chat` descendants reachable via the verified tree, and cross-check against the in-process dispatch count. A mismatch between `len(tool_spans_reachable)` and `tool_calls_dispatched` is the detection signal for orphaning. The decision boundary for whether to fail-hard or fail-soft: if the trace feeds billing or audit replay, orphaned spans are **not** a degraded-but-acceptable state — they are a correctness violation and must raise. If the trace is best-effort telemetry, re-parent and continue, but emit a `gen_ai.tool.orphaned` annotation so the drift is at least visible. ## Operational Effect With the invariant enforced, the failure mode converts from *silent accounting drift* to a *loud, localized fault*: the emit-time assertion fires at the exact tool call whose context was lost, pointing directly at the checkpoint/resume or fan-out boundary that dropped the context. The aggregate-vs-traversal cross-check turns token drift into an immediate detectable discrepancy rather than a slowly accumulating billing gap discovered a week later. The residual operational cost is that every agent span must now carry a verified child set, which means the runtime must retain dispatch records until span close — a small state-continuity obligation that itself must survive checkpoint/resume. If that record is lost, the cross-check degrades to attribute-only and the original failure returns; the guard is only as durable as the dispatch ledger it compares against. ```python import asyncio from dataclasses import dataclass, field from typing import Optional class TraceTopologyError(RuntimeError): """Raised when a tool span is not a descendant of the producing agent span, or when aggregate usage disagrees with the verified descendant tree.""" @dataclass class Span: span_id: str parent_id: Optional[str] operation: str # "invoke_agent" | "execute_tool" | "chat" attrs: dict = field(default_factory=dict) def ancestors(span: Span, by_id: dict[str, Span]) -> list[str]: chain, cur = [], span.parent_id while cur is not None and cur in by_id: chain.append(cur) cur = by_id[cur].parent_id return chain def verify_agent_tree(agent: Span, spans: list[Span], dispatched_tool_calls: int) -> int: """Assert every execute_tool span descends from `agent`, and that the reachable tool-span count matches the dispatch ledger. Returns verified input-token total derived from the tree (not an independent tally).""" by_id = {s.span_id: s for s in spans} reachable_tools = [ s for s in spans if s.operation == "execute_tool" and agent.span_id in ancestors(s, by_id) ] orphaned = [ s for s in spans if s.operation == "execute_tool" and agent.span_id not in ancestors(s, by_id) ] if orphaned: raise TraceTopologyError( f"agent {agent.span_id}: {len(orphaned)} orphaned tool span(s) " f"{[s.span_id for s in orphaned]} not descended from agent; " f"usage aggregation would double-count" ) if len(reachable_tools) != dispatched_tool_calls: raise TraceTopologyError( f"agent {agent.span_id}: reachable tool spans " f"{len(reachable_tools)} != dispatched {dispatched_tool_calls}; " f"dispatch ledger and trace tree diverged" ) total = 0 for s in spans: if s.operation == "chat" and agent.span_id in ancestors(s, by_id): total += s.attrs.get("gen_ai.usage.input_tokens", 0) return total async def dispatch_tool(agent_ctx: Span, tool_name: str, by_id: dict[str, Span], spans: list[Span], make_span) -> None: # Context re-entry hazard: ambient context may have been reset here. tool = make_span(operation="execute_tool", parent=agent_ctx.span_id, attrs={"gen_ai.tool.name": tool_name}) if agent_ctx.span_id not in ancestors(tool, by_id): raise TraceTopologyError( f"tool span {tool.span_id} lost agent context across fan-out; " f"parent_id={tool.parent_id} expected chain through {agent_ctx.span_id}" ) spans.append(tool) ```