# Under what conditions must an instance refuse to close a GenAI span when the token-accounting invariant `gen_ai.usage.input_tokens + gen_ai.usage.output_tokens == gen_ai.usage.total_tokens` cannot be satisfied by the provider's reported counters **Date of Record:** 2026 December 3 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*` attributes) where token usage is reported by a remote inference provider or local tokenizer. Does not apply to spans where usage is entirely synthesized from a trusted local tokenizer with a single deterministic counting method, nor to non-generative spans. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and `gen_ai.usage.total_tokens` as *reported measurements*, not as a *derived identity*. Practitioners routinely assume the three counters form a closed arithmetic system — that `total = input + output` always holds. It does not. The provider's `total_tokens` field is frequently computed against a different tokenizer, a different prompt-rendering path (chat template vs. raw completion), or includes cached/reasoning tokens that are not partitioned into input/output at all. The boundary condition is this: **a span emitter must treat the three counters as three independent observations, and must never "repair" a non-additive triple by silently rescaling one of them.** The moment an emitter forces additivity by rewriting `output_tokens` to equal `total − input`, it destroys the only signal downstream consumers have that the provider's accounting diverged — and that signal is exactly what the agent needs to detect a tool-call loop that is being billed but not produced. ## What Was Observed An agent executing a multi-step tool-call plan (search → fetch → summarize → verify) emitted one `gen_ai.chat` span per model turn, each with a nested `gen_ai.tool.call` child span. The provider returned usage blocks of the form: ``` {turn 3} input=8120 output=340 total=8460 # additive, fine {turn 4} input=8460 output=290 total=8760 # 8460+290 = 8750 ≠ 8760 (Δ=+10) {turn 5} input=8750 output=120 total=8870 # 8750+120 = 8870 (Δ=0) {turn 6} input=8870 output=0 total=9870 # 8870+0 = 8870 ≠ 9870 (Δ=+1000) ``` Turn 4's +10 delta was a reasoning-token surcharge billed to `total` but not partitioned. Turn 6's +1000 delta was the real failure: the model emitted a `tool_call` block that the runtime's parser rejected (malformed JSON arguments), so `output_tokens` was reported as 0 by the streaming finish handler — but the provider had already billed 1000 completion tokens that were never surfaced as text or as a parsed tool call. The agent's loop controller, reading `output_tokens == 0`, concluded the turn produced no work and retried. The retry reproduced the malformed call. Three retries later, the agent had burned 3000 tokens across spans that each reported `output_tokens=0`, and the token-budget guard — which summed `output_tokens` — never fired. The arithmetic non-additivity at turn 6 was the *only* in-band signal that the turn had produced billed output the runtime failed to consume. It was invisible because the emitter's usage-export helper had a normalization step: `if total != input + output: output = total - input`. That single line erased the divergence and made the budget guard blind. ## Condition of Validity The additivity invariant `input + output == total` is valid **only** when all three counters originate from a single provider response object, under a single tokenizer, with no cached-prefix or reasoning-token partitioning, and with the runtime's parser consuming exactly the completion the provider billed. Any of the following voids it: 1. **Partitioned billing.** Providers that bill reasoning/thinking tokens to `total` but not to `output` (or vice versa) break additivity by construction. 2. **Parser shortfall.** When the runtime fails to parse a tool call, stop sequence, or structured output, `output_tokens` (as measured by the runtime's finish handler) undercounts the provider's billed completion. 3. **Prompt-cache accounting.** Cached input tokens may be reported in `total` while `input_tokens` reflects only uncached input. 4. **Multi-provider fan-out.** A single logical agent turn that fans out to a router + fallback provider yields two usage blocks whose totals are not additive with respect to each other. Under any of these, the emitter must **preserve the raw triple verbatim** and annotate the divergence, not repair it. ## Decision Boundary The emitter must decide, per span, between two mutually exclusive behaviors: - **Emit-as-reported** (default): write `input`, `output`, `total` exactly as the provider returned them. If `input + output != total`, set an attribute `gen_ai.usage.accounting_divergence = total - (input + output)` and do **not** alter any of the three. Downstream budget guards must sum `total`, never `output`. - **Refuse-and-sever** (boundary): if the divergence exceeds a configured fraction of `total` (observed threshold: `|Δ| > 0.10 * total`) **and** the span carries a `gen_ai.tool.call` child whose status is `error` or whose parse failed, the emitter must raise and fail the span closed rather than emit a triple that a naive consumer will treat as additive. A large positive Δ on a turn with a failed tool call is the signature of billed-but-unconsumed output; emitting it as a clean additive triple is the bug. The boundary is not "divergence exists" — small divergences are routine. The boundary is "divergence exists **and** correlates with a tool-call parse failure," which is the precise condition under which the divergence is load-bearing for loop control. ## Operational Effect When the emitter refuses to normalize, three downstream behaviors change: 1. **Budget guards become sound.** Summing `total` (not `output`) means the turn-6 retry storm is caught on the first retry, not the fourth. 2. **Loop controllers gain a divergence signal.** A rising `accounting_divergence` across consecutive spans is a leading indicator of parser/model contract drift — the model is emitting a tool-call dialect the runtime cannot parse, and every turn is being billed at full completion cost while producing zero consumable work. 3. **Replay reconciliation becomes possible.** An auditor replaying the trace can reconstruct the exact provider-billed cost per span even when the runtime's parser lost the completion, because the raw triple is preserved. The invariant to enforce is therefore not additivity but **fidelity**: the span must carry the provider's numbers unmodified, plus an explicit divergence attribute, plus a hard failure when divergence co-occurs with tool-call parse failure. Silent normalization is the failure mode; preserving the raw triple and failing closed on the correlated case is the guardrail. ```python from dataclasses import dataclass class GenAIUsageAccountingError(RuntimeError): """Raised when a GenAI span's token triple cannot be safely emitted.""" @dataclass(frozen=True) class UsageTriple: input_tokens: int output_tokens: int total_tokens: int @property def divergence(self) -> int: return self.total_tokens - (self.input_tokens + self.output_tokens) def finalize_genai_span( usage: UsageTriple, tool_call_parse_failed: bool, divergence_fraction_threshold: float = 0.10, ) -> dict: """ Return span attributes for a gen_ai.chat span. Invariant: never rewrite input/output/total. Preserve the provider's raw triple and annotate divergence. Fail closed only when divergence co-occurs with a tool-call parse failure above threshold. """ if usage.total_tokens < 0 or usage.input_tokens < 0 or usage.output_tokens < 0: raise GenAIUsageAccountingError( f"negative token counter in usage triple: {usage!r}" ) attrs = { "gen_ai.usage.input_tokens": usage.input_tokens, "gen_ai.usage.output_tokens": usage.output_tokens, "gen_ai.usage.total_tokens": usage.total_tokens, "gen_ai.usage.accounting_divergence": usage.divergence, } if usage.divergence != 0: denom = max(usage.total_tokens, 1) frac = abs(usage.divergence) / denom if tool_call_parse_failed and frac > divergence_fraction_threshold: # Billed-but-unconsumed output signature: refuse to emit an # additive-looking triple that would blind the budget guard. raise GenAIUsageAccountingError( "refusing to close span: divergence " f"{usage.divergence} ({frac:.2%}) co-occurs with tool-call " f"parse failure; raw triple={usage!r}" ) attrs["gen_ai.usage.divergence_flagged"] = True return attrs ```