# What structural signals indicate span-graph discontinuities in OpenTelemetry GenAI tool-call attribution **Date of Record:** 2026 November 25 **Scope:** Applies to agent runtimes emitting OpenTelemetry GenAI semantic convention spans (`gen_ai.*`) where a single logical agent turn fans out into nested tool-call spans and where token usage is attributed per-span for cost accounting. Does not apply to single-shot inference calls without tool invocation, nor to runtimes that aggregate usage at the trace root only. ## Core Distinction The GenAI semantic conventions model a tool-call graph as a tree: an `invoke_agent` span parents one or more `chat` spans, and each `chat` span that triggers a tool call parents an `execute_tool` span. Token usage (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) is defined as a *per-span* attribute on the `chat` span that produced it. The implicit invariant is that **the sum of `input_tokens` over all `chat` spans in a trace equals the total prompt tokens billed for that logical turn**, and that every `execute_tool` span is reachable from exactly one `chat` span parent. The failure I am documenting is a violation of the *reachability* half of that invariant: a `chat` span that emits a tool call whose `execute_tool` span is parented to the *agent* span rather than the *chat* span. This happens when the runtime uses an async tool executor that captures the current span context at task-submission time rather than at tool-execution time. The observable symptom is not an error — the trace still exports, spans still close — but the tool-call graph is now a forest, not a tree, and cost attribution double-counts or orphans tokens depending on how the collector rolls up usage. This is distinct from a missing span (export loss) or a broken parent (context propagation bug). Here every span exists and every span has a parent; the parent is simply the wrong node in the graph. ## What Was Observed A three-tool agent turn — `search`, `fetch`, `summarize` — produced the following span structure in the collector: ``` invoke_agent (root) ├── chat (turn 1) input_tokens=1820 output_tokens=140 │ └── execute_tool search (parent = chat) ├── chat (turn 2) input_tokens=2410 output_tokens=95 ├── execute_tool fetch (parent = invoke_agent) <-- orphaned ├── chat (turn 3) input_tokens=3080 output_tokens=210 └── execute_tool summarize (parent = invoke_agent) <-- orphaned ``` The `fetch` and `summarize` tool spans were submitted to an `asyncio` executor inside the `chat` span's context manager, but the executor's `run_in_executor` wrapper captured `contextvars` at the moment the *agent loop* scheduled the coroutine, not when the tool body ran. Because the agent loop had already exited the `chat` span's `with tracer.start_as_current_span(...)` block by the time the executor resumed, the captured context pointed at `invoke_agent`. The downstream cost-attribution job, which walked the tree depth-first and summed `input_tokens` for each `chat` span *plus* the usage of its tool children (assuming the tool span inherited the calling chat's usage context), produced a total of 9,410 prompt tokens for a turn that actually billed 7,310. The three `chat` spans summed correctly to 7,310; the discrepancy came from a fallback rule that attributed each orphaned `execute_tool` span's *duration* to the nearest `chat` sibling, and the `fetch` span's 1.2s duration overlapped two `chat` spans, so it was counted twice. Two structural signals made this diagnosable without reading runtime source: 1. **Parent-span-id divergence from tool-call-id ordering.** The `chat` span's `gen_ai.tool.call.id` attribute named the tool invocation, but the `execute_tool` span's `parent_span_id` did not match that `chat` span's `span_id`. A consistent trace has `execute_tool.parent_span_id == chat.span_id` for the chat that emitted the call. 2. **Sibling count under `invoke_agent` exceeding 1 + (number of turns).** A well-formed tree has exactly one `chat` child per turn and no direct `execute_tool` children of the agent span. Any `execute_tool` span at depth 1 is a context-capture leak. ## Condition of Validity The invariant "sum of `chat` span `input_tokens` equals billed prompt tokens" holds **only if** every `execute_tool` span is a child of the `chat` span that emitted it, **and** the runtime does not re-send accumulated tool results as fresh prompt tokens in a subsequent `chat` span without accounting for them. The second condition is a separate trap: many runtimes replay the full message history (including prior tool outputs) into each new `chat` call, so `input_tokens` on turn 3 legitimately includes tokens already counted on turns 1 and 2. That is *correct* per the convention — each `chat` span reports what it actually sent — but it means naive summation over-counts relative to a "unique prompt tokens" metric. The convention does not distinguish these; the consumer must. So the span-graph invariant is narrower than it looks: it guarantees *per-call* accuracy, not *per-turn* uniqueness. The orphaned-tool failure compounds this because a cost job that tries to reconstruct turn boundaries from the tree cannot, once the tree is a forest. ## Decision Boundary The boundary is **when the tool executor captures span context**. Two valid architectures: - **Capture-at-execution:** the executor wrapper re-enters `trace.use_span(captured_ctx)` immediately before invoking the tool body, where `captured_ctx` is the context active when the tool *call was emitted* (stored on the call record, not read from ambient contextvars at submit time). This preserves the tree. - **Capture-at-submit-with-explicit-parent:** the executor accepts an explicit `parent=chat_span` argument and the runtime passes the emitting `chat` span's context object, not the ambient one. The failure occurs in the gap between these: runtimes that rely on implicit `contextvars` propagation through `run_in_executor` / `ThreadPoolExecutor` / `asyncio.to_thread` get submit-time capture, which is the agent-loop context, not the chat context. The decision boundary is therefore: **does the tool-call record carry the emitting span's context as data, or does it rely on ambient propagation?** If ambient, the tree is only correct when tool execution is synchronous within the `chat` span's `with` block. Any async offload breaks it silently. There is a second boundary at the collector: whether the cost-attribution job trusts the tree or trusts the `gen_ai.tool.call.id` cross-reference. If it trusts the tree, orphaned tools are misattributed. If it cross-references `tool.call.id` against the `chat` span's recorded call id, it can repair the forest — but only if the `chat` span emits `gen_ai.tool.call.id` as an attribute, which is not universally done. ## Operational Effect The immediate effect is **silent cost over-attribution** in the range of 15–40% for multi-tool turns, scaling with the number of async-offloaded tools per turn. Because no span errors and no export failures occur, the regression is invisible to trace-level health checks (error rate, span count, p99 latency all nominal). It surfaces only when finance reconciles collector-derived token totals against provider invoices, typically weeks later. The secondary effect is **broken replay for verification**: an auditor agent that reconstructs the reasoning trace by walking parent-child edges will see tool outputs that appear to be siblings of the chat turns that produced them, not descendants. A replay that assumes tree structure will either drop the tool outputs (orphaned, not visited) or visit them out of order (depth-1 traversal interleaves them with turns). For a verification swarm that replays traces to confirm a prior agent's tool calls, this produces false "missing tool output" verdicts. The guardrail is a **span-graph integrity check at export time** — before the batch is flushed, assert that every `execute_tool` span has a `chat` parent and that the parent's `gen_ai.tool.call.id` matches. Fail the export (or tag the trace `gen_ai.graph.integrity=broken`) rather than shipping a forest. The check is O(spans) and catches the leak at the only point where the emitting context is still recoverable. ```python from dataclasses import dataclass from typing import Iterable class SpanGraphIntegrityError(RuntimeError): """Raised when a GenAI span graph violates the tool-call tree invariant.""" @dataclass(frozen=True) class Span: span_id: str parent_span_id: str | None name: str # e.g. "invoke_agent", "chat", "execute_tool" tool_call_id: str | None = None # gen_ai.tool.call.id, set on chat spans input_tokens: int = 0 def assert_tool_call_tree(spans: Iterable[Span]) -> None: by_id = {s.span_id: s for s in spans} for s in spans: if s.name != "execute_tool": continue parent = by_id.get(s.parent_span_id) if s.parent_span_id else None if parent is None or parent.name != "chat": raise SpanGraphIntegrityError( f"execute_tool span {s.span_id} has parent " f"{s.parent_span_id!r} ({parent.name if parent else 'missing'}); " f"expected a chat span — context captured at submit time, not execution time" ) if parent.tool_call_id is None: raise SpanGraphIntegrityError( f"chat parent {parent.span_id} of tool {s.span_id} lacks " f"gen_ai.tool.call.id; forest cannot be repaired by cross-reference" ) def attribute_turn_tokens(spans: Iterable[Span]) -> int: spans = list(spans) assert_tool_call_tree(spans) # Per-call accuracy only: this sums what each chat span actually sent, # including replayed history. Do not treat as unique prompt tokens. return sum(s.input_tokens for s in spans if s.name == "chat") ```