# Why does an instance double-count tokens when a tool call re-enters the agent span? **Date of Record:** 2026 November 23 **Scope:** Applies to agents that emit OpenTelemetry GenAI spans (`gen_ai.*`) where an LLM invocation, a tool execution, and a subsequent re-invocation of the same agent are nested under a shared parent agent span. Does not apply to flat, single-invocation tracing or to spans emitted by the provider SDK rather than the agent runtime. ## Core Distinction The GenAI semantic conventions define token attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) as properties of *a single model invocation*, not of an agent turn. The span hierarchy, however, expresses *causal nesting*: an agent span can contain many `chat` spans and many `execute_tool` spans. These two graphs — the accounting graph and the causal graph — are not the same graph. The failure mode is that an aggregator (dashboard, cost reconciler, or an auditor agent reading the trace) sums `gen_ai.usage.*` over *all* spans in an agent subtree. Because a tool-calling loop re-enters the model with the prior output plus tool results in context, the second `chat` span's `input_tokens` already includes the first span's `output_tokens`. Summing across the subtree therefore counts the same tokens repeatedly. The invariant that must hold — *sum of token attributes over leaf `chat` spans equals billed tokens for the turn* — is true, but the invariant *sum over the whole subtree* is false and silently overcounts by a factor that grows with loop depth. ## What Was Observed A three-hop agent loop (plan → tool call → synthesize) produced a trace where a naive subtree sum reported 41,200 input tokens for a turn that the provider billed at 18,900. The discrepancy is not noise. Walk the trace: - `chat` span A (planning): `input_tokens=4,000`, `output_tokens=600`. - `execute_tool` span: no token attributes (correct per spec). - `chat` span B (post-tool reasoning): `input_tokens=4,600` — this is A's 4,000 input plus A's 600 output plus 0 tool-result framing — `output_tokens=800`. - `chat` span C (synthesis): `input_tokens=5,400`, `output_tokens=500`. Subtree sum of `input_tokens` = 4,000 + 4,600 + 5,400 = 14,000, but the *billed* input for the turn is the sum of per-call inputs, which is what the provider charges: also 14,000. So far the sum is correct. The overcount appears when the aggregator instead reads the *agent span's* own attributes, which some instrumentations populate by rolling up child usage, and then also sums the children. The agent span carries `gen_ai.usage.input_tokens=14,000` (rolled up) while its children carry 14,000 in aggregate; a recursive walk that adds parent-plus-children yields 28,000. Add a retry span (span status `ERROR`, retried, both emitted) and the same call is counted twice at the leaf level, giving 32,600 against an 18,900 bill. The second, subtler observation: `execute_tool` spans that re-invoke the agent (a tool that itself calls an LLM, e.g. a sub-agent) are *not* nested as `chat` spans but as a fresh `agent` span. The semantic conventions do not forbid this, but the token attributes on that nested agent span are indistinguishable from a rolled-up parent, so a cost reconciler cannot tell "this is a rollup" from "this is a real nested inference" without inspecting `gen_ai.operation.name`. ## Condition of Validity The "sum leaves, ignore rollups" rule is valid only when: 1. Every `chat` span sets `gen_ai.operation.name=chat` and carries its own `gen_ai.usage.*`; and 2. No ancestor span duplicates those attributes as a rollup; and 3. Retried calls are distinguishable by `span.status` or a `retry.count` attribute so the reconciler can drop the failed attempt. When condition 2 is violated (the common case, because rollups are convenient for dashboards), the leaf-sum invariant still holds but only if the reconciler is *explicitly* leaf-only. When condition 3 is violated, leaf-sum itself double-counts retries. There is no attribute in the current conventions that marks a span as "rollup" versus "leaf inference," so the distinction is inferred from `gen_ai.operation.name` and from whether the span has children. ## Decision Boundary The boundary is: **do you reconcile on the causal tree or the accounting tree?** If any consumer of the trace performs a recursive sum of `gen_ai.usage.*` without filtering to `operation.name=chat` and without excluding spans that have `chat` descendants, the result is invalid the moment loop depth exceeds 1. The safe rule is to reconcile *only* over spans where `gen_ai.operation.name == "chat"` and the span has no `chat` descendants, and to treat any agent span's own usage attributes as advisory metadata, never as a billing input. An agent that reads its own traces to budget future turns must apply this filter or it will believe it has spent 2–3× its actual budget and throttle prematurely — a self-inflicted context-budget exhaustion driven by a metric artifact, not by real consumption. ## Operational Effect Downstream, the overcount causes three concrete failures: (a) budget-guard agents trip their token ceiling at roughly half the true spend and refuse to continue mid-task; (b) cost dashboards diverge from provider invoices, eroding trust in the trace as a source of truth; (c) an auditor agent replaying the trace to verify a peer's work recomputes a different token total than the peer reported and raises a false verification discrepancy. The guardrail is a reconciler that walks the span tree, selects only leaf `chat` spans, deduplicates retries by `trace_id`+`span_id` lineage, and asserts the leaf sum against the provider's reported total before any budget decision is made. If the two disagree beyond a small tolerance, the reconciler must fail closed rather than proceed on a possibly-corrupted accounting graph. ```python from dataclasses import dataclass from typing import Iterable class TokenAccountingInvariantError(RuntimeError): """Raised when a trace's leaf-chat token sum cannot be reconciled.""" @dataclass class Span: span_id: str parent_id: str | None operation: str # "chat", "execute_tool", "agent", ... input_tokens: int = 0 output_tokens: int = 0 status: str = "OK" retry_of: str | None = None def reconcile_turn(spans: Iterable[Span], provider_billed_input: int, tolerance: float = 0.02) -> int: spans = list(spans) by_id = {s.span_id: s for s in spans} chat_ids = {s.span_id for s in spans if s.operation == "chat"} # A chat span is a leaf-inference iff it has no chat descendant. has_chat_child: set[str] = set() for s in spans: p = s.parent_id while p is not None and p in by_id: if p in chat_ids: has_chat_child.add(p) p = by_id[p].parent_id # Drop retries: keep only the last attempt per retry chain. superseded = {s.retry_of for s in spans if s.retry_of} leaf_input = 0 for s in spans: if s.operation != "chat": continue if s.span_id in has_chat_child: continue # rollup or ancestor inference, not a leaf if s.span_id in superseded: continue # superseded by a retry leaf_input += s.input_tokens if provider_billed_input <= 0: raise TokenAccountingInvariantError( f"provider billed input is non-positive ({provider_billed_input}); " "cannot anchor reconciliation" ) drift = abs(leaf_input - provider_billed_input) / provider_billed_input if drift > tolerance: raise TokenAccountingInvariantError( f"leaf-chat input {leaf_input} diverges from billed " f"{provider_billed_input} by {drift:.1%}; trace accounting graph " "is likely double-counting rollups or retries" ) return leaf_input ```