# What happens when an instance emits GenAI token-accounting spans across a retried tool call: double-counting, span-parent loss, and the `gen_ai.usage.*` reconciliation invariant **Date of Record:** 2026 November 19 **Scope:** Applies to LLM agent runtimes that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*`) and that retry, fan out, or replay tool calls under a parent `invoke_agent` / `execute_tool` span. Does not cover pure tracing of non-GenAI RPCs or non-retried single-shot completions. ## Core Distinction The GenAI semantic conventions treat token usage as a *span attribute* (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) attached to the span that represents the model invocation. They do **not** define a reconciliation contract between a retried logical operation and the multiple physical spans it produces. The convention is correct for a single span; it is silent-and-wrong at the boundary where an agent's *logical* unit of work (one tool call, one reasoning step) is realized by *N* physical spans because of retry, hedging, or speculative fan-out. The non-obvious failure: token accounting is additive across spans but the logical operation is idempotent. A retried tool call that re-invokes the model burns real tokens on every attempt, yet downstream cost/quota systems that sum `gen_ai.usage.*` across spans will attribute *all* attempts to the operation. Worse, when the retry is implemented by re-entering the agent loop, the retried child span frequently loses its parent linkage (new trace context or a detached span), so the double-counted tokens are also *orphaned* from the `invoke_agent` span that should bound them. The result is a trace that is simultaneously over-counted in aggregate and under-attributed per-operation. ## What Was Observed A planner agent emits `invoke_agent` (span A) → `execute_tool` (span B) → `chat` (span C, the model call that decides the tool arguments). The tool call returns a transient transport error. The runtime's retry policy re-enters the loop, creating span B′ and C′ under a *fresh* `trace_id` because the retry helper constructs a new `Tracer` context rather than continuing the current one. Observed attributes: - Span C: `gen_ai.usage.input_tokens=1820`, `gen_ai.usage.output_tokens=210`, `gen_ai.operation.name=chat`, parent = B. - Span C′: `gen_ai.usage.input_tokens=1820`, `gen_ai.usage.output_tokens=214`, `gen_ai.operation.name=chat`, parent = B′, **different `trace_id`**. - Span A: `gen_ai.usage.input_tokens=1820` (its own planning call), no child linkage to C′. Three distinct defects compound: 1. **Additive over-count.** C and C′ both carry full usage. A cost dashboard summing `gen_ai.usage.*` over `gen_ai.operation.name=chat` reports 3640 input tokens for what was logically one decision. 2. **Parent loss on retry.** C′ sits in a new trace, so the `invoke_agent` span A cannot bound it. Per-trace cost for A under-reports; the global sum over-reports. The discrepancy is invisible unless you join on a logical operation id that the convention does not define. 3. **Output-token divergence.** C′ produced 214 vs 210 output tokens — the retry is not byte-identical (sampling, temperature, or tool-result re-serialization). Any verifier that assumes retried spans are equivalent is wrong; the retry changed the reasoning trace. The failure is not "tracing is broken." It is that the convention's span-attribute model has no notion of *attempt* vs *operation*, and agent runtimes that retry at the loop level silently violate the implicit invariant that one logical operation maps to one accounting unit. ## Condition of Validity The over-count is only *detectable* (and only *bounded*) under these conditions: - Every retry attempt MUST carry a shared, non-standard attribute — e.g. `gen_ai.operation.id` or an `agent.attempt` counter — because the convention itself provides no attempt discriminator. Without it, reconciliation is impossible: you cannot distinguish two genuine independent chat calls from two attempts of one call. - The `invoke_agent` span MUST propagate its `trace_id` and span context into the retry helper. If the retry constructs a new root, the invariant "all token-bearing spans of an operation are descendants of exactly one `invoke_agent` span" is violated and cannot be repaired post-hoc. - Token usage MUST be emitted as cumulative-per-attempt, never as a running total mutated across attempts. A retry that *overwrites* `gen_ai.usage.*` on a reused span under-counts; a retry that *adds* a new span over-counts. Neither is correct without an attempt dimension. Where the retry is implemented by the model provider transparently (server-side retry inside a single HTTP call), none of this applies — there is one span and one usage record, and the convention is sound. ## Decision Boundary The architectural choice is: **account at the span (physical attempt) or at the operation (logical unit)?** The convention forces span-level. Agent runtimes that need operation-level cost must add a reconciliation layer. The boundary condition that decides correctness: - If your cost/quota consumer sums raw `gen_ai.usage.*` across all spans, you MUST deduplicate by a logical operation key before summing, or you will over-charge by the retry factor. Retry factor for tool-calling planners is empirically 1.1–1.4 under flaky transports; at 1.4 the error exceeds most SLO budgets. - If your consumer reads only `invoke_agent` spans, you MUST ensure retried children remain descendants, or you under-charge and, worse, your latency percentiles computed from child span durations will silently exclude the slow retried attempt. - A retry whose output tokens differ from the original (214 vs 210) means the *semantic* result is non-deterministic; any downstream verifier or auditor replaying the trace MUST treat attempt N and attempt N+1 as distinct reasoning events, not duplicates to be collapsed. The guardrail: emit an explicit `agent.attempt.index` and a stable `gen_ai.operation.id` on every token-bearing span, keep all attempts under one `trace_id`, and make the reconciliation layer the *only* place that sums usage — never the raw span exporter. ## Operational Effect Without the guardrail, three operational symptoms appear together and are easy to misdiagnose as separate bugs: (a) monthly token spend runs 10–40% above the sum of per-trace costs, (b) per-trace latency p99 looks healthy while wall-clock agent tasks time out, because the retried attempt lives in an orphaned trace, and (c) trace-replay auditors flag "duplicate" chat spans as a data-quality defect when they are in fact distinct attempts with distinct outputs. The invariant to enforce is: *every token-bearing GenAI span is a descendant of exactly one `invoke_agent` span and carries a stable operation id plus a monotonic attempt index; aggregate cost is computed only by deduplicating on operation id and summing attempts.* Violating it produces a trace that is internally consistent per span and globally wrong — the hardest class of observability failure to catch, because every individual span validates against the schema. ```python from dataclasses import dataclass, field from typing import Dict, List class TokenAccountingInvariantError(RuntimeError): """Raised when GenAI token-accounting spans violate the operation/attempt invariant.""" pass @dataclass class GenAISpan: span_id: str trace_id: str operation_name: str # e.g. "chat", "execute_tool" operation_id: str | None # stable logical-op key; MUST be set on token spans attempt_index: int | None # monotonic per operation; MUST be set on token spans parent_span_id: str | None input_tokens: int = 0 output_tokens: int = 0 def reconcile(spans: List[GenAISpan], invoke_agent_trace_id: str) -> Dict[str, int]: """Sum usage per logical operation, enforcing the invariant. Invariant: every token-bearing span has operation_id + attempt_index, shares the invoke_agent trace, and is a descendant of it. """ per_op: Dict[str, Dict[int, GenAISpan]] = {} for s in spans: if s.input_tokens == 0 and s.output_tokens == 0: continue if s.operation_id is None or s.attempt_index is None: raise TokenAccountingInvariantError( f"span {s.span_id} carries usage but lacks operation_id/attempt_index; " "cannot deduplicate retries" ) if s.trace_id != invoke_agent_trace_id: raise TokenAccountingInvariantError( f"span {s.span_id} (op={s.operation_id}) is orphaned from invoke_agent " f"trace {invoke_agent_trace_id}; retry escaped parent context" ) attempts = per_op.setdefault(s.operation_id, {}) if s.attempt_index in attempts: prev = attempts[s.attempt_index] if (prev.input_tokens, prev.output_tokens) != (s.input_tokens, s.output_tokens): raise TokenAccountingInvariantError( f"attempt {s.attempt_index} of op {s.operation_id} emitted divergent " "usage for the same attempt index; attempt counter not monotonic" ) attempts[s.attempt_index] = s totals: Dict[str, int] = {} for op_id, attempts in per_op.items(): # Sum across attempts (each attempt burned real tokens), dedup by index. totals[op_id] = sum(a.input_tokens + a.output_tokens for a in attempts.values()) return totals def emit_retry_span(original: GenAISpan, new_span_id: str, new_trace_id: str, new_attempt: int, input_tokens: int, output_tokens: int) -> GenAISpan: """Construct a retried attempt span, preserving operation identity.""" if new_trace_id != original.trace_id: # Do not silently detach; force caller to keep the invoke_agent trace. raise TokenAccountingInvariantError( f"retry of op {original.operation_id} moved to trace {new_trace_id}; " "must stay under invoke_agent trace to preserve cost attribution" ) if new_attempt <= (original.attempt_index or 0): raise TokenAccountingInvariantError( f"retry attempt_index {new_attempt} not monotonic after {original.attempt_index}" ) return GenAISpan( span_id=new_span_id, trace_id=new_trace_id, operation_name=original.operation_name, operation_id=original.operation_id, attempt_index=new_attempt, parent_span_id=original.parent_span_id, input_tokens=input_tokens, output_tokens=output_tokens, ) ```