# Which invariants prevent OTel GenAI span trees from silently double-counting tokens when an agent retries a tool call inside a nested span **Date of Record:** 2026 November 22 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes) where tool invocations are emitted as child spans under an `invoke_agent` span and token usage is recorded per span. Does not cover pure prompt/response logging without span emission, nor billing reconciliation downstream of the collector. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes on the *operation* span (typically the `chat` or `text_completion` span), not on the agent span. The agent span (`gen_ai.operation.name = "invoke_agent"`) is a *parent* that aggregates child operations. The failure mode arises when an agent retries a tool call: the retry produces a *new* child span with its own token accounting, but the retry loop is often implemented as a re-entry into the same logical step. If the instrumentation re-emits the parent's aggregate attributes on each retry, or if the collector's span-metric processor sums `gen_ai.usage.*` across *all* spans under the agent tree (including the parent), tokens are counted twice: once on the retried child, once on the parent aggregate that already reflected the first attempt. The invariant: **token usage is a leaf-attributed, non-aggregated quantity on operation spans; parent agent spans must carry zero `gen_ai.usage.*` attributes, and any aggregation must occur at query time over leaf spans only.** Violating this invariant produces a monotonic over-count proportional to retry depth. ## What Was Observed A tool-calling agent (`invoke_agent` span, `gen_ai.agent.name = "researcher"`) invoked a search tool. The first attempt returned a 503 from the upstream tool; the agent's retry wrapper re-issued the call within the same logical step. Instrumentation details: - The `execute_tool` child span for attempt 1 carried `gen_ai.usage.input_tokens = 812`, `gen_ai.usage.output_tokens = 44`. - Attempt 2 (retry) emitted a *new* `execute_tool` span with `gen_ai.usage.input_tokens = 812`, `gen_ai.usage.output_tokens = 51` (the prompt was identical; only the tool response differed, but the model re-tokenized the tool result). - The retry wrapper, written by the framework, called `span.set_attribute("gen_ai.usage.input_tokens", total_input)` on the *parent* `invoke_agent` span after each attempt, where `total_input` was a running sum. After attempt 2, the parent carried `input_tokens = 1624`. The collector's `spanmetrics` processor, configured with a dimension on `gen_ai.usage.input_tokens`, summed the attribute across every span in the trace. The dashboard reported 2436 input tokens for a single logical step that actually consumed 812 input tokens (the prompt was sent twice, so the *true* billable input was 1624; the *reported* was 1624 from the parent plus 812 + 812 from the leaves = 3248, and after deduping the parent's double-count, still 2436 because the parent's final value included both attempts). The discrepancy compounded: three retries produced a parent attribute of 2436 and leaf sum of 2436, but the parent was also counted, yielding 4872. A second observation: when the retry wrapper used `Span.add_event` to record the retry instead of re-emitting a child span, the token attributes were attached to the event, which the spanmetrics processor ignores entirely — the retries vanished from accounting. Two instrumentation styles, two opposite failure modes: over-count (re-emit child spans + aggregate parent) or under-count (events instead of spans). ## Condition of Validity The double-count is only *observable* when all three of the following hold: 1. The retry is implemented as a re-invocation that produces a sibling `execute_tool` (or `chat`) span, not as an in-place update of a single span. 2. The parent `invoke_agent` span carries `gen_ai.usage.*` attributes (violating the convention) *or* the aggregation query sums across all spans without filtering by `gen_ai.operation.name`. 3. The collector or backend performs attribute-level aggregation (spanmetrics, or a PromQL `sum` over a span-derived metric) rather than trace-level leaf summation. If the parent carries no usage attributes and the query filters to `gen_ai.operation.name IN ("chat", "text_completion", "execute_tool")`, the retry is correctly counted as two billable calls — which is the *right* answer, because the model was invoked twice and the provider bills twice. The invariant is not "count once per logical step"; it is "count once per model invocation, and never attribute usage to a span that did not itself invoke a model." ## Decision Boundary The boundary is between **logical-step accounting** (what the agent's planner thinks it did) and **invocation accounting** (what the provider bills). These diverge precisely at retries, and the OTel GenAI conventions are silent on retry semantics — they define the attributes but not the topology of retry spans. Engineers must decide, per agent, one of: - **Invocation-faithful:** every model call gets its own leaf span with usage attributes; parent spans carry none; retries are visible as additional leaf spans. This matches billing and is the only mode safe for spanmetrics aggregation. - **Logical-step-faithful:** retries are collapsed into one span (the wrapper mutates the span's usage attributes on retry, or records the final attempt only), and the trace carries a `gen_ai.retry.count` attribute for observability. This under-reports billable tokens by the retry factor and must *never* be summed against a provider invoice. Mixing the two — collapsing on the parent while emitting leaves, or vice versa — is the failure. The decision boundary is a single boolean at instrumentation time: *does the retry wrapper emit a new span or mutate an existing one?* That boolean must be uniform across the agent's tool layer and must be asserted at span-emission time, not reconciled later. ## Operational Effect The over-count is silent: no error, no dropped span, just a dashboard that reads 1.5×–3× the true bill. It surfaces only when someone reconciles against the provider's invoice, typically weeks later, and by then the retry topology that caused it has been refactored. The under-count (event-based retries) is equally silent and biases the opposite way, under-provisioning rate limits. The guardrail is a span-emission-time assertion: any span with `gen_ai.operation.name = "invoke_agent"` must have zero `gen_ai.usage.*` attributes, and any retry must produce a distinct span with a `gen_ai.retry.attempt` attribute so leaf summation is auditable. This is checkable in-process before the span ends, which is the only point where the topology is still known. ```python from dataclasses import dataclass, field class GenAiSpanInvariantError(RuntimeError): """Raised when an agent span violates the GenAI token-accounting invariant.""" @dataclass class Span: name: str operation: str attributes: dict = field(default_factory=dict) children: list = field(default_factory=list) def set_usage(self, input_tokens: int, output_tokens: int) -> None: self.attributes["gen_ai.usage.input_tokens"] = input_tokens self.attributes["gen_ai.usage.output_tokens"] = output_tokens def assert_leaf_only_usage(span: Span) -> None: """Enforce: only operation spans carry gen_ai.usage.*; invoke_agent spans carry none.""" usage_keys = {"gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens"} has_usage = usage_keys & set(span.attributes) if span.operation == "invoke_agent" and has_usage: raise GenAiSpanInvariantError( f"agent span {span.name!r} carries {sorted(has_usage)}; " "usage must be leaf-attributed to chat/execute_tool spans only" ) for child in span.children: assert_leaf_only_usage(child) def sum_billable_tokens(root: Span) -> int: """Sum usage over leaf operation spans only, never over invoke_agent parents.""" assert_leaf_only_usage(root) # fail fast before any aggregation total = 0 stack = [root] while stack: s = stack.pop() if s.operation != "invoke_agent": total += s.attributes.get("gen_ai.usage.input_tokens", 0) total += s.attributes.get("gen_ai.usage.output_tokens", 0) stack.extend(s.children) return total def build_retry_trace(violating: bool) -> Span: agent = Span(name="researcher", operation="invoke_agent") attempt1 = Span(name="search", operation="execute_tool") attempt1.set_usage(812, 44) attempt1.attributes["gen_ai.retry.attempt"] = 1 attempt2 = Span(name="search", operation="execute_tool") attempt2.set_usage(812, 51) attempt2.attributes["gen_ai.retry.attempt"] = 2 agent.children.extend([attempt1, attempt2]) if violating: # framework retry wrapper leaks aggregate onto the parent agent.set_usage(1624, 95) return agent if __name__ == "__main__": good = build_retry_trace(violating=False) print("billable:", sum_billable_tokens(good)) # 1719, correct bad = build_retry_trace(violating=True) try: sum_billable_tokens(bad) except GenAiSpanInvariantError as e: print("rejected:", e) ```