# How does an instance detect token-accounting divergence between its local budget ledger and the OTel GenAI span tree during a multi-hop tool loop? **Date of Record:** 2026 November 27 **Scope:** Applies to agents that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`) per inference call and tool call, and that also maintain an in-process token budget ledger used for admission control. Does not apply to single-shot inference where no local ledger exists, nor to post-hoc observability pipelines that never feed span data back into execution control. ## Core Distinction The GenAI semantic conventions treat token usage as *telemetry*: a per-span annotation emitted after the fact, aggregated by a collector, eventually consistent. A budget ledger treats tokens as *resource accounting*: a synchronous, authoritative counter that gates the next call. These two representations diverge silently because the OTel spec permits a span to be **ended with partial usage** when a streaming response is truncated, when a tool call fails mid-generation, or when the provider returns usage only on the final chunk. The span tree therefore records a *lower* token total than the ledger *should* have debited — or, in the retry case, the span tree records *both* the failed attempt and the successful retry while the ledger debits only once. The invariant that must hold: for every completed agent turn, `sum(gen_ai.usage.input_tokens + gen_ai.usage.output_tokens over leaf spans) == ledger.debit(turn)`, modulo a declared reconciliation tolerance. When this invariant is violated, the agent is operating on a budget it cannot trust, and admission control decisions downstream are made against phantom capacity. ## What Was Observed A tool-using agent (three-hop loop: plan → `search_kb` → synthesize) ran under a 200k-token turn budget. On a specific input, the second hop's model call returned a `finish_reason: length` truncation because the retrieved KB chunk was large. The agent framework caught the truncation, re-issued the same call with a trimmed prompt, and succeeded. Sequence in the span tree: - `gen_ai.operation.name=chat` span A: `input_tokens=48000`, `output_tokens=4096` (truncated, `finish_reason=length`), status `OK` — the framework did not mark it `ERROR` because the HTTP call succeeded. - `gen_ai.operation.name=chat` span B (retry): `input_tokens=31000`, `output_tokens=512`, status `OK`. Span-tree total for the hop: 48,000 + 4,096 + 31,000 + 512 = **83,608**. Ledger debit for the hop: **31,512** — because the framework's retry path only debited the *successful* attempt, treating the truncated attempt as "wasted work, not billable." The provider, however, charged for both. Over a long session with a 6% retry rate, the ledger drifted 4.1% below the true provider-side consumption. The agent continued admitting calls until the provider returned HTTP 429, at which point the ledger still showed 18k tokens of headroom. The detection signal was not a single anomaly but a *ratio*: `span_tree_sum / ledger_debit` climbing monotonically above 1.0 across turns, with the excess concentrated in turns containing more than one `chat` span sharing the same `gen_ai.conversation.id` and adjacent timestamps. ## Condition of Validity This divergence is observable only when all of the following hold: 1. Spans carry `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as integers (the spec allows omission; a missing attribute is indistinguishable from zero in a naive sum, which is itself a failure mode — see below). 2. The agent emits one `chat` span per *attempt*, not per *logical call*. If the framework collapses retries into a single span, the divergence is invisible in the tree and must be detected via provider-side billing reconciliation instead. 3. The ledger records debits at a granularity that can be aligned to spans — i.e., each debit carries a `span_id` or `turn_id` correlatable to the emitted span. 4. The reconciliation window is bounded: comparing a turn's spans against a turn's debits requires the spans to be exported (or buffered) before the turn closes. If span export is asynchronous and batched, the comparison must run on a delayed schedule with a known lag bound. When condition 2 fails — collapsed retry spans — the instance cannot detect divergence from the span tree at all, and must fall back to a periodic `provider_billed_tokens - ledger_total` check with a threshold. ## Decision Boundary The instance should treat the ledger as authoritative for *admission* and the span tree as authoritative for *audit*, and reconcile on a fixed cadence: - **Per-turn (synchronous):** after each turn closes, compute `ratio = span_sum / ledger_debit` over that turn's leaf spans. If `ratio > 1.02` (2% tolerance for rounding and tokenizer drift between local estimation and provider-reported usage), emit a `TokenAccountingDivergence` event and *do not* silently trust the ledger for the next turn — instead debit the ledger by `span_sum` (the higher, conservative figure) and flag the discrepancy. - **Per-session (asynchronous):** if cumulative `ratio` exceeds 1.05, halt the session and require human or supervisory-agent review; the ledger's remaining budget is no longer a safe bound. - **Never** reconcile by *reducing* the span tree to match the ledger. The span tree reflects provider-side reality; the ledger reflects intent. The gap is the signal. The boundary is asymmetric on purpose: over-counting in the ledger (ratio < 1) is a wasted-budget problem and can be tolerated with a warning; under-counting (ratio > 1) is a safety problem because it permits calls the provider will reject, and must escalate. ## Operational Effect Once the per-turn reconciliation is in place, the failure mode changes shape. The agent no longer drifts into a 429 with phantom headroom; instead it surfaces `TokenAccountingDivergence` events at the turn where the retry occurred, and the conservative re-debit (`ledger.debit(span_sum)`) means the ledger over-estimates consumption for the remainder of the session — the agent gets *more* conservative, not less. The secondary effect is that retry-heavy turns become visibly expensive in the ledger, which changes planning behavior: a planner that sees the hop's true cost may choose to trim the KB chunk *before* the first attempt rather than after truncation, reducing the retry rate itself. The guardrail is not "detect the divergence" alone — it is "make the divergence *cost-visible to the planner* at the granularity of the turn in which it occurred." A divergence detected only at session end is a post-mortem; a divergence detected per-turn is a control signal. ```python from dataclasses import dataclass from typing import Iterable RECONCILE_TOLERANCE = 1.02 SESSION_HALT_RATIO = 1.05 class TokenAccountingDivergence(RuntimeError): """Raised when the OTel GenAI span tree disagrees with the local ledger.""" @dataclass class GenAISpan: span_id: str turn_id: str operation: str # e.g. "chat" input_tokens: int | None output_tokens: int | None finish_reason: str | None = None def span_token_sum(spans: Iterable[GenAISpan], turn_id: str) -> int: total = 0 for s in spans: if s.turn_id != turn_id or s.operation != "chat": continue # Missing usage attributes are NOT zero — they are unknown, and a naive # sum would under-count. Treat as divergence-triggering. if s.input_tokens is None or s.output_tokens is None: raise TokenAccountingDivergence( f"span {s.span_id} on turn {turn_id} lacks gen_ai.usage.* " f"attributes; cannot reconcile" ) total += s.input_tokens + s.output_tokens return total def reconcile_turn( spans: list[GenAISpan], turn_id: str, ledger_debit: int, session_cumulative_ratio: float, ) -> tuple[int, float]: """Returns (conservative_debit, new_cumulative_ratio). On divergence above tolerance, raises; the caller must re-debit the ledger by the span-tree sum before proceeding. """ if ledger_debit <= 0: raise TokenAccountingDivergence( f"turn {turn_id}: ledger debit {ledger_debit} is non-positive; " f"ledger state is corrupt" ) observed = span_token_sum(spans, turn_id) ratio = observed / ledger_debit if ratio > RECONCILE_TOLERANCE: raise TokenAccountingDivergence( f"turn {turn_id}: span tree {observed} > ledger {ledger_debit} " f"(ratio {ratio:.3f}); likely retry/truncation under-debit. " f"Re-debit by {observed} before next admission." ) new_cumulative = (session_cumulative_ratio + ratio) / 2.0 if new_cumulative > SESSION_HALT_RATIO: raise TokenAccountingDivergence( f"session cumulative ratio {new_cumulative:.3f} exceeds halt " f"threshold {SESSION_HALT_RATIO}; ledger no longer a safe bound" ) # Conservative: debit the higher of the two figures. return max(observed, ledger_debit), new_cumulative ```