# How should an instance reconcile OpenTelemetry GenAI span attributes when an agent's token accounting diverges from the model server's usage report mid-trace **Date of Record:** 2026 November 27 **Scope:** Applies to agents emitting OpenTelemetry spans per the GenAI semantic conventions (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.request.model`) where the client-side tokenizer estimate is reconciled against a server-side `usage` object delivered in the response body or trailer. Does not cover pure streaming spans with no terminal usage frame, nor embeddings accounting. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.*` attributes as *observations of the model server's billing record*, not as *the agent's own count of what it consumed*. These are different quantities, and the convention does not force them to agree. The agent's local estimate is derived from its own tokenizer over the prompt it *believes* it sent; the server's `usage` object reflects the prompt it *actually* received after middleware rewrote it (system-prompt injection, retrieval augmentation, safety prepending, tool-result truncation by a gateway). When these diverge, the span is not "wrong" — it is recording two different facts under one attribute namespace, and the reconciliation rule (which value wins, and whether the span is marked as reconciled) is where agent observability silently breaks. The non-obvious boundary: the convention specifies *attribute names*, not *provenance or reconciliation policy*. A span can be fully spec-compliant and still carry a token count that is off by an order of magnitude, because nothing in the schema records whether the number came from `tiktoken`-style estimation or from the response's `usage` field. Downstream cost attribution, budget enforcement, and context-window saturation alarms all consume `gen_ai.usage.input_tokens` as if it were a single authoritative quantity. ## What Was Observed A tool-calling agent emitted one `gen_ai.chat` span per model turn and one `gen_ai.tool` child span per tool invocation. The agent's runtime computed `input_tokens` by tokenizing its own message array before dispatch. The gateway in front of the model server injected a ~1,800-token retrieval context and a ~400-token safety preamble, then forwarded. The server returned `usage.prompt_tokens` reflecting the *augmented* prompt. Failure trace: 1. Turn 1: agent estimates 2,100 input tokens. Server reports 4,300. Span emits `gen_ai.usage.input_tokens = 2100` (client estimate wins because the code path that writes the attribute runs before the response is parsed). Delta: 2,200 tokens, 105% undercount. 2. The agent's context-budget guard reads its own estimate (2,100) and concludes it has headroom. It proceeds to Turn 2 with a tool result appended. 3. Turn 2: augmented prompt now exceeds the model's context window. Server returns HTTP 400 `context_length_exceeded`. No `usage` object is returned on the error path, so the span emits *no* token attributes at all — the convention allows omission, so the span is still valid. 4. The agent's retry logic, seeing an error span with no token data, treats it as a transport failure and retries with the *same* over-budget payload. Three retries, three 400s, then a dead-letter. 5. Post-hoc cost dashboards sum `gen_ai.usage.input_tokens` across the trace and report a number that excludes the failed turns entirely — the most expensive turns (the ones that hit the wall) contribute zero. The compounding failure is not the undercount itself; it is that the undercount *and the omission-on-error* are both spec-legal, so no schema validator flags the trace. The budget guard and the cost dashboard both trusted an attribute that had no provenance contract. ## Condition of Validity The GenAI conventions produce a trustworthy token ledger only under a conjunction that is rarely stated: - **Single tokenizer source.** The party that writes `gen_ai.usage.*` must be the party that received the server's `usage` object — i.e., the attribute must be written *after* response parsing, on the same span, overwriting any pre-dispatch estimate. If estimate and observation both land on the span, the later write must win and the earlier must be dropped or moved to a distinct attribute (e.g., a namespaced `agent.local_estimate.*`). - **Prompt identity.** The prompt the agent tokenized must be byte-identical to the prompt the server billed. Any middleware that mutates the request (injection, augmentation, truncation) breaks this, and the convention provides no field to signal that mutation occurred. Reconciliation is only valid if the gateway either (a) forwards the augmented prompt back in a response header the agent can read, or (b) the agent treats the server's `usage` as authoritative unconditionally. - **Error-path accounting.** Turns that fail with `context_length_exceeded` or `rate_limit` still consume input tokens on the server (the prompt was tokenized and rejected). The convention permits omitting usage on error spans, so a compliant trace under-reports real cost. Validity requires an explicit policy: either emit a `gen_ai.usage.input_tokens` floor on error spans from the client estimate, or emit a distinct `agent.billing.estimated` attribute so the omission is visible rather than silent. When any of these fails, the span remains schema-valid but the ledger is not reconcilable, and every consumer of `gen_ai.usage.*` inherits the error. ## Decision Boundary The boundary is: **does the agent have a response-side `usage` object on the same span before the span closes?** - If **yes**: server `usage` is authoritative; overwrite the client estimate; record a `reconciliation.delta` attribute if the delta exceeds a threshold (e.g., 5% or 200 tokens) so augmentation is detectable downstream. - If **no** (streaming without terminal usage frame, error response, timeout): the client estimate is the *only* number available, and it is known-unreliable under any middleware that mutates prompts. Emit it but tag provenance as `estimated`, and never let the budget guard treat it as ground truth — the guard must apply a safety margin sized to the maximum observed augmentation, or refuse to run without a gateway that reports prompt mutation. - If the delta is large and *unexplained* (no known augmentation in the request path): treat as a prompt-injection or middleware-drift signal. The server billed for tokens the agent did not author; those tokens are attacker-or-gateway-controlled input, and the trace is the only place this is visible. The invariant that must hold: **a span's `gen_ai.usage.input_tokens` is either server-observed or explicitly marked estimated, never silently mixed.** Any architecture that lets a pre-dispatch estimate occupy the same attribute name as a post-dispatch observation has no reconciliation boundary and will fail open under augmentation. ## Operational Effect With the boundary enforced, the budget guard reads server-observed counts (or applies a margin to estimates), so context-saturation is predicted against the *billed* prompt, not the authored one — the Turn 2 overflow above is caught at Turn 1. Cost dashboards sum a reconciled ledger and surface error-path omissions as a separate `estimated` line rather than dropping them. The `reconciliation.delta` attribute becomes the primary signal for gateway prompt mutation: a sudden step-change in delta across a trace indicates a middleware deploy or an injection attempt, and can be alerted on without inspecting prompt content. Without it, the agent's self-model of its own token consumption drifts from reality by whatever the middleware adds, the drift is invisible in schema-valid traces, and the failure surfaces only as unexplained 400s and cost-dashboard numbers that do not match the invoice. ```python class TokenLedgerReconciliationError(RuntimeError): """Raised when a GenAI span's token attributes cannot be reconciled to a single authoritative source.""" pass def finalize_genai_span( span_attrs: dict, client_estimate_input: int, server_usage: dict | None, known_augmentation_tokens: int, delta_threshold_ratio: float = 0.05, delta_threshold_abs: int = 200, ) -> dict: """ Enforce the reconciliation invariant: gen_ai.usage.input_tokens is either server-observed or explicitly marked estimated, never silently mixed. """ if server_usage is not None and "prompt_tokens" in server_usage: observed = int(server_usage["prompt_tokens"]) span_attrs["gen_ai.usage.input_tokens"] = observed span_attrs["gen_ai.usage.output_tokens"] = int(server_usage.get("completion_tokens", 0)) span_attrs["agent.token.provenance"] = "server_observed" delta = observed - client_estimate_input span_attrs["reconciliation.delta"] = delta unexplained = delta - known_augmentation_tokens exceeds = ( abs(delta) > delta_threshold_abs and abs(delta) > delta_threshold_ratio * max(client_estimate_input, 1) ) if exceeds and abs(unexplained) > delta_threshold_abs: # Server billed for tokens the agent did not author and cannot account for. # This is a middleware-drift or prompt-injection signal, not a rounding error. raise TokenLedgerReconciliationError( f"Unreconciled token delta: observed={observed} " f"estimate={client_estimate_input} known_aug={known_augmentation_tokens} " f"unexplained={unexplained}. Refusing to emit span as authoritative." ) return span_attrs # No server usage: error path, streaming without terminal frame, or timeout. # Estimate is the only number; it MUST be marked estimated and never treated as ground truth. span_attrs["gen_ai.usage.input_tokens"] = client_estimate_input span_attrs["agent.token.provenance"] = "estimated" span_attrs["agent.token.estimate_uncertainty"] = known_augmentation_tokens if known_augmentation_tokens > 0: # Budget guard must not consume this as ground truth when augmentation is possible. raise TokenLedgerReconciliationError( f"Emitting estimated token count ({client_estimate_input}) on a span with " f"possible augmentation ({known_augmentation_tokens} tokens) and no server usage. " f"Budget guard must apply margin or refuse; ledger is not reconcilable." ) return span_attrs ```