# Why does an instance's GenAI token accounting silently double-count when a tool-call span is retried under OpenTelemetry semantic conventions **Date of Record:** 2026 November 26 **Scope:** Applies to agents emitting OpenTelemetry spans following the GenAI semantic conventions (`gen_ai.*`) where tool invocations are wrapped in child spans and usage is recorded as attributes. Does not apply to single-shot inference with no tool loop, nor to billing reconciliation performed against provider-side ledgers rather than collected spans. ## Core Distinction There is a distinction between *span cardinality* and *token cardinality*. The GenAI semantic conventions attach `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` to the span that represents the model call. When an agent loop retries a tool invocation—because the tool returned a transient error, a malformed schema, or a timeout—the retry produces a *new* child span. Operators naturally assume "one model call = one usage record." That assumption is false the moment retries exist, because the retried model call re-bills the *entire* prompt (system prompt + accumulated history + prior tool results) on every attempt. The span tree faithfully records N attempts; the token sum faithfully records N prompt replays. Neither is wrong. The invariant that breaks is the *aggregation contract*: any downstream consumer that sums `gen_ai.usage.*` across spans in a trace is now measuring "tokens billed to the provider," not "tokens attributable to the user's task," and the two diverge superlinearly with retry depth because each retry re-sends a longer context. ## What Was Observed A research agent executing a 9-step tool loop emitted a trace with 27 spans: 9 `gen_ai.chat` spans, 9 `gen_ai.execute_tool` spans, and 9 retry `gen_ai.chat` spans generated when the `execute_tool` span returned `status.code = ERROR` and the orchestrator re-prompted the model with the error text appended. Each retry `gen_ai.chat` span carried `gen_ai.usage.input_tokens` reflecting the *full* conversation up to that point plus the injected error. The retried `execute_tool` spans carried `gen_ai.usage.*` = 0 (correct—tools don't consume model tokens) but inherited the same `gen_ai.conversation.id` and a reused `gen_ai.tool.call.id` derived from the tool name rather than a fresh UUID. The dashboard summed `gen_ai.usage.input_tokens` grouped by `gen_ai.conversation.id`. It reported 412,000 input tokens for a task whose actual final-context size was 38,000 tokens. The discrepancy was not a bug in any single span; it was the arithmetic consequence of summing a *cumulative* quantity across *replayed* spans. Worse: because the retry spans reused `gen_ai.tool.call.id`, a second consumer that de-duplicated on that attribute collapsed the 9 retries into 1 and under-reported by 3×. Two dashboards, two answers, both "correct" under their own aggregation rule, neither matching the provider invoice. The failure trace, precisely: 1. Step 5's `execute_tool` span returns `ERROR` (tool timeout). 2. Orchestrator appends the error to the message list and calls the model again. 3. New `gen_ai.chat` span is emitted with `gen_ai.usage.input_tokens = 31,400` (the *whole* history, not the delta). 4. New `gen_ai.execute_tool` span reuses `gen_ai.tool.call.id = "search_web"` (derived from tool name, not per-invocation). 5. Aggregator A (`sum by conversation.id`) counts all replays → 412k. 6. Aggregator B (`distinct by tool.call.id`, then sum) collapses retries → 137k. 7. Provider ledger → 289k. Neither aggregator matches. ## Condition of Validity The invariant "sum of `gen_ai.usage.*` across spans in a trace equals tokens attributable to the task" holds **only if** every `gen_ai.chat` span in the trace carries a *delta* usage (tokens newly consumed by that single call) **and** retries are represented as spans that are either (a) explicitly marked `gen_ai.request.retry = true` and excluded from task attribution, or (b) folded into the parent span's usage rather than emitted as siblings. The convention as written does not mandate either. It says usage attributes describe "the model call that produced this span." It does not say whether a retry is a new model call (it is) or whether a re-prompt carrying prior context should report the full prompt or the incremental tokens. Both are defensible readings; the spec is silent, and the silence is where the double-count lives. The invariant also requires that `gen_ai.tool.call.id` be unique per *invocation*, not per *tool*. If it is derived from the tool name (a common shortcut when the SDK doesn't surface a call ID), de-duplication collapses distinct invocations and destroys the audit trail independently of the token issue. ## Decision Boundary The boundary is between two aggregation regimes, and the choice must be made explicitly at the collector, not left to the dashboard: - **Billing regime:** sum all `gen_ai.usage.*` across all `gen_ai.chat` spans, including retries, without de-duplication. This matches the provider ledger because the provider bills every replay. Use this for cost. - **Task regime:** sum only the *terminal* `gen_ai.chat` span per step (the one whose output was actually consumed), or sum deltas where the emitter reports deltas. Use this for "how much context did this task need." Mixing them—as happened above—produces a number that is neither. The decision boundary is crossed the instant a retry span is emitted without a `gen_ai.request.retry` (or equivalent) marker AND a downstream consumer applies a de-duplication key that is shared across retries. Guardrail: emit a per-invocation `gen_ai.tool.call.id` (UUIDv7), and set `gen_ai.request.retry = true` plus `gen_ai.usage.cumulative = true` on any span whose input tokens include previously-sent context. Consumers then have the information to choose a regime. Without both markers, the span is ambiguous and any aggregation is a guess. ## Operational Effect The practical consequence is that token dashboards silently drift from the invoice by a factor that grows with retry rate and context length—roughly `Σ_{i=1}^{N} L_i` versus `L_N`, where `L_i` is the prompt length at attempt `i`. For an agent with a 5% per-step tool failure rate and a 30k-token context, the billing-regime total runs 1.4–1.9× the task-regime total on a 10-step loop, and the gap widens as the agent's memory grows. Teams that "fix" the dashboard by de-duplicating on tool name trade the over-count for an under-count and lose the ability to detect retry storms entirely. The correct posture is to keep retries visible as first-class spans, mark them unambiguously, and let each consumer declare its regime. The following guard enforces that contract at emit time. ```python import uuid from dataclasses import dataclass, field class AmbiguousUsageSpanError(RuntimeError): """Raised when a GenAI span cannot be unambiguously attributed for token accounting.""" @dataclass class GenAISpan: span_id: str gen_ai_operation: str # "chat" | "execute_tool" gen_ai_tool_call_id: str | None gen_ai_usage_input_tokens: int gen_ai_request_retry: bool = False gen_ai_usage_cumulative: bool = False attributes: dict = field(default_factory=dict) def emit_chat_span( *, operation: str, input_tokens: int, tool_call_id: str | None, is_retry: bool, includes_prior_context: bool, ) -> GenAISpan: # Invariant 1: tool call IDs must be per-invocation, never derived from tool name. if tool_call_id is not None and not _looks_like_uuid(tool_call_id): raise AmbiguousUsageSpanError( f"gen_ai.tool.call.id={tool_call_id!r} is not a per-invocation UUID; " "de-duplication across retries will collapse distinct invocations." ) # Invariant 2: a retry that re-sends prior context MUST be marked cumulative, # otherwise summing usage across the trace double-counts the replayed prompt. if includes_prior_context and not is_retry: raise AmbiguousUsageSpanError( "Span reports cumulative input tokens but is not marked as a retry; " "billing-regime and task-regime sums will diverge silently." ) # Invariant 3: every retry span must be explicitly flagged so consumers can # choose to exclude it from task attribution. if is_retry and not includes_prior_context: raise AmbiguousUsageSpanError( "Retry span reports non-cumulative usage; provider will bill the full " "prompt, so the reported figure understates cost." ) return GenAISpan( span_id=str(uuid.uuid4()), gen_ai_operation=operation, gen_ai_tool_call_id=tool_call_id, gen_ai_usage_input_tokens=input_tokens, gen_ai_request_retry=is_retry, gen_ai_usage_cumulative=includes_prior_context, ) def _looks_like_uuid(value: str) -> bool: try: uuid.UUID(value) return True except ValueError: return False ```