# When must an instance distrust a parent span's gen_ai.usage token counts after a tool-call fan-out **Date of Record:** 2026 November 24 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`, `gen_ai.response.model`) and reconstruct per-task cost, lineage, or model provenance by rolling child tool-call spans up into a parent `invoke_agent` span. Does not apply to single-shot inference with no tool fan-out, nor to runtimes that account tokens only at the provider response object and never re-derive them from span attributes. ## Core Distinction A GenAI span's `gen_ai.usage.*` attributes are a *claim about a single model response*, not a *conserved quantity over a subtree*. The semantic conventions define them per inference call. They were never specified to be additive across a parent-child span tree, yet almost every cost-and-provenance pipeline treats the parent `invoke_agent` span's usage attributes as the authoritative total for everything beneath it. The boundary failure lives exactly there: when an agent performs N tool calls, each tool call may itself trigger a nested model invocation (a sub-agent, a summarizer, a router) that emits its own usage attributes, and the parent span's usage attributes were populated from *one* of those responses — usually the last, sometimes the first, occasionally a manually summed value that double-counts. The invariant that must hold before a parent's token counts can be trusted as a subtree total is: **the parent span must have been closed by an accounting authority that observed every descendant inference response, and the span must carry an explicit aggregation marker distinguishing "summed" from "single-response" semantics.** The conventions provide no such marker. Therefore the default posture must be distrust. ## What Was Observed An orchestrator agent (`gen_ai.operation.name = "invoke_agent"`, `gen_ai.request.model = "claude-3-5-sonnet"`) ran a 7-step tool loop. Each tool call was wrapped in a `gen_ai.operation.name = "execute_tool"` span, and three of those tools internally invoked a cheaper model (`gen_ai.request.model = "claude-3-haiku"`) to summarize retrieval results, emitting nested `chat` spans with their own `gen_ai.usage.input_tokens` / `output_tokens`. The parent `invoke_agent` span was instrumented by the SDK's auto-instrumentation, which sets usage attributes from the *last* model response it saw on the parent's own inference loop. That last response happened to be a 240-token final-answer turn. The three nested haiku summarizations (totaling 18,400 input tokens) and the six earlier sonnet turns (totaling 61,200 input tokens) were emitted only on their own child spans. The cost pipeline summed `gen_ai.usage.input_tokens` across the *entire trace* to avoid double-counting parents — but it also carried a fallback: for any trace where the root span had usage attributes, it trusted the root and skipped descendants. Because the root `invoke_agent` span *did* carry usage attributes (240 in / 90 out), the fallback fired and the trace was recorded at 240 input tokens. Actual consumption was 79,840. The undercount was 99.7%, silent, and consistent across every trace from that agent version. A second, subtler observation: `gen_ai.response.model` on the parent span reported `claude-3-5-sonnet`, while two child `chat` spans reported `claude-3-haiku`. A provenance query asking "which model produced this trace's output" returned sonnet — correct for the final answer, wrong for the retrieval summaries that the final answer was conditioned on. Lineage was not lost, but it was flattened by the parent's single-model provenance attribute. ## Condition of Validity A parent span's `gen_ai.usage.*` may be treated as a subtree total **only if all three hold**: 1. The span was emitted with an explicit aggregation attribute (a custom `gen_ai.usage.aggregation = "subtree_sum"` or equivalent) set by an accounting layer that closed the span *after* all descendants closed — i.e., the parent's `end_time` is strictly greater than every descendant's `end_time`, and the accounting layer had visibility into every descendant response object. 2. No descendant span carries `gen_ai.usage.*` attributes of its own that are not already included in the parent's count. If descendants carry usage and the parent carries usage, the parent is a *single-response claim* and must be treated as such. 3. The parent's `gen_ai.response.model` matches the set of models used by all descendants that contributed to the output, or the parent carries per-model breakdown attributes. A single `gen_ai.response.model` on a span with heterogeneous descendants is a provenance claim about one response, not the subtree. When any condition fails — which is the default with stock auto-instrumentation — the parent's usage attributes must be read as "the usage of the one inference call that closed this span," and the subtree total must be recomputed by summing leaf `chat`/`execute_tool` spans that carry usage, deduplicating by `trace_id` + `span_id` of the response-emitting span, never by parent. ## Decision Boundary The decision is not "trust the parent or trust the children." It is: *at what point does re-derivation from leaves become unsafe, and the parent must be quarantined rather than corrected?* - If every leaf inference span carries usage attributes and the leaf set is closed (all leaves have `end_time` before the parent's `end_time`), re-derivation from leaves is safe and is the correct accounting path. - If any leaf inference span is missing usage attributes (dropped by sampling, by an uninstrumented tool, or by an SDK that only sets usage on the root), re-derivation under-counts, and the parent's count is *also* wrong. The trace is **unaccountable**: neither the parent nor the leaves yield a defensible total. This is the quarantine boundary. - If the parent carries an explicit aggregation marker and the leaf sum disagrees with it by more than a configured tolerance (e.g., 2%), the aggregation layer itself is suspect — a race in span closing, a lost descendant, or a double-counted retry — and the trace must be flagged for replay rather than silently reconciled to either number. The boundary is therefore not a threshold on magnitude but a threshold on *closure*: a trace is accountable iff the set of response-emitting spans is closed and each carries usage, or a trusted aggregator closed the parent after observing all of them. Absent closure, any number is a guess dressed as telemetry. ## Operational Effect Downstream effects are not merely cost misreporting. Provenance queries that resolve "which model answered" from the root span will attribute haiku-generated retrieval summaries to sonnet, poisoning model-quality comparisons and regression baselines. Budget enforcement that reads the root span will never trip a per-task cap, because the root always reports the small final turn. Lineage reconstruction that walks parent-to-child expecting cumulative usage will compute negative or zero marginal costs for children whose usage exceeds the parent's. And because the failure is silent and stable, it survives every green dashboard: the numbers are internally consistent, just systematically wrong by the fan-out factor. The guardrail is a span-closure accounting pass that runs after trace completion, enumerates response-emitting spans by `gen_ai.operation.name in {"chat", "text_completion", "generate_content"}` plus any `execute_tool` span that carries usage, verifies closure, and either re-derives the total or emits an unaccountable-trace marker. The parent's usage attributes are read only as a *cross-check*, never as the source of truth. The following routine encodes exactly that boundary and refuses to emit a total when closure fails. ```python from dataclasses import dataclass from typing import Iterable class UnaccountableTraceError(RuntimeError): """Raised when a trace's token total cannot be defensibly derived from span closure.""" @dataclass(frozen=True) class GenAISpan: span_id: str parent_id: str | None operation: str # gen_ai.operation.name end_time_ns: int input_tokens: int | None # gen_ai.usage.input_tokens, None if absent output_tokens: int | None response_model: str | None # gen_ai.response.model aggregation: str | None = None # custom subtree_sum marker, if any INFERENCE_OPS = {"chat", "text_completion", "generate_content"} def derive_trace_tokens(spans: Iterable[GenAISpan], tolerance: float = 0.02) -> dict: spans = list(spans) if not spans: raise UnaccountableTraceError("empty trace: no spans to account") roots = [s for s in spans if s.parent_id is None] if len(roots) != 1: raise UnaccountableTraceError( f"expected exactly one root span, found {len(roots)}" ) root = roots[0] by_id = {s.span_id: s for s in spans} # Closure: every span must end at or before the root's end_time. late = [s.span_id for s in spans if s.end_time_ns > root.end_time_ns] if late: raise UnaccountableTraceError( f"span closure violated: {late} end after root {root.span_id}" ) # Response-emitting spans: inference ops, plus any tool span carrying usage. emitters = [ s for s in spans if s.operation in INFERENCE_OPS or (s.operation == "execute_tool" and s.input_tokens is not None) ] if not emitters: raise UnaccountableTraceError("no response-emitting spans with usage found") missing = [s.span_id for s in emitters if s.input_tokens is None or s.output_tokens is None] if missing: # Leaves are incomplete: re-derivation under-counts and the parent # is a single-response claim. Neither is defensible. raise UnaccountableTraceError( f"usage attributes missing on response-emitting spans: {missing}" ) leaf_in = sum(s.input_tokens for s in emitters) leaf_out = sum(s.output_tokens for s in emitters) # Cross-check against an explicit aggregator, if the root claims one. if root.aggregation == "subtree_sum": if root.input_tokens is None or root.output_tokens is None: raise UnaccountableTraceError( "root claims subtree_sum aggregation but lacks usage attributes" ) denom = max(leaf_in, 1) drift = abs(root.input_tokens - leaf_in) / denom if drift > tolerance: raise UnaccountableTraceError( f"aggregator drift {drift:.3f} exceeds tolerance {tolerance}: " f"root={root.input_tokens} leaves={leaf_in} — suspect lost or " f"double-counted descendant, replay required" ) models = {s.response_model for s in emitters if s.response_model} if root.response_model and len(models) > 1: # Root provenance is a single-response claim; do not flatten. provenance = "heterogeneous" else: provenance = root.response_model or "unknown" return { "input_tokens": leaf_in, "output_tokens": leaf_out, "provenance": provenance, "models_seen": sorted(models), "source": "leaf_rederivation", } ```