# When must an instance emit a terminal `gen_ai.agent.span` event before its child tool spans close, and why token accounting silently corrupts when it does not **Date of Record:** 2026 November 20 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.agent.*`, `gen_ai.tool.*`, `gen_ai.chat`) with parent/child span linkage across a single agent invocation, where token usage is aggregated up the span tree. Does not apply to single-shot chat completions with no tool-call fan-out, nor to runtimes that emit only flat, unparented spans. ## Core Distinction The failure is not "spans close out of order." The failure is that a *terminal* agent event — the one carrying the final `gen_ai.usage.output_tokens` and the terminal `gen_ai.agent.status` — is emitted while child tool spans are still open, so the aggregator that rolls usage up the parent chain snapshots an incomplete subtree. The distinction that matters operationally: **span end-order is a causal constraint, not a cosmetic one.** A tool span that closes *after* its parent agent span has ended is not merely mis-nested; its token contribution is attributed to a parent that has already been finalized, and the finalized value is what gets exported, sampled, and billed against. The parent's recorded usage becomes a lower bound that silently under-reports, and no downstream validator flags it because the number is internally consistent — it just isn't the whole subtree. This is distinct from the ordinary "orphaned span" problem. An orphaned span (parent context lost) is *detectable* — it has no parent and a validator can reject it. The corruption here is *undetectable from the span alone*: the parent span is well-formed, its children are well-formed, and each child's own usage is correct. Only the *sum* is wrong, and only relative to a truth (the actual tool invocations) that lives outside the trace. ## What Was Observed An agent loop with a ReAct-style controller was instrumented per the GenAI conventions. The controller span (`gen_ai.agent.invoke`) opened at task start. Each reasoning step emitted a `gen_ai.chat` child span, and each tool invocation emitted a `gen_ai.tool.call` child span. On task completion the controller emitted its terminal attributes — `gen_ai.agent.status=completed`, aggregate `gen_ai.usage.input_tokens`, aggregate `gen_ai.usage.output_tokens` — and then ended the span. Under normal load the trace was clean. Under a specific condition the sequence inverted: the controller's terminal event fired, *then* a still-running tool span ended. The trigger was a tool whose result the controller did not need to finish — specifically, a fire-and-forget side-effect tool (a log write, a notification dispatch) that the model invoked in its final reasoning step and whose result the controller did not block on. The controller treated the step as terminal, emitted its aggregate usage (computed from the chat spans it had already seen), and ended. The tool span, still awaiting its I/O, closed milliseconds later and carried its own `gen_ai.usage` — which the aggregator, finding the parent already finalized, either dropped or attached to a synthetic root. The observable signature in the exported trace: - Parent `gen_ai.agent.invoke` span: `end_time` *earlier* than child `gen_ai.tool.call` span `end_time`. - Parent aggregate `output_tokens` = sum over chat spans only; the tool span's tokens absent from the parent. - Child tool span present, correct, and parented — but its usage not reflected anywhere in the rollup. - No error, no dropped span, no sampling anomaly. The trace *looks* complete. The corruption compounds. Because the parent's terminal usage was already exported, a later reconciliation pass that re-reads child spans and tries to correct the parent finds a finalized value it cannot amend without emitting a second terminal event — which is itself a protocol violation (an agent span must have exactly one terminal event). ## Condition of Validity The invariant holds — and the failure is bounded — only under this conjunction: 1. **Usage is aggregated at the parent from child spans observed before parent end.** If the aggregator instead recomputes from the full descendant set at export time (post-hoc tree walk), late-closing children are included and the failure does not occur. The failure requires *streaming* aggregation at parent-end. 2. **The controller can reach a terminal decision without awaiting all dispatched tool spans.** If the runtime joins on every tool future before emitting the terminal agent event, the ordering cannot invert. The failure requires a non-blocking dispatch path — fire-and-forget, detached, or "result not required for next step." 3. **The parent span has a single-terminal-event contract.** If the runtime permits amending a closed agent span's usage, the corruption is recoverable and the invariant is soft. The hard failure requires the exactly-one-terminal-event rule that the GenAI conventions imply for status-bearing agent spans. When any conjunct fails, this is not the operative boundary; do not apply this record. In particular, do not apply it to runtimes that emit flat spans with post-hoc aggregation — there the sum is always computed over the complete set. ## Decision Boundary The architectural guardrail is a **drain-before-terminate barrier**: the agent span MUST NOT emit its terminal event (status + aggregate usage) until every child span it has opened has ended, or has been explicitly cancelled and marked `gen_ai.tool.status=cancelled` with its usage zeroed. Concretely: - The controller maintains a live set of open child span handles. Terminal emission is gated on `open_children == empty`. - Fire-and-forget tools are not exempt: they must either be *detached into a separate trace root* (so they are not children of the agent span and cannot corrupt its rollup) or be *awaited to span-close* before terminal emission. There is no third option that preserves the invariant. - If a tool exceeds a deadline, the barrier does not wait indefinitely: it cancels the tool, ends its span with `cancelled` status and zeroed usage, and *then* permits terminal emission. Cancellation is a span-close; abandonment is not. The decision boundary for the operator: **if your runtime can dispatch a tool whose result the controller does not await, you have this bug unless you detach it to a separate root or join on its span-close.** The presence of a non-blocking tool dispatch is the predicate that selects this record. ## Operational Effect Unmitigated, the effect is a systematic *under-count* of tokens attributed to agent spans, proportional to the token cost of fire-and-forget tools, and biased toward tasks that end on side-effect actions (logging, notification, cleanup) — which are exactly the tasks most likely to be high-volume and least likely to be spot-checked. Billing reconciliation against provider-side usage will diverge from trace-side usage, and the divergence will not be traceable to any single span because each span is individually correct. The under-count is also *non-stationary*: as tool latency varies, the fraction of tools that close after parent-end varies, so the error is load-dependent and resists a fixed correction factor. With the drain-before-terminate barrier, the parent's aggregate usage is exact by construction, late-closing children cannot exist under a finalized parent, and the exactly-one-terminal-event contract is preserved. The cost is latency: terminal emission waits on the slowest open child (bounded by the cancellation deadline). That latency is the price of a correct rollup, and it is the correct trade — a fast wrong number is worse than a slow right one when the number is billed against. ```python import time from dataclasses import dataclass, field class TerminalBeforeDrainError(RuntimeError): """Raised when an agent span attempts to emit its terminal event while child spans remain open.""" pass @dataclass class SpanHandle: span_id: str kind: str # "chat" | "tool" end_time: float | None = None usage_output_tokens: int = 0 cancelled: bool = False def is_open(self) -> bool: return self.end_time is None and not self.cancelled @dataclass class AgentSpan: span_id: str open_children: dict[str, SpanHandle] = field(default_factory=dict) terminal_emitted: bool = False aggregate_output_tokens: int = 0 def open_child(self, handle: SpanHandle) -> None: if self.terminal_emitted: # A child opened under a finalized parent can never be rolled up. raise TerminalBeforeDrainError( f"parent {self.span_id} already terminal; child {handle.span_id} would be orphaned from rollup" ) self.open_children[handle.span_id] = handle def close_child(self, span_id: str, output_tokens: int, cancelled: bool = False) -> None: h = self.open_children[span_id] h.end_time = time.monotonic() h.cancelled = cancelled h.usage_output_tokens = 0 if cancelled else output_tokens def _drain(self, deadline_s: float) -> None: """Cancel any still-open child so it closes as a span before terminal emission.""" start = time.monotonic() for h in list(self.open_children.values()): if h.is_open(): if time.monotonic() - start > deadline_s: # Deadline exceeded: cancel (a span-close), do not abandon. self.close_child(h.span_id, output_tokens=0, cancelled=True) else: raise TerminalBeforeDrainError( f"child {h.span_id} still open at terminal emission for parent {self.span_id}" ) def emit_terminal(self, status: str, deadline_s: float = 0.0) -> int: if self.terminal_emitted: raise TerminalBeforeDrainError(f"parent {self.span_id} emitted terminal event twice") self._drain(deadline_s) self.aggregate_output_tokens = sum(h.usage_output_tokens for h in self.open_children.values()) self.terminal_emitted = True return self.aggregate_output_tokens def run_agent_step(agent: AgentSpan, tool_tokens: int, await_tool: bool) -> int: """Simulate a controller step. Non-awaited tools must be detached, not left open under the parent.""" tool = SpanHandle(span_id="tool-1", kind="tool") agent.open_child(tool) if await_tool: agent.close_child(tool.span_id, output_tokens=tool_tokens) else: # Fire-and-forget: detach to a separate root, or the drain barrier will (correctly) refuse. agent.open_children.pop(tool.span_id) return agent.emit_terminal(status="completed", deadline_s=0.0) ```