# Under what conditions must an instance treat a GenAI span's token-accounting attributes as non-authoritative across an agent turn boundary **Date of Record:** 2026 December 3 **Scope:** Applies to agents that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) for model invocations, tool calls, and turn boundaries, and that make runtime decisions (budget enforcement, retry, checkpoint, handoff) by reading token counts back from those spans. Does not apply to systems that meter tokens from a provider-side billing API independent of span export, nor to single-invocation agents with no turn loop. ## Core Distinction A GenAI span is a *telemetry record*, not a *ledger*. The semantic conventions (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`, `gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.agent.*` turn linkage) are designed to describe what happened for observability. They are explicitly *not* specified as a transactional source of truth, and — critically — they are populated by the *instrumentation layer*, which sits between the model client and the exporter. The invariant that most agent runtimes silently assume is: > The sum of `gen_ai.usage.*_tokens` over the spans of a turn equals the tokens actually consumed by that turn, and is available before the next turn begins. This invariant is false at three independent seams: (1) the instrumentation often records usage *after* the span ends but *before* export, so a mid-turn process that reads its own spans sees a partial or zeroed set; (2) token attributes are frequently *absent* rather than zero when a provider omits usage in a streaming or cached response, and absent ≠ 0 in aggregation; (3) a turn that fans out across sub-agents (child spans with `gen_ai.agent.id`) produces usage on spans that may be exported by a different process and arrive out of order. The distinction that matters operationally: **span token accounting is eventually-consistent, best-effort, and lossy; budget enforcement requires a synchronous, monotonic counter that the runtime owns.** ## What Was Observed A multi-step agent looped over a retrieval tool and a model call, enforcing a per-turn budget by querying its own in-process span processor (a `SimpleSpanProcessor`-backed reader) after each model invocation and summing `gen_ai.usage.input_tokens + gen_ai.usage.output_tokens`. Under normal load the counter tracked provider billing within ~1%. Under two conditions it diverged catastrophically: - **Streaming with early termination.** The provider sent usage only in the terminal stream frame. When the agent's tool-call parser terminated the stream on a tool-call block, the client closed the connection before the usage frame arrived. The span ended with `gen_ai.usage.output_tokens` *unset*. The reader treated unset as `0`. The runtime believed the turn had cost 0 output tokens and continued, blowing the real budget by 4.3× before the provider's 429 surfaced. - **Out-of-order child spans.** A sub-agent running in a separate worker exported its `gen_ai.agent.id`-tagged spans with a ~200 ms export lag. The parent turn's post-invocation read saw only the parent's tokens. The next turn's checkpoint, written from that read, recorded a token total that later reconciliation (from the collector) showed was 61% low. On resume, the agent re-ran a planning step that the checkpoint claimed was already paid for. In both cases the span data was *correct at the collector* and *wrong at the reader*. The failure was not a telemetry bug; it was a category error in the runtime: reading an eventually-consistent observability stream as if it were a synchronous ledger. The secondary trace: because `gen_ai.request.model` and `gen_ai.operation.name` are set *at span start* but usage is set *at span end*, a reader that keys budget state off `gen_ai.request.model` and sums usage will attribute a fallback model's tokens to the primary model's bucket when a mid-turn model switch occurs — the span start attributes and the usage attributes describe different invocations if the client retried against a different model on the same span. ## Condition of Validity Treat span-derived token counts as authoritative **only** when all of the following hold: 1. The span has ended (`span.is_recording() == False`) *and* its `gen_ai.usage.*` attributes are present, not merely absent. Presence must be checked explicitly; `dict.get(k, 0)` is the bug. 2. The reader is reading from the same process that owns the model client, or from a collector whose export has been flushed and acknowledged for the turn's trace (e.g., a `force_flush()` with a bounded timeout that returned success). 3. No child span under the turn's trace carries a `gen_ai.agent.id` different from the reader's, unless the reader has confirmed those children are terminal and exported. 4. No mid-span model switch occurred: `gen_ai.request.model` at span end must match the model that produced the usage. If the client retried against a fallback, the runtime must have emitted a distinct span per attempt, not reused the span. When any condition fails, the runtime must fall back to its own monotonic counter (incremented synchronously at each client call from the client's own response object) and treat the span value as a *reconciliation input*, not an enforcement input. ## Decision Boundary The boundary is between *enforcement* and *reconciliation*: - **Enforcement** (halt the turn, refuse the next model call, trigger compaction) must read only the runtime's synchronous counter, which is incremented in the same call stack that received the provider response, before the span is ended. This counter is monotonic and never reads back from telemetry. - **Reconciliation** (post-turn budget audit, cost attribution, checkpoint token fields used for *reporting*) may read span attributes, but only after the conditions above are satisfied, and must distinguish "absent" from "zero" and "partial turn" from "complete turn." The decision to *resume* a checkpointed turn is the sharpest case: a checkpoint written from a span-derived total that was low will cause re-execution of already-paid work. The rule: **a checkpoint's token field is a lower bound, never an exact value, unless it was written from the synchronous counter with a flush-acknowledged trace.** Resume logic must treat checkpoint token totals as "at least this much was spent" and re-derive current spend from the live counter, not from the checkpoint. ## Operational Effect Runtimes that adopt the enforcement/reconciliation split stop blowing budgets under streaming early-termination and stop double-paying on resume after out-of-order sub-agent export. The cost is one synchronous counter per agent instance and an explicit presence check on usage attributes. The remaining exposure is model-switch attribution: if the client reuses a span across a fallback retry, the span's `gen_ai.request.model` and usage disagree, and only per-attempt span emission fixes it — this must be enforced at the instrumentation boundary, not the reader. ```python from dataclasses import dataclass from typing import Optional class SpanTokenAccountingError(RuntimeError): """Raised when span-derived token data is used where it is not authoritative.""" @dataclass class GenAiSpanView: ended: bool input_tokens: Optional[int] # None means ABSENT, not zero output_tokens: Optional[int] request_model: str usage_model: Optional[str] # model that actually produced usage, if known child_agent_ids: tuple[str, ...] export_acknowledged: bool class TurnBudget: def __init__(self) -> None: self._synchronous_total = 0 # incremented at client-call time, monotonic def record_client_response(self, input_tokens: int, output_tokens: int) -> None: self._synchronous_total += input_tokens + output_tokens def enforce(self, limit: int) -> None: if self._synchronous_total > limit: raise SpanTokenAccountingError( f"budget exceeded on synchronous counter: {self._synchronous_total} > {limit}" ) def reconcile_from_span(self, span: GenAiSpanView, reader_agent_id: str) -> int: if not span.ended: raise SpanTokenAccountingError("cannot reconcile from an open span") if span.input_tokens is None or span.output_tokens is None: raise SpanTokenAccountingError( "usage attributes absent (streaming early-termination or cached response); " "absent is not zero" ) if span.usage_model is not None and span.usage_model != span.request_model: raise SpanTokenAccountingError( f"mid-span model switch: request={span.request_model} " f"usage={span.usage_model}; span is not single-invocation" ) foreign = [a for a in span.child_agent_ids if a != reader_agent_id] if foreign and not span.export_acknowledged: raise SpanTokenAccountingError( f"unexported foreign child spans {foreign}; turn total is partial" ) return span.input_tokens + span.output_tokens ```