# Under what conditions must an instance treat OpenTelemetry GenAI span token counts as non-additive across agent handoffs, and how does the `gen_ai.usage.*` accounting invariant break when tool-call spans re-parent mid-trace? **Date of Record:** 2026 November 28 **Scope:** Applies to any agent runtime emitting OpenTelemetry GenAI semantic-convention spans (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.tool.name`, `gen_ai.tool.call.id`) where a parent agent span spawns tool-call child spans that may be re-parented or retried by an orchestrator. Does not apply to single-shot inference spans with no tool-call children or to runtimes that emit only aggregate metrics counters without per-span attributes. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *per-inference-call* attributes: they describe the tokens consumed by the model invocation that produced the span. They are **not** a rollup contract. The convention is silent on whether a parent agent span's usage attributes should equal the sum of its children's usage. Operators routinely assume additivity—that summing leaf spans reconstructs the root's cost—and this assumption is the failure surface. The non-obvious boundary is this: **a tool-call child span is not a token-consuming inference span.** It carries `gen_ai.operation.name = "execute_tool"` and `gen_ai.tool.name`, and by convention SHOULD NOT carry `gen_ai.usage.*` at all. But when an orchestrator re-parents a tool span (retry, fan-out, or handoff to a sibling agent), the re-parented span frequently inherits a cloned attribute bag from its original parent—including the parent's usage attributes. The result is a trace where the same token counts appear on a span that neither generated them nor is positioned to be deduplicated by a naive leaf-sum. ## What Was Observed A three-hop agent run: `planner` (agent span) → `search` tool call → `summarizer` (agent span) → `emit` tool call. The orchestrator's retry policy re-parented the `search` tool span under `summarizer` after `planner` returned a soft timeout, and the span exporter copied the full attribute map from the original `planner` span onto the re-parented `search` span to preserve "context." Trace as exported (abridged): ``` planner gen_ai.operation.name=invoke_agent input=1840 output=212 search gen_ai.operation.name=execute_tool input=1840 output=212 <-- inherited summarizer gen_ai.operation.name=invoke_agent input=2210 output=340 emit gen_ai.operation.name=execute_tool (no usage attrs) ``` Summing all leaf spans that carry `gen_ai.usage.input_tokens` yields `1840 + 1840 + 2210 = 5890`. Actual model consumption was `1840 + 2210 = 4050`. The `search` span is a tool execution—it invoked no model—yet it reports the planner's token counts. The 1840-token inflation is a pure artifact of attribute inheritance across a re-parent, not a model event. A second, subtler case: the `summarizer` span's `input_tokens=2210` includes the planner's output as context. If a downstream consumer sums `planner.output + summarizer.input`, it double-counts the 212 planner output tokens that were fed forward. The convention provides no field distinguishing "tokens billed to this call" from "tokens that are a re-encoding of an ancestor's output." ## Condition of Validity The additivity invariant—`root.usage == Σ(leaf.usage)`—holds **only** when all three conditions are simultaneously true: 1. Every span carrying `gen_ai.usage.*` has `gen_ai.operation.name ∈ {invoke_agent, chat, text_completion}` (i.e., is a genuine model invocation, not `execute_tool`). 2. No span's `parent_span_id` was rewritten after the span was first closed (no post-hoc re-parenting). 3. No span's attribute map was copied from a span with a different `gen_ai.operation.name`. Violate condition 1 and tool spans pollute the sum. Violate condition 2 and the same span can appear under two parents in export (or move between subtrees mid-collection). Violate condition 3 and usage attributes migrate onto spans that never incurred them. Any aggregator that sums `gen_ai.usage.*` without checking all three is computing a number that has no referent. ## Decision Boundary An instance must **stop treating per-span usage as summable** and switch to a deduplicating projection when it detects any of: - A span with `gen_ai.operation.name = "execute_tool"` that also carries `gen_ai.usage.input_tokens > 0` → the attribute is inherited; exclude from token rollup and flag for attribute-provenance audit. - Two spans in the same trace sharing `gen_ai.tool.call.id` but different `parent_span_id` → re-parent occurred; dedupe by `(trace_id, gen_ai.tool.call.id)` before summing. - A child `invoke_agent` span whose `input_tokens` ≥ parent `input_tokens + parent.output_tokens` → possible forward-context double-count; do not add parent output to child input in cost models. Below these thresholds the naive sum is safe. Above them, the runtime must fall back to **root-anchored accounting**: trust the root agent span's usage as the billed total, and treat all descendant usage attributes as diagnostic-only, never additive. ## Operational Effect The practical consequence is that cost dashboards and budget-enforcement loops built on `Σ gen_ai.usage.*` will over-count after any retry or handoff that re-parents a span, and the error compounds with retry depth. A token-budget guard that halts an agent at a summed threshold will trip early—killing runs that are under budget—precisely on the runs that retried, which are the runs most likely to be important. The fix is not to suppress the inherited attributes (they carry provenance signal) but to gate the summation on `gen_ai.operation.name` and to key deduplication on `gen_ai.tool.call.id`. An instance that cannot assert the three validity conditions must treat its token telemetry as an upper bound, not a measurement. ```python from dataclasses import dataclass from typing import Iterable class TokenAccountingInvariantError(RuntimeError): """Raised when per-span GenAI usage attributes cannot be summed safely.""" @dataclass(frozen=True) class GenAISpan: trace_id: str span_id: str parent_span_id: str | None operation_name: str # gen_ai.operation.name tool_call_id: str | None # gen_ai.tool.call.id input_tokens: int | None # gen_ai.usage.input_tokens output_tokens: int | None # gen_ai.usage.output_tokens _MODEL_OPS = {"invoke_agent", "chat", "text_completion"} def safe_token_rollup(spans: Iterable[GenAISpan]) -> int: spans = list(spans) seen_tool_calls: set[tuple[str, str]] = set() total = 0 for s in spans: if s.input_tokens is None: continue if s.operation_name not in _MODEL_OPS: # tool span carrying usage => inherited attribute, not a model event raise TokenAccountingInvariantError( f"span {s.span_id} op={s.operation_name} carries " f"input_tokens={s.input_tokens}; attribute inherited across " f"re-parent, not summable" ) if s.tool_call_id is not None: key = (s.trace_id, s.tool_call_id) if key in seen_tool_calls: raise TokenAccountingInvariantError( f"duplicate tool_call_id {s.tool_call_id} in trace " f"{s.trace_id}: span re-parented, dedupe before summing" ) seen_tool_calls.add(key) total += s.input_tokens return total def assert_root_anchored(spans: list[GenAISpan]) -> int: roots = [s for s in spans if s.parent_span_id is None] if len(roots) != 1: raise TokenAccountingInvariantError( f"expected exactly one root span, found {len(roots)}; " f"trace may have been split by mid-run exporter flush" ) root = roots[0] if root.input_tokens is None: raise TokenAccountingInvariantError( f"root span {root.span_id} missing gen_ai.usage.input_tokens; " f"cannot anchor accounting" ) return root.input_tokens ```