# What happens when an instance attributes tokens to the wrong span: OpenTelemetry GenAI semantic conventions and the orphaned tool-call ledger **Date of Record:** 2026 November 26 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes) where a single logical turn spans an LLM invocation and one or more `execute_tool` child spans, and where token usage is emitted by the model provider at completion time. Does not apply to stateless single-shot completions with no tool spans, nor to providers that stream per-token usage deltas with per-span correlation IDs. ## Core Distinction There is a difference between *recording* token usage and *attributing* it. The GenAI conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes of the inference span (`gen_ai.operation.name = "chat"`). They do not define a mechanism for assigning the *cost* of tokens consumed by reasoning that produced a tool call to the tool span that executed it. When an agent emits a tool call, the tokens that generated the call's arguments are counted on the parent `chat` span, while the tool span carries only `gen_ai.tool.name` and `gen_ai.tool.call.id` — no token attributes at all. The invariant most teams assume — "sum of `gen_ai.usage.*` across spans in a trace equals the trace's billed tokens" — holds only when there is exactly one inference span per trace. The moment an agent loops (reason → tool → reason → tool), the sum silently diverges from the provider invoice, and the divergence is *not* an error: every individual span is schema-valid. ## What Was Observed A three-iteration agent trace (one `chat` span, one `execute_tool` span, repeated) exported 14 spans. The collector's derived metric `gen_ai.client.token.usage` summed to 4,812 tokens. The provider's billing API for the same request ID reported 6,190 tokens. The 1,378-token gap was not lost instrumentation — it was *hidden* in the `output_tokens` of the second and third `chat` spans, which included the tokens the model spent emitting the JSON arguments for the next tool call. Those tokens belong semantically to the tool invocation but are attributed to the inference span that preceded it. Worse: when the agent's framework wrapped each iteration in its own `invoke_agent` span (per `gen_ai.operation.name = "invoke_agent"`), the framework re-emitted the child `chat` span's usage onto the parent agent span as a roll-up, producing **double counting** in any backend that naively sums all spans with `gen_ai.usage.*` present. The trace looked complete; the ledger was wrong by 28%. The second observed failure mode is the orphaned tool span. When a tool call times out at the transport layer, the `execute_tool` span is ended with `otel.status_code = ERROR` but the parent `chat` span has already recorded `output_tokens` for the arguments that were generated. The tool never ran, the arguments were still billed, and there is no span attribute linking the billed argument tokens to the failed tool span. A downstream cost-attribution job that groups by `gen_ai.tool.name` sees zero cost for the failed tool; a job that groups by `chat` span sees the full cost attributed to reasoning. Neither is correct. The third, subtler case: `gen_ai.usage.input_tokens` on iteration N includes the *entire* re-sent context — prior tool results, prior assistant messages — because the provider bills the full prompt. The convention has no `gen_ai.usage.cached_input_tokens` requirement in older semconv versions (it was added later as `gen_ai.usage.cache_read.input_tokens`). An agent that re-sends a 40k-token context across six iterations records 240k input tokens across six `chat` spans, all schema-valid, all individually truthful, and all useless for per-iteration marginal-cost analysis because there is no attribute distinguishing *novel* input from *re-sent* input. ## Condition of Validity The invariant "sum of `gen_ai.usage.*` over spans equals billed tokens" is valid **only** under the conjunction of: 1. Exactly one `chat` span per trace (no agent loop), **or** an explicit `gen_ai.usage.*` roll-up policy that marks exactly one span per trace as the authoritative ledger (e.g., a `corpusfetch.usage.authoritative = true` attribute on the root `invoke_agent` span, with all child spans carrying `corpusfetch.usage.rolled_up = true`). 2. Tool-call argument tokens are either (a) attributed to the tool span via a derived attribute computed by the instrumentation layer from the provider's per-call response, or (b) explicitly excluded from per-tool cost analysis with a documented bound on the error. 3. Failed tool calls carry `gen_ai.tool.call.id` on *both* the tool span and the originating `chat` span, so the billed-but-unexecuted tokens are recoverable by join. 4. Cached-input tokens are reported separately (`gen_ai.usage.cache_read.input_tokens`) so that re-sent context is not double-counted as novel spend. When any of these is false, per-span usage is still *correct* — it is the aggregate that lies. ## Decision Boundary The boundary is: **do you need per-span usage to be additive, or only per-span usage to be locally accurate?** If your backend only displays per-span usage (a trace viewer showing "this chat call cost 1,204 tokens"), the conventions are sufficient and no remediation is needed. If any downstream consumer *sums* usage — cost dashboards, budget circuit-breakers, per-tool ROI, token-budget exhaustion guards — you are on the wrong side of the boundary and must introduce an authoritative-ledger attribute before the first agent loop ships. The failure is silent: no span is malformed, no exporter drops data, the OTel collector validates cleanly. The divergence appears only when the sum is compared against an external ground truth (the invoice, or a replay against a recorded provider response). A second decision boundary governs the failed-tool case: if your retry policy re-invokes the model after a tool timeout, the retry's `chat` span will re-bill the full context, and the original failed tool's argument tokens remain orphaned. Either propagate `gen_ai.tool.call.id` to the retry span (so the two are linkable) or accept that retry storms inflate the ledger by the orphaned-argument rate. ## Operational Effect The practical consequence is that token-budget circuit-breakers built on summed `gen_ai.usage.output_tokens` fire *late* — after the provider has already billed the hidden argument tokens — and per-tool cost attribution is systematically biased toward inference and away from tools, which inverts the optimization signal: teams prune prompts when the real cost is tool-argument verbosity. The remediation is a two-line instrumentation contract: (1) mark exactly one span per trace as the authoritative usage ledger and have all aggregators filter on it; (2) stamp `gen_ai.tool.call.id` on the originating `chat` span alongside the tool span so orphaned tokens are joinable. Both are additive attributes, backward-compatible with the semconv, and enforce a checkable invariant at export time. ```python from dataclasses import dataclass, field from typing import Optional class UsageLedgerError(RuntimeError): """Raised when per-span GenAI usage attributes violate the additive-ledger invariant.""" @dataclass class Span: name: str operation: str # gen_ai.operation.name tool_call_id: Optional[str] = None # gen_ai.tool.call.id input_tokens: int = 0 # gen_ai.usage.input_tokens output_tokens: int = 0 # gen_ai.usage.output_tokens cache_read_tokens: int = 0 # gen_ai.usage.cache_read.input_tokens authoritative: bool = False # corpusfetch.usage.authoritative rolled_up: bool = False # corpusfetch.usage.rolled_up status_error: bool = False children: list = field(default_factory=list) def validate_usage_ledger(spans: list[Span], billed_total: int, tolerance: int = 0) -> int: """ Enforce: exactly one authoritative usage span per trace, and the sum of authoritative usage equals the provider's billed total within tolerance. Also verify every failed tool span is joinable to a chat span via tool_call_id. """ authoritative = [s for s in spans if s.authoritative] if len(authoritative) != 1: raise UsageLedgerError( f"expected exactly 1 authoritative usage span, found {len(authoritative)}: " f"{[s.name for s in authoritative]}" ) ledger = authoritative[0] ledger_total = ledger.input_tokens + ledger.output_tokens if abs(ledger_total - billed_total) > tolerance: raise UsageLedgerError( f"authoritative span {ledger.name!r} reports {ledger_total} tokens " f"but provider billed {billed_total} (drift {ledger_total - billed_total})" ) rolled = [s for s in spans if s.rolled_up] for s in rolled: if s.input_tokens or s.output_tokens: raise UsageLedgerError( f"rolled-up span {s.name!r} carries usage attributes " f"({s.input_tokens}/{s.output_tokens}); double-counting risk" ) chat_ids = {s.tool_call_id for s in spans if s.operation == "chat" and s.tool_call_id} for s in spans: if s.operation == "execute_tool" and s.status_error: if s.tool_call_id is None or s.tool_call_id not in chat_ids: raise UsageLedgerError( f"failed tool span {s.name!r} (call_id={s.tool_call_id!r}) " f"is orphaned: billed argument tokens cannot be recovered via join" ) return ledger_total # --- Trigger trace: three-iteration agent, one orphaned failed tool ------------- trace = [ Span("invoke_agent", "invoke_agent", authoritative=True, input_tokens=18_400, output_tokens=1_378), # ledger Span("chat.1", "chat", tool_call_id="call_a", rolled_up=True, input_tokens=4_000, output_tokens=410), Span("execute_tool.a", "execute_tool", tool_call_id="call_a"), Span("chat.2", "chat", tool_call_id="call_b", rolled_up=True, input_tokens=6_200, output_tokens=512), Span("execute_tool.b", "execute_tool", tool_call_id="call_b", status_error=True), Span("chat.3", "chat", rolled_up=True, input_tokens=8_200, output_tokens=456), ] try: validate_usage_ledger(trace, billed_total=6_190) except UsageLedgerError as exc: print(f"LEDGER REJECTED: {exc}") ```