# Which invariants prevent token-accounting drift when OpenTelemetry GenAI spans are re-parented across agent handoffs **Date of Record:** 2026 November 25 **Scope:** Applies to multi-agent systems that emit OpenTelemetry spans using the GenAI semantic conventions (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, `gen_ai.system`) and that hand off execution between agent instances via link-based or re-parented span contexts. Does not cover single-agent tracing, nor cost aggregation performed purely from billing-side metering. ## Core Distinction The GenAI semantic conventions treat a span's `gen_ai.usage.*` attributes as *terminal, additive facts about a single model invocation*. The tracing model, however, treats parent/child relationships as *structural, mutable topology*. These two contracts collide at handoff boundaries. When agent A delegates to agent B, the natural instrumentation pattern is to start B's span as a child of A's span so the trace tree reads as a call graph. But a child span's usage attributes are, by the conventions, still additive — a naive collector that sums `gen_ai.usage.input_tokens` over all spans in a trace will double-count the moment a delegated agent re-emits or inherits the parent's prompt context. The distinction that matters: **usage accounting is per-span and non-inheritable; lineage is per-trace and inheritable.** Any implementation that lets lineage imply inheritance of usage has already broken the invariant. ## What Was Observed A three-tier pipeline (planner → executor → verifier) instrumented each hop as a child span. The planner span recorded `input_tokens=8200, output_tokens=640`. The executor received the planner's full output plus a 6k-token tool schema and recorded `input_tokens=9100`. The verifier received planner output + executor output + rubric and recorded `input_tokens=11800`. A dashboard summing `gen_ai.usage.input_tokens` across the trace reported 29,100 input tokens. The actual provider-side bill was 19,940. The gap (9,160) equals the re-transmitted planner context counted once per downstream hop. No span was malformed; every span faithfully described its own invocation. The corruption arose purely at the aggregation layer, driven by the assumption that a parent-child edge means "child's tokens are a subset of parent's." A second, subtler failure appeared on retry. When the executor's first attempt failed with a tool timeout and was retried as a *sibling* span (same parent, new span ID, `retry.count=1`), the two executor spans both carried full `input_tokens`. The trace now had two sibling spans each claiming the same logical work. Summation doubled the executor's cost; a `min()`-based dedup undercounted because the retry legitimately consumed fresh tokens. ## Condition of Validity The additive-usage invariant holds **only if** every span in a trace represents a *disjoint* model invocation whose prompt is not a superset of any other span's prompt on the same trace path. This is violated whenever: 1. **Context forwarding** — a child agent's prompt includes the parent's prompt verbatim (the common case in planner/executor/verifier topologies). 2. **Retry-as-sibling** — a retried invocation is emitted as a new span with the same logical identity rather than as a span event on the original. 3. **Handoff re-emission** — an agent restates its received context into a new span's `gen_ai.prompt` events, and a downstream exporter derives usage from prompt length rather than from the provider's reported `usage` block. In all three, the per-span usage attributes remain individually correct. The invariant that fails is the *aggregation* invariant: `sum(usage) over trace == provider-billed usage`. That equality is only valid on a trace where prompts are disjoint. The GenAI conventions do not enforce disjointness; they only define the attribute schema. The guardrail must live in the collector or the instrumentation wrapper. ## Decision Boundary The boundary is: **does the child span's prompt contain tokens already billed on an ancestor span?** - If **no** (fan-out to independent sub-tasks, parallel tool calls with distinct inputs) → additive summation across the trace is valid; parent-child edges are safe. - If **yes** (sequential handoff with context forwarding) → the trace must carry a `gen_ai.usage.forwarded_tokens` (or equivalent) attribute recording how many input tokens were inherited from the parent, and the aggregator must compute `sum(input_tokens - forwarded_tokens)`. Without this, the trace is not summable and must be flagged. - If **retry** → the retry span must be distinguished either as a span *event* on the original span (preserving one logical invocation) or as a sibling carrying `gen_ai.usage.retry_of=`, with aggregation taking `max` over the retry group, not `sum`. The failure mode is silent: no span is invalid, no attribute is out of schema, and the trace renders correctly in a waterfall view. Only the cost and budget-enforcement paths observe the drift, and they observe it as a number that is simply wrong. ## Operational Effect Budget enforcement built on trace-summed tokens over-fires: an agent that forwards context through three hops appears to consume ~1.5× its real budget, tripping circuit breakers early and starving downstream work. Conversely, `max`-based dedup under-fires on legitimate retries, letting a flaky tool loop exhaust provider quota before the breaker trips. The correct posture is to make forwarded-token accounting an explicit instrumentation obligation — emit `forwarded_tokens` at every handoff, reject traces where `forwarded_tokens > 0` but the aggregator lacks a forwarding-aware reducer, and treat retry spans as a distinct aggregation class. The invariant to encode: *a trace is cost-summable iff every span's input-token set is disjoint from its ancestors' input-token sets; otherwise the trace is a lineage graph, not a cost ledger.* ```python from dataclasses import dataclass from typing import Iterable class TokenAccountingDrift(RuntimeError): """Raised when trace-level token summation would double-count forwarded context.""" pass @dataclass class GenAISpan: span_id: str parent_id: str | None input_tokens: int output_tokens: int forwarded_tokens: int = 0 # tokens inherited verbatim from parent prompt retry_of: str | None = None def aggregate_trace_usage(spans: Iterable[GenAISpan]) -> tuple[int, int]: """Return (billed_input, billed_output) for a trace, or raise on drift.""" by_id = {s.span_id: s for s in spans} billed_in = 0 billed_out = 0 for s in spans: # Retry spans: count once per retry group via max, not sum. if s.retry_of is not None: continue if s.forwarded_tokens > s.input_tokens: raise TokenAccountingDrift( f"span {s.span_id}: forwarded_tokens={s.forwarded_tokens} " f"exceeds input_tokens={s.input_tokens}" ) # Walk ancestors: forwarded tokens must not exceed any ancestor's billed share. ancestor = by_id.get(s.parent_id) if s.parent_id else None while ancestor is not None: if s.forwarded_tokens > ancestor.input_tokens: raise TokenAccountingDrift( f"span {s.span_id} forwards {s.forwarded_tokens} tokens but " f"ancestor {ancestor.span_id} only billed {ancestor.input_tokens}" ) ancestor = by_id.get(ancestor.parent_id) if ancestor.parent_id else None billed_in += s.input_tokens - s.forwarded_tokens billed_out += s.output_tokens # Fold retry groups: take max input/output per retry_of target. retry_groups: dict[str, list[GenAISpan]] = {} for s in spans: if s.retry_of is not None: retry_groups.setdefault(s.retry_of, []).append(s) for target, group in retry_groups.items(): if target not in by_id: raise TokenAccountingDrift( f"retry group references missing span {target}" ) billed_in += max(g.input_tokens - g.forwarded_tokens for g in group) billed_out += max(g.output_tokens for g in group) return billed_in, billed_out def enforce_summable_trace(spans: list[GenAISpan]) -> None: """Guardrail: reject traces whose lineage cannot be reduced to a cost ledger.""" for s in spans: if s.parent_id is not None and s.forwarded_tokens == 0: parent = next((p for p in spans if p.span_id == s.parent_id), None) if parent is not None and s.input_tokens > parent.output_tokens: # Child input exceeds what parent could have emitted: context was # forwarded from further up but not declared. Not summable. raise TokenAccountingDrift( f"span {s.span_id} input_tokens={s.input_tokens} exceeds " f"parent {parent.span_id} output_tokens={parent.output_tokens} " f"without forwarded_tokens declaration" ) ```