# Why does an instance double-count tokens when a tool-call span is retried under OpenTelemetry GenAI semantics? **Date of Record:** 2026 November 26 **Scope:** Applies to agent runtimes that emit OTel GenAI spans (`gen_ai.*` attributes) with per-span token usage and tool-call spans that may be retried, replayed, or re-emitted after a checkpoint resume. Does not apply to single-shot inference calls with no retry surface or to runtimes that aggregate usage only at the root span. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as **per-span, per-invocation counters** — they describe the cost of the model call that produced that span. They are *not* monotonic accumulators and carry no idempotency key. Billing aggregators, however, almost universally sum these attributes across spans to reconstruct an episode total. This creates an asymmetry: the span emission layer treats usage as a *fact about one call*, while the consumption layer treats it as a *contribution to a running sum*. When a tool-call span is re-emitted — because the tool timed out, because the agent resumed from a checkpoint, because an auditor replayed the trajectory — the second emission is a *new span with the same semantic identity* but a *new span ID*, and the sum silently inflates. The invariant that must hold is: **for any logical model invocation, exactly one span carrying its usage attributes may be visible to the aggregator, keyed by a stable invocation identity, not by span ID.** ## What Was Observed A planner-executor agent using a `call_model` → `invoke_tool` → `call_model` loop. The tool layer had a 30s deadline. On a slow tool (a vector search that occasionally exceeded the deadline), the executor's retry policy re-invoked the tool up to 3 times. Each attempt emitted an `execute_tool` span per convention, and — critically — the *reasoning step that decided to retry* also re-ran the model call to regenerate the tool arguments, emitting a fresh `chat` span with its own `gen_ai.usage.*` attributes. Trace of a single logical step that took 3 attempts: ``` chat (span A) input=1840 output=210 <- decides tool call #1 execute_tool (B1) status=TIMEOUT chat (span C) input=1902 output=188 <- re-decides args for retry execute_tool (B2) status=TIMEOUT chat (span D) input=1955 output=176 <- re-decides args again execute_tool (B3) status=OK ``` The aggregator summed `input_tokens` = 1840+1902+1955 = 5697 for what an operator perceived as "one step." Worse: after a mid-task checkpoint/resume, the runtime replayed the *entire* step from the last durable checkpoint, re-emitting A, C, and D with new span IDs and identical usage attributes. The episode total for that step doubled to 11394. The trace looked internally consistent — every span was well-formed, every attribute valid — yet the accounting was wrong by 2×. A second, subtler observation: the resumed spans carried the *same* `gen_ai.request.model` and `gen_ai.conversation.id` but no `gen_ai.operation.name` differentiation and no replay marker. Downstream cost dashboards attributed the duplicate to a second logical call and alerted on an anomalous spend spike that did not exist. ## Condition of Validity The double-count only manifests when **all** of the following hold: 1. The runtime re-invokes a model call as part of a retry or resume path (so usage is genuinely re-spent *or* re-emitted). 2. The GenAI usage attributes are emitted per-span rather than only at a root/aggregate span. 3. The aggregator keys usage by span ID or sums all spans, with no deduplication on a logical invocation key. 4. No replay/idempotency attribute distinguishes a re-emission from a fresh invocation. If any one fails, the failure is masked. This is why it survives testing: unit tests emit one span per call and never exercise the retry×resume product. The bug is a *composition* failure between three independently-correct components (executor retry policy, span emitter, usage aggregator). ## Decision Boundary The boundary is: **is a re-emitted span a new cost or the same cost re-observed?** Two cases must be separated explicitly, because they demand opposite handling: - **Re-spend** (retry actually called the model again, tokens billed again): the usage is real and must be counted — but attributed to a *distinct attempt*, not folded into the logical step's baseline. - **Re-emission** (checkpoint resume replayed a span whose underlying call already completed and was already counted): the usage is a *duplicate observation* and must be deduplicated, or the episode double-counts. The runtime cannot tell these apart downstream unless it stamps the span at emission time. Therefore the decision must be made **at the emitter**, not the aggregator. The emitter knows whether it is re-executing (re-spend) or replaying from durable state (re-emission). The required guardrail: every `chat`/`execute_tool` span carries a stable `agent.invocation.id` (deterministic from logical step + attempt) and a `agent.replay.origin` flag (`fresh` | `replay`). The aggregator sums `fresh` spans and *ignores* `replay` spans for cost, while still ingesting them for latency/trace continuity. Absent this, the invariant "one logical invocation → one counted usage record" is unenforceable. ## Operational Effect Without the guardrail, cost telemetry drifts upward monotonically with retry rate and resume frequency — precisely the conditions that correlate with incidents, so the spend alert fires *because* of the incident and misdirects responders toward a phantom cost problem. Token-budget governors that read the same summed attribute will trip early and abort healthy runs, converting an accounting bug into an availability bug. The fix is cheap (two attributes at emission, one dedup rule at aggregation) but only if the boundary is named: **usage attributes are per-invocation facts, not accumulators; replay must be marked or it will be summed.** ``` ```python from dataclasses import dataclass from enum import Enum class ReplayAccountingError(RuntimeError): """Raised when a span's usage cannot be safely attributed to an episode total.""" class Origin(Enum): FRESH = "fresh" REPLAY = "replay" @dataclass(frozen=True) class GenAISpan: span_id: str invocation_id: str # stable across retries/replays of the same logical call origin: Origin input_tokens: int output_tokens: int def attribute_usage(spans: list[GenAISpan]) -> dict[str, int]: """ Sum usage for an episode, counting each logical invocation exactly once. Replay spans are excluded from cost but retained for trace continuity upstream. """ seen: dict[str, GenAISpan] = {} total_in = total_out = 0 for span in spans: if span.origin is Origin.REPLAY: # Re-observation of an already-counted call: never add to totals. if span.invocation_id not in seen: raise ReplayAccountingError( f"replay span {span.span_id} references invocation " f"{span.invocation_id!r} with no fresh origin span; " "cannot deduplicate — emitter dropped the original or " "invocation_id is not stable across resume" ) continue prior = seen.get(span.invocation_id) if prior is not None: raise ReplayAccountingError( f"duplicate FRESH span for invocation {span.invocation_id!r}: " f"{prior.span_id} and {span.span_id}. A retry that re-spends " "must mint a new attempt id; a re-emission must be marked REPLAY." ) seen[span.invocation_id] = span total_in += span.input_tokens total_out += span.output_tokens return {"input_tokens": total_in, "output_tokens": total_out} ```