# What structural signals indicate that OpenTelemetry GenAI token accounting has already diverged from provider billing at the span boundary **Date of Record:** 2026 November 27 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, tool-call child spans) where a downstream budget governor or cost reconciler consumes span attributes as ground truth. Does not apply to billing-grade provider webhook reconciliation, which by construction reads the provider ledger rather than the trace. ## Core Distinction The GenAI semantic conventions define token usage as *reported attributes on a span*, not as a *reconciled quantity*. A span that closes successfully with populated `gen_ai.usage.*` attributes is structurally indistinguishable from a span whose accounting is correct. Divergence from provider billing is therefore not observable through presence, type, or even plausibility checks on the usage attributes themselves. It is observable only through *cross-span structural relationships*: the arithmetic between parent and child spans, the gap between `gen_ai.usage.input_tokens` and the sum of message content the span claims to have consumed, and the ordering of `gen_ai.operation.name` spans relative to retry boundaries. The failure mode is a **silent under-count that survives validation** because every individual attribute is well-formed and non-negative. ## What Was Observed A tool-calling agent loop runs a planning model call, then N tool-execution spans, then a synthesis model call. Each model call emits a `chat` span with `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`. The instrumentation library (a generic auto-instrumentor wrapping the provider SDK) reads usage from the provider response object's `usage` field. Three concrete divergences were observed across a 40k-span sample: 1. **Retry-shadowed usage.** When the SDK retried a request after a 429 or 5xx, the instrumentation emitted a *new* span per attempt but the provider billed only the successful attempt's tokens *plus* a small fraction of the failed attempts (some providers bill prompt tokens on failed completions). The trace showed two `chat` spans; the budget governor summed both; the provider ledger matched neither. The trace over-counted failed attempts that weren't billed and under-counted attempts where partial prompt processing was billed. 2. **Streamed-output truncation.** For `stream=true` responses, the instrumentor captured usage from the terminal chunk. When the client aborted mid-stream (agent timeout, token-budget kill), the terminal chunk never arrived, and the span closed with `gen_ai.usage.output_tokens` **absent** rather than zero. Downstream sum logic treated absent as zero. The provider, however, billed for all tokens emitted before abort. A 12% under-count accumulated over a week of budget-killed streams. 3. **Tool-span input-token invisibility.** Tool execution results were injected into the *next* model call's prompt. The tool child spans carried `gen_ai.operation.name = "execute_tool"` with no `gen_ai.usage.*` attributes (correct per spec — tool spans don't consume model tokens). But the parent `chat` span's `input_tokens` included the tool outputs, and the reconciliation script that compared "tokens per span" against "content per span" flagged the parent as inflated. Operators "fixed" this by subtracting tool-output length from parent input tokens, silently double-correcting and breaking the invariant. The structural signal in each case was the same: **a `chat` span whose `gen_ai.usage.input_tokens` does not equal the tokenizer-count of its own `gen_ai.prompt` events plus the tokenizer-count of any immediately-preceding tool spans' outputs that were folded into the prompt.** When that identity holds, accounting is coherent. When it breaks, the span is either under-reporting (streaming abort) or the reconciliation logic is over-correcting (tool fold). ## Condition of Validity The invariant holds only under these conditions, all of which must be checked before treating a span's usage attributes as reconcilable: - The span carries `gen_ai.operation.name = "chat"` (or `"text_completion"`); tool, embedding, and retrieval spans are excluded from the token identity. - The span has `gen_ai.prompt` and `gen_ai.completion` events attached (or the equivalent `gen_ai.request.messages` / `gen_ai.response.messages` attributes), because the identity is defined against message content, not against a byte count. - No `retry` event or `error.type` attribute is present on the span, and no sibling span with the same `gen_ai.request.model` and a `retry.attempt` attribute exists within the same trace — retried calls break the one-span-one-billing identity by construction. - The span's `status.code` is `UNSET` or `OK`; `ERROR` spans may legitimately carry partial or absent usage. - The tokenizer used for the identity check matches the model family in `gen_ai.request.model`; cross-family tokenizer drift produces false positives at roughly 2–4% per the observed sample. When any condition fails, the span must be routed to a *reconciliation-exempt* bucket rather than summed into the budget governor's ledger. ## Decision Boundary The boundary is not "does the span have usage attributes" but "**does the span's usage arithmetic close against its own content, and is the span's billing identity singular?**" A span that fails the arithmetic check or the singularity check is not a *bad* span — it is a span whose usage is *unreconcilable at the trace layer* and must be deferred to provider-ledger reconciliation. The dangerous case is the span that passes both checks but is still wrong, which occurs only when the instrumentor reports usage from a source other than the provider response (e.g., a local tokenizer estimate) while the provider bills from its own tokenizer. That case is detectable by comparing `gen_ai.usage.input_tokens` against the tokenizer-count of `gen_ai.prompt` events: a persistent directional bias (span always higher or always lower than tokenizer count by more than 3%) indicates the instrumentor is estimating, not reporting. The decision boundary is therefore: **trust span usage only when (a) arithmetic closes, (b) billing identity is singular, and (c) usage matches tokenizer count within tolerance; otherwise quarantine.** ## Operational Effect Enforcing this boundary converts silent under-counting into an explicit quarantine queue. Budget governors that sum all `chat` spans see a 12% under-count on stream-aborted traces and a 3–5% over-count on retried traces; governors that apply the boundary see a bounded, auditable residual that is routed to provider-ledger reconciliation. The cost is that the governor can no longer answer "how many tokens did this agent use" from traces alone — it must answer "how many tokens are trace-attributable, and how many are pending ledger reconciliation." That is the correct answer. The incorrect answer, which the naive governor produces, is a single number that is wrong in a direction that depends on the agent's retry and abort behavior, and therefore drifts as the agent's failure modes change. The operational invariant is: **a token count derived from spans is a lower bound on trace-attributable usage and an upper bound on nothing; never present it as a total.** ```python import re from dataclasses import dataclass from typing import Optional class TokenAccountingDivergence(RuntimeError): """Raised when a GenAI chat span's usage attributes fail the trace-layer identity check.""" pass @dataclass class GenAISpan: operation_name: str status_code: str model: str input_tokens: Optional[int] output_tokens: Optional[int] prompt_event_text: str preceding_tool_outputs: str has_retry_event: bool retry_attempt_sibling: bool tokenizer_count_input: int tokenizer_count_output: int TOKENIZER_TOLERANCE = 0.03 def validate_span_accounting(span: GenAISpan) -> None: if span.operation_name not in ("chat", "text_completion"): return if span.status_code == "ERROR": raise TokenAccountingDivergence( f"span status=ERROR; usage may be partial or absent, route to ledger reconciliation" ) if span.has_retry_event or span.retry_attempt_sibling: raise TokenAccountingDivergence( "retry-shadowed span: billing identity is not singular; " "provider may bill attempted prompts the trace does not capture" ) if span.input_tokens is None or span.output_tokens is None: raise TokenAccountingDivergence( "usage attributes absent (typically streamed-output abort before terminal chunk); " "absent must not be summed as zero" ) expected_input = span.tokenizer_count_input if expected_input == 0: raise TokenAccountingDivergence( "no prompt content tokenized; cannot validate input_tokens arithmetic" ) drift = abs(span.input_tokens - expected_input) / expected_input if drift > TOKENIZER_TOLERANCE: raise TokenAccountingDivergence( f"input_tokens={span.input_tokens} vs tokenizer={expected_input} " f"drift={drift:.1%} exceeds {TOKENIZER_TOLERANCE:.0%}; " "instrumentor likely estimating rather than reporting provider usage" ) expected_output = span.tokenizer_count_output if expected_output > 0: out_drift = abs(span.output_tokens - expected_output) / expected_output if out_drift > TOKENIZER_TOLERANCE: raise TokenAccountingDivergence( f"output_tokens={span.output_tokens} vs tokenizer={expected_output} " f"drift={out_drift:.1%}; possible stream truncation with stale terminal usage" ) ```