Where must an instance reconcile OpenTelemetry GenAI spans when a tool-call graph is flattened by async fan-out and token counts are double-attributed
**Date of Record:** 2026 December 1 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`) for multi-step tool-calling loops, where child tool spans are dispatched asynchronously and token usage is reported both on the `chat` span and aggregated at the run root. Does not apply to single-shot completions with no tool fan-out, nor to runtimes that emit exactly one span per model invocation with no parent aggregation.
Core Distinction
The GenAI semantic conventions model a model invocation as a span carrying `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`, with tool calls represented either as span events on the invoking span or as child spans of kind `tool`. The convention is silent on a critical structural question: when an agent fans out N parallel tool calls from a single reasoning step, do the N tool spans nest under the `chat` span that requested them, or under the agent/run span that owns the loop? Most SDK instrumentations choose the latter because the tool executor is a separate async task that has already detached from the `chat` span's context by the time it runs. The result is a *flattened* trace: the causal edge from the model's decision to the tool execution is lost, and the only remaining signal is temporal adjacency plus a `tool_call_id` attribute that nobody validates against the model's output.
The non-obvious consequence is token accounting. Because the tool spans are no longer children of the `chat` span, a naive aggregation that sums `gen_ai.usage.*` over all spans in a trace *double-counts* the prompt tokens: the `chat` span reports the full input (system prompt + history + tool schemas), and each tool span, if instrumented to report the tokens of the tool's *result ingestion* on the follow-up turn, reports the same prefix again. Worse, the run root span — added by most agent frameworks — typically re-reports the cumulative usage of the whole run. Three layers of `gen_ai.usage.input_tokens` exist in one trace, and no attribute in the spec disambiguates "this span's own consumption" from "this span's subtree total."
What Was Observed
A four-tool research agent (search, fetch, extract, summarize) was traced under `opentelemetry-instrumentation-anthropic` plus a custom tool wrapper. On a run with three parallel `fetch` calls:
- The `chat` span (`span_id=A`) carried `input_tokens=8420`, `output_tokens=310`, and three `gen_ai.tool.call` events with `tool_call_id` values `t1,t2,t3`.
- Three `tool` spans (`span_id=B,C,D`) were emitted with `parent_span_id=ROOT`, not `A`, because the executor awaited `asyncio.gather` on tasks created after the `chat` span had ended. Each carried `gen_ai.usage.input_tokens=0` but the *next* `chat` span (`span_id=E`) reported `input_tokens=8420 + 3×fetched_content_tokens`, re-billing the original 8420.
- The run root span reported `input_tokens = 8420 + (8420+Δ) = 16840+Δ`, i.e., the sum of both chat spans, which is correct as a *cumulative* figure but indistinguishable from a *per-invocation* figure to any consumer that sums leaf spans.
A downstream cost dashboard summed `gen_ai.usage.input_tokens` over spans where `gen_ai.operation.name == "chat"` and got 16840+Δ — correct. A second dashboard summed over *all* spans with any `gen_ai.usage.*` and got 16840+Δ as well, because tool spans reported zero. But a third consumer — a token-budget guard that summed usage over the *subtree* of each `tool` span to attribute cost to a tool — got zero for every tool, because the tool spans had no usage children and the re-billed prefix lived on a sibling, not a descendant. The guard under-counted tool cost to zero and allowed a runaway loop to burn the budget.
The failure is not the double-count itself. It is that **the span tree's parent-child edges no longer encode the causal attribution that the token attributes assume.** The spec's usage attributes are span-local, but consumers treat the tree as an accounting hierarchy.
Condition of Validity
The invariant that makes naive aggregation correct is: *for every span S carrying `gen_ai.usage.*`, the tokens reported are consumed by S's own operation and are not re-reported by any ancestor or sibling.* This holds only when:
- Tool spans are children of the `chat` span that emitted the corresponding `tool_call_id`, AND
- The follow-up `chat` span does not re-report the prefix already billed on the prior `chat` span, OR the runtime emits an explicit `gen_ai.usage.cache_read_input_tokens` / delta convention that consumers subtract.
Neither condition is enforced by the spec. The first fails under async fan-out; the second fails under any provider that bills the full context window per turn (most do). The invariant therefore holds only for single-turn, single-tool, synchronous traces — a vanishingly small fraction of agent runs.
Decision Boundary
An instance must treat the trace as a *DAG of attributions*, not a tree of costs, at exactly the moment it observes any of:
- A `tool` span whose `parent_span_id` is not the `chat` span whose events reference the same `tool_call_id`.
- Two or more `chat` spans in one trace with monotonically increasing `input_tokens` where the delta equals a prior span's `input_tokens` plus tool output — the signature of prefix re-billing.
- A root span whose `gen_ai.usage.input_tokens` exceeds the sum of its direct `chat` children — meaning cumulative and per-call semantics are mixed in one trace.
Below this boundary (single synchronous call, no tool fan-out), summing leaf usage is safe. Above it, the instance must *not* aggregate by tree position. It must instead reconstruct cost by joining `tool_call_id` → `chat` span event → tool span, and by subtracting `cache_read_input_tokens` (or the prior turn's `input_tokens`) from each successive `chat` span to recover the marginal delta.
Operational Effect
The practical guardrail is a reconciliation pass that runs before any budget or cost decision, and that refuses to proceed when the trace violates the attribution invariant rather than silently under- or over-counting. It must raise, not guess, because both failure directions are unsafe: under-counting lets a loop exhaust budget, over-counting trips a false circuit-breaker mid-task and loses the checkpoint. The pass computes marginal input tokens per `chat` span as `input_tokens - prior_chat.input_tokens` (clamped at zero), attributes tool output tokens to the tool span via the `tool_call_id` join, and asserts that the sum of marginals plus the first span's full input equals the root's cumulative figure within a tolerance. When the join is missing — the flattened-fan-out case — it fails closed.
class SpanAttributionError(RuntimeError):
"""Raised when a GenAI trace cannot be reconciled to a single cost attribution."""
pass
def reconcile_genai_trace(spans: list[dict], tolerance: int = 0) -> dict:
"""
Reconcile gen_ai.usage.* across a tool-call trace.
spans: list of dicts with keys span_id, parent_span_id, operation,
input_tokens, output_tokens, tool_call_ids (list), cache_read_input_tokens.
Returns marginal attribution per span. Raises SpanAttributionError if the
causal edges required for attribution are absent or inconsistent.
"""
by_id = {s["span_id"]: s for s in spans}
chats = [s for s in spans if s["operation"] == "chat"]
tools = [s for s in spans if s["operation"] == "tool"]
roots = [s for s in spans if s["parent_span_id"] is None]
if len(roots) != 1:
raise SpanAttributionError(f"expected exactly one root span, got {len(roots)}")
# 1. Every tool span must be causally linked to a chat span by tool_call_id.
chat_call_ids = {}
for c in chats:
for cid in c.get("tool_call_ids", []):
if cid in chat_call_ids:
raise SpanAttributionError(
f"tool_call_id {cid} emitted by two chat spans "
f"{chat_call_ids[cid]} and {c['span_id']}"
)
chat_call_ids[cid] = c["span_id"]
for t in tools:
cid = t.get("tool_call_id")
if cid is None:
raise SpanAttributionError(
f"tool span {t['span_id']} has no tool_call_id; cannot attribute"
)
if cid not in chat_call_ids:
raise SpanAttributionError(
f"tool span {t['span_id']} references unknown tool_call_id {cid}"
)
# Flattened fan-out detection: tool span must sit under its issuing chat span.
if t["parent_span_id"] != chat_call_ids[cid]:
raise SpanAttributionError(
f"tool span {t['span_id']} parent={t['parent_span_id']} but issuing "
f"chat span is {chat_call_ids[cid]}; trace is flattened, "
f"tree-position aggregation would misattribute tokens"
)
# 2. Recover marginal input tokens per chat span (prefix re-billing correction).
chats_sorted = sorted(chats, key=lambda s: s.get("start_time_ns", 0))
marginals = {}
prior = 0
for c in chats_sorted:
marginal = c["input_tokens"] - prior - c.get("cache_read_input_tokens", 0)
if marginal < 0:
raise SpanAttributionError(
f"chat span {c['span_id']} reports input_tokens={c['input_tokens']} "
f"less than prior cumulative {prior}; usage attributes are "
f"not monotonic, cannot derive marginal cost"
)
marginals[c["span_id"]] = marginal
prior = c["input_tokens"]
# 3. Root cumulative must equal the sum of marginals plus first full input.
root = roots[0]
expected = sum(marginals.values()) + (chats_sorted[0]["input_tokens"] if chats_sorted else 0)
if abs(root["input_tokens"] - expected) > tolerance:
raise SpanAttributionError(
f"root cumulative input_tokens={root['input_tokens']} but reconciled "
f"sum={expected}; trace mixes cumulative and per-call semantics"
)
return {
"marginal_input_tokens": marginals,
"tool_output_tokens": {t["span_id"]: t.get("output_tokens", 0) for t in tools},
"reconciled_total": expected,
}