# Which invariants prevent token-accounting drift from silently corrupting OTel GenAI agent spans when tool-call retries re-enter the reasoning loop **Date of Record:** 2026 November 27 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes) where tool calls are retried or re-entered inside a single logical reasoning turn, and where token usage is aggregated from child spans up into an agent root span. Does not cover streaming-only completion spans without tool invocation, nor provider-native billing reconciliation outside the trace. ## Core Distinction A GenAI span records two different things that look identical at the attribute level: *what the model was asked to do* and *what the runtime actually paid for*. The `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` attributes and the `gen_ai.operation.name` / `gen_ai.tool.name` attributes are emitted by two different subsystems — the model client and the tool dispatcher — and they agree only under a strict invariant: **each `gen_ai.tool.name` span must have exactly one corresponding `gen_ai.operation.name = "chat"` parent that accounted for the tokens that produced the tool-call arguments, and that chat span must not be re-emitted on retry.** The boundary failure is not "tokens are wrong." It is that a retried tool call produces a *second* chat span with a *second* token count for the *same* logical step, and the agent root span's aggregator (which is almost always a naive `sum()` over descendant `gen_ai.usage.*`) double-counts the input tokens while the trace *looks* structurally valid: one tool span, correct tool name, correct status, monotonically increasing timestamps. The corruption is invisible to schema validation because every individual span is well-formed. Only the invariant — one chat span per tool-call-producing reasoning step — catches it. ## What Was Observed A research agent using a ReAct loop with a `search` tool. The tool dispatcher had a 30-second timeout with one automatic retry. On a slow backend, the following trace was emitted for a single user turn: - `invoke_agent` (root), `gen_ai.operation.name = "invoke_agent"` - `chat` span #1, `gen_ai.usage.input_tokens = 4820`, `output_tokens = 210`, `finish_reasons = ["tool_calls"]` - `execute_tool` span, `gen_ai.tool.name = "search"`, **status = ERROR (timeout)** - `chat` span #2, `gen_ai.usage.input_tokens = 4820`, `output_tokens = 210`, `finish_reasons = ["tool_calls"]` — *the retry re-sent the same prompt* - `execute_tool` span, `gen_ai.tool.name = "search"`, status = OK - `chat` span #3, `gen_ai.usage.input_tokens = 5310`, `output_tokens = 340`, `finish_reasons = ["stop"]` The root span's aggregator summed all descendant chat spans: `input_tokens = 14,950`, `output_tokens = 760`. The actual billed input was `4820 + 5310 = 10,130` (the retry was a genuine re-billing, but the *logical* step consumed 4,820 once from the agent's planning perspective). Two distinct errors compounded: 1. **Retry double-count at the model layer.** The retried chat span #2 is a real billing event but a *phantom* reasoning step. Any downstream metric that treats `chat` span count as "number of reasoning steps" now overcounts by one, and any cost-per-step metric divides by the wrong denominator. 2. **Aggregation double-count at the root.** The root `sum()` conflates "tokens billed across the turn" with "tokens attributable to the logical step," and there is no attribute distinguishing chat span #2 as a retry. `gen_ai.operation.name` is identical; there is no `retry.count` or `gen_ai.request.retry_attempt` attribute in the current conventions to mark it. The failure surfaced three days later when a cost-regression alert fired on a workload whose *actual* spend was flat. The trace was the only artifact, and it lied. ## Condition of Validity The invariant holds — and the failure is bounded — only when all of the following are true: - **Chat spans are emitted at the model-client boundary, not the loop boundary.** If the ReAct loop emits one chat span per *iteration* and attributes retries as span events (`gen_ai.retry` event with `attempt` attribute) rather than child spans, the root aggregator sees one chat span per logical step and the double-count cannot occur. - **The tool span is a child of the chat span that produced its arguments**, not a sibling under the root. This makes the retry's provenance unambiguous: a retried tool span's parent chat span is the *retry* chat span, and the aggregation tree mirrors the actual call graph. - **The aggregator distinguishes `sum` from `dedupe`.** A root span that sums `gen_ai.usage.input_tokens` over all descendants is only correct when every descendant chat span represents a distinct input payload. When retries re-send identical prompts, the aggregator must either (a) sum only leaf-most chat spans per `(tool.name, arguments.hash)` tuple, or (b) report both `gen_ai.usage.input_tokens` (billed) and a separate `agent.logical_input_tokens` (deduped) and never conflate them. When any of these is false, the trace is *schema-valid and semantically wrong*, which is the worst class of observability defect: it passes every validator and fails every audit. ## Decision Boundary The decision boundary is whether a retried tool call is modeled as **a new reasoning step** or **a re-execution of an existing one**. The GenAI conventions do not currently force this choice, and the two choices produce incompatible token accounting: - **Model as new step:** emit a fresh chat span per retry, let the aggregator sum, and accept that `input_tokens` reflects billed tokens (including retry re-billing). This is correct for *cost* but wrong for *step-count* and *per-step efficiency* metrics. You must then never derive "reasoning steps" from chat span count. - **Model as re-execution:** emit one chat span, attach retries as span events, and the aggregator sums once. This is correct for *logical step accounting* but understates *billed cost* by the retry amount. The boundary is crossed silently because neither choice is marked in the trace. The guardrail: **every `chat` span that is a retry MUST carry `gen_ai.request.retry_attempt > 0` (or an equivalent `gen_ai.retry.of_span_id` back-reference), and every root aggregator MUST branch on its presence.** Absent that attribute, the aggregator cannot know which model it is in and will produce a number that is wrong under both interpretations. ## Operational Effect Concretely, without the invariant: - **Cost dashboards drift upward** on any workload with retry-prone tools (search, code execution, external APIs), by exactly the retry rate times the mean input-token count. A 5% timeout rate on a 5k-token prompt inflates reported input tokens by ~250 tokens per affected turn — enough to trip budget alerts and misroute capacity planning. - **Per-step efficiency metrics become non-comparable across agents**, because agents with different retry policies produce different chat-span-to-step ratios. An A/B test between two agent versions with different retry configurations will attribute a "reasoning efficiency regression" that is purely a retry-policy artifact. - **Trace-based replay and evaluation break.** An evaluator that replays the chat spans to reconstruct the reasoning trajectory will see a duplicated step and may conclude the agent "repeated itself" — a hallucination signal — when it was a transport retry. This is the most dangerous effect: the observability layer manufactures a false reasoning-failure signal. The invariant that bounds all of this: **token usage attributed to a logical reasoning step must be deduplicated across retries, and the deduplication key must be recorded in the trace, not inferred by the aggregator.** The trace must be self-describing about which spans are retries, because the aggregator's correctness depends on information only the emitter has. ```python from dataclasses import dataclass, field from typing import Optional class GenAiTokenAccountingError(RuntimeError): """Raised when a GenAI agent trace violates the retry-dedup invariant.""" @dataclass class ChatSpan: span_id: str parent_span_id: Optional[str] operation: str # gen_ai.operation.name input_tokens: int # gen_ai.usage.input_tokens output_tokens: int # gen_ai.usage.output_tokens retry_attempt: Optional[int] = None # gen_ai.request.retry_attempt (None == not a retry) retry_of_span_id: Optional[str] = None @dataclass class ToolSpan: span_id: str parent_span_id: Optional[str] tool_name: str # gen_ai.tool.name status: str @dataclass class AgentTrace: root_span_id: str chat_spans: list = field(default_factory=list) tool_spans: list = field(default_factory=list) def aggregate_logical_tokens(trace: AgentTrace) -> dict: """ Sum token usage over chat spans, deduplicating retries against their original span. Requires every retry span to declare retry_of_span_id. """ by_id = {s.span_id: s for s in trace.chat_spans} seen_originals: set = set() logical_input = 0 logical_output = 0 billed_input = 0 billed_output = 0 for span in trace.chat_spans: if span.operation != "chat": continue billed_input += span.input_tokens billed_output += span.output_tokens if span.retry_attempt is not None and span.retry_attempt > 0: # Retry: must back-reference the original to be dedupable. if span.retry_of_span_id is None or span.retry_of_span_id not in by_id: raise GenAiTokenAccountingError( f"chat span {span.span_id} is a retry (attempt=" f"{span.retry_attempt}) but has no valid " f"gen_ai.retry.of_span_id back-reference; token " f"deduplication is impossible and logical input_tokens " f"would be double-counted." ) # Dedup: the original span already contributed to logical totals. continue # Non-retry span: this is the logical step's authoritative accounting. if span.span_id in seen_originals: raise GenAiTokenAccountingError( f"chat span {span.span_id} counted twice as a logical step." ) seen_originals.add(span.span_id) logical_input += span.input_tokens logical_output += span.output_tokens # Invariant: a retried tool span must be a child of its retry chat span. chat_ids = {s.span_id for s in trace.chat_spans} for tool in trace.tool_spans: if tool.parent_span_id not in chat_ids: raise GenAiTokenAccountingError( f"tool span {tool.span_id} ({tool.tool_name}) is not a child " f"of any chat span; retry provenance cannot be resolved and " f"the aggregation tree does not mirror the call graph." ) if logical_input > billed_input: raise GenAiTokenAccountingError( f"logical input_tokens ({logical_input}) exceeds billed " f"({billed_input}); dedup logic is inverted or spans are missing." ) return { "gen_ai.usage.input_tokens": billed_input, "gen_ai.usage.output_tokens": billed_output, "agent.logical_input_tokens": logical_input, "agent.logical_output_tokens": logical_output, } ```