# Under what conditions must an instance reconcile OpenTelemetry GenAI token-accounting attributes against the tool-call span tree before closing an agent trace **Date of Record:** 2026 November 24 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans using the GenAI semantic conventions (`gen_ai.*`) and nests `execute_tool` child spans under a parent `invoke_agent` span. Does not apply to single-shot completion calls with no tool loop, nor to runtimes that delegate token accounting entirely to a billing-side aggregator. ## Core Distinction The GenAI semantic conventions define token usage as an attribute of the *model invocation* span (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`), not of the agent span. An agent span that fans out into N tool-call turns will therefore contain N child `chat`/`generate_content` spans, each carrying its own usage attributes, plus a parent `invoke_agent` span that — per convention — carries no aggregated token total. The failure mode is the assumption that the parent span is authoritative for accounting. It is not. The parent span is a *structural* record; the token truth lives in the leaves. When a runtime closes the agent trace by writing an aggregate onto the parent (or by trusting a single leaf), it silently drops tokens from turns whose spans were emitted by a different instrumentation library, a different sampling decision, or a retry path that produced an orphaned child. The non-obvious boundary: **the sum of child token attributes is not guaranteed to equal the tokens the agent actually consumed**, because tool-call turns can be re-entrant (a tool invokes the model again), and re-entrant turns produce spans that are grandchildren, not children. A naive `sum(children)` undercounts by exactly the fan-out depth of any tool that calls back into the model. ## What Was Observed A research agent with a `search_documents` tool that internally performs a query-rewrite LLM call. Trace structure observed in the collector: ``` invoke_agent (agent.run) ├── chat (turn 1, input=812, output=140) ├── execute_tool (search_documents) │ └── chat (query rewrite, input=310, output=48) ← grandchild ├── chat (turn 2, input=1104, output=95) └── execute_tool (search_documents) └── chat (query rewrite, input=298, output=51) ← grandchild ``` The runtime's accounting hook walked `span.children` of `invoke_agent`, summed `gen_ai.usage.input_tokens` across the two `chat` children (812 + 1104 = 1916) and the two `execute_tool` children (which carry no usage attributes, contributing 0). It wrote `gen_ai.usage.input_tokens = 1916` onto the parent. The actual consumed input tokens were 1916 + 310 + 298 = 2524 — a 24% undercount. The grandchild spans existed in the trace but were invisible to the accounting walk because it used direct-children traversal. A second, compounding observation: on retry, the failed `chat` span for turn 2 was emitted with `gen_ai.usage.input_tokens = 1104` *and* a `status = ERROR`, then a fresh span was emitted for the successful retry with the same 1104. The naive sum double-counted the failed attempt. Whether that is correct depends on whether the provider bills failed-but-tokenized calls — which varies. The convention is silent on this, so the runtime must decide and record the decision. ## Condition of Validity The invariant — *parent aggregate equals true consumption* — holds only when all of the following are true: 1. **Traversal is depth-first over the full subtree**, not direct-children. Any tool that re-enters the model creates grandchild usage spans. 2. **Span status is consulted before summing.** Spans with `status = ERROR` and no `gen_ai.usage.output_tokens` are typically non-billable; spans with `status = ERROR` *and* populated usage are billable and must be included. The GenAI conventions do not encode billability, so the runtime must carry a local policy attribute (e.g., `agent.billing.include_failed = true`). 3. **Exactly one span per model invocation is emitted per retry attempt**, and retries are linked via `span.links` to the failed attempt rather than reusing the span ID. Reused span IDs collapse two consumption events into one. 4. **The accounting pass runs after the last child span has ended**, not on `invoke_agent`'s `on_end` if any child can still be in-flight. In async tool execution this is a real race: a fire-and-forget tool call can emit its usage span after the parent has closed. When any of these is violated, the parent aggregate is not a valid accounting record and must be marked as such rather than written as truth. ## Decision Boundary The runtime must choose between two postures at trace close: - **Reconcile-and-fail-closed:** if the depth-first subtree sum disagrees with any provider-reported total (e.g., a `gen_ai.response.id`-keyed billing reconciliation), or if any in-flight child is detected, do not write the aggregate; emit `agent.accounting.incomplete = true` and raise. This is correct for cost-attribution pipelines and for agents whose budgets are enforced from span data. - **Reconcile-and-annotate:** write the depth-first sum but attach `agent.accounting.method = "subtree_sum"` and `agent.accounting.excluded_spans = [ids]`. This is correct for observability-only pipelines where a downstream reconciler will correct against billing. The boundary is crossed the moment a budget-enforcement loop reads the parent aggregate. If the agent's own token budget is decremented from `invoke_agent`'s aggregate, an undercount from grandchild omission means the budget never trips — the agent runs past its limit because its own telemetry lied to it. That is the invariant that matters: **telemetry used as control input must be reconciled to the leaf, not the branch.** ## Operational Effect Runtimes that adopt depth-first reconciliation with explicit retry policy see two effects. First, token budgets trip at the correct turn rather than one to three turns late, which changes the shape of agent trajectories near the budget ceiling — the agent truncates earlier and with less wasted context. Second, cost dashboards stop under-reporting by the fan-out factor of re-entrant tools; in the observed case the correction was 24%, and for agents with nested retrieval it commonly exceeds 40%. The cost of the guardrail is a full-subtree walk at trace close, which is O(spans) and negligible against model latency — but it must be scheduled after quiescence, which means the runtime needs an explicit "all children ended" barrier rather than relying on parent `on_end` ordering. ```python from dataclasses import dataclass, field from typing import Iterable class TokenAccountingReconciliationError(RuntimeError): """Raised when a GenAI agent span's aggregate cannot be validly reconciled.""" @dataclass class Span: span_id: str name: str parent_id: str | None status: str # "OK" | "ERROR" | "UNSET" input_tokens: int | None = None output_tokens: int | None = None ended: bool = True children: list["Span"] = field(default_factory=list) def _walk_subtree(root: Span) -> Iterable[Span]: yield root for child in root.children: yield from _walk_subtree(child) def reconcile_agent_tokens( agent_span: Span, *, include_failed_usage: bool, require_quiescence: bool = True, ) -> int: """Depth-first reconcile token usage for an invoke_agent span. Sums gen_ai.usage.input_tokens across the full subtree, honoring the local billability policy for ERROR spans. Fails closed on in-flight children or on any child lacking a usage attribute on a chat span. """ total_input = 0 for span in _walk_subtree(agent_span): if span.span_id == agent_span.span_id: continue if require_quiescence and not span.ended: raise TokenAccountingReconciliationError( f"child span {span.span_id} ({span.name}) still in-flight " f"at accounting time; parent aggregate would be incomplete" ) if span.name not in ("chat", "generate_content"): continue if span.input_tokens is None: raise TokenAccountingReconciliationError( f"model span {span.span_id} missing gen_ai.usage.input_tokens; " f"cannot reconcile subtree" ) if span.status == "ERROR" and not include_failed_usage: continue total_input += span.input_tokens if total_input == 0: raise TokenAccountingReconciliationError( f"agent span {agent_span.span_id} reconciled to zero input tokens; " f"refusing to write aggregate (likely instrumentation gap)" ) return total_input ```