# How does an instance detect a token-accounting divergence between GenAI span attributes and the model's own usage envelope at turn boundaries? **Date of Record:** 2026 November 23 **Scope:** Applies to agent runtimes emitting OpenTelemetry GenAI semantic-convention spans (`gen_ai.*` attributes) for LLM turns and tool calls, where the runtime reconciles per-turn `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` against the provider's response usage block. Does not cover pure tracing pipelines with no reconciliation loop, nor non-GenAI spans. ## Core Distinction A GenAI span is a *record of what the runtime believed happened*, not a record of what the model actually consumed. The `gen_ai.usage.*` attributes are written by the client at span close, sourced from either (a) the provider's response `usage` object, or (b) a local tokenizer estimate when the provider omits usage (streaming, certain tool-call paths, cached-prefix responses). These two sources diverge silently. The failure is not "wrong numbers in traces" — it is that the *agent's own budget governor* reads the span attributes back (or the same estimate function) and therefore under- or over-counts remaining context, producing a mid-task context-window saturation or premature truncation that no exception ever surfaces. The non-obvious invariant: **for any turn boundary, `sum(gen_ai.usage.input_tokens across child spans of the turn) + gen_ai.usage.output_tokens of the parent turn span` must be monotonic non-decreasing relative to the provider's cumulative usage, and the delta must equal the re-sent history.** When tool-call spans are modeled as children that each re-declare the *full* prompt as `input_tokens`, the sum double-counts the shared prefix. When they declare only the *incremental* tool-result tokens, the sum under-counts. Both are legal under the semantic conventions, which do not mandate a prefix-accounting rule — and that ambiguity is the boundary. ## What Was Observed A three-step agent turn: `chat` (parent) → `execute_tool` (child) → `chat` (parent, resumed). The provider returned usage `{input: 4200, output: 180}` on the first call and `{input: 5100, output: 90}` on the resumed call. The runtime emitted: - Parent span A: `gen_ai.usage.input_tokens=4200`, `output_tokens=180` - Child tool span: `gen_ai.usage.input_tokens=4200` (re-declared full prompt), `output_tokens=0` - Parent span B: `gen_ai.usage.input_tokens=5100`, `output_tokens=90` A downstream turn-budget governor summing `input_tokens` over the turn's span tree computed `4200 + 4200 + 5100 = 13500` against a 16k window, concluded 2.5k remained, and forced a history compaction that dropped the tool result the agent needed. The provider had actually consumed at most `5100` input tokens on any single call. The agent's next reasoning step diverged because its evidence was gone — no error, no span status `ERROR`, just a quietly wrong compaction. The trace *looked* healthy. The inverse failure was also reproduced: when tool spans were configured to emit only incremental tool-result tokens (`input_tokens=900`), the governor computed `4200 + 900 + 5100 = 10200`, believed 5.8k remained, and let the turn run into a provider-side `context_length_exceeded` — which the runtime mapped to a generic retry, re-sending the same oversized history three times before surfacing. ## Condition of Validity The divergence is detectable only if the runtime retains, per turn, the **provider-reported cumulative input usage** alongside the span-emitted values, and compares them at span close. This requires: 1. The provider response `usage` object is captured *before* any local tokenizer fallback overwrites it. Streaming paths that synthesize usage from chunk counts violate this and must be flagged. 2. Tool-call child spans carry an explicit accounting mode attribute (e.g., `gen_ai.tool.accounting = "cumulative" | "incremental"`). Without it, the reconciliation cannot know whether to sum or take-max. 3. The reconciliation runs *at the turn boundary*, not per-span, because the shared-prefix term only resolves once the full turn tree is closed. Where the provider omits usage entirely (some cached-prefix and speculative-decoding responses), the invariant is *not* checkable and the runtime must mark the turn `usage_source=estimated` and refuse to drive a hard budget decision from it. ## Decision Boundary The runtime must choose, per turn: - If `usage_source == "provider"` and the span-tree sum exceeds the provider cumulative by more than the re-sent-history bound → **accounting divergence**: do not compact, do not truncate; emit a diagnostic span attribute and fall back to provider cumulative as the budget truth. - If `usage_source == "estimated"` → the governor may *warn* but must not *act* (no forced compaction, no hard truncation). Acting on an estimate is the failure. - If the delta is negative (span sum < provider cumulative) beyond a small epsilon → tool-result tokens were dropped from the tree; treat as under-count and clamp the budget to provider cumulative. - Only when `usage_source == "provider"` *and* the delta is within `[0, re_sent_history_tokens]` may the governor trust the span tree for a hard decision. The re-sent-history bound is the number of tokens the runtime itself re-included in the resumed prompt (prior assistant output + tool results), which it knows exactly and must record on the parent span as `gen_ai.request.history_tokens`. ## Operational Effect Enforcing the boundary converts a silent mis-budget into an explicit, attributable signal. In the reproduced case, the governor stops compacting on the double-counted 13500, keeps the tool result, and the turn completes within the real 5100-token envelope. The under-count case surfaces as a pre-flight rejection with `usage_source` and `history_tokens` attached, so the retry loop does not triple-send an oversized prompt. The cost is one reconciliation pass per turn boundary and one mandatory attribute (`gen_ai.tool.accounting`) that every tool-span emitter must set — a schema-negotiation obligation that, if skipped, silently re-opens the boundary. ```python from dataclasses import dataclass from typing import Optional class UsageAccountingDivergence(RuntimeError): """Raised when span-emitted token usage cannot be reconciled with the provider envelope.""" pass @dataclass class TurnUsage: provider_input: Optional[int] # from response.usage; None if provider omitted it provider_output: Optional[int] span_input_sum: int # sum of gen_ai.usage.input_tokens over turn span tree span_output_sum: int history_tokens: int # tokens the runtime re-sent on resume accounting_mode: str # "cumulative" | "incremental" epsilon: int = 8 def reconcile_turn_usage(u: TurnUsage) -> str: if u.provider_input is None: # Estimated source: governor may warn, must not act. return "estimated_no_hard_decision" if u.accounting_mode not in ("cumulative", "incremental"): raise UsageAccountingDivergence( f"unknown tool accounting_mode={u.accounting_mode!r}; cannot reconcile span tree" ) delta = u.span_input_sum - u.provider_input # Negative beyond epsilon: tool-result tokens dropped from the tree. if delta < -u.epsilon: return "undercount_clamp_to_provider" # Positive beyond the re-sent-history bound: shared prefix double-counted. if delta > u.history_tokens + u.epsilon: raise UsageAccountingDivergence( "span input sum exceeds provider cumulative beyond re-sent-history bound: " f"span_sum={u.span_input_sum} provider={u.provider_input} " f"history={u.history_tokens} mode={u.accounting_mode}" ) return "trust_span_tree" def govern_turn(u: TurnUsage, window: int) -> int: verdict = reconcile_turn_usage(u) if verdict == "estimated_no_hard_decision": return window - (u.span_input_sum + u.span_output_sum) # advisory only if verdict == "undercount_clamp_to_provider": return window - (u.provider_input + u.provider_output) # trust_span_tree return window - (u.provider_input + u.provider_output) ```