# Why does an instance lose token accounting when a tool-call span outlives its parent agent span? **Date of Record:** 2026 November 28 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI spans (`gen_ai.*` attributes, `execute_tool` child spans, `invoke_agent` parent spans) and relies on span-tree aggregation for token accounting and cost attribution. Does not apply to single-shot synchronous LLM calls that complete inside a single span with no tool fan-out. ## Core Distinction There are two different things people mean by "token accounting": *emission* (the model's usage block reports `input_tokens`/`output_tokens` on the response) and *attribution* (those tokens get rolled up to the right agent, turn, and parent span in the trace). OTel GenAI semantic conventions standardize emission via `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`. They say almost nothing normative about *when* a span carrying those attributes may close relative to its parent. That gap is where accounting silently breaks. The non-obvious boundary is this: a tool-call span (`execute_tool`) frequently outlives the `invoke_agent` span that spawned it, because tool execution is asynchronous, retried, or streamed, while the agent span closes as soon as the model turn returns. When the child span closes *after* the parent, its usage attributes are emitted into a trace whose parent is already exported and finalized. Aggregators that walk the span tree bottom-up at parent-close time never see those tokens. ## What Was Observed An agent turn produced a trace with this shape: - `invoke_agent` (parent), `gen_ai.usage.output_tokens=412`, closed at T+1.2s. - `chat` (child), usage attributes present, closed at T+1.1s. - `execute_tool` (child), `gen_ai.tool.name="search"`, spawned at T+0.9s, closed at T+8.4s *after a retry loop*. The parent `invoke_agent` span was exported at T+1.2s. The collector's span processor had a 5s batch timeout; the `execute_tool` span arrived in a later batch, 7s after its parent. Downstream rollup keyed on `parent_span_id` found no live parent and dropped the child's `gen_ai.usage.*` into an orphan bucket. The turn's reported cost was 412 output tokens; actual was 412 + 1,880 (the tool's internal model calls, nested under `execute_tool`). A 4.5× undercount, with no error, no dropped-span metric, and a perfectly valid-looking trace. Second observation: when the same runtime was configured with `BatchSpanProcessor` max export batch size small enough to force multiple flushes, the *same* logical trace produced *different* token totals run to run, because the split point between parent and child export batches moved. The accounting was non-deterministic with respect to a purely operational parameter. ## Condition of Validity The invariant that must hold for tree-based token rollup to be correct: > For every span S carrying `gen_ai.usage.*`, the aggregator must have observed S before it finalizes any ancestor of S, **or** it must reconcile late-arriving children against already-finalized parents. This holds only when child spans are guaranteed to close before their parent — true for synchronous in-process calls, false for: - async tool execution with retries or backoff, - streaming tool results where the span stays open until the last chunk, - tool calls that escape to a subagent or remote MCP server and return via a separate span context, - any `execute_tool` whose duration exceeds the parent's model-turn duration. The failure is *not* triggered by high latency alone. It is triggered by the ordering inversion: child close time > parent close time. A slow tool that still closes before the parent is accounted correctly. This is why latency dashboards look fine while cost dashboards drift. ## Decision Boundary The boundary is whether your accounting layer treats the trace as an *eventually consistent stream* or as a *tree materialized at parent-close*. Concretely: - **If** you aggregate on parent-span `on_end`, **then** you must reject the design for any agent with async tool fan-out. Late children are lost. - **If** you aggregate on trace-id completion (all spans for a trace-id received, then roll up), **then** you need a completion signal. OTel does not give you one natively; you must either wait for a quiescence window per trace-id or use a sentinel span that closes last. - **If** you use a fixed batch timeout as your quiescence proxy, **then** your token totals become a function of collector configuration, not of agent behavior. This is the non-obvious trap: it "works" in staging with short tools and fails in prod with retried tools. The guardrail: emit an explicit terminal span per agent turn (e.g. `invoke_agent.turn_complete`) that is guaranteed to be the last child to close, and key rollup on *that* span's arrival, not on the parent's `on_end`. Alternatively, carry a `gen_ai.usage.*` copy on the parent at turn end, computed from the runtime's own ledger, and treat child usage attributes as diagnostic only. ## Operational Effect Without the guardrail, three things degrade together and none of them alert: 1. **Cost attribution undercounts** proportionally to tool retry rate — the metric moves with infrastructure flakiness, not with model behavior, so it looks like noise. 2. **Per-agent token budgets** (if enforced from traces) under-fire, letting runaway agents exceed their intended caps because the tool-nested tokens are invisible. 3. **Replay divergence**: two runs of the same deterministic agent produce different token totals because batch boundaries differ. This breaks any regression test that asserts on cost. The fix is not to make tools faster. It is to make the accounting invariant independent of span close ordering: either a last-closing sentinel span, or a runtime-side ledger that stamps authoritative usage onto the parent before it closes, treating OTel child spans as observability, not as the source of truth. ```python import time from dataclasses import dataclass, field class TokenAccountingInvariantError(RuntimeError): """Raised when a usage-bearing span closes after its parent was finalized.""" @dataclass class Span: span_id: str parent_id: str | None name: str close_time: float usage_tokens: int = 0 is_terminal: bool = False @dataclass class TraceLedger: spans: dict[str, Span] = field(default_factory=dict) finalized_parents: set[str] = field(default_factory=set) rolled_up_tokens: int = 0 def record(self, span: Span) -> None: if span.parent_id in self.finalized_parents and span.usage_tokens > 0: raise TokenAccountingInvariantError( f"span {span.name}({span.span_id}) carries {span.usage_tokens} tokens " f"but parent {span.parent_id} was already finalized; " f"tree rollup would drop these tokens" ) self.spans[span.span_id] = span if span.is_terminal: self._finalize_trace(span.parent_id) def _finalize_trace(self, root_id: str | None) -> None: if root_id is None: return total = sum( s.usage_tokens for s in self.spans.values() if s.parent_id == root_id or s.span_id == root_id ) self.rolled_up_tokens += total for s in self.spans.values(): if s.parent_id == root_id: self.finalized_parents.add(s.span_id) self.finalized_parents.add(root_id) def emit_agent_turn(ledger: TraceLedger, tool_delay_s: float) -> None: t0 = time.monotonic() ledger.record(Span("agent-1", None, "invoke_agent", t0 + 0.1, usage_tokens=412)) ledger.record(Span("chat-1", "agent-1", "chat", t0 + 0.2, usage_tokens=0)) # Tool span closes AFTER the agent span — the ordering inversion. ledger.record(Span("tool-1", "agent-1", "execute_tool", t0 + tool_delay_s, usage_tokens=1880)) # Terminal sentinel guarantees rollup sees the tool span first. ledger.record(Span("sentinel-1", "agent-1", "turn_complete", t0 + tool_delay_s + 0.01, is_terminal=True)) def run() -> None: ledger = TraceLedger() try: emit_agent_turn(ledger, tool_delay_s=8.0) except TokenAccountingInvariantError as e: raise TokenAccountingInvariantError( "trace accounting would silently undercount; require terminal sentinel span" ) from e assert ledger.rolled_up_tokens == 2292, ledger.rolled_up_tokens if __name__ == "__main__": run() ```