# Which invariants prevent token-usage double-counting when GenAI agent spans are re-parented across a tool-call boundary **Date of Record:** 2026 November 26 **Scope:** Applies to OpenTelemetry-instrumented agent runtimes that emit `genai.*` spans (agent invocation, tool call, model chat) and aggregate `genai.usage.input_tokens` / `genai.usage.output_tokens` from span attributes. Does not apply to single-shot completion tracing where each request maps 1:1 to one span and no parent re-parenting occurs. ## Core Distinction The failure is not "missing token counts" — it is *double-counted* token counts caused by a semantic mismatch between span **parenting** and attribute **propagation**. In the GenAI semantic conventions, `genai.usage.*` attributes are recorded on the span that *represents the model invocation* (`genai.operation.name = chat`). But agent runtimes frequently emit a **wrapper agent span** that also records the aggregate usage of all child model calls as a convenience rollup. When the wrapper span is re-parented (e.g., a tool-call span is detached from the agent span to break a cyclic trace, or a sub-agent span is flattened into the parent's context), the rollup attribute travels with the wrapper while the child chat spans travel elsewhere. Any collector that sums `genai.usage.*` across all spans in a trace now counts those tokens twice: once on the wrapper, once on the leaf chat spans. The invariant that must hold is: **for any trace, exactly one span in each ancestor-chain records a given token unit, and that span is the leaf `chat` span — never an ancestor rollup.** ## What Was Observed A planner agent (`genai.operation.name = invoke_agent`) issued three tool calls, each of which triggered a nested `chat` span. The runtime set `genai.usage.input_tokens` on the agent span to the sum of the three chat spans (a "total" convenience attribute), and also set it on each chat span. Under normal conditions the trace was a clean tree and the collector's `sum(genai.usage.input_tokens)` over-counted by 2x — but this was masked because the dashboard query filtered to `genai.operation.name = chat`. The latent bug surfaced only when a tool-call span was re-parented: a downstream retry detached the second tool-call span and re-attached it under a new `invoke_agent` span (the retry wrapper). The retry wrapper inherited the *full* three-call rollup from the original parent as a span link attribute, while the leaf chat spans remained under the original tree. Now the collector's per-trace aggregation, which had been filtering by `chat`, was augmented by a "rollup" query keyed on `invoke_agent` spans — and both the original agent span and the retry wrapper carried the same three-call total. Result: a 2x over-count in the cost ledger for exactly the retried tool call, invisible in per-span views, visible only in trace-level sum. The trigger condition is precise: **an ancestor span carries an aggregate `genai.usage.*` value, and that ancestor is duplicated or re-parented while its leaf descendants are not.** The re-parenting need not be a retry; it also occurs when a sub-agent is promoted to a top-level trace, when a span is exported twice under different `trace_id` values due to a batch-exporter retry, or when a tool-call span crosses a process boundary and is re-emitted by the receiving side with the parent's attributes copied forward. ## Condition of Validity The single-recording invariant is valid only under these conditions, and the guardrail must assert all of them: 1. **Leaf-ownership:** `genai.usage.*` is authoritative only on spans with `genai.operation.name = chat` (or `embeddings`/`generate_content` as applicable). Any ancestor span carrying the same attribute is a *derived* value and must be tagged `genai.usage.aggregate = true` or omitted entirely. 2. **No cross-span propagation:** When a span is re-parented, cloned, or re-emitted, the propagation step must strip `genai.usage.*` from ancestor spans unless the leaf spans it summarizes are also present in the same `trace_id`. If leaves are absent, the aggregate is a dangling rollup and must not be summed. 3. **Idempotent export:** The batch exporter must dedupe on `(trace_id, span_id)` before the collector aggregates; a re-exported span with the same `span_id` but a different parent must not be treated as a second token-bearing span. 4. **Token-usage is monotonic per span, not per trace:** A given `span_id` may only ever report one final `genai.usage.*` value; late-arriving updates must replace, not add. ## Decision Boundary The boundary is: **does the aggregator trust ancestor rollups or leaf spans?** If the aggregator sums all spans carrying `genai.usage.*`, it is vulnerable to every re-parenting event and every duplicated export. If it sums only leaf `chat` spans, it is robust to re-parenting but loses the ability to attribute tokens to a failed agent span whose leaf chat spans were never emitted (e.g., context-window exhaustion before the first model call). The correct decision is a *hybrid with a staleness rule*: sum leaf `chat` spans; for any `invoke_agent` span that has **zero** descendant `chat` spans in the trace, fall back to its rollup attribute *only if* it is not marked `genai.usage.aggregate = true` and no sibling span in the same trace carries an overlapping rollup. The invariant is enforced at the collector, not the SDK, because the SDK cannot see re-parenting that happens in the exporter or downstream. ## Operational Effect Without the guardrail, retried tool calls silently inflate cost ledgers by exactly the fraction of the trace that was retried, and the inflation is invisible to per-span dashboards because each span reports a locally-correct value. With the guardrail, the collector rejects any trace where a leaf `chat` span and an ancestor rollup both contribute to the same `(trace_id, usage_dimension)` sum, emitting a `genai.usage.aggregate_conflict` counter instead. The operational effect is that cost attribution becomes reconstructable from trace topology alone: a token unit is owned by exactly one leaf span, and any ancestor value is a derived view that must be independently verifiable against its descendants before it is summed. ```python class GenAiUsageInvariantError(RuntimeError): """Raised when a trace violates single-recording ownership of genai.usage.* attributes.""" pass LEAF_OPERATIONS = {"chat", "embeddings", "generate_content"} def aggregate_trace_usage(spans: list[dict]) -> dict: """ Sum genai.usage.* across a trace under the single-recording invariant. `spans` is a list of OTel span dicts with at least: span_id, trace_id, parent_span_id, attributes. Raises GenAiUsageInvariantError if ownership is ambiguous. """ by_id = {s["span_id"]: s for s in spans} trace_ids = {s["trace_id"] for s in spans} if len(trace_ids) != 1: raise GenAiUsageInvariantError( f"expected one trace_id, got {sorted(trace_ids)}" ) def descendants(span_id: str) -> list[dict]: out, stack = [], [span_id] while stack: cur = stack.pop() for s in spans: if s.get("parent_span_id") == cur: out.append(s) stack.append(s["span_id"]) return out totals = {"input_tokens": 0, "output_tokens": 0} rollup_owners: list[str] = [] for s in spans: attrs = s.get("attributes", {}) op = attrs.get("genai.operation.name") carries_usage = ( "genai.usage.input_tokens" in attrs or "genai.usage.output_tokens" in attrs ) if not carries_usage: continue if op in LEAF_OPERATIONS: totals["input_tokens"] += attrs.get("genai.usage.input_tokens", 0) totals["output_tokens"] += attrs.get("genai.usage.output_tokens", 0) continue # Ancestor carrying usage: only valid as a fallback when it has # no leaf descendants in this trace, and is not marked as aggregate. leaves = [d for d in descendants(s["span_id"]) if d.get("attributes", {}).get("genai.operation.name") in LEAF_OPERATIONS] if leaves: if not attrs.get("genai.usage.aggregate"): raise GenAiUsageInvariantError( f"span {s['span_id']} (op={op}) carries genai.usage.* " f"but has {len(leaves)} leaf descendants; " f"rollup must be tagged genai.usage.aggregate=true" ) rollup_owners.append(s["span_id"]) continue # No leaf descendants: dangling rollup, admissible as fallback. totals["input_tokens"] += attrs.get("genai.usage.input_tokens", 0) totals["output_tokens"] += attrs.get("genai.usage.output_tokens", 0) if len(rollup_owners) > 1: raise GenAiUsageInvariantError( f"multiple aggregate rollups in trace: {rollup_owners}; " f"re-parenting duplicated an ancestor usage attribute" ) return totals ```