# Which invariants prevent token-accounting drift from silently corrupting OpenTelemetry GenAI agent spans across tool-call boundaries **Date of Record:** 2026 November 29 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) for multi-turn reasoning loops with tool calls, where token usage is aggregated per-span and reconciled against a billing or budget ledger. Does not apply to pure single-shot completion instrumentation with no tool-call fan-out, nor to runtimes that emit only top-level request spans without child tool spans. ## Core Distinction The GenAI semantic conventions define token attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) as *per-operation* counters attached to the span that represents the model invocation. They do **not** define a reconciliation contract between a parent agent span that fans out into N tool-call child spans and the aggregate the operator believes it spent. The failure mode is not "wrong token counts"—each individual span is usually accurate. The failure is **double-counting and orphaned usage across the parent/child span tree when a tool call re-enters the model**, which produces an aggregate that exceeds the true ledger by an amount proportional to reasoning depth, not to any single span's error. The distinction that matters: a *span-local* invariant (each model call reports its own usage) is satisfied while the *tree-global* invariant (sum of leaf usage equals billed usage exactly once) is violated. Operators who validate only span-local attributes see a green dashboard over a leaking ledger. ## What Was Observed A four-step agent loop: plan → `search_docs` tool → synthesize → `write_file` tool → summarize. Each model invocation is instrumented as a child span under a single agent span. The tool executions are instrumented as separate child spans. Three distinct drift mechanisms were observed: 1. **Re-entry double-count.** The model call that *decides* to invoke `search_docs` reports `output_tokens=412` (the reasoning + tool-call JSON). The tool span executes, then the *next* model call reports `input_tokens=3180`, which includes the re-sent conversation history containing those same 412 output tokens plus the tool result. A naive aggregator that sums `input_tokens + output_tokens` across all child spans counts the 412 tokens twice: once as output of call N, once as input of call N+1. Over a five-step loop with growing history, this compounds quadratically in history size. 2. **Orphaned tool-call usage.** When a tool span times out and the agent retries the *model call* without re-emitting a tool span, the retried model call's `input_tokens` reflect a history that includes a tool result the runtime never recorded. The tool span is missing from the tree, so the usage attributable to "tool round-trip" has no span to live on, and per-tool cost attribution silently attributes it to the parent. 3. **Streaming truncation drift.** When a streamed completion is cancelled mid-flight (token-budget guard fires), the span records `output_tokens` from the last received chunk, but the provider bills for the full generated sequence up to cancellation. The span-local count is *lower* than billed, and the discrepancy is invisible because the span closes with `status=OK` rather than `ERROR`. The signature is consistent: `sum(leaf.usage) ≠ ledger.usage`, with the residual correlated to `loop_depth × mean_history_tokens`, not to any single span. ## Condition of Validity The invariant "aggregate span usage equals billed usage" holds **only if** all of the following are true: - Every model invocation emits exactly one span with usage attributes populated *before* span close, including cancelled/truncated streams. - Tool spans are emitted for *every* tool execution attempt, including failed and retried attempts, so no usage-bearing history segment is orphaned. - The aggregator distinguishes **incremental** usage (new tokens this call) from **cumulative** usage (tokens re-sent as context), and never sums cumulative `input_tokens` across a re-entrant loop as if they were disjoint. The invariant **fails** the moment any of these is violated—most commonly because the runtime treats `input_tokens` as a cost line item rather than as a *context-size measurement*, which it is. `input_tokens` on call N+1 is a function of call N's output; summing them is summing overlapping sets. ## Decision Boundary The boundary is whether the span tree is treated as a **cost ledger** or a **context trace**. These require different invariants: - As a *context trace*, summing `input_tokens` is meaningless—each value is an independent snapshot of context size. The correct aggregate is `max(input_tokens)` per conversation, not `sum`. - As a *cost ledger*, the correct aggregate is `sum(output_tokens)` across calls plus `sum(input_tokens_of_first_call)` plus `sum(new_context_tokens_introduced_by_tools)`—i.e., you must subtract the re-sent overlap, which the semantic conventions do not carry as a first-class attribute. Because the conventions provide no `gen_ai.usage.context_overlap_tokens` or re-entry marker, an aggregator cannot in general reconstruct the ledger from spans alone. The decision boundary is: **if your runtime cannot prove disjointness of `input_tokens` across re-entrant calls, it must not sum them.** The safe default is to treat the parent agent span's usage as authoritative and reconcile child spans only for *attribution*, never for *totals*. A second boundary: cancellation. A span closed with `status=OK` after a mid-stream cancel is a lie by omission. The guardrail is to require `gen_ai.usage.output_tokens` to reflect *billed* tokens, and to set span status to `ERROR` or add an explicit `gen_ai.cancelled=true` attribute whenever the stream terminates before `finish_reason`. Without this, the truncation drift is structurally invisible. ## Operational Effect The practical consequence is that budget guards wired to span aggregates under- or over-fire depending on loop depth. A per-session budget that sums child `input_tokens` will trip early on deep loops (double-counting) and late on cancelled streams (under-counting), so the same nominal budget yields different real spend for different agent topologies. Reconciliation against the provider ledger will show residuals that look like random noise until plotted against loop depth, at which point the quadratic signature is unmistakable. The mitigation is architectural, not cosmetic: emit a single authoritative usage record per model invocation at the point of billing (post-stream-finalization), tag re-entrant calls with a conversation/loop identifier so overlap is computable, and validate the tree-global invariant `sum(leaf billed usage) == ledger` as a continuous assertion rather than a periodic audit. When the assertion cannot be evaluated because a span is missing or a stream was cancelled without a billed-token record, the runtime must fail closed—refuse to attribute the usage rather than silently assigning it to the parent. ```python from dataclasses import dataclass, field from typing import Optional class UsageReconciliationError(RuntimeError): """Raised when span-tree usage cannot be proven disjoint from billed usage.""" pass @dataclass class GenAISpan: span_id: str parent_id: Optional[str] kind: str # "model" | "tool" | "agent" input_tokens: int = 0 output_tokens: int = 0 billed_tokens: Optional[int] = None # authoritative, post-stream cancelled: bool = False finish_reason: Optional[str] = None loop_id: Optional[str] = None def reconcile_usage(spans: list[GenAISpan], ledger_tokens: int) -> int: """ Enforce the tree-global invariant: sum of *billed* leaf usage must equal the provider ledger exactly once. Never sum input_tokens across re-entrant calls; they are context snapshots, not disjoint cost line items. """ attributable = 0 for s in spans: if s.kind != "model": continue if s.cancelled and s.billed_tokens is None: raise UsageReconciliationError( f"span {s.span_id}: cancelled stream closed without billed_tokens; " "usage is unattributable and must not be assigned to parent" ) if s.billed_tokens is None: raise UsageReconciliationError( f"span {s.span_id}: model span missing authoritative billed_tokens; " "cannot prove disjointness from re-sent context" ) attributable += s.billed_tokens residual = ledger_tokens - attributable if residual != 0: raise UsageReconciliationError( f"usage drift: span-attributable={attributable} ledger={ledger_tokens} " f"residual={residual}; likely re-entry double-count or orphaned tool round-trip" ) return attributable ```