# What structural signals indicate token-usage metric corruption when OpenTelemetry GenAI agent spans are closed out of causal order **Date of Record:** 2026 November 25 **Scope:** Applies to agents that emit OpenTelemetry GenAI spans (`gen_ai.*` semantic conventions) where a parent agent span's `gen_ai.usage.input_tokens`/`output_tokens` is derived by aggregation of child tool-call and LLM-call spans, and where those children may complete after the parent's `end()` is invoked. Does not apply to flat, single-span instrumentation or to backends that recompute usage from raw event streams independent of span lifecycle. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.*` as a *span-local* attribute: each span reports the tokens it consumed. What most agent runtimes actually need is a *subtree-aggregate*: the parent agent span must report the sum of its own reasoning tokens plus every descendant LLM and tool-call span. These are not the same number, and the conventions do not specify aggregation semantics. The failure mode lives in the gap: when a parent span ends before its children, any aggregation performed at `end()` time silently under-counts, and the resulting metric is not merely wrong—it is *structurally* inconsistent with the child spans that later arrive and reference a `parent_span_id` pointing at a span the exporter has already finalized. This is a boundary condition, not a bug in any single SDK. It is the collision between span lifecycle (parent must end last) and the reality of fire-and-forget tool dispatch, streaming LLM completions, and async sub-agent handoffs where the orchestrator's control flow returns before the child's token accounting is known. ## What Was Observed A three-tool agent turn (`search`, `fetch`, `summarize`) produced the following trace fragment. The orchestrator span `agent.turn` was closed immediately after dispatching `summarize`, because the orchestrator used a `asyncio.create_task` fan-out and did not await the final tool. Observed attributes: - `agent.turn` span: `end_time` = T+410ms, `gen_ai.usage.input_tokens=1840`, `gen_ai.usage.output_tokens=210`. These are the orchestrator's *own* LLM call tokens only. - `tool.summarize` span: `start_time` = T+395ms, `end_time` = T+920ms, `gen_ai.usage.input_tokens=0` (tool, not LLM), but its child `llm.summarize` span carried `input_tokens=6120`, `output_tokens=880`. The backend's span-tree reconstructor, which computes `agent.turn` subtree totals, found a child (`tool.summarize`) whose `end_time` (T+920ms) exceeded the parent's `end_time` (T+410ms). Depending on backend, one of three things happened: (a) the child was orphaned because the parent span was already flushed and the `parent_span_id` no longer resolved to a live span; (b) the child was attached but excluded from the parent's aggregate because aggregation ran at parent-finalize time; (c) the span was rejected by a strict validator asserting `child.end_time <= parent.end_time`. The observable structural signal, in all three cases, is a **negative or truncated subtree token delta**: `sum(subtree_usage) - parent_reported_usage` is large and positive (here ~7000 tokens) while the parent's own `end_time` precedes the child's. A second signal: the count of spans referencing a given `parent_span_id` at ingestion time is less than the count observed at query time—the parent "gained children" post-hoc, which is impossible under a correct causal model. ## Condition of Validity The aggregate-usage invariant holds only when the following three conditions are jointly true: 1. **Causal closure:** every descendant span's `end_time` is less than or equal to its parent's `end_time`. Equivalently, the parent span is finalized strictly after all children. 2. **Monotonic attribute assignment:** `gen_ai.usage.*` is set once, before `end()`, and never mutated after export. The conventions permit setting attributes up to `end()`; post-end mutation is undefined and silently dropped by most exporters. 3. **Referential integrity at ingest:** the `parent_span_id` of every child resolves to a span that is still open (not yet exported) at the moment the child is exported. When any condition fails, subtree aggregation is *not* a well-defined function of the exported spans. The metric is not "slightly off"; it is a function of export ordering, which is nondeterministic under async runtimes. The same agent turn can produce different token totals across two runs with identical logic. ## Decision Boundary The boundary is: **does the orchestrator's control flow join all descendant work before closing its span?** - If the orchestrator `await`s every tool and LLM call (structured concurrency, `asyncio.TaskGroup`, explicit join), condition 1 holds and aggregation at `end()` is correct. - If the orchestrator fans out and returns (fire-and-forget, detached tasks, streaming with early return), condition 1 is violated and the parent *must not* attempt subtree aggregation at `end()`. Instead it must either (a) emit only its own usage and defer aggregation to a backend that tolerates late children, or (b) hold the span open via an explicit reference-counted close that waits on outstanding child handles. The decision cannot be made per-call; it must be a property of the span's *aggregation contract*, declared at span creation. A span that declares `aggregation=subtree` and then closes with outstanding children is in an invalid state and must be flagged, not silently exported. ## Operational Effect Downstream, the corrupted metric propagates into cost attribution and budget enforcement. A budget guard that reads `agent.turn` subtree tokens will under-count by the entire fan-out tail—here 7000 of 9050 tokens, a 77% under-count. The agent's token-budget loop therefore believes it has headroom it does not have, and continues dispatching until the *provider-side* limit (which is ground truth) rejects a call. The failure surfaces not as a metric anomaly but as a hard `429`/`context_length_exceeded` mid-turn, with the trace exonerating the agent because the parent span's usage looked fine. The guardrail is a **close-time invariant check with a reference-counted span handle**: the parent span tracks outstanding child handles and refuses to `end()` (raising) if any remain, forcing the orchestrator to either join or explicitly downgrade its aggregation contract to `self-only`. A second guardrail is an ingest-time validator that rejects any span whose `end_time` precedes a known child's `end_time`, quarantining the parent rather than exporting a truncated aggregate. ```python import time from dataclasses import dataclass, field from typing import Dict, Optional class SpanClosureViolation(RuntimeError): """Raised when an agent span with subtree aggregation closes with outstanding children.""" pass class UsageAggregationError(RuntimeError): """Raised when subtree token aggregation is not well-defined due to causal ordering.""" pass @dataclass class GenAISpan: name: str parent_id: Optional[str] aggregation: str = "self-only" # or "subtree" input_tokens: int = 0 output_tokens: int = 0 start_time: float = field(default_factory=time.monotonic) end_time: Optional[float] = None _outstanding_children: int = 0 _closed: bool = False def open_child(self) -> None: if self._closed: raise SpanClosureViolation( f"span {self.name!r} is closed; cannot open child under a finalized parent" ) self._outstanding_children += 1 def close_child(self) -> None: if self._outstanding_children <= 0: raise SpanClosureViolation( f"span {self.name!r} has no outstanding children to close" ) self._outstanding_children -= 1 def end(self) -> None: if self.aggregation == "subtree" and self._outstanding_children > 0: raise SpanClosureViolation( f"span {self.name!r} declares aggregation=subtree but has " f"{self._outstanding_children} outstanding child handle(s); " f"subtree token usage would be truncated at end()" ) self.end_time = time.monotonic() self._closed = True def aggregate_subtree_usage( parent: GenAISpan, children: Dict[str, GenAISpan] ) -> Dict[str, int]: if parent.aggregation != "subtree": return { "input_tokens": parent.input_tokens, "output_tokens": parent.output_tokens, } if parent.end_time is None: raise UsageAggregationError( f"parent {parent.name!r} not yet ended; cannot aggregate" ) total_in = parent.input_tokens total_out = parent.output_tokens for child in children.values(): if child.end_time is None: raise UsageAggregationError( f"child {child.name!r} has no end_time; aggregation undefined" ) if child.end_time > parent.end_time: raise UsageAggregationError( f"causal ordering violated: child {child.name!r} ended at " f"{child.end_time:.3f} after parent {parent.name!r} at " f"{parent.end_time:.3f}; subtree usage is truncated by " f"{child.input_tokens + child.output_tokens} tokens" ) total_in += child.input_tokens total_out += child.output_tokens return {"input_tokens": total_in, "output_tokens": total_out} ```