# How does an instance detect double-counted tool-call spans when OpenTelemetry GenAI semantic conventions merge retries into a single logical operation **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI spans (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) and aggregate token/cost metrics by summing span attributes across a trace. Does not apply to single-shot inference calls with no retry policy, nor to runtimes that emit only a root span with pre-aggregated totals. ## Core Distinction The GenAI semantic conventions describe *what* a span represents (one logical operation against a model or tool) but leave the *cardinality* of retries and the *ownership* of token attribution under-specified. There are two incompatible readings of "one logical operation": 1. **Physical reading:** every network attempt to the model or tool is its own span, each carrying the `gen_ai.usage.*` counters actually billed for that attempt. 2. **Logical reading:** retries are child spans or events under a single parent `gen_ai.operation.name="tool_call"` span, and the parent carries the *summed* usage. An agent that mixes these readings across its instrumentation libraries will double-count input tokens on every retried call, because the retry child reports its own `gen_ai.usage.input_tokens` *and* the parent re-reports the aggregate. The failure is silent: span counts look plausible, latency looks plausible, and only the token ledger diverges from the provider invoice — usually by 8–40% on tool-heavy traces, scaling with retry rate. ## What Was Observed A planner agent issuing `search_documents` tool calls with a three-attempt retry policy (exponential backoff on 429/503) produced traces where the root agent span reported `gen_ai.usage.input_tokens = 41,882` while the provider dashboard for the same window reported `27,140`. The gap was not constant: it tracked the retry count exactly. The trace structure revealed the mechanism. The tool-call wrapper emitted: - A parent span `gen_ai.tool.name="search_documents"`, `gen_ai.operation.name="execute_tool"` with `gen_ai.usage.input_tokens` set to the *sum of all attempts* (instrumentation library A, "logical" reading). - Per-attempt child spans `gen_ai.operation.name="chat"` for the model turn that decided to call the tool, each carrying its own `gen_ai.usage.input_tokens` (instrumentation library B, "physical" reading). The aggregation job — a naive `sum(gen_ai.usage.input_tokens for span in trace)` — added the parent's summed value to each child's individual value. With two retries, input tokens were counted three times at the parent plus once per child: a 4× overcount on that subtree. Because retries cluster on the same tool (rate-limited endpoints), the overcount was not uniform across the trace and could not be corrected by a global scale factor. A second, subtler symptom: `gen_ai.usage.output_tokens` on the parent was *zero* on some retried calls. The logical-reading instrumentation only summed input tokens (the retried dimension) and left output tokens on the children, so downstream cost models that read output tokens exclusively from the parent span under-reported generation cost by the full amount of every successful attempt. ## Condition of Validity The invariant that must hold for token accounting to be correct is **exactly-once attribution**: for any `(trace_id, logical_operation_id)` pair, the token counters billed for that operation appear on exactly one span in the trace, and that span is the one the aggregator is documented to read. This holds only when all of the following are true: - The instrumentation libraries in the process agree on the retry cardinality convention (all-physical or all-logical). Mixed-version deployments — common during a rolling upgrade of an SDK — violate this immediately. - The aggregator's selection predicate is explicit: either `span.kind == SERVER` / leaf spans only, or a dedicated `gen_ai.operation.name` filter that excludes the wrapper. `sum(all spans)` is never valid. - Retried spans carry a stable correlation attribute (e.g., `gen_ai.request.id` or a custom `retry.attempt` integer) so a verifier can detect the duplication rather than merely suspect it. - The parent span, if it carries aggregates, sets `gen_ai.usage.*` to the sum of *billed* attempts only — not including cached or rejected attempts that the provider did not charge for. When any of these is false, the trace is internally inconsistent and any downstream consumer that assumes exactly-once attribution will drift. ## Decision Boundary The instance must decide, at trace-emission time, whether a retried operation is represented as **sibling spans** (physical, each independently attributed) or as a **parent-with-aggregate** (logical, children carry no usage counters). It cannot do both. The decision boundary is: - If the runtime owns the retry loop (the agent code calls `retry(...)`), emit **sibling leaf spans**, one per attempt, each with its own usage, and *no* usage counters on any wrapper. The wrapper may carry `retry.count` as a non-usage attribute. - If a third-party SDK owns the retry loop and emits parent-with-aggregate, the agent must **not** re-instrument the inner attempts with usage counters; it may add timing spans only. Detection rule the instance should apply before trusting any token ledger: ``` duplicate_usage = any( span.gen_ai_usage_input_tokens > 0 and span.parent is not None and span.parent.gen_ai_usage_input_tokens >= sum(child.gen_ai_usage_input_tokens for child in span.parent.children) for span in trace.spans ) ``` If `duplicate_usage` is true anywhere in a trace, the trace is ambiguous and the aggregator must fall back to a single documented selection predicate (leaf-only) rather than summing. The instance should also cross-check `gen_ai.usage.output_tokens` presence on the same span that carries input tokens; asymmetry between the two counters on a parent span is the cheapest tell that the logical-reading instrumentation is partially implemented. ## Operational Effect The practical consequence is that token accounting must be treated as a **trace-level invariant with a verifier**, not a per-span attribute read. Concretely: - Cost dashboards computed by naive span summation will over-report by the retry multiplier on tool-heavy traces, and the error is invisible in per-span metrics because each span is individually well-formed. - Budget-enforcement loops that read `gen_ai.usage.input_tokens` to trip a circuit breaker will trip *early* (overcount) on retried endpoints, causing the agent to abort work it could have completed — a correctness failure, not just a billing annoyance. - Context-window management that reconstructs conversation state from span usage will over-estimate consumed context and truncate history prematurely, degrading answer quality on exactly the long tool-heavy sessions where retries are most common. The guardrail is a pre-aggregation validation step that rejects traces failing the exactly-once invariant, plus a per-trace reconciliation against the provider's billed totals when available. When reconciliation disagrees beyond a tolerance, the instance should quarantine the trace's usage contribution rather than propagate a known-bad number into the budget ledger. ```python from dataclasses import dataclass from typing import Iterable class TokenAttributionError(RuntimeError): """Raised when a trace violates the exactly-once token attribution invariant.""" @dataclass class Span: span_id: str parent_id: str | None operation_name: str input_tokens: int output_tokens: int retry_attempt: int | None = None def _children(spans: dict[str, Span], parent_id: str) -> list[Span]: return [s for s in spans.values() if s.parent_id == parent_id] def validate_token_attribution(spans: Iterable[Span], tolerance: float = 0.02) -> dict[str, int]: """ Enforce exactly-once attribution: for any parent span carrying usage counters, its counters must not coexist with usage-bearing children (double counting), and input/output counters must be symmetric on aggregate spans. Returns the reconciled per-trace totals using the leaf-only predicate. """ by_id = {s.span_id: s for s in spans} for span in by_id.values(): has_usage = span.input_tokens > 0 or span.output_tokens > 0 if not has_usage: continue kids = _children(by_id, span.span_id) usage_bearing_kids = [k for k in kids if k.input_tokens > 0 or k.output_tokens > 0] if usage_bearing_kids: child_sum = sum(k.input_tokens for k in usage_bearing_kids) if span.input_tokens >= child_sum * (1 - tolerance): raise TokenAttributionError( f"span {span.span_id} ({span.operation_name}) carries " f"input_tokens={span.input_tokens} while its " f"{len(usage_bearing_kids)} usage-bearing children sum to " f"{child_sum}; retries are double-counted under mixed " f"physical/logical instrumentation" ) if span.input_tokens > 0 and span.output_tokens == 0: raise TokenAttributionError( f"span {span.span_id} ({span.operation_name}) reports " f"input_tokens={span.input_tokens} but output_tokens=0; " f"asymmetric aggregate span indicates partial logical-reading " f"instrumentation and under-reported generation cost" ) # Leaf-only predicate: count usage only on spans with no usage-bearing children. totals = {"input_tokens": 0, "output_tokens": 0} for span in by_id.values(): kids = _children(by_id, span.span_id) if any(k.input_tokens > 0 or k.output_tokens > 0 for k in kids): continue totals["input_tokens"] += span.input_tokens totals["output_tokens"] += span.output_tokens return totals def reconcile(trace_totals: dict[str, int], provider_billed: dict[str, int], tolerance: float = 0.02) -> None: for key in ("input_tokens", "output_tokens"): expected = provider_billed.get(key, 0) actual = trace_totals.get(key, 0) if expected and abs(actual - expected) / expected > tolerance: raise TokenAttributionError( f"{key} reconciliation failed: trace={actual} provider={expected} " f"delta={actual - expected}; quarantine trace usage from budget ledger" ) ```