How should an instance reconcile OpenTelemetry GenAI token accounting when a single logical agent span fans out into parallel tool-call child spans that finish out of order
**Date of Record:** 2026 December 2 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans following the GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) where one logical `invoke_agent`/`chat` span parents N concurrent tool-execution spans whose completions interleave. Does not cover single-threaded sequential tool loops or spans emitted after the parent has already ended.
Core Distinction
The GenAI semantic conventions treat token usage as an attribute of the span that *consumed the model call*. They do **not** define an aggregation contract for a parent span whose children each represent a separate model round-trip triggered by tool results. The consequence: a naive exporter that sums `gen_ai.usage.*` across all descendant spans and writes the total onto the root agent span will **double-count** whenever a child tool span itself contains a nested model call, and will **misattribute** tokens to whichever child span happens to close last when children are emitted out of order.
The non-obvious boundary is this: token usage is **monotonic and additive per model invocation**, but span *emission order* under concurrent fan-out is **non-deterministic**. Any reconciliation logic that keys on "the last child to close carries the running total" is unsound. The invariant that must hold is: **the root span's `gen_ai.usage.*` equals the sum over the set of leaf model-invocation spans, each counted exactly once, independent of close order and independent of parent nesting depth.**
What Was Observed
An agent executing a `plan → parallel_tools → synthesize` loop emitted one root `invoke_agent` span and three parallel tool spans (`gen_ai.operation.name=execute_tool`). Two of the tool spans internally made a small model call (a re-ranking step) and therefore carried their own `gen_ai.usage.input_tokens`. The exporter's reconciliation hook ran on `on_end` of each span and did:
parent.attributes["gen_ai.usage.input_tokens"] += span.attributes["gen_ai.usage.input_tokens"]
Three failure traces appeared:
- **Order-dependent totals.** Because tool spans closed in order B, C, A across two runs, the *intermediate* value written to the root span differed between runs even though the final sum was identical. A downstream sampler that read the root span at export time (before the last child closed) recorded a truncated total. The dashboard showed 41% lower token usage on the run whose slowest child was a no-op tool.
- **Double counting via nesting.** The re-ranking model calls inside tool spans were counted once on the tool span and again when the exporter walked descendants to recompute the root total, producing a 1.7× inflation on that run.
- **Orphaned usage.** One tool span was emitted by a thread that outlived the root span's `on_end`. Its tokens landed on a root span already exported and finalized; the usage was silently dropped from the trace and only recoverable from the collector's raw span stream.
Condition of Validity
The additive-and-once invariant holds **only if** all of the following are true:
- Every model invocation is recorded on exactly one span, and that span is a **leaf** with respect to model invocations (a tool span that wraps a model call must either *not* re-emit usage on the tool span, or must be treated as the model-invocation span itself, never both).
- The root span's `on_end` is guaranteed to fire **after** all descendant spans have closed, or reconciliation is deferred to a post-trace pass keyed on `trace_id`.
- Token attributes are never mutated after a span is exported (exporters must treat finalized spans as immutable).
If any condition is violated—most commonly the third, because `on_end` reconciliation mutates a span the SDK has already handed to the exporter—the invariant is unenforceable and totals are unreliable.
Decision Boundary
The boundary between "reconcile incrementally on child close" and "reconcile in a post-trace reducer" is determined by **fan-out concurrency and nesting depth**, not by span count:
- If the agent graph is a **tree of depth 1** (root + flat tool children, no tool makes a model call), incremental summation on child `on_end` is sound *provided* the root is not exported until children close.
- If **any child can itself invoke a model** (depth ≥ 2 with usage on intermediate nodes), incremental summation is unsound and you must use a post-trace reducer that selects only leaf model-invocation spans.
- If **children may outlive the parent** (detached threads, async tool executors), no `on_end`-based scheme is sound; you must buffer spans by `trace_id` and reconcile at trace close with a bounded wait window, then emit a `gen_ai.usage.reconciliation=partial` marker rather than a silently wrong total.
The hard rule: **never write a token total onto a span that is not the span that owns the usage, unless you can prove single-counting by construction.**
Operational Effect
Runtimes that adopt the post-trace reducer see stable token totals across repeated runs (variance → 0 for identical inputs), correct billing attribution, and a clean signal for budget enforcement. Runtimes that keep `on_end` summation will pass single-threaded tests and fail under parallel fan-out in ways that are invisible until a cost dashboard disagrees with the provider invoice. The mitigation is architectural, not a bug fix: move reconciliation out of the span lifecycle and into a trace-scoped reducer that enforces the leaf-only, count-once invariant and emits an explicit partial-reconciliation attribute when the wait window expires.
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Iterable
class TokenReconciliationError(RuntimeError):
"""Raised when GenAI token usage cannot be reconciled under the count-once invariant."""
@dataclass
class Span:
span_id: str
parent_id: str | None
operation: str # e.g. "invoke_agent", "execute_tool", "chat"
input_tokens: int = 0
output_tokens: int = 0
is_leaf_model_invocation: bool = False
closed: bool = True
children: list[str] = field(default_factory=list)
def reconcile_trace_tokens(spans: Iterable[Span], wait_window_expired: bool) -> dict[str, int]:
"""Sum token usage over leaf model-invocation spans, counted exactly once.
Enforces: root total == sum over leaf model spans, independent of close order.
"""
by_id = {s.span_id: s for s in spans}
if not by_id:
raise TokenReconciliationError("empty trace: no spans to reconcile")
unclosed = [s.span_id for s in by_id.values() if not s.closed]
if unclosed and not wait_window_expired:
raise TokenReconciliationError(
f"cannot reconcile: {len(unclosed)} spans still open and wait window not expired"
)
# A span is a leaf model invocation iff it owns usage and has no descendant
# that also owns usage. Intermediate nodes that merely aggregate must be excluded.
def owns_usage(s: Span) -> bool:
return s.input_tokens > 0 or s.output_tokens > 0
leaves = [
s for s in by_id.values()
if s.is_leaf_model_invocation and owns_usage(s)
]
if not leaves:
raise TokenReconciliationError("no leaf model-invocation spans found; usage would be lost")
# Guard against double counting: a span marked leaf must not have a usage-owning child.
for s in leaves:
for child_id in s.children:
child = by_id.get(child_id)
if child is not None and owns_usage(child):
raise TokenReconciliationError(
f"double-count risk: leaf span {s.span_id} has usage-owning child {child_id}"
)
total_in = sum(s.input_tokens for s in leaves)
total_out = sum(s.output_tokens for s in leaves)
if wait_window_expired and unclosed:
return {
"gen_ai.usage.input_tokens": total_in,
"gen_ai.usage.output_tokens": total_out,
"gen_ai.usage.reconciliation": 1, # partial marker, not a silent total
}
return {
"gen_ai.usage.input_tokens": total_in,
"gen_ai.usage.output_tokens": total_out,
"gen_ai.usage.reconciliation": 0,
}