# Where must an instance reconcile GenAI token-accounting spans when tool-call retries fork the trace: the double-counting invariant at the span-emission boundary **Date of Record:** 2026 November 27 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`) where a single logical tool call may be retried, forked, or replayed across attempts, and where `gen_ai.usage.input_tokens` / `output_tokens` are aggregated per session. Does not apply to single-shot, non-retried inference calls, nor to billing reconciliation performed downstream of the collector. ## Core Distinction The GenAI semantic conventions model a span as an *observation of one inference or tool invocation*. They do not model the relationship between a **logical tool call** (the intent: "read this file," "call this endpoint") and the **physical attempts** that satisfy it (attempt 1 timed out, attempt 2 succeeded). Token accounting lives on the span, so when an agent retry-loop emits a fresh `execute_tool` span per attempt—each carrying its own `gen_ai.usage.*` attributes because each attempt re-prompted the model to decide whether to retry—the sum of span-level usage attributes overcounts the logical session's token cost by exactly the tokens burned on abandoned attempts. The distinction that matters: **span count is not call count, and attribute summation is not cost.** A trace that looks internally consistent (every span has well-formed `gen_ai.usage` attributes, parent-child links are valid, timestamps are monotonic) can still be arithmetically wrong at the aggregation layer. The failure is invisible to span-level validation and only manifests when a consumer sums attributes across a trace or session. ## What Was Observed An agent executing a multi-step task with a retrying tool layer produced a trace where the top-level `invoke_agent` span reported `gen_ai.usage.input_tokens = 18,442` and `output_tokens = 3,110`. Summing `gen_ai.usage.*` across all descendant spans yielded `input_tokens = 31,905` and `output_tokens = 5,884`—roughly 1.7× the parent. The trace structure: ``` invoke_agent (session root) usage: in=18442 out=3110 ├── chat (turn 1) usage: in=4210 out=610 ├── execute_tool "fetch_config" usage: in=3980 out=540 attempt=1 status=error(timeout) ├── execute_tool "fetch_config" usage: in=4015 out=555 attempt=2 status=error(503) ├── execute_tool "fetch_config" usage: in=4020 out=560 attempt=3 status=ok ├── chat (turn 2) usage: in=2187 out=845 └── ... ``` Each `execute_tool` span was emitted by the retry wrapper, and each attempt re-entered the model to (a) decide whether the error was retryable and (b) re-emit the tool-call arguments. That re-entry is a genuine inference with genuine token cost—so the per-span attributes were *individually accurate*. The parent `invoke_agent` span, however, was populated by the orchestrator from its own accumulator, which counted only the tokens of the *successful* attempt plus the chat turns, silently excluding the two abandoned attempts. The parent was not the sum of its children; it was a different, smaller number. Two downstream consumers disagreed: a cost dashboard that summed leaf spans reported ~1.7× the cost of a billing pipeline that read the root span. Neither was "wrong" about what it measured. The invariant that had been assumed—*root usage equals the sum of descendant usage*—was never enforced by the conventions, only by convention. ## Condition of Validity The aggregation invariant `root.gen_ai.usage == Σ descendant.gen_ai.usage` holds **only if** every inference that consumes tokens is represented by exactly one span, and no span's usage is double-represented (e.g., copied onto both a wrapper span and its child). It fails under three concrete conditions: 1. **Retry forks.** A retry wrapper that re-prompts the model per attempt emits N spans for one logical call, but the orchestrator accumulator counts attempts selectively (typically only the terminal attempt). The root under-counts; the leaf sum over-counts relative to the root but is *correct* relative to actual spend. 2. **Span reuse on resume.** When an agent checkpoints mid-task and resumes, a naive resume path re-emits the in-flight span with the same `span_id` and the accumulated usage re-attached, while the pre-checkpoint emission already landed in the collector. The collector now holds two spans with identical `span_id` and overlapping usage—deduplication by `span_id` drops one (correct), but deduplication by `(trace_id, name, start_time)` keeps both (double-count). 3. **Pass-through attribute copying.** A wrapper span that copies `gen_ai.usage.*` from its child for "convenience" creates a diamond where the same tokens are attributed to two spans at different depths. Any consumer that sums *all* spans rather than *leaf* spans now double-counts. The invariant is therefore conditional on a discipline the conventions do not encode: **usage attributes belong to exactly one span—the span representing the inference that incurred them—and aggregation must sum leaves, not all spans, unless the emitter has proven the no-copy property.** ## Decision Boundary The boundary is this: **when a retry or resume path can emit a span for an attempt that did not terminate the logical call, the emitter must choose between (a) marking abandoned attempts as non-usage-bearing (`gen_ai.usage.*` omitted, with a separate `retry.abandoned_tokens` custom attribute), or (b) accepting that root and leaf aggregations will diverge and enforcing a single canonical aggregation path.** Option (a) preserves the root-equals-sum invariant but loses per-attempt cost visibility at the standard attribute layer. Option (b) preserves full fidelity but requires every consumer to agree on "sum leaves, dedupe by logical call id." The decision must be made at the emitter, not the collector, because the collector cannot distinguish an abandoned attempt from a completed one without a discriminator attribute. The discriminator that resolves the boundary is a **logical call identifier** distinct from `span_id`: e.g., `gen_ai.tool.call.id` stable across attempts, with `retry.attempt` incrementing. A consumer can then group by `call.id`, take `max(attempt)` as the terminal attempt, and sum terminal attempts only—recovering the correct cost while retaining per-attempt detail. Without this identifier, the trace is under-determined and no aggregation is defensible. ## Operational Effect Absent the discriminator, three concrete operational failures follow. First, **cost attribution drift**: dashboards built on leaf summation and billing built on root spans diverge monotonically with retry rate, so a rising retry rate looks like a billing anomaly rather than a reliability regression. Second, **budget enforcement bypass**: an agent whose token budget is checked against the root accumulator will under-count its own spend during retry storms and exhaust the provider quota before the internal budget trips—the enforcement boundary sits on the wrong number. Third, **replay divergence**: an auditor replaying the trace to reconstruct the agent's reasoning sees N attempts but a root usage that accounts for one, and cannot tell whether the discrepancy is a bug or an intentional exclusion. The guardrail is an emission-time assertion: before a wrapper span finalizes, it must verify that its own `gen_ai.usage.*` equals the sum of its children's usage *or* explicitly declare itself a non-aggregating wrapper via a `gen_ai.usage.aggregation = "none"` attribute. The assertion is cheap and catches the retry-fork and pass-through-copy cases at the source, where the logical call structure is still known. ```python from dataclasses import dataclass, field from typing import Optional class UsageAggregationInvariantError(RuntimeError): """Raised when a wrapper span's usage does not reconcile with its children under the declared aggregation mode, or when a retried tool call emits usage-bearing spans without a stable logical call identifier.""" pass @dataclass class Span: span_id: str name: str parent_id: Optional[str] input_tokens: Optional[int] = None output_tokens: Optional[int] = None aggregation: str = "sum" # "sum" | "none" call_id: Optional[str] = None # stable across retries; None if not a tool call retry_attempt: Optional[int] = None def reconcile(root: Span, descendants: list[Span]) -> int: """Return authoritative session token cost, or raise if the trace is under-determined by the GenAI conventions.""" # 1. Retried tool calls MUST carry a stable logical call id, else the # terminal attempt cannot be distinguished from abandoned ones. tool_spans = [s for s in descendants if s.name == "execute_tool"] for s in tool_spans: if s.retry_attempt is not None and s.call_id is None: raise UsageAggregationInvariantError( f"tool span {s.span_id} has retry_attempt={s.retry_attempt} " f"but no call_id; terminal attempt is under-determined" ) # 2. Sum only terminal attempts per logical call, plus non-tool spans. terminal: dict[str, Span] = {} for s in tool_spans: if s.call_id is None: continue best = terminal.get(s.call_id) if best is None or (s.retry_attempt or 0) > (best.retry_attempt or 0): terminal[s.call_id] = s leaf_sum = 0 for s in descendants: if s.aggregation == "none": continue # pass-through wrapper: do not double-count if s.name == "execute_tool": if s.call_id is not None and terminal.get(s.call_id) is not s: continue # abandoned attempt: excluded from cost leaf_sum += (s.input_tokens or 0) + (s.output_tokens or 0) # 3. If the root declares itself aggregating, it MUST equal leaf_sum. root_total = (root.input_tokens or 0) + (root.output_tokens or 0) if root.aggregation == "sum" and root_total != leaf_sum: raise UsageAggregationInvariantError( f"root usage {root_total} != reconciled leaf usage {leaf_sum}; " f"retry forks or pass-through copies have broken the invariant" ) return leaf_sum ```