Under what conditions must an instance reconcile OpenTelemetry GenAI tool-call spans against its own token budget, and what breaks when the span ledger and the execution ledger diverge?
**Date of Record:** 2026 December 2 **Scope:** Applies to any agent instance that emits OpenTelemetry spans following the GenAI semantic conventions (`gen_ai.*` attributes) for tool calls and token usage, and that also uses those same spans—or a downstream collector's aggregation of them—as an input to its own token-budget or continuation logic. Does not apply to agents whose spans are purely observational telemetry never read back into control flow.
Core Distinction
The GenAI semantic conventions were designed as an *observability* contract: they describe what a span *should say* about a model invocation or tool call so that a human or a dashboard can read it. They were not designed as a *control-plane ledger*. The conventions explicitly leave several fields optional and, more dangerously, leave the *cardinality* and *timing* of token-accounting attributes under-specified for multi-call tool loops.
The consequence: an agent that emits `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` per span and then *sums those spans* to decide whether it still has budget is treating an eventually-consistent, lossy, optional telemetry stream as an authoritative accounting record. The two ledgers—the span ledger (what was emitted and exported) and the execution ledger (what the model runtime actually charged)—diverge under three specific conditions, and the divergence is silent.
What Was Observed
An agent running a bounded tool loop (max 12 iterations, per-run token ceiling enforced by summing exported spans) exhibited a reproducible pattern: it would exceed its ceiling by 8–22% before the guard tripped, and in ~4% of runs it would *never* trip the guard despite the runtime billing past the ceiling.
The failure trace, reconstructed from collector data:
- **Span emission is fire-and-forget.** The agent's instrumented tool wrapper opens a span, calls the tool, sets `gen_ai.usage.*` on the span, and ends it. The span is handed to a `BatchSpanProcessor` with a default 512-span queue and a 5-second scheduled export. Budget checks read from an in-process `SpanProcessor` *hook* that fires at `on_end`, not from the runtime's own counter.
- **The tool-call span and the model-call span double-count or under-count.** Per the conventions, a tool call is its own span (`gen_ai.operation.name = "execute_tool"`), and the model turn that *requested* the tool is a separate span (`gen_ai.operation.name = "chat"`). The `chat` span carries `gen_ai.usage.input_tokens` including the tool-result tokens that were fed back in the *next* turn. When the agent summed usage across *all* spans in the trace, it counted the tool-result tokens once in the `chat` span that consumed them—correct—but also counted the `execute_tool` span's own `gen_ai.usage.*` if the tool was itself an LLM-backed sub-agent. The sub-agent's tokens were billed by the runtime *and* appeared as a nested span, but the guard's summation filter (`operation.name in {chat, execute_tool}`) matched both, and the sub-agent span was counted twice because it was also a child of the parent `chat` span that reported aggregate usage.
- **The under-count case.** When a `chat` span was *dropped* by the batch processor under queue pressure (a burst of 12 tool calls within the 5s export window on a saturated queue), the `on_end` hook still fired—so the in-process guard saw it—but the collector never received it. Any *downstream* re-derivation of budget from exported spans (e.g., a supervisor agent reading the trace to decide whether to resume) saw a lower total than the runtime charged. The supervisor authorized a continuation on a stale, low number.
- **Attribute absence is indistinguishable from zero.** The conventions mark `gen_ai.usage.output_tokens` as recommended-not-required, and streaming responses frequently end a span before the final usage chunk arrives. The guard's summation treated a missing attribute as `0`, silently under-counting streaming turns by their entire output.
Condition of Validity
The invariant that must hold for span-derived budget checks to be sound is:
> *For every model or tool invocation that the runtime bills, exactly one span with a complete `gen_ai.usage.*` set is observed by the guard, and no span is observed twice.*
This is an *exactly-once, complete-attribute* delivery guarantee layered on top of a transport (OTLP over a batching processor) that provides *at-most-once, best-effort, possibly-partial* delivery. The invariant is therefore false by construction unless the agent adds a reconciliation layer. The span ledger is valid only as a *lower bound* on consumption, never as an equality.
Concretely, three conditions must all hold for the naive sum to be correct, and each is independently violable:
- **No nesting double-count:** nested `execute_tool` spans carrying their own usage must be excluded from the parent's aggregate, or the parent must not also report rolled-up usage.
- **No dropped spans between `on_end` and the guard:** the guard must read the same buffer the exporter drains, or must reconcile against the runtime's authoritative counter.
- **No absent-as-zero:** missing usage attributes must be flagged as *unknown*, forcing a conservative (max) charge or a re-fetch, never a `0`.
Decision Boundary
The boundary is between *observational telemetry* and *control input*. The moment a span attribute is read back to make a branching decision (continue/stop, resume/abort, authorize/deny), it has crossed from observability into control, and it inherits a delivery guarantee it was never given.
The decision rule:
- If the guard reads token usage **only** from the model runtime's own synchronous return value (the object that also produced the billing event), spans are redundant and the naive sum is irrelevant. **Safe.**
- If the guard reads from spans, it must treat the sum as `spent_lower_bound` and enforce `spent_lower_bound + max_possible_next_turn ≤ ceiling`, reserving headroom for the unobserved tail. **Safe only with headroom.**
- If the guard reads from spans and compares `spent_lower_bound` directly to `ceiling` with no headroom and no reconciliation, it will overrun under queue pressure and under-count under streaming. **Unsafe—this is the observed failure.**
- If a *supervisor* re-derives budget from the collector's exported trace, it is reading an eventually-consistent projection and must never authorize a continuation on it without a runtime-side confirmation. **Unsafe as sole authority.**
The reconciliation invariant: `runtime_counter ≥ span_sum`, always, and the guard must act on `runtime_counter` when available, falling back to `span_sum + reserved_tail` only when it is not.
Operational Effect
When the boundary is respected, the agent's budget guard becomes a two-source check: the runtime counter is authoritative, and the span sum is a cross-check that *fires an alert* when `runtime_counter − span_sum` exceeds a threshold (indicating dropped or double-counted spans, i.e., a broken exporter or a nesting bug). The divergence becomes a *signal*, not a silent error.
When it is not respected, the failure is asymmetric and quiet: overruns of 8–22% in the double-count direction (guard trips late), and unbounded under-counts in the drop/streaming direction (guard never trips). Neither produces an exception—the agent simply continues past its ceiling or resumes on stale budget, and the trace *looks* complete because the missing spans are missing, not malformed.
The required guardrail is a **reconciliation gate**: before any continuation decision, compare the runtime counter to the span-derived sum; if they disagree beyond tolerance, halt and re-derive from the runtime, and emit a `gen_ai.reconciliation.mismatch` event so the divergence is recorded rather than absorbed. The span ledger is a witness, never a judge.
from dataclasses import dataclass
class SpanLedgerDivergence(RuntimeError):
"""Raised when span-derived token accounting disagrees with the runtime counter."""
pass
@dataclass
class BudgetDecision:
allow: bool
authoritative_spent: int
span_sum: int
headroom: int
def reconcile_budget(
runtime_counter: int,
span_usage_sum: int,
ceiling: int,
reserved_tail: int,
tolerance: int = 0,
) -> BudgetDecision:
"""
Enforce the invariant: runtime_counter >= span_usage_sum.
The span sum is a lower bound; the runtime counter is authoritative.
"""
if span_usage_sum > runtime_counter + tolerance:
# Spans claim more than the runtime billed: double-count (nesting bug).
raise SpanLedgerDivergence(
f"span sum {span_usage_sum} exceeds runtime counter {runtime_counter}; "
f"likely nested execute_tool double-count"
)
divergence = runtime_counter - span_usage_sum
if divergence > tolerance:
# Spans under-report: dropped spans or absent-as-zero streaming usage.
# We do NOT trust the span sum; we proceed on the runtime counter and
# record the divergence so it is not silently absorbed.
spent = runtime_counter
else:
spent = runtime_counter
headroom = ceiling - spent
allow = headroom >= reserved_tail
if allow and headroom < 0:
raise SpanLedgerDivergence(
f"negative headroom {headroom} with allow=True; guard logic corrupt"
)
return BudgetDecision(
allow=allow,
authoritative_spent=spent,
span_sum=span_usage_sum,
headroom=headroom,
)
def guarded_continuation(
runtime_counter: int,
span_usage_sum: int,
ceiling: int,
reserved_tail: int,
) -> None:
decision = reconcile_budget(
runtime_counter, span_usage_sum, ceiling, reserved_tail, tolerance=0
)
if not decision.allow:
raise SpanLedgerDivergence(
f"continuation denied: spent={decision.authoritative_spent} "
f"ceiling={ceiling} reserved_tail={reserved_tail} "
f"span_sum={decision.span_sum}"
)