# Which invariants prevent token-accounting drift across parent/child agent spans when tool-call attributes are emitted after the model-invocation event closes **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) where a single agent step (one parent `invoke_agent` span) contains one or more `chat`/model-invocation child spans plus `execute_tool` spans. Does not apply to single-shot completion logging where no parent span aggregates child token usage. ## Core Distinction The failure is not "wrong token counts on a span." It is a **temporal ordering violation**: the GenAI conventions treat `gen_ai.usage.input_tokens` / `output_tokens` as terminal attributes of a model-invocation span — they are knowable only when the response finishes. But an agent step's *total* cost is only knowable after every tool call in the step completes, because tool results get fed back into a subsequent model invocation. When a runtime emits tool-call attributes (`gen_ai.tool.name`, `gen_ai.tool.call.id`) onto the *parent* agent span lazily — after the child model span has already been finalized and exported — the parent's aggregated usage either omits the follow-up invocation or double-counts the retry. The distinction that matters: **span completion order is not the same as causal completion order**, and the semantic conventions silently assume they are. ## What Was Observed A ReAct-style agent step executed: 1. `chat` span A opens → model returns a tool call → span A closes with `input_tokens=1180, output_tokens=42`. 2. `execute_tool` span B opens → tool runs 340ms → returns a 9KB result → span B closes. 3. The runtime re-invokes the model with the tool result appended. `chat` span C opens → returns final answer → closes with `input_tokens=2410, output_tokens=88`. 4. The runtime *then* attaches `gen_ai.tool.name` and the aggregated `gen_ai.usage.*` to the **parent** `invoke_agent` span, computing the total as A+C. Under normal conditions this is correct. The failure appeared under **span-export backpressure**: the OTLP exporter batched and flushed span A before step 3 completed. Because span A had already been exported with its terminal usage, the collector's parent-aggregation logic (which sums child `gen_ai.usage.*` at parent-close time) had no way to know a *third* invocation (C) was part of the same agent step — the tool attribute that would have linked C to the parent arrived only on the parent span, never on C. Result: the parent span reported `input_tokens=2410` (only C) while the trace backend's rollup reported `1180 + 2410 = 3590`. Neither number was wrong in isolation; the **invariant that parent usage equals the sum of its children's usage at export time** was violated because one child was exported before the parent's linkage attribute existed. A second, subtler trace: on a retry path, span A was re-emitted (retry of the same model call) with the *same* `gen_ai.tool.call.id` but a new span ID. The dedup key the collector used was `(parent_span_id, tool.call.id)`, so the retry collapsed onto the original — undercounting by one full invocation's tokens. The dedup was correct for idempotent tool execution, wrong for token accounting, because a retried model call *does* consume tokens twice. ## Condition of Validity The aggregation invariant `parent.gen_ai.usage.input_tokens == Σ child.gen_ai.usage.input_tokens` holds **only if** all of the following are true: - Every model invocation that contributes to the agent step is emitted as a child span of the parent *before* the parent closes, and - No child span is exported to a backend that performs rollup *before* its final usage attributes are set, and - Retried invocations are distinguishable by span ID, not by `tool.call.id` (which is stable across retries by design and therefore unsafe as a token-accounting dedup key), and - The parent does not *also* carry aggregated usage that the backend will sum against the children (double-counting). When any of these fails, the invariant is undefined — the reported number depends on export timing, not on actual consumption. This is the boundary: token accounting is only well-defined for spans whose causal closure precedes their export. ## Decision Boundary The guardrail is a **two-phase emission rule**, not a retry or a reconciliation job: - Model-invocation spans MUST set `gen_ai.usage.*` as their *last* operation before `end()`, and MUST NOT be exported until `end()` — i.e., usage is a terminal, not incremental, attribute. - The parent `invoke_agent` span MUST NOT carry aggregated `gen_ai.usage.*` at all if any child carries it; aggregation is the backend's job, keyed on `parent_span_id`. Carrying both is the double-count trap. - Retry dedup MUST key on `(span_id)` for usage and on `(tool.call.id)` only for tool *side-effect* idempotency — these are different dedup domains and must not share a key. - If the runtime cannot guarantee causal closure before export (streaming, async tool fan-out), it MUST emit a `gen_ai.usage.partial=true` marker and the collector MUST treat the parent as non-authoritative. The decision boundary: if you cannot prove causal closure precedes export for a given agent step, do not emit aggregated usage on the parent — emit only per-child usage and let the backend roll up with explicit partial markers. ## Operational Effect Without the invariant, token dashboards drift by exactly the number of tool-call round-trips per step — typically 10–40% undercount on multi-tool agents, and *overcount* on retry-heavy agents because stable `tool.call.id` collapses retries. Cost attribution, rate-limit budgeting, and context-window-pressure alerts all inherit the error. The fix is cheap (terminal usage attributes + no parent aggregation + span-ID dedup for usage), but it must be enforced at emit time; no post-hoc reconciliation can recover the lost causal linkage once a child span has been exported ahead of its parent's linkage attribute. ```python from dataclasses import dataclass, field from typing import Optional class UsageInvariantError(RuntimeError): """Raised when parent/child GenAI token accounting cannot be proven consistent.""" pass @dataclass class GenAISpan: span_id: str parent_span_id: Optional[str] kind: str # "invoke_agent" | "chat" | "execute_tool" input_tokens: int = 0 output_tokens: int = 0 tool_call_id: Optional[str] = None usage_partial: bool = False exported: bool = False ended: bool = False def finalize_and_export(span: GenAISpan, export_fn) -> None: if not span.ended: raise UsageInvariantError( f"span {span.span_id} exported before end(); usage is not terminal" ) if span.kind == "chat" and span.usage_partial: raise UsageInvariantError( f"chat span {span.span_id} has partial usage; cannot export as terminal" ) span.exported = True export_fn(span) def aggregate_parent_usage(parent: GenAISpan, children: list[GenAISpan]) -> int: if parent.kind != "invoke_agent": raise UsageInvariantError(f"span {parent.span_id} is not an agent span") if parent.input_tokens != 0: raise UsageInvariantError( f"parent {parent.span_id} carries aggregated usage; double-count risk" ) seen_span_ids: set[str] = set() total = 0 for child in children: if child.parent_span_id != parent.span_id: raise UsageInvariantError( f"child {child.span_id} does not belong to parent {parent.span_id}" ) if child.kind != "chat": continue if not child.ended or child.usage_partial: raise UsageInvariantError( f"child {child.span_id} causal closure not proven before parent close" ) if child.span_id in seen_span_ids: raise UsageInvariantError( f"duplicate span_id {child.span_id} in aggregation" ) seen_span_ids.add(child.span_id) total += child.input_tokens + child.output_tokens return total def dedup_retries_by_tool_call(children: list[GenAISpan]) -> list[GenAISpan]: # NOTE: safe ONLY for tool side-effect idempotency, NEVER for usage. seen: dict[str, GenAISpan] = {} for c in children: if c.kind != "chat" or c.tool_call_id is None: continue if c.tool_call_id in seen and seen[c.tool_call_id].span_id != c.span_id: raise UsageInvariantError( f"retry of tool_call {c.tool_call_id} has distinct span_id " f"{c.span_id}; must count as a separate invocation, not dedup" ) seen[c.tool_call_id] = c return list(seen.values()) ```