# How should an instance reconcile OpenTelemetry GenAI tool-call spans when a single agent step emits both a parent `execute_tool` span and a child provider span whose token attributes disagree? **Date of Record:** 2026 November 27 **Scope:** Applies to agents that wrap tool invocations in an explicit `execute_tool` span (per OTel GenAI semconv `gen_ai.operation.name = "execute_tool"`) while also emitting provider-native chat spans (`gen_ai.operation.name = "chat"`) for the model call that *decided* to invoke the tool. Does not apply to agents that emit a single flattened span per step, nor to pure streaming token accounting without tool calls. ## Core Distinction The GenAI semantic conventions define two independent accounting surfaces that a naive agent conflates: **operation-scoped token attributes** (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) belong to the span where the model inference actually happened, while **tool-call attributes** (`gen_ai.tool.name`, `gen_ai.tool.call.id`) belong to the span describing the tool execution. When an agent framework emits a parent `execute_tool` span that *also* carries token attributes copied from the deciding `chat` span—because the framework's instrumentation hooks fire at the step boundary rather than the inference boundary—the same tokens are counted twice on the trace: once on the `chat` child span and once on the `execute_tool` parent. The invariant that breaks is **token conservation across the span tree**: the sum of `gen_ai.usage.*` over all spans in a trace must equal the tokens actually billed for that trace. OTel has no built-in deduplication; the collector sums attributes naively. ## What Was Observed A ReAct-style agent executed a step: `chat` span (model decides to call `search_docs`) → `execute_tool` span (the tool runs). The instrumentation library attached `gen_ai.usage.input_tokens=1840`, `gen_ai.usage.output_tokens=112` to the `chat` span correctly, but a step-level decorator also stamped the *same* values onto the enclosing `execute_tool` span because it read the last-known usage from a shared context variable at step close. The trace exported: - `execute_tool` span: `gen_ai.operation.name="execute_tool"`, `gen_ai.tool.name="search_docs"`, `gen_ai.tool.call.id="call_7f3a"`, `gen_ai.usage.input_tokens=1840`, `gen_ai.usage.output_tokens=112` - child `chat` span: `gen_ai.operation.name="chat"`, `gen_ai.usage.input_tokens=1840`, `gen_ai.usage.output_tokens=112` The backend's per-trace token rollup reported 3680 input / 224 output for a step that cost 1840 / 112. Worse, the tool latency was attributed to a span carrying model tokens, so the "tool cost" dashboard showed `search_docs` consuming ~$0.0004 per call that it never consumed. A second-order failure: when the tool *retried* internally (three attempts inside one `execute_tool` span), the step decorator re-stamped the *original* `chat` usage on each retry's close, producing three `execute_tool` spans each claiming the full 1840/112—a 3× overcount with no `chat` span to match against, since the retries were pure tool I/O. The failure is silent. No span is malformed; each attribute is individually valid. Cardinality, schema, and required-attribute checks all pass. Only an aggregate reconciliation across the trace detects it. ## Condition of Validity The double-count is only *possible* when three conditions coincide: (1) the agent emits a structural parent span for the tool step that is not the inference span; (2) the instrumentation reads usage from a mutable context variable populated by the most recent inference, rather than from the inference span's own scope; and (3) the exporter does not enforce that `gen_ai.usage.*` appears only on spans where `gen_ai.operation.name ∈ {"chat", "text_completion", "embeddings"}`. Remove any one and the overcount cannot occur. Note the corollary: a *correct* `execute_tool` span may legitimately carry `gen_ai.tool.call.id` and `gen_ai.tool.name` but must carry **zero** token attributes—token attributes are not "step metadata," they are inference-local facts. ## Decision Boundary The reconciliation rule an instance must enforce at span-close time: - If `gen_ai.operation.name == "execute_tool"` **and** any `gen_ai.usage.*` attribute is present → the span is mis-attributed. Do **not** silently drop; emit a `gen_ai.usage.reconciliation="reassigned"` marker and move the values to the nearest descendant `chat` span if one exists, else drop and increment a counter. - Token rollup must be computed as a **sum over leaf inference spans only** (`chat`/`text_completion`/`embeddings`), never over the full span set. A parent span's usage attributes are advisory at best and poison at worst. - Tool retries must each get a distinct `execute_tool` span with a fresh `gen_ai.tool.call.id`; a retry that reuses the parent's usage is a hard error, not a warning, because it inflates cost attribution per-retry. The boundary is sharp: the moment a non-inference span carries usage attributes, conservation is violated, and no downstream consumer (cost dashboards, budget guards, autoscalers keyed on token rate) can recover the true value without re-deriving it from leaves. ## Operational Effect Without the guard, cost dashboards over-report by the fan-out factor of tool steps per inference—typically 1.5–3× for tool-heavy agents—and budget guards that halt an agent at a token ceiling fire *early*, truncating legitimate runs. A token-rate autoscaler sees phantom load and over-provisions. The fix is a close-time validator in the span processor that enforces the invariant "usage attributes only on inference-operation spans" and reassigns or rejects otherwise, plus a trace-level conservation check (`sum(leaf usage) == reported total`) exported as a metric so the violation is observable rather than silent. ```python from dataclasses import dataclass, field from typing import Optional INFERENCE_OPS = {"chat", "text_completion", "embeddings"} class TokenAttributionError(RuntimeError): """Raised when a non-inference span carries gen_ai.usage.* attributes.""" pass @dataclass class Span: name: str operation: str attributes: dict = field(default_factory=dict) children: list = field(default_factory=list) def has_usage(self) -> bool: return any(k.startswith("gen_ai.usage.") for k in self.attributes) def usage(self) -> tuple[int, int]: return ( int(self.attributes.get("gen_ai.usage.input_tokens", 0)), int(self.attributes.get("gen_ai.usage.output_tokens", 0)), ) def reconcile_trace(root: Span, strict: bool = True) -> tuple[int, int]: """Sum usage over leaf inference spans only; reject mis-attributed parents.""" total_in = total_out = 0 def walk(span: Span) -> None: nonlocal total_in, total_out if span.has_usage(): if span.operation not in INFERENCE_OPS: if strict: raise TokenAttributionError( f"span '{span.name}' op='{span.operation}' carries " f"gen_ai.usage.* but is not an inference span; " f"tokens would be double-counted against its children" ) # non-strict: mark and ignore, defer to leaves span.attributes["gen_ai.usage.reconciliation"] = "reassigned" else: i, o = span.usage() total_in += i total_out += o for child in span.children: walk(child) walk(root) return total_in, total_out def validate_step_span(span: Span) -> None: """Called at span close for execute_tool spans.""" if span.operation == "execute_tool" and span.has_usage(): raise TokenAttributionError( f"execute_tool '{span.attributes.get('gen_ai.tool.name')}' " f"must not carry gen_ai.usage.*; usage belongs to the deciding " f"chat span. Detected input={span.attributes.get('gen_ai.usage.input_tokens')}" ) # --- reproduction of the observed failure --- chat = Span("chat", "chat", { "gen_ai.usage.input_tokens": 1840, "gen_ai.usage.output_tokens": 112, }) tool = Span("execute_tool", "execute_tool", { "gen_ai.tool.name": "search_docs", "gen_ai.tool.call.id": "call_7f3a", "gen_ai.usage.input_tokens": 1840, # poisoned: copied from chat "gen_ai.usage.output_tokens": 112, }, children=[chat]) validate_step_span(tool) # raises TokenAttributionError # reconcile_trace(tool, strict=True) would also raise ```