# Why does an instance's token accounting diverge from its trace when a tool call is retried across a span boundary **Date of Record:** 2026 November 26 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*` attributes) and that perform automatic retries of tool calls within a single logical agent turn. Does not apply to single-shot LLM calls without tool loops, nor to systems that emit exactly one span per billable API request with no retry fan-out. ## Core Distinction There are two different quantities that both travel under the name "tokens": the **billable usage** reported by the inference provider on each HTTP response (`usage.prompt_tokens`, `usage.completion_tokens`), and the **semantic token attribution** that a trace consumer reconstructs by summing `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` across spans in a trace. These are equal only when every provider response maps to exactly one span and every span carries exactly one response's usage. The GenAI semantic conventions do not mandate that invariant; they only define attribute names and types. The moment a retried tool call produces two provider responses but the runtime reuses one logical span (or folds the retry into the parent agent span), the trace-summed token count diverges from the provider's invoice. This is not a rounding error — it is a structural accounting leak that scales with retry rate. ## What Was Observed A ReAct-style agent executes a turn: `chat.completions` with tool definitions → model returns a `tool_calls` payload → runtime invokes the tool → tool returns a transient error (HTTP 503 from a downstream API) → runtime retries the tool → tool succeeds → runtime issues a **second** `chat.completions` call to feed the tool result back. The runtime, following a common pattern, wraps the *entire* tool invocation (attempt 1 + attempt 2) in a single span named `execute_tool search_docs` with `gen_ai.operation.name = "execute_tool"`. The two `chat.completions` calls each get their own `gen_ai.operation.name = "chat"` span, and each correctly records its own `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`. The problem surfaces on the **second** `chat` call. Because the first tool attempt failed, the model's second call includes the tool result *and* — depending on the runtime's message-history construction — either one or two `tool` role messages. If the runtime appends both the failed attempt's synthetic error message and the successful retry's result, the second `chat` call's prompt is larger than the model actually conditioned on in a clean run. The provider bills for the larger prompt. The span records it faithfully. But a trace consumer that sums `gen_ai.usage.input_tokens` across all `chat` spans in the trace and compares it to the *first* call's prompt size to estimate "context growth per turn" sees a jump that is not attributable to the model's reasoning — it is attributable to the retry's injected error message. Worse: some runtimes set `gen_ai.usage.*` on the *parent* agent span by summing children, and *also* leave the per-call usage on the child spans. A naive collector that sums all spans with a `gen_ai.usage.input_tokens` attribute double-counts. The OTel spec does not forbid usage attributes on parent spans; it also does not define a de-duplication rule. The trace is internally consistent as a tree but numerically ambiguous as a sum. ## Condition of Validity The invariant "sum of `gen_ai.usage.input_tokens` over all spans in a trace equals the provider's billed input tokens for that trace" holds **only if** all three of the following are true: 1. Every provider response is represented by exactly one span carrying its usage, and no span carries usage derived from more than one response. 2. Retried tool attempts that trigger additional provider calls are represented as distinct child spans, not folded into the parent. 3. No ancestor span in the trace also carries `gen_ai.usage.*` attributes (or, if it does, the consumer knows to read only leaf spans). In the observed system, condition 1 held, condition 2 held for the `chat` spans but *not* for the tool span (the tool span carried no usage, which is correct, but its retry structure was invisible), and condition 3 failed because the agent span carried summed usage. The trace passed schema validation and failed arithmetic reconciliation. ## Decision Boundary The boundary is: **does the trace consumer need per-call attribution or per-turn totals?** If per-call (e.g., to detect prompt bloat from retry-injected messages), the consumer must read only spans where `gen_ai.operation.name == "chat"` and must be aware that a retry can inflate the *next* call's `input_tokens` by the size of the injected error message. If per-turn totals (e.g., for cost dashboards), the consumer must read only the top-level agent span's `gen_ai.usage.*` and must trust the runtime to have summed correctly — which it will not have done if it summed children that include both the failed and successful tool attempts' downstream chat calls. The correct guardrail is to **never** emit `gen_ai.usage.*` on non-leaf spans, and to emit a dedicated `gen_ai.tool.retry_count` attribute on the tool span so that downstream consumers can detect that a `chat` span's prompt includes retry-injected content. Without that attribute, the divergence is silent. ## Operational Effect A cost dashboard built on trace-summed `gen_ai.usage.input_tokens` will under-report by the amount of double-counting on parent spans and will mis-attribute retry inflation to "model verbosity." An agent-debugging tool that compares `input_tokens` across turns to detect context-window saturation will fire false alarms on retry-heavy turns. The fix is a two-part schema discipline: (a) usage attributes only on leaf `chat` spans, (b) a `gen_ai.tool.retry_count` integer attribute on every `execute_tool` span, and a reconciliation check that asserts `sum(leaf chat input_tokens) - sum(retry_injected_tokens) ≈ provider_billed_input_tokens` within a tolerance of one message boundary. ```python class TraceTokenReconciliationError(RuntimeError): """Raised when trace-summed GenAI token usage cannot be reconciled with provider billing.""" pass def reconcile_trace_tokens(spans: list[dict], provider_billed_input_tokens: int, tolerance: int = 0) -> int: """ Reconcile OTel GenAI span usage against provider billing. Invariant enforced: - usage attributes appear only on leaf spans with gen_ai.operation.name == "chat" - no ancestor span carries gen_ai.usage.* (would cause double-count) - retry-injected prompt tokens are subtracted before comparison """ usage_spans = [s for s in spans if "gen_ai.usage.input_tokens" in s.get("attributes", {})] non_chat_usage = [s for s in usage_spans if s["attributes"].get("gen_ai.operation.name") != "chat"] if non_chat_usage: raise TraceTokenReconciliationError( f"{len(non_chat_usage)} non-chat span(s) carry gen_ai.usage.*; " f"double-counting risk. Offending span ids: {[s['span_id'] for s in non_chat_usage]}" ) # Detect parent spans that also carry usage (condition 3 violation). span_ids = {s["span_id"] for s in spans} for s in usage_spans: parent = s.get("parent_span_id") if parent in span_ids and any(p["span_id"] == parent and "gen_ai.usage.input_tokens" in p.get("attributes", {}) for p in spans): raise TraceTokenReconciliationError( f"span {s['span_id']} and its parent {parent} both carry gen_ai.usage.input_tokens; " f"trace sum is ambiguous" ) trace_sum = sum(s["attributes"]["gen_ai.usage.input_tokens"] for s in usage_spans) # Subtract tokens attributable to retry-injected error messages. retry_overhead = 0 for s in spans: if s["attributes"].get("gen_ai.operation.name") == "execute_tool": retries = s["attributes"].get("gen_ai.tool.retry_count", 0) if retries > 0: # each retry injects one synthetic tool-error message into the next chat prompt retry_overhead += retries * s["attributes"].get("gen_ai.tool.error_message_tokens", 0) reconciled = trace_sum - retry_overhead if abs(reconciled - provider_billed_input_tokens) > tolerance: raise TraceTokenReconciliationError( f"token divergence: trace_sum={trace_sum} retry_overhead={retry_overhead} " f"reconciled={reconciled} provider_billed={provider_billed_input_tokens} " f"delta={reconciled - provider_billed_input_tokens}" ) return reconciled ```