Why does an instance lose token accounting fidelity when GenAI semantic-convention spans are closed out of order across nested tool calls

**Date of Record:** 2026 December 1 **Scope:** Applies to LLM agent runtimes that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*` attributes) for a parent agent span with nested tool-call and sub-inference spans, where token usage is accumulated via span attributes and exported to a collector. Does not apply to single-shot inference with no nested tool calls, nor to systems that buffer usage in a separate metrics pipeline independent of span lifecycle.

Core Distinction

The GenAI semantic conventions treat token accounting as a *span-local attribute* (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and their cached/reasoning variants) attached to the span that *consumed* the tokens. They do not define a parent-aggregation rule, a monotonicity guarantee, or an ordering constraint on span closure. This is fine when spans are emitted as a flat, event-ordered stream. It breaks when an agent runtime *nests* inference spans inside tool-call spans and then closes them in a different order than they were opened—a routine occurrence because tool execution is async and inference can be re-entered mid-tool (e.g., an LLM-driven sub-agent invoked inside a tool call).

The distinction that matters operationally: **token usage is a property of a span's lifetime, but aggregation is a property of the span's position in the trace tree.** When a child inference span closes *after* its parent tool span has already been ended and exported, the collector receives the child's `gen_ai.usage.*` attributes with a parent span ID that no longer has a live aggregator. The child's tokens are counted at the leaf but never rolled up to the agent-level total. The trace looks complete; the sum is silently short.

What Was Observed

A multi-tool agent (planner → retriever tool → summarizer sub-inference → writer tool) produced traces where the agent-level span reported `gen_ai.usage.input_tokens = 8,412` while the sum of all descendant `gen_ai.usage.input_tokens` was `11,907`. The delta of 3,495 tokens was exactly the input-token count of the summarizer sub-inference span. That span had been opened inside the retriever tool's execution context, but the retriever tool's `span.end()` was called when the tool's *return value* was produced—before the summarizer sub-inference, which consumed the tool output, finished streaming. The summarizer span therefore ended after its logical parent.

Reproduction trace (abbreviated, from a Jaeger export):

span_id=A1  parent=—   name=agent.run            status=OK  end=t0
span_id=B2  parent=A1  name=tool.retriever       status=OK  end=t1
span_id=C3  parent=B2  name=gen_ai.inference     status=OK  end=t2   # t2 > t1
  gen_ai.usage.input_tokens=3495
  gen_ai.usage.output_tokens=612

Because `C3.end=t2 > B2.end=t1`, the runtime's in-process aggregator (which walked the live span tree at `B2.end`) had already snapshotted `B2`'s subtree before `C3` was attached. `C3` was exported as a root-orphaned span with a dangling parent reference. The collector's trace assembler accepted it (OTLP does not require parent-before-child), but the agent-level rollup—computed at `A1.end` from the *live* tree—never saw it.

A second, subtler observation: when the runtime *did* re-aggregate at export time by walking the full span set, it double-counted. The summarizer's tokens were already included in `B2`'s `gen_ai.usage.*` because the tool had copied them in (a common "propagate child usage to parent tool span" pattern), and the export-time rollup added them again. Net error flipped from −3,495 to +3,495 depending on which aggregation path fired.

Condition of Validity

The invariant that must hold for correct token accounting is:

> **For every span `S` carrying `gen_ai.usage.*` attributes, all spans in `subtree(S)` must have ended before `S.end()` is invoked, OR the aggregation must be deferred to a post-export tree walk that is the *sole* source of truth for rollups.**

Two valid regimes exist, and mixing them is the failure:

  1. **Live-tree aggregation** (aggregate at `span.end()` from the in-memory tree). Valid *only if* the runtime enforces a strict "children end before parents" discipline—i.e., it must forbid a child span from being created or kept open inside a parent whose `end()` is imminent. This requires the tool-execution wrapper to hold the tool span open until all inference spawned from its output completes, which contradicts the natural "tool returns → tool span ends" pattern.
  2. **Export-time aggregation** (walk the exported span set, build the tree by `parent_span_id`, sum leaves). Valid *only if* no span also pre-propagates child usage into its own `gen_ai.usage.*` attributes. The moment a parent copies its children's usage, export-time rollup double-counts.

The condition of validity is therefore a *global* one: the runtime must pick exactly one aggregation regime and enforce it across every code path that touches `gen_ai.usage.*`. A runtime that uses live-tree aggregation for the agent span but propagates usage on tool spans (a very common hybrid) is invalid by construction.

Decision Boundary

The boundary is crossed at the moment a tool span's `end()` is called while a descendant inference span is still open. Concretely, the decision is: **does the tool-execution wrapper end the tool span at tool-return, or at tool-output-consumed?**

The boundary is sharp: you cannot have a tool span that (a) ends at tool-return, (b) carries propagated child usage, and (c) participates in live-tree rollup. Any two are mutually compatible; all three are not. The operational decision is which property to sacrifice—latency fidelity, usage propagation, or live rollup—and to enforce that choice at the span-emission layer, not at the dashboard.

Operational Effect

The effect is a silent, direction-inconsistent token under/over-count that is invisible to span-count and trace-completeness checks (the trace has the right number of spans; only the sum is wrong). It corrupts cost attribution per agent run, breaks budget-enforcement guardrails that read `gen_ai.usage.*` from the agent span to decide whether to halt a run, and makes token-budget exhaustion thresholds non-reproducible across runs (the same agent trajectory can trip or not trip a budget depending on tool/inference interleaving timing).

The required guardrail: a `GenAiUsageAggregationError` raised at span-close time when the runtime detects a child carrying `gen_ai.usage.*` ending after a parent that already snapshotted its subtree, or when a span's `gen_ai.usage.*` is found to already contain a descendant's contribution at export-time rollup. This converts a silent accounting drift into a hard, attributable failure at the emission boundary.

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Dict, Optional


class GenAiUsageAggregationError(RuntimeError):
    """Raised when GenAI token accounting violates the single-regime invariant."""


@dataclass
class GenAiSpan:
    span_id: str
    parent_id: Optional[str]
    name: str
    input_tokens: int = 0
    output_tokens: int = 0
    ended: bool = False
    # True if this span copied a descendant's usage into its own attributes.
    propagated_child_usage: bool = False
    children: list[str] = field(default_factory=list)


class UsageAggregator:
    """Enforces exactly one aggregation regime: live-tree OR export-time, never both."""

    def __init__(self, regime: str) -> None:
        if regime not in ("live_tree", "export_time"):
            raise GenAiUsageAggregationError(f"unknown regime {regime!r}")
        self.regime = regime
        self.spans: Dict[str, GenAiSpan] = {}

    def open(self, span: GenAiSpan) -> None:
        self.spans[span.span_id] = span
        if span.parent_id and span.parent_id in self.spans:
            self.spans[span.parent_id].children.append(span.span_id)

    def end(self, span_id: str) -> None:
        span = self.spans[span_id]
        if self.regime == "live_tree":
            # Invariant: every descendant must already be ended.
            for child_id in span.children:
                child = self.spans[child_id]
                if not child.ended:
                    raise GenAiUsageAggregationError(
                        f"span {span_id} ({span.name}) ended before descendant "
                        f"{child_id} ({child.name}); live-tree rollup would drop "
                        f"{child.input_tokens} input / {child.output_tokens} output tokens"
                    )
            if span.propagated_child_usage:
                raise GenAiUsageAggregationError(
                    f"span {span_id} ({span.name}) propagates child usage under "
                    f"live_tree regime; rollup would double-count"
                )
        else:  # export_time
            if span.propagated_child_usage:
                raise GenAiUsageAggregationError(
                    f"span {span_id} ({span.name}) pre-propagates child usage under "
                    f"export_time regime; export-time walk would double-count"
                )
        span.ended = True

    def rollup(self, root_id: str) -> tuple[int, int]:
        if self.regime == "live_tree":
            raise GenAiUsageAggregationError(
                "live_tree regime must not call export-time rollup; totals are "
                "snapshotted at end()"
            )
        total_in = total_out = 0
        stack = [root_id]
        while stack:
            sid = stack.pop()
            s = self.spans[sid]
            if not s.ended:
                raise GenAiUsageAggregationError(
                    f"rollup over unfinished span {sid} ({s.name})"
                )
            total_in += s.input_tokens
            total_out += s.output_tokens
            stack.extend(s.children)
        return total_in, total_out


def reproduce_orphan_case() -> None:
    agg = UsageAggregator(regime="live_tree")
    agg.open(GenAiSpan("A1", None, "agent.run"))
    agg.open(GenAiSpan("B2", "A1", "tool.retriever"))
    agg.open(GenAiSpan("C3", "B2", "gen_ai.inference", input_tokens=3495, output_tokens=612))
    agg.end("B2")  # tool returns before its spawned inference finishes
    agg.end("C3")
    agg.end("A1")


if __name__ == "__main__":
    reproduce_orphan_case()