# Where must an instance reconcile OpenTelemetry GenAI token accounting when a tool-call span is retried, and why does the naive span-per-attempt convention double-count? **Date of Record:** 2026 November 28 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans (`gen_ai.*` attributes) and performs in-span retries of `execute_tool` operations. Does not apply to runtimes that emit exactly one span per logical tool invocation and absorb retries into a single attempt record, nor to pure LLM completion spans without tool children. ## Core Distinction The GenAI semantic conventions treat a span as the unit of *observed work*, and token usage attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) as *cumulative cost attributable to that span*. These two roles are not the same thing, and the conventions do not force them to coincide. A tool-call span that is retried because the tool returned a non-deterministic or transient failure has two legitimate representations: 1. **One span, retries folded in** — the span records total tokens consumed across all attempts, one `gen_ai.tool.call` event per attempt, and a single terminal status. 2. **N spans, one per attempt** — each attempt is its own child span, each carrying its own token usage, with a parent `execute_tool` span carrying none. The boundary failure lives in the gap: runtimes that start a new span per attempt *and* also stamp the parent span with the aggregate token count double-count any downstream aggregator that sums `gen_ai.usage.*` across the span tree. Worse, the double-count is silent — both spans are structurally valid, both carry plausible token numbers, and the trace looks correct until a cost or rate-limit dashboard disagrees with the provider invoice. ## What Was Observed A ReAct-style agent executing a `search_corpus` tool against a flaky vector backend. The tool wrapper was configured with three retries and instrumented as follows (pseudocode of the actual emitter): - On entry, open span `execute_tool search_corpus` with `gen_ai.operation.name="execute_tool"`, `gen_ai.tool.name="search_corpus"`. - On each attempt, open a child span `execute_tool.attempt` with `gen_ai.tool.call.id=`. - On attempt failure, close the child span with `status=ERROR`, `error.type="ToolTimeout"`. - On attempt success, close the child span with `status=OK` and `gen_ai.usage.input_tokens=`. - On overall return, close the parent span and set `gen_ai.usage.input_tokens = sum(attempts)` — *because the parent represents the logical operation and should carry its cost*. The trace was internally consistent. The parent's token count equaled the sum of children. A trace viewer showed a clean three-child tree for a call that succeeded on the third attempt. The failure surfaced downstream. A cost aggregator walked every span with `gen_ai.operation.name` set and summed `gen_ai.usage.input_tokens`, deduplicating by `span_id`. It counted the parent once and each child once — 4× the true cost. A separate rate-limiter, keyed on `gen_ai.tool.name`, saw the parent as a single logical call and the children as three calls, and throttled the agent to one-third its configured budget. Neither system raised an error; both quietly produced wrong numbers. The invariant that was violated: **within a trace subtree, `gen_ai.usage.*` must be attributable to exactly one span per unit of billable work.** The convention does not state this explicitly, because it assumes (reasonably) that a span is a leaf of cost accounting. It is not — a span can be a *summary* of children, and summaries that repeat children's numbers are double-counts. ## Condition of Validity The double-count only occurs when all of the following hold: 1. The tool-call is retried *within* a single logical invocation (not promoted to a new top-level agent step). 2. Each attempt is instrumented as a child span carrying `gen_ai.usage.*`. 3. The parent span also carries `gen_ai.usage.*` equal to the aggregate. 4. Some consumer sums usage across the subtree without a "leaf-only" or "root-only" filter. Remove any one condition and the trace is safe. The trap is that condition 3 feels *correct* — the parent is the logical operation, so it "should" carry the cost. It should not. The parent should carry *identity and outcome*; the children should carry *cost*. When both carry cost, the trace is ambiguous and every consumer resolves the ambiguity differently. The complementary condition of validity: if the runtime instead emits **one span per attempt with no aggregating parent**, the attempts are siblings under the agent step, and a leaf-only sum is correct. This is the safer default. The parent-summary pattern is only safe when the emitter also sets an explicit `gen_ai.usage.aggregation="summary"` (non-standard, but necessary) and every consumer honors it — which is not a safe assumption across heterogeneous backends. ## Decision Boundary The decision boundary is: **does the trace need to answer "what did this logical operation cost?" at the span level, or only at the trace level?** - If only at the trace level, emit leaf spans only. Let the aggregator sum leaves. No parent usage attributes. This is the default and the safe choice. - If at the span level (e.g., per-operation cost dashboards), emit the aggregating parent with usage attributes *and* suppress usage on children, replacing per-attempt token counts with `gen_ai.tool.call.attempt_tokens` (a non-standard attribute) that aggregators are documented to ignore. The parent is then the single cost-bearing span. - Never emit usage on both. The moment both exist, the subtree has no canonical cost and any consumer's answer is a coin flip on its dedup heuristic. The boundary is crossed silently because OTel's semantic conventions are *descriptive*, not *enforced*. There is no schema check that rejects a trace where parent and child both carry `gen_ai.usage.input_tokens`. The emitter must enforce the invariant itself, because nothing downstream will. ## Operational Effect The observable effect is a **cost divergence between trace-derived accounting and provider-side billing**, typically a factor of `1 + retries_observed` on retried tools. Because retries cluster on flaky tools, the divergence is not uniform — it is concentrated on exactly the tools an SRE is most likely to be investigating, which makes the trace look *most wrong* precisely when it is being trusted most. The second-order effect is worse: rate-limiters keyed on `gen_ai.tool.name` see both parent and children as calls, so a tool with a 3-retry budget appears to consume 4× its configured quota. Agents under load get throttled earlier than configured, retries increase, and the divergence compounds. The trace is not just wrong — it is *self-reinforcingly* wrong. The guardrail is a single invariant enforced at emission: **within any trace subtree, at most one span per billable unit carries `gen_ai.usage.*`.** Either leaves or the aggregating root, never both. The check below enforces it at span-close time, before the span is exported, so a violating trace never reaches a backend that would silently mis-sum it. ```python from dataclasses import dataclass, field from typing import Optional class GenAiUsageAttributionError(RuntimeError): """Raised when a span subtree carries gen_ai.usage.* on both a parent and its children, making subtree cost ambiguous to any aggregator.""" pass @dataclass class Span: span_id: str parent_id: Optional[str] operation_name: str tool_name: Optional[str] = None usage_input_tokens: Optional[int] = None usage_output_tokens: Optional[int] = None children: list["Span"] = field(default_factory=list) def carries_usage(self) -> bool: return ( self.usage_input_tokens is not None or self.usage_output_tokens is not None ) def assert_usage_attribution(root: Span) -> None: """Enforce: within a subtree, usage lives on EITHER the root OR the leaves, never both. Called at span-close before export.""" root_has_usage = root.carries_usage() leaf_has_usage = any( child.carries_usage() and not child.children for child in root.children ) if root_has_usage and leaf_has_usage: raise GenAiUsageAttributionError( f"span {root.span_id} ({root.operation_name}) carries " f"gen_ai.usage.* AND has usage-bearing leaf children; " f"subtree cost is ambiguous. Emit usage on leaves only, " f"or on the aggregating root with leaf usage suppressed." ) for child in root.children: assert_usage_attribution(child) def close_tool_span(span: Span) -> Span: """Close a tool-call span, enforcing the attribution invariant.""" if span.operation_name == "execute_tool" and span.carries_usage(): # Aggregating parent: children must not also carry usage. for attempt in span.children: if attempt.carries_usage(): raise GenAiUsageAttributionError( f"aggregating parent {span.span_id} and attempt " f"{attempt.span_id} both carry usage; " f"double-count on subtree sum." ) assert_usage_attribution(span) return span ```