# Why does an instance lose token accounting when a tool-call span closes before its parent agent span, and how do you bound it? **Date of Record:** 2026 November 23 **Scope:** Applies to agents emitting OpenTelemetry GenAI spans (`gen_ai.*` attributes) where tool invocations are instrumented as child spans of an agent span and token usage is aggregated upward. Does not apply to flat, single-span agents that emit one terminal span per turn, nor to providers that emit server-side usage records independent of client instrumentation. ## Core Distinction The failure is not "missing attributes." It is a **temporal aggregation invariant violation**: the GenAI semantic conventions expect usage counters (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) to be attributable to the span that *consumed* the model call, and for agent-level totals to be *derivable* from the span tree at export time. When a tool-call span closes before its parent agent span, and the tool implementation itself issues a nested LLM call (e.g., a summarizer, a re-ranker, a sub-agent invoked as a "tool"), the child's token usage lands on a span whose parent has not yet computed its own totals. If the exporter or collector computes parent totals by summing *closed* children at span-close time, the parent's `gen_ai.usage.*` is frozen before the late child closes. The distinction that matters: **span-close ordering is not a property of the semantic conventions — it is a property of the SDK's span processor and the agent's control flow, and the two are not synchronized.** ## What Was Observed A planner agent (span `agent.plan`, `gen_ai.operation.name=chat`) dispatched three tool calls. The second tool, `summarize_context`, internally invoked a small model to compress retrieved passages. Instrumentation used the standard `BatchSpanProcessor`, so spans were queued and exported on flush, but the *parent's* usage attributes were computed eagerly in the agent's `finally` block by reading `span.attributes` on children that had already closed — a common pattern: ``` with tracer.start_as_current_span("agent.plan") as agent_span: for tool in tools: with tracer.start_as_current_span(f"tool.{tool.name}") as t: result = tool.run() # tool 2 issues a nested chat span # tool 2's nested chat span closes here # agent_span totals computed here, reading only direct children ``` The trace exported with `gen_ai.usage.output_tokens=0` on `agent.plan` and a *detached* `gen_ai.usage.output_tokens=412` on `tool.summarize_context`'s grandchild chat span. The agent-level total was undercounted by exactly the nested model's usage. Downstream cost attribution saw a plan span with zero output tokens and a tool span with 412 tokens whose `gen_ai.operation.name=chat` — a tool span claiming to be a chat operation. Two invariants broke simultaneously: **usage monotonicity** (parent total < sum of descendants) and **operation-name consistency** (a `tool.*` span carrying chat usage). A second observation: when the nested call was retried (transient 429), the retry opened a *new* chat span as a sibling of the original grandchild, and the tool's own usage attribute — set once from the first attempt — was never updated. The trace showed two chat spans under the tool, one with usage and one without, and the tool span's usage matched neither. ## Condition of Validity The invariant "parent `gen_ai.usage.*` ≥ sum over descendant spans of `gen_ai.usage.*`" holds **if and only if** all of the following are true at the moment the parent's usage attributes are written: 1. Every descendant span that will ever carry `gen_ai.usage.*` has already closed, *or* the parent does not write usage attributes eagerly and instead defers to a post-export aggregation pass. 2. Retries do not produce sibling spans with divergent usage; either the retry reuses the same span (updating attributes) or the retry's usage is explicitly summed into the parent's accounting. 3. The tool implementation does not issue model calls on a *different* tracer/tracer-provider whose spans are not children of the tool span (e.g., a background goroutine, a thread pool, or an async task that escaped the context). Violating (1) gives silent undercounting; violating (2) gives double-counting or orphaned usage; violating (3) gives usage that never appears in the agent's subtree at all. The conventions do not encode any of this — `gen_ai.usage.*` is defined as "the number of tokens used," with no statement about *when* it must be written relative to the tree. ## Decision Boundary The boundary is: **do you compute usage at span-close (eager) or at export (deferred)?** - **Eager (in the `finally` block, reading closed children):** correct only for strictly nested, single-threaded, non-retrying tools. Any nested model call that closes after the read, or any retry that spawns a sibling, corrupts the total. This is the default most agents ship with, and it is the wrong default for any agent that uses tools which themselves call models. - **Deferred (a `SpanProcessor.on_end` that accumulates into a parent keyed by `parent_span_id`, or a collector-side `groupbytrace` + aggregate):** correct for arbitrary nesting and retries, at the cost of needing the full trace to be present before aggregation. It requires the collector to buffer until the root closes, which interacts badly with `BatchSpanProcessor` timeouts on long agent turns. The invariant to enforce: **a span carrying `gen_ai.usage.*` must have `gen_ai.operation.name=chat` (or `embeddings`), and no span may carry usage for a descendant it does not own.** If you cannot guarantee deferred aggregation, you must forbid nested model calls inside tool spans — instrument them as siblings under the agent, not children of the tool. ## Operational Effect Agents that ship eager aggregation exhibit a characteristic cost profile: **agent-level token totals are systematically low, and tool spans carry chat usage.** The bias is not random — it scales with tool depth. A planner with three tools where one nests a model call undercounts by that tool's usage every turn; a multi-agent swarm where "delegate" is a tool that spawns a sub-agent undercounts by the *entire* sub-agent's usage, because the sub-agent's chat spans are grandchildren of the delegating tool span. Budget alarms keyed on `agent.*` token totals fire late or never; per-tool cost dashboards show impossible operation-name/usage combinations; and retry-induced sibling spans create phantom usage that no parent accounts for. The fix is not an attribute change — it is a change to *where* usage is written: either defer aggregation to a processor that sees the closed trace, or flatten nested model calls to siblings of the tool span so the agent's direct children are the complete set. ```python from dataclasses import dataclass, field class UsageAttributionError(RuntimeError): """Raised when GenAI usage attributes violate the span-tree accounting invariant.""" @dataclass class Span: name: str parent_id: str | None operation: str | None = None # gen_ai.operation.name usage_out: int | None = None # gen_ai.usage.output_tokens closed: bool = False children: list["Span"] = field(default_factory=list) def assert_usage_invariant(root: Span) -> None: """ Enforce: (1) usage only on chat/embeddings spans, (2) parent total >= sum of descendants, (3) no usage written on a span whose descendants closed after it. """ def walk(s: Span, ancestors_closed_early: bool) -> int: if s.usage_out is not None and s.operation not in (None, "chat", "embeddings"): raise UsageAttributionError( f"span {s.name!r} carries usage_out={s.usage_out} but " f"operation={s.operation!r}; usage must live on a chat/embeddings span" ) if s.usage_out is not None and not s.closed: raise UsageAttributionError( f"span {s.name!r} has usage written before close; eager aggregation " f"cannot see late-closing descendants" ) child_total = 0 for c in s.children: child_total += walk(c, ancestors_closed_early or (s.closed and not c.closed)) if s.usage_out is not None and s.usage_out < child_total: raise UsageAttributionError( f"span {s.name!r} usage_out={s.usage_out} < descendant sum={child_total}; " f"monotonicity violated (nested model call undercounted)" ) return (s.usage_out or 0) + child_total walk(root, False) def emit_agent_usage(agent: Span, deferred: bool) -> None: if not deferred: # Eager path: only legal if every descendant is already closed. if any(not d.closed for d in _descendants(agent)): raise UsageAttributionError( f"eager aggregation on {agent.name!r} while descendants still open; " f"switch to deferred processor or flatten nested model calls" ) assert_usage_invariant(agent) def _descendants(s: Span): for c in s.children: yield c yield from _descendants(c) ```