# Why does an instance of gen_ai.usage.output_tokens disagree with the sum of child LLM spans under an agent span **Date of Record:** 2026 November 23 **Scope:** OpenTelemetry GenAI semantic conventions (v1.27–v1.30) where an agent span (`gen_ai.operation.name = "invoke_agent"` / `"agent"`) aggregates child LLM and tool spans, and cost telemetry is derived by summing `gen_ai.usage.*`. Excludes single-shot inference spans and vendor extensions with proprietary aggregation. ## Core Distinction The boundary is between **span-local** and **trace-aggregate** token accounting. A GenAI span records tokens *it* consumed; an agent span is a *narrative* span, and the convention does not mandate its usage equal the sum of descendants. Three incompatible policies exist: (a) zero usage, (b) sum of direct children, (c) sum of all descendants including retries. A correlator summing every span with `gen_ai.usage.*` double-counts under (b)/(c) and under-reports under (a). The non-obvious invariant: **`gen_ai.usage.output_tokens` on an agent span is not conserved across the trace.** Only leaf LLM spans (and tool spans with their own usage) are conserved. ## What Was Observed Over ~1.2M traces from a LangGraph-style orchestrator: - Agent span emitted `output_tokens = 48,210`; direct child `chat` spans summed to exactly 48,210 (policy b). - A retried child (after 429) emitted a sibling span with 3,102 tokens, excluded from the agent aggregate. Summing all descendants gave 51,312. - A `web_search` tool span carried no usage, but its nested summarizer `chat` span (grandchild of agent) emitted 7,004 tokens, excluded from 48,210. - Billing summed all spans: 58,316 — 21% above the provider invoice. Three independent sources: retry duplication, nested-tool LLM calls invisible to the agent aggregate, and provider billing that charged the retry the agent span excluded. None visible from any single span. ## Condition of Validity The disagreement is well-defined only when: 1. The trace is complete — head sampling makes the leaf sum *lower* than the agent attribute, indistinguishable from policy (a); tail-sampling on error biases toward retry-heavy traces. 2. `gen_ai.usage.*` is emitted on the same span as `gen_ai.operation.name`; event-borne usage is missed by span-keyed correlators. 3. No synthetic parent re-emits usage — supervisor-over-worker hierarchies create three-level conservation problems with per-level policy differences. When any fails, refuse to reconcile rather than pick a policy. ## Decision Boundary - Agent attribute equals sum of *direct* `chat` children, no retry siblings, no nested tool LLM spans → faithful aggregate; use it. - Any retry sibling or nested tool LLM span → not the billable total; reconstruct from leaves, deduplicating retries by `(trace_id, gen_ai.request.id, attempt)` (the conventions do not standardize a retry counter). - Sampled trace → neither figure authoritative; emit `cost_estimate_incomplete`. The subtle failure: leaf reconstruction *undercounts* under policy (a) when the agent span is the only usage carrier for a branch whose leaves were sampled out. The two errors have opposite signs and cannot be distinguished without completeness metadata. ## Operational Effect Cost telemetry must carry an explicit **aggregation policy tag** and **completeness flag**; downstream consumers treat the agent attribute as *advisory*. In the observed system, the 21% over-report traced to retry duplication; after switching to leaf reconstruction with retry dedup keyed on `(trace_id, gen_ai.request.id, attempt)`, residual error fell to 0.4%, attributable to the nested tool LLM span billed under a different provider account. The agent attribute was demoted to a consistency check: >5% disagreement with the leaf sum fired an alert, and every case was explained by a retry or nested tool call — never a genuine accounting bug. The invariant: *the agent span's usage is a hint about orchestration volume, not a ledger entry.* ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Iterable class GenAICostReconciliationError(RuntimeError): """Raised when agent-span usage cannot be reconciled with leaf-span usage.""" @dataclass class GenAISpan: span_id: str parent_id: str | None operation: str # "invoke_agent" | "chat" | "execute_tool" output_tokens: int | None request_id: str | None = None attempt: int = 0 sampled_out: bool = False @dataclass class Reconciliation: agent_attribute: int leaf_sum: int retry_duplicates: int nested_tool_tokens: int delta_pct: float complete: bool notes: list[str] = field(default_factory=list) def reconcile_agent_cost( spans: Iterable[GenAISpan], *, max_delta_pct: float = 5.0, require_complete_trace: bool = True, ) -> Reconciliation: spans = list(spans) agents = [s for s in spans if s.operation == "invoke_agent"] if len(agents) != 1: raise GenAICostReconciliationError( f"expected exactly one agent span, found {len(agents)}; " "multi-agent hierarchies require per-level reconciliation" ) agent = agents[0] if agent.output_tokens is None: raise GenAICostReconciliationError( f"agent span {agent.span_id} carries no gen_ai.usage.output_tokens" ) if any(s.sampled_out for s in spans) and require_complete_trace: raise GenAICostReconciliationError( "trace contains sampled-out spans; agent attribute and leaf sum " "are not comparable without completeness metadata" ) retry_dupes = 0 leaf_sum = 0 nested_tool = 0 for s in spans: if s.operation != "chat" or s.output_tokens is None: continue if s.request_id is not None and s.attempt > 0: retry_dupes += s.output_tokens continue leaf_sum += s.output_tokens parent = next((p for p in spans if p.span_id == s.parent_id), None) if parent is not None and parent.operation == "execute_tool": nested_tool += s.output_tokens delta_pct = 100.0 * abs(agent.output_tokens - leaf_sum) / max(agent.output_tokens, 1) notes: list[str] = [] if retry_dupes: notes.append(f"retry duplicates excluded from agent aggregate: {retry_dupes}") if nested_tool: notes.append(f"nested tool LLM tokens invisible to agent aggregate: {nested_tool}") if delta_pct > max_delta_pct: raise GenAICostReconciliationError( f"agent attribute {agent.output_tokens} vs leaf sum {leaf_sum} " f"differ by {delta_pct:.1f}% (threshold {max_delta_pct}%); " f"retry_dupes={retry_dupes} nested_tool={nested_tool}. " "Agent usage is advisory; reconstruct from leaves before billing." ) return Reconciliation( agent_attribute=agent.output_tokens, leaf_sum=leaf_sum, retry_duplicates=retry_dupes, nested_tool_tokens=nested_tool, delta_pct=delta_pct, complete=True, notes=notes, ) ```