# What structural signals indicate token-accounting divergence between OpenTelemetry GenAI span attributes and the agent's own usage ledger **Date of Record:** 2026 November 23 **Scope:** Applies to agents that emit OpenTelemetry spans following the GenAI semantic conventions (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, `gen_ai.tool.name`) while also maintaining an internal token budget ledger for cost control or context-window management. Does not apply to systems that treat OTel spans as the sole source of truth for token accounting, nor to pure tracing without budget enforcement. ## Core Distinction The confusion this record resolves is between *observability token counts* and *enforcement token counts*. The OpenTelemetry GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes on the span that *reports* a model invocation. The agent's budget ledger, by contrast, is a mutable counter that gates whether the *next* invocation is permitted. These two numbers are computed at different points in the execution lifecycle, by different code, against different tokenizers, and—critically—the OTel span is finalized *after* the model call returns, while the ledger must be debited *before or during* the call to prevent overspend. The invariant that is silently violated is: **the sum of `gen_ai.usage.*` across the span tree must equal the ledger debit for the same logical operation.** Agents routinely assume this holds and build budget enforcement on top of span aggregation; it does not hold under retries, streaming, tool-augmented turns, and multi-provider fallback. ## What Was Observed A tool-using agent emitted a parent span `gen_ai.operation.name=chat` with three child spans for tool calls, each child carrying its own `gen_ai.usage` attributes (because the tool invocation triggered an internal LLM call for argument synthesis). The parent span's `gen_ai.usage.input_tokens` was set to the *final* request's prompt tokens only—the orchestrator overwrote the attribute on each retry rather than accumulating. The ledger, however, debited every attempt including two failed retries that returned `429` before producing any completion. The structural signals of divergence, in order of how early they can be detected: 1. **Span count exceeds ledger transaction count.** Two retries produced spans (each with a `status.code=ERROR` and `gen_ai.usage` present but zero output tokens) that the ledger collapsed into a single debit. Signal: `count(spans where gen_ai.operation.name=chat) > count(ledger.transactions where op=chat)`. 2. **Parent attribute is non-additive across children.** The parent's `input_tokens` was less than the sum of its children's `input_tokens` plus its own prompt. Signal: `parent.gen_ai.usage.input_tokens < Σ child.gen_ai.usage.input_tokens + parent_prompt_estimate`. This is the canonical "overwrite instead of accumulate" defect. 3. **Output tokens present on a span whose status is ERROR.** A failed call cannot have produced output tokens; their presence indicates the attribute was copied from a prior attempt or a fallback provider. Signal: `gen_ai.usage.output_tokens > 0 AND status.code = ERROR`. 4. **Model identifier mismatch between span and ledger.** Fallback routing (`gen_ai.request.model` = primary, but completion served by secondary) leaves `gen_ai.response.model` differing from `gen_ai.request.model`; the ledger priced at the requested model's rate. Signal: `gen_ai.response.model != gen_ai.request.model` with no corresponding ledger rate adjustment. 5. **Streaming spans with absent usage.** Under streaming, `gen_ai.usage.output_tokens` is often only known at stream close; if the consumer aborts mid-stream, the span closes without usage attributes, and the ledger either debits zero (undercount) or a pre-estimate (overcount). Signal: `gen_ai.operation.name=chat AND span has no gen_ai.usage.output_tokens AND duration > 0`. ## Condition of Validity The equality invariant `Σ span.gen_ai.usage == ledger.debit` is valid **only** when all of the following hold: - The span is emitted exactly once per billable model call, with no retry collapsing and no fallback re-emission. - Usage attributes are *accumulated* on the parent from children, not overwritten. - The tokenizer used to populate `gen_ai.usage.*` is identical to the tokenizer used by the ledger's debit computation (same model, same version, same special-token handling). - Streaming completions are finalized (span closed with usage) before the ledger reconciles. - No tool call triggers a nested LLM invocation whose usage is attributed to the child span but billed through the parent's budget. When any of these fails, the invariant is not merely imprecise—it is *structurally* violated, and any budget guardrail built on span aggregation will drift monotonically in one direction (usually undercounting, because retries and aborted streams lose usage). ## Decision Boundary The decision boundary is whether to treat OTel GenAI spans as **authoritative** or **advisory** for enforcement. The rule this record establishes: - **Advisory (default):** spans are for observability, cost attribution, and post-hoc reconciliation. The ledger is authoritative and is debited at call initiation with a conservative pre-estimate, then reconciled against `gen_ai.usage.*` at span close. Divergence is logged, not enforced. - **Authoritative (only under the validity conditions above):** spans may gate the next call. This requires a span processor that *validates* the structural signals before promoting span usage to ledger truth. If any signal fires, the span is quarantined and the ledger retains its pre-estimate. The boundary is crossed the moment an agent uses `gen_ai.usage.*` to decide "can I afford the next turn?" without first verifying additivity, retry-collapse absence, and response-model agreement. Below that line, span aggregation is safe; above it, it is a silent budget leak. ## Operational Effect The operational consequence of getting this wrong is a **monotonic budget drift** that is invisible in dashboards because both the span aggregate and the ledger look internally consistent—they just disagree with each other, and the disagreement grows with retry rate and streaming abort rate. Agents that enforce on span aggregates overspend precisely when the provider is degraded (high retry rate), which is the worst time to lose budget control. The mitigation is a reconciliation guardrail: on every span close, compare the span's usage against the ledger's pre-debit; if the structural signals fire, emit a `TokenAccountingDivergence` and hold the ledger at the conservative estimate rather than the (possibly undercounted) span value. The guardrail must be a *hard* failure on the reconciliation path, not a warning, because a warning on a monotonic drift is a warning that fires forever and is ignored. ```python import dataclasses from typing import Optional class TokenAccountingDivergence(RuntimeError): """Raised when OTel GenAI span usage cannot be reconciled with the agent ledger.""" pass @dataclasses.dataclass class SpanUsage: operation: str input_tokens: Optional[int] output_tokens: Optional[int] status_code: str # "OK" or "ERROR" request_model: Optional[str] response_model: Optional[str] child_input_sum: int = 0 parent_prompt_estimate: int = 0 @dataclasses.dataclass class LedgerEntry: operation: str debited_tokens: int transaction_count: int def reconcile_span_to_ledger( span: SpanUsage, ledger: LedgerEntry, span_count_for_op: int, ) -> int: """ Validate that a closed GenAI span's usage attributes are structurally reconcilable with the ledger. Returns the tokens to credit back to the ledger on success; raises TokenAccountingDivergence on any structural violation, in which case the caller must retain the conservative pre-estimate rather than promoting span usage to ledger truth. """ # Signal 3: output tokens on an ERROR span are impossible. if span.status_code == "ERROR" and (span.output_tokens or 0) > 0: raise TokenAccountingDivergence( f"output_tokens={span.output_tokens} on ERROR span for op={span.operation}; " "attribute likely copied from prior attempt or fallback provider" ) # Signal 1: retry collapse — more spans than ledger transactions. if span_count_for_op > ledger.transaction_count: raise TokenAccountingDivergence( f"span_count={span_count_for_op} > ledger.transactions={ledger.transaction_count} " f"for op={span.operation}; retries emitted spans that ledger collapsed" ) # Signal 2: parent attribute non-additive across children. if span.input_tokens is not None: floor = span.child_input_sum + span.parent_prompt_estimate if span.input_tokens < floor: raise TokenAccountingDivergence( f"parent input_tokens={span.input_tokens} < child_sum+prompt={floor} " f"for op={span.operation}; attribute overwritten instead of accumulated" ) # Signal 4: response model diverged from request model without rate adjustment. if ( span.request_model is not None and span.response_model is not None and span.request_model != span.response_model and ledger.debited_tokens == 0 ): raise TokenAccountingDivergence( f"fallback model {span.response_model} served request for {span.request_model} " f"but ledger has no rate-adjusted debit for op={span.operation}" ) # Signal 5: streaming span closed without usage. if span.input_tokens is None or span.output_tokens is None: raise TokenAccountingDivergence( f"span for op={span.operation} closed without complete gen_ai.usage; " "streaming abort or premature span close — retain pre-estimate" ) return span.input_tokens + span.output_tokens ```