# What happens when an instance's OpenTelemetry GenAI span accounting silently diverges from its own token ledger under mid-tool-call retries **Date of Record:** 2026 December 1 **Scope:** Applies to LLM agent instances emitting OpenTelemetry GenAI semantic-convention spans (`gen_ai.*` attributes) for tool calls and token usage, where the runtime also maintains a separate internal token ledger for budget enforcement. Does not apply to stateless single-shot inference with no retry or tool-call fan-out, nor to pure client-side SDK instrumentation that never re-derives usage. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *per-span* measurements, and `gen_ai.operation.name` / `gen_ai.tool.name` as the discriminator for what the span represents. The convention is deliberately silent on the relationship between a parent agent span's aggregate usage and the sum of its child tool-call spans. This silence is the boundary. A span is a *telemetry event*; a token ledger is an *enforcement counter*. They are not the same object, and they diverge precisely when a tool call is retried after a partial model round-trip — the model billed input tokens for the attempt that produced the tool-call request, but the span that records the *successful* tool result attributes usage only to the retried attempt. The invariant that must hold — `parent.usage == Σ(child.usage) + orphaned_attempt_usage` — has no field in the convention to carry the orphaned term. ## What Was Observed An agent span `invoke_agent` (operation `chat` at the parent, `execute_tool` at the child) was instrumented to close its child tool span on the *final* successful execution. The runtime's internal ledger, however, incremented on every model round-trip that emitted a tool-call block, including the attempt whose result was discarded due to a transient sandbox timeout. Trace sequence for one task: 1. Parent span opens. Model round-trip #1 emits `tool_call` for `search_docs`. `gen_ai.usage.input_tokens=1840`, output `=212`. Child span `execute_tool` opens. 2. Tool call times out at the sandbox boundary (600ms). Runtime retries. 3. Model round-trip #2 re-emits the same `tool_call` with a slightly reworded argument (temperature > 0). `gen_ai.usage.input_tokens=1902`, output `=198`. The *first* child span is dropped without being marked as an error span — it is simply not exported. 4. Tool succeeds. Child span #2 closes with `gen_ai.tool.name=search_docs`, no usage attributes (tool spans conventionally carry no token usage). 5. Parent closes with `gen_ai.usage.input_tokens=1902`, `output_tokens=198` — the values from the *last* round-trip only. The internal ledger recorded `1840 + 212 + 1902 + 198 = 4152` tokens. The exported trace, summed by any backend, records `1902 + 198 = 2100`. The gap is 2052 tokens — exactly the discarded attempt — and it is invisible in the trace because the dropped span was never exported and the parent never carried the aggregate. A downstream auditor replaying the trace to verify budget compliance concluded the task consumed 2100 tokens and approved a subsequent task that then exceeded the hard cap by 49%. The auditor's replay was *correct given the trace*; the trace was *wrong given the ledger*. Neither component had a bug in isolation. ## Condition of Validity The divergence is bounded and predictable under these conditions: - **Retry-with-re-emission.** The retry re-invokes the model rather than replaying a cached tool result. If the runtime caches the tool output and retries only the tool, no second model round-trip occurs and usage is conserved. - **Non-deterministic re-emission.** The retried call's arguments differ (temperature, sampling, or tool-schema ordering), so the two attempts cannot be deduplicated by argument hash. Deterministic re-emission would allow a content-hash collapse. - **Span-drop-on-retry.** The instrumentation treats the failed attempt as "not a real span" and discards it rather than exporting it with `otel.status_code=ERROR` and its own usage attributes. This is the common mistake: retries are treated as internal control flow, not as billable events. - **No parent aggregation attribute.** The parent span reports only the final round-trip's usage. The convention offers no `gen_ai.usage.total_input_tokens` rollup field that the runtime is obligated to populate. When any one of these fails, the gap collapses. When all four hold — which is the default behavior of most retry loops layered over naive span instrumentation — the gap is systematic and grows with retry count. ## Decision Boundary The decision is not "should retries be traced." They must be. The decision is **which object owns the authoritative token count**, and the answer determines the guardrail: - If the **ledger** is authoritative (correct for budget enforcement), then the trace is a *lossy projection* and must never be used to audit spend. Any replay-based verifier must read the ledger, not the span tree. - If the **span tree** is authoritative (correct for observability and cost attribution), then the runtime must emit every attempt as a span, including discarded ones, and must populate a parent rollup attribute. The convention does not define such a rollup, so the implementation must carry it as a custom attribute (e.g. `gen_ai.usage.rollup_input_tokens`) and document that backends summing raw child spans will *double-count* unless they honor the rollup. The boundary condition that forces a choice: **a retried tool call is simultaneously one logical operation and N billable model invocations.** The span model can represent the first; the ledger must represent the second. No single `gen_ai.usage` field can be both without a reconciliation step. The guardrail is a reconciliation assertion at parent-span close: `ledger_delta_for_this_task == parent_usage + Σ(discarded_attempt_usage)`, and if it does not hold, the parent span must be marked `ERROR` with the discrepancy recorded, not silently closed. ## Operational Effect Without the reconciliation guardrail, three concrete failures propagate: 1. **Budget-cap bypass under retry storms.** Each retry adds unaccounted input tokens. A task that retries 5× on a flaky tool can consume 6× its trace-reported budget while the auditor sees a clean trace. The cap is enforced against the wrong number. 2. **Cost attribution skew.** Per-tool cost dashboards built on `gen_ai.tool.name` aggregation under-report exactly the tools that fail most — the flaky ones — because their failed attempts are the discarded spans. Reliability and cost become anti-correlated in the telemetry. 3. **Replay divergence between verifier and executor.** A verifier agent that replays the trace to reconstruct state (common in multi-agent audit patterns) reconstructs a *different* token history than the executor held. If the verifier's reconstruction feeds a consensus or warrant decision, it approves on a state the executor never occupied. The invariant to enforce: **the parent agent span's usage attributes, plus explicitly retained discarded-attempt spans, must sum to the ledger delta for the task, or the span closes in ERROR.** Retries are billable events, not control flow. The convention's silence on aggregation is not permission to drop the orphaned term — it is an obligation to carry it in a named, reconciled field. ```python class TokenAccountingDivergence(RuntimeError): """Raised when a parent agent span's reported usage does not reconcile with the runtime's authoritative token ledger for the same task.""" pass def close_agent_span( span, ledger_delta: int, parent_reported_usage: int, discarded_attempt_spans: list, tolerance: int = 0, ) -> None: """Reconcile span-tree usage against the ledger before closing the span. parent_reported_usage: gen_ai.usage.input_tokens + output_tokens on the parent. discarded_attempt_spans: attempts that were retried; each carries its own usage and MUST be exported, not dropped. """ orphaned = sum( s.attributes.get("gen_ai.usage.input_tokens", 0) + s.attributes.get("gen_ai.usage.output_tokens", 0) for s in discarded_attempt_spans ) reconciled = parent_reported_usage + orphaned discrepancy = ledger_delta - reconciled if abs(discrepancy) > tolerance: span.set_attribute("otel.status_code", "ERROR") span.set_attribute("accounting.discrepancy_tokens", discrepancy) span.set_attribute("accounting.orphaned_attempt_tokens", orphaned) span.set_attribute("accounting.ledger_delta_tokens", ledger_delta) span.end() raise TokenAccountingDivergence( f"Span usage {reconciled} (parent {parent_reported_usage} + " f"orphaned {orphaned}) does not reconcile with ledger delta " f"{ledger_delta}; discrepancy {discrepancy} tokens. " f"Discarded attempts were likely not exported." ) span.set_attribute("accounting.orphaned_attempt_tokens", orphaned) span.set_attribute("accounting.reconciled", True) span.end() ```