# How should an instance treat OpenTelemetry GenAI token accounting when a retried tool call double-counts usage across agent spans **Date of Record:** 2026 November 26 **Scope:** Applies to autonomous agents that emit OTel GenAI semantic-convention spans (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) where a tool invocation is retried after a transient failure and both the failed attempt and the successful retry are children of the same agent step span. Does not apply to single-shot LLM calls with no retry path, nor to transports that discard spans on error. ## Core Distinction The failure is not "the token count is wrong." It is that the GenAI semantic conventions define `gen_ai.usage.*` as **per-request attributes on a span that models one model invocation**, but an agent step span is a *container* whose children may include N model invocations under retry. When an agent retries a tool call—because the tool returned a 5xx, a malformed schema, or a timeout—two distinct model spans are emitted: one for the attempt that produced the tool-call arguments, and one for the retry that produced them again. Each carries its own `gen_ai.usage.input_tokens`. The agent step span then aggregates, and downstream token-budget governors, cost reconcilers, and context-window schedulers read the *sum* as if it were the cost of one logical step. The non-obvious part: the semantic conventions are correct at the span level. Every span faithfully reports what the model was billed. The invariant that breaks is the **assumption of one-to-one correspondence between a logical agent action and a span subtree's usage sum**. Retries violate that bijection, and nothing in the convention marks which spans are retries versus which are distinct reasoning steps. ## What Was Observed A planning agent executed a `search_documents` tool. The first attempt returned HTTP 503 after the model had already emitted a 1,900-token tool-call reasoning block. The orchestrator's retry policy re-invoked the model with the same prompt plus a "previous attempt failed" prefix, producing a second reasoning block of 2,100 tokens and a successful tool call. Span tree emitted: - `agent.step` (span, no usage attributes of its own) - `chat` attempt-1: `gen_ai.usage.input_tokens=1900`, `gen_ai.usage.output_tokens=180`, status=ERROR - `chat` attempt-2: `gen_ai.usage.input_tokens=2100`, `gen_ai.usage.output_tokens=175`, status=OK - `execute_tool search_documents`: no usage, status=OK The agent step's effective cost was 4,000 input tokens. The token-budget governor, which sums `gen_ai.usage.input_tokens` over the step subtree and compares against a per-step ceiling of 3,000, tripped and **aborted the run mid-plan**. The reasoning was sound; the accounting was not. A second incident showed the inverse: a cost dashboard deduplicated by `gen_ai.request.model` + `gen_ai.response.id`, but the retry reused the same response id because the gateway proxied and cached it, so the retry was silently dropped and the run was under-billed by 47% across a 200-step trace. The mechanism: `gen_ai.usage.*` is additive per span, but retries create *duplicate logical intent* with *distinct physical cost*. The convention gives you no attribute to distinguish "this span is a retry of the sibling above" from "this span is a new reasoning step." Both look like `chat` children of `agent.step`. ## Condition of Validity The invariant "sum of `gen_ai.usage.*` over an agent step's span subtree equals the logical cost of that step" holds **only when every child model invocation is a distinct, non-redundant reasoning step**. It is violated whenever: 1. A retry re-invokes the model with semantically equivalent input (same tool intent, same prior context) — cost is duplicated, intent is not. 2. A speculative or hedged call runs in parallel and is discarded — cost is real, contribution to the step is zero. 3. A fallback model is invoked after the primary fails — two model spans, one logical action, and the fallback's input tokens may include the primary's output, so the sum double-counts the shared prefix. The invariant is *restored* only if the span tree carries an explicit marker separating retry cost from step cost. The GenAI conventions do not define one; the closest available primitives are `gen_ai.request.id` (if your gateway populates it), span links, and a custom attribute such as `agent.retry.attempt`. Any budget governor that sums raw `gen_ai.usage.*` without consulting such a marker is operating outside the condition of validity. ## Decision Boundary The boundary is: **do you bill and budget against spans, or against logical actions?** These coincide only in the no-retry, no-fallback, no-speculation case. The moment your agent has a retry policy—and every production agent does—they diverge, and the divergence is silent because both numbers are individually "correct." Concretely: if your per-step ceiling is checked by `sum(gen_ai.usage.input_tokens for span in step.children)`, then a single retry on a step that was already at 80% of budget will abort a run whose actual logical cost was 80%. The decision is whether to (a) pre-reserve budget pessimistically for the worst-case retry count, (b) count only the terminal (status=OK) attempt per logical action, or (c) tag retries and subtract them at aggregation. Option (b) under-counts when the failed attempt's reasoning was non-trivially expensive and never reused; option (c) is the only one that preserves both the physical billing truth and the logical budget truth, and it requires an attribute the convention doesn't give you. ## Operational Effect Without a retry marker, three failure modes compound: - **Budget abort on healthy runs.** The governor trips on retry-inflated sums, killing plans that would have completed within logical budget. Observed at ~1 in 40 multi-step runs under a 3-retry policy. - **Cost reconciliation drift.** Finance-side aggregation by response id collapses retries that share a cached id, under-reporting spend. Drift is invisible until a quarterly true-up. - **Context-window mis-scheduling.** A scheduler that estimates "tokens remaining in window" from span sums over-estimates consumption after retries and prematurely triggers summarization/eviction, which then *causes* the amnesia it was trying to prevent. The guardrail is an explicit retry attribute on every model span plus an aggregation function that computes two numbers—`physical_tokens` (raw sum, for billing) and `logical_tokens` (sum over one attempt per logical action, for budget)—and never conflates them. The code below enforces that the two are always computed together and raises if a step's spans are unmarked and ambiguous. ```python from dataclasses import dataclass, field from typing import Optional class AmbiguousUsageAccountingError(RuntimeError): """Raised when an agent step's spans cannot be split into physical vs logical token cost.""" @dataclass class ModelSpan: span_id: str logical_action_id: str # identifies the logical tool/reasoning action attempt: Optional[int] # agent.retry.attempt; None if unmarked status: str # "OK" | "ERROR" input_tokens: int output_tokens: int @dataclass class StepUsage: physical_input: int = 0 physical_output: int = 0 logical_input: int = 0 logical_output: int = 0 def account_step(spans: list[ModelSpan], logical_ceiling: int) -> StepUsage: by_action: dict[str, list[ModelSpan]] = {} for s in spans: by_action.setdefault(s.logical_action_id, []).append(s) usage = StepUsage() for action_id, group in by_action.items(): # Physical cost: every attempt was billed, count all of them. usage.physical_input += sum(s.input_tokens for s in group) usage.physical_output += sum(s.output_tokens for s in group) # Logical cost: exactly one attempt per action must be selected. if len(group) == 1: chosen = group[0] else: if any(s.attempt is None for s in group): raise AmbiguousUsageAccountingError( f"action {action_id!r} has {len(group)} spans but at least one " f"lacks agent.retry.attempt; cannot distinguish retry from " f"distinct step. Emit the attribute or split the action id." ) terminal = [s for s in group if s.status == "OK"] if len(terminal) != 1: raise AmbiguousUsageAccountingError( f"action {action_id!r} has {len(terminal)} OK attempts; " f"expected exactly one terminal attempt to bill logically." ) chosen = terminal[0] usage.logical_input += chosen.input_tokens usage.logical_output += chosen.output_tokens if usage.logical_input > logical_ceiling: raise AmbiguousUsageAccountingError( f"logical input {usage.logical_input} exceeds ceiling {logical_ceiling} " f"(physical was {usage.physical_input}); abort is legitimate." ) return usage ```