# Why does an instance lose token accounting across a GenAI agent span when tool-call attributes are emitted after child span closure **Date of Record:** 2026 November 26 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*`) that emit a parent `invoke_agent` span plus child `execute_tool` spans and aggregate `gen_ai.usage.input_tokens`/`output_tokens` at the parent. Does not apply to single-call, single-span LLM wrappers where all attributes are set before span end. ## Core Distinction There are two distinct notions of "token accounting" in a GenAI agent trace, and conflating them is the root of the failure: - **Per-span usage** — the `gen_ai.usage.*` attributes bound to the span whose `gen_ai.operation.name` produced the tokens (an `chat` span, or the `invoke_agent` span that wraps a reasoning turn). - **Rollup usage** — the sum a parent agent span reports for its whole subtree, which downstream cost dashboards, budget guards, and context-window estimators actually consume. The semantic convention only defines the *per-span* attributes. It says nothing about when a parent may finalize its rollup. The boundary condition is this: **a parent agent span's token rollup is only correct if every child span that carries `gen_ai.usage.*` ends before the parent span ends, and the parent reads those attributes after child end.** When a tool-call child span is exported *after* the parent's `end()` has already computed and emitted its rollup, the parent's `gen_ai.usage.*` silently under-reports. The trace is structurally valid, passes schema validation, and is wrong. ## What Was Observed A ReAct-style agent (one `invoke_agent` span per user turn, N child `execute_tool` spans, and one child `chat` span per model call) was instrumented so that the parent span computed its rollup in an `on_end` hook by summing `gen_ai.usage.input_tokens` and `output_tokens` across already-exported children. Trace excerpt from a failing run (fields abbreviated): ``` span invoke_agent turn=7 parent gen_ai.operation.name = invoke_agent gen_ai.usage.input_tokens = 4120 <-- rollup, emitted at parent end gen_ai.usage.output_tokens = 610 child execute_tool get_weather ended, no usage attrs child chat step=1 input=2048 output=310 (ended, seen by rollup) child execute_tool search_docs ended, no usage attrs child chat step=2 input=2072 output=300 (ended, seen by rollup) child execute_tool fetch_url ENDED AFTER PARENT <-- async, late export ``` The parent rollup captured steps 1 and 2 (`2048+2072 = 4120`, `310+300 = 610`) but missed a third `chat` span that the tool-execution path spawned *concurrently* with the parent's own finalization. The tool `fetch_url` was dispatched through an async executor; its completion callback fired the third model call, whose `chat` span ended ~40ms after the parent's `end()` had already frozen the rollup. The third call consumed `input=3110 output=180`, all of it absent from the parent. The result: the agent's per-turn cost was under-reported by 43% (`3110/7230` of input tokens). No error, no dropped span — the third `chat` span exists in the backend, orphaned from the parent's rollup. A budget guard keyed on the parent's `gen_ai.usage.input_tokens` never tripped, and the turn ran three more iterations before a separate wall-clock limit fired. ## Condition of Validity The rollup invariant holds only under a conjunction that is easy to violate: 1. **Span lifetime containment.** For every child span `c` carrying `gen_ai.usage.*`, `c.end_time < parent.end_time` in the export order observed by the rollup computation. OpenTelemetry does not enforce this; spans are independent objects and a parent may end while children are live. 2. **Attribute visibility at read time.** The parent reads child usage attributes *after* the child's `end()`, because `gen_ai.usage.*` are set by the child's instrumentation during its own execution. Reading a live child yields zero or stale values. 3. **No fan-out after parent end.** The agent must not spawn tool work whose completion triggers further model calls after the parent has decided the turn is over. This is the actual failure: the parent's notion of "turn complete" and the executor's notion of "no pending work" diverged. Condition 3 is where LLM agents break the model that ordinary request-scoped tracing assumes. A classic RPC handler ends only when all its work is done. An agent's `invoke_agent` span often ends when the *reasoning loop* decides to stop, while tool side-effects and their follow-on model calls are still in flight. The parent has no structural knowledge of outstanding executor tasks unless instrumentation tracks them explicitly. ## Decision Boundary The correct guardrail is not "sum harder" — it is to make the parent's finalization conditional on quiescence of the tool executor, and to treat missing-child-usage as a detectable fault rather than silence. Concretely: - **Track outstanding tool futures in the agent span.** Increment a counter on tool dispatch, decrement on completion callback. The parent's rollup hook must block until the counter is zero (bounded by a deadline), or refuse to emit a rollup. - **Distinguish "no usage" from "usage not yet known."** A child `execute_tool` span legitimately has no `gen_ai.usage.*`. A child `chat` span that has ended but whose usage is absent is a fault. Instrumentation must set a sentinel (`gen_ai.usage.input_tokens` present-and-zero vs. absent) so the rollup can tell them apart. - **Emit the rollup as a separate, later span when quiescence cannot be guaranteed.** If the deadline expires with outstanding work, do not fabricate a rollup on `invoke_agent`; emit a `gen_ai.usage.rollup.incomplete = true` flag and let a downstream aggregator reconcile by `trace_id` over the full child set. - **Never let a budget guard trust a parent rollup that lacks the completeness flag.** The guard must fail closed. The decision boundary is: *if `outstanding_tool_futures > 0` at parent end, the rollup is not authoritative.* Emitting it as if it were is the defect. ## Operational Effect Without the guardrail, the failure is silent and compounding. Each turn with async tool fan-out under-reports cost, so a token-budget agent that should halt at 80% of a 200k window instead halts at ~140k of actual consumption — or, in the observed run, never halts on budget at all and dies on wall-clock. The under-report is non-deterministic: it depends on the race between the parent's `end()` and the executor's completion callback, so the same agent on the same input reports different totals across runs. Cost dashboards built on parent rollups drift downward over time as more tools are made async, and the drift is invisible because every individual span validates. The invariant to enforce operationally: **parent `gen_ai.usage.*` is a lower bound, never an equality, unless the span also carries `gen_ai.usage.rollup.complete = true`.** Consumers (budget guards, context-window estimators, cost attribution) must treat the unmarked value as partial and reconcile against the child `chat` spans by `trace_id`. The trace remains the source of truth; the rollup is only a cache, and caches that lie about their completeness are worse than no cache. ```python from dataclasses import dataclass, field from typing import Optional class IncompleteTokenRollupError(RuntimeError): """Raised when a parent agent span tries to emit an authoritative gen_ai.usage rollup while child tool/model work is still in flight.""" pass @dataclass class AgentSpanRollup: trace_id: str outstanding_tool_futures: int = 0 child_input_tokens: int = 0 child_output_tokens: int = 0 rollup_complete: bool = False _finalized: bool = False def dispatch_tool(self) -> None: if self._finalized: raise IncompleteTokenRollupError( f"tool dispatched after parent span {self.trace_id} finalized" ) self.outstanding_tool_futures += 1 def complete_tool(self, input_tokens: int = 0, output_tokens: int = 0) -> None: # A tool completion may trigger a follow-on chat span; its usage # must land here before the parent is allowed to finalize. if self.outstanding_tool_futures <= 0: raise IncompleteTokenRollupError( f"tool completion with no outstanding future on {self.trace_id}" ) self.outstanding_tool_futures -= 1 self.child_input_tokens += input_tokens self.child_output_tokens += output_tokens def finalize(self, deadline_exceeded: bool = False) -> dict: if self.outstanding_tool_futures > 0: # Do NOT fabricate an authoritative rollup. Emit a partial, # explicitly-flagged value and let the aggregator reconcile # against child chat spans by trace_id. if not deadline_exceeded: raise IncompleteTokenRollupError( f"{self.outstanding_tool_futures} tool futures still live " f"at parent end for {self.trace_id}; refusing authoritative rollup" ) self._finalized = True return { "gen_ai.usage.input_tokens": self.child_input_tokens, "gen_ai.usage.output_tokens": self.child_output_tokens, "gen_ai.usage.rollup.complete": False, } self._finalized = True self.rollup_complete = True return { "gen_ai.usage.input_tokens": self.child_input_tokens, "gen_ai.usage.output_tokens": self.child_output_tokens, "gen_ai.usage.rollup.complete": True, } def budget_guard(rollup_attrs: dict, ceiling: int) -> Optional[str]: """Fail closed: an incomplete rollup must never authorize more spend.""" if not rollup_attrs.get("gen_ai.usage.rollup.complete", False): raise IncompleteTokenRollupError( "budget guard received a rollup without rollup.complete=true; " "reconcile against child chat spans before trusting it" ) used = rollup_attrs["gen_ai.usage.input_tokens"] + rollup_attrs["gen_ai.usage.output_tokens"] if used > ceiling: return f"budget exceeded: {used} > {ceiling}" return None ```