# What happens when an instance emits GenAI tool-call spans whose token accounting collapses parent and child spans into a single non-idempotent counter **Date of Record:** 2026 November 23 **Scope:** Applies to any agent runtime that instruments tool-calling loops with OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes) and aggregates `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` across a span tree. Does not apply to single-span, single-call instrumentation or to runtimes that emit no parent/child span hierarchy. ## Core Distinction There are two ways to read a `gen_ai.usage.input_tokens` attribute. The first treats it as a *per-span delta*: the tokens consumed by the model invocation that the span directly wraps. The second treats it as a *cumulative subtree total*: the full prompt+completion cost attributable to the span and everything beneath it. The GenAI semantic conventions specify the attribute on the span that wraps the model call, which is the delta interpretation — but agent spans (the `invoke_agent` / tool-call parent spans) frequently re-emit the same attribute to make the trace "self-describing." When a collector or backend sums `gen_ai.usage.*` across all spans in a trace, delta and cumulative readings are indistinguishable, and the aggregate double- or triple-counts every tool call. The failure is not a missing attribute or a malformed span; it is a *semantic collision* between two valid readings of the same key on different span kinds, and it silently inflates cost accounting by a factor that grows with tool-call fan-out. ## What Was Observed An agent executing a 6-step tool loop (one `invoke_agent` root, six `execute_tool` children, six nested `chat` spans for the model invocations that decided each tool call) emitted the following on each `chat` span: `gen_ai.usage.input_tokens=1840`, `gen_ai.usage.output_tokens=210`. The runtime's instrumentation layer, intending to surface per-tool cost, also stamped the *sum of the child's decision call* onto each `execute_tool` span, and the *running total* onto the `invoke_agent` root. The backend's cost rollup, which grouped by `trace_id` and summed `gen_ai.usage.input_tokens` across all spans, produced `1840 × 6 (chat) + 1840 × 6 (execute_tool, duplicated) + 11040 (root running total) = 33,120` input tokens for a session whose true cost was `11,040`. The inflation factor was exactly 3.0 — a clean multiple, which is the tell: it means every token was counted once at the leaf, once at the tool parent, and once at the agent root. The more insidious observation: when the agent loop *retried* a failed tool call (step 3 timed out and re-executed), the retry produced a new `execute_tool` span with the same `gen_ai.tool.name` and the same `gen_ai.usage` delta, but the `invoke_agent` root's running total was recomputed from scratch rather than incremented. The root therefore under-reported by exactly one retry's worth of tokens while the leaf spans over-reported by the same amount when summed. The two errors did not cancel; they landed in different aggregation buckets (root vs. sum-of-leaves), so a dashboard reading the root saw a 9% undercount and a dashboard reading the leaf sum saw a 9% overcount, and both were "correct" per their query. ## Condition of Validity The invariant that must hold for token accounting to be sound is: **for any trace, exactly one span per model invocation carries the `gen_ai.usage.*` delta, and no ancestor span carries a value that is derivable by summing its descendants.** This is the "single-writer per invocation" rule. It is valid only when: 1. The instrumentation layer knows, at span-start time, whether a span *wraps* a model call (delta writer) or only *contains* spans that do (aggregator, which must carry no `gen_ai.usage.*` at all). 2. Retries create *sibling* `execute_tool` spans under a stable logical step identifier (e.g., `gen_ai.tool.call.id`), so the backend can dedupe by call id rather than by span id. 3. No span re-emits a descendant's usage under a different attribute name (e.g., `gen_ai.usage.total_tokens` on the root) that a naive rollup would also sum. The convention is *invalid* — and the accounting collapses — as soon as an agent framework auto-instruments the root span with a "convenience" total, because the root total and the leaf sum are both present in the same trace and no attribute distinguishes "this is a rollup, do not sum me" from "this is a delta, sum me." The semantic conventions do not currently define a `gen_ai.usage.aggregation` discriminator, so the backend cannot tell the two apart by schema alone. ## Decision Boundary The boundary is crossed at the moment an agent span emits `gen_ai.usage.*` on a span that has `gen_ai.operation.name` of `invoke_agent` or `execute_tool` rather than `chat`. Below that boundary — usage only on `chat` spans — a sum-over-trace is correct and idempotent. Above it, the sum is no longer a function of the trace alone; it depends on which spans the backend chose to include, and the same trace yields different totals under different `GROUP BY` clauses. The correct decision at the boundary is not "stop emitting root totals" (operators legitimately want per-agent cost without a subtree walk) but "emit root totals under a *distinct* namespace that rollups exclude by default," e.g. `gen_ai.agent.cumulative_input_tokens`, and reserve `gen_ai.usage.*` strictly for delta writers. The guardrail is a collector-side processor that rejects any span where `gen_ai.usage.input_tokens` is present and the span has ≥1 child span carrying the same attribute — that span is a rollup masquerading as a delta, and admitting it into the aggregate is the failure. ## Operational Effect Downstream, the effect is a cost dashboard that is internally consistent (the number is stable across queries) but externally wrong by a fan-out-dependent factor, which means it is *undetectable by anomaly detection*: the inflation is proportional to tool-call depth, so a healthy agent with more tool calls looks more expensive in a way that mimics genuine load. Budget alerts fire on the inflated number, throttling kicks in on agents that are actually within budget, and the retry-undercount on the root masks the throttle-induced retries that follow. The trace remains a faithful record of what happened; only the aggregate lies. Recovery requires re-deriving cost from leaf `chat` spans alone and treating every `invoke_agent`/`execute_tool` usage attribute as advisory metadata, never as an aggregation input. ```python class GenAIUsageDoubleCountError(RuntimeError): """Raised when a span carries gen_ai.usage.* while a descendant carries the same key, making delta vs. cumulative readings indistinguishable to a sum-over-trace rollup.""" pass DELTA_OPERATIONS = {"chat"} def validate_usage_span(span: dict, descendant_usage_keys: set[str]) -> None: op = span.get("attributes", {}).get("gen_ai.operation.name") has_usage = any( k.startswith("gen_ai.usage.") for k in span.get("attributes", {}) ) if not has_usage: return if op in DELTA_OPERATIONS: return # Non-delta span (invoke_agent / execute_tool) carrying usage while a child # also carries usage => this span is a rollup, not a delta. Reject it from # the aggregation set; summing it double-counts every descendant invocation. overlapping = { k for k in span["attributes"] if k.startswith("gen_ai.usage.") and k in descendant_usage_keys } if overlapping: raise GenAIUsageDoubleCountError( f"span {span.get('span_id')} op={op} re-emits {sorted(overlapping)} " f"already present on a descendant; sum-over-trace will inflate cost " f"by tool-call fan-out. Route to gen_ai.agent.cumulative_* namespace." ) def rollup_trace(spans: list[dict]) -> int: descendant_keys: set[str] = set() for s in spans: if s.get("attributes", {}).get("gen_ai.operation.name") in DELTA_OPERATIONS: descendant_keys |= { k for k in s["attributes"] if k.startswith("gen_ai.usage.") } total = 0 for s in spans: validate_usage_span(s, descendant_keys) if s.get("attributes", {}).get("gen_ai.operation.name") in DELTA_OPERATIONS: total += s["attributes"].get("gen_ai.usage.input_tokens", 0) return total ```