Which invariants prevent token-accounting drift from corrupting OTel GenAI agent span trees across retry and fan-out boundaries

**Date of Record:** 2026 December 2 **Scope:** Applies to any agent runtime that emits OpenTelemetry `gen_ai.*` spans where a single logical agent turn fans out into multiple tool calls, model invocations, or retries, and where token usage is aggregated upward into a parent span. Does not apply to single-shot, single-span inference calls with no parent/child token rollup.

Core Distinction

The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes on the *model invocation* span (`gen_ai.operation.name = "chat"`). They do **not** define an aggregation contract for parent agent spans (`gen_ai.operation.name = "invoke_agent"` or `"execute_tool"`). This gap is the entire problem. A parent agent span's token total is a *derived* quantity computed by the SDK or collector, and derivation is where drift enters.

The distinction that matters operationally: a **model invocation span** owns an authoritative, provider-reported usage tuple. An **agent span** owns only a *sum over children that the runtime chose to include*. When retries, speculative fan-out, or tool-mediated sub-invocations occur, the set of children whose tokens "count" toward the parent is not defined by the spec — it is defined by the emit-time policy of whoever wrote the span code. Two runtimes can emit identical span trees and disagree on the parent total by 2–3× purely from retry-inclusion policy. Downstream cost attribution, budget enforcement, and loop-detection heuristics all read that parent total.

What Was Observed

A planner agent (`invoke_agent` span, root) issued a `chat` call that the provider rejected with a 429 at the transport layer. The runtime's retry wrapper re-issued the request. The first attempt had already streamed 1,842 input tokens (the prompt was accepted; the failure was mid-stream on rate-limit backpressure). The retry re-sent the full prompt: another 1,842 input tokens, plus 610 output tokens on success.

The span tree emitted was:

The root total was correct *by accident*: the SDK's aggregator deduplicated by `gen_ai.request.id` and counted only the successful child. But the same runtime, three turns later, emitted a `execute_tool` span that fanned out to two parallel `chat` sub-invocations (a self-consistency check), and the aggregator summed **both** children into the tool span — inflating the tool's attributed cost by exactly the duplicate. The dedup rule keyed on request ID, and the two fan-out children had distinct request IDs, so they were both counted. The retry case and the fan-out case were governed by the same aggregation code but produced opposite correctness outcomes because the *semantic intent* differed (retry = one logical call, fan-out = two logical calls) while the *mechanical signal* (request ID equality) did not.

The drift surfaced as a budget alarm: the agent's per-turn token budget was enforced against the parent `invoke_agent` total, which had accumulated fan-out duplicates across 14 turns. The runtime tripped its budget guardrail and hard-halted an agent that had consumed 61% of its actual allowance. This is the failure mode: **the guardrail fired on a derived quantity that exceeded the true quantity because the aggregation invariant was never stated.**

Condition of Validity

The invariant that must hold for parent-span token totals to be trustworthy:

> For every agent span S, `S.usage == sum over the set of *logical* model invocations L(S) of the authoritative usage tuple reported by the provider for each l in L(S)`, where L(S) is the set of invocations the runtime *intends* to bill to S, and retries of a single logical invocation contribute exactly one element to L(S) — the successful one, or the last-attempted one if all fail.

This invariant is only valid when three conditions hold:

  1. **Retry identity is explicit, not inferred.** The runtime must tag retried attempts with a stable `gen_ai.request.id` *or* an explicit `retry.attempt` counter on the child, and the aggregator must key dedup on that tag — not on span name, not on timing proximity.
  2. **Fan-out intent is explicit.** Parallel sub-invocations that are *logically distinct* (self-consistency samples, ensemble votes) must be distinguishable from *logically identical* parallel attempts (hedged requests). Hedged requests are retries and must dedup; ensemble samples must not. Without an explicit `gen_ai.fanout.role = "sample" | "hedge"` (or equivalent), the aggregator cannot decide, and will pick one policy for both.
  3. **Failed-attempt tokens are accounted, not discarded.** A 429 that consumed 1,842 input tokens before failing still cost money. If the aggregator sums only `OK` children, the parent total *under*-reports true spend. The correct policy: count failed attempts' provider-reported usage toward the parent, but count each logical invocation once. These two rules (count failures; dedup retries) are independent and both must be stated, because a naive "sum all children" satisfies the first and violates the second, while "sum only OK children" satisfies the second and violates the first.

The invariant is **invalid** — and the parent total must be treated as advisory-only — when any of the three conditions is unmet. In that case the only trustworthy number is the per-`chat`-span usage attribute, and any budget guardrail must be enforced at the leaf level, not the agent level.

Decision Boundary

The decision the runtime must make at emit time, for each child model invocation, is: *does this child's usage roll into the parent's total, and if so, as a new logical invocation or as a replacement for a prior attempt?* The boundary is crossed wrongly in three specific ways:

The safe decision rule: **roll up failed attempts' usage (they cost money), dedup retries by an explicit attempt-identity tag, and never dedup fan-out samples (they are distinct logical invocations).** If the runtime cannot emit the attempt-identity tag or the fan-out role tag, it must not emit a parent token total at all — emit the leaf spans and let the collector aggregate with a policy it declares.

Operational Effect

When the invariant holds, the parent `invoke_agent` token total is a sound input to budget enforcement, cost attribution, and loop detection (a runaway agent shows monotonic parent-token growth per turn). When it is violated, three downstream systems corrupt simultaneously and silently:

The guardrail that bounds the failure: **enforce budgets at the leaf `chat` span, where usage is authoritative and provider-reported, and treat the parent total as a derived, advisory metric that must carry an explicit `gen_ai.usage.aggregation_policy` attribute naming the dedup and failure-inclusion rules used.** A parent total without that attribute is not a number an agent should make decisions on. The invariant is not "sum the children" — it is "sum the children under a declared policy, and refuse to enforce on the sum when the policy is undeclared."

class TokenAggregationInvariantError(RuntimeError):
    """Raised when a parent agent span's token total cannot be soundly derived
    from its child model-invocation spans under the declared policy."""
    pass


def aggregate_agent_usage(children: list[dict], policy: dict) -> dict:
    """
    children: list of leaf chat-span dicts, each with keys:
        request_id, attempt (int|None), fanout_role ('sample'|'hedge'|None),
        status ('OK'|'ERROR'), input_tokens, output_tokens
    policy: {'dedup': 'attempt_id'|'request_id'|'none',
             'include_failed': bool,
             'require_fanout_role': bool}
    """
    if policy.get("require_fanout_role"):
        for c in children:
            if c.get("fanout_role") is None and policy["dedup"] == "request_id":
                # request_id dedup is only sound when fan-out intent is explicit;
                # a child with no role tag makes the dedup decision ambiguous.
                raise TokenAggregationInvariantError(
                    f"child {c['request_id']} has no fanout_role but policy "
                    "dedups by request_id; cannot distinguish hedged retry "
                    "from ensemble sample — parent token total is unsound"
                )

    # Step 1: drop failed attempts only if policy says so; otherwise they
    # are billable and must be counted.
    billable = [c for c in children if policy["include_failed"] or c["status"] == "OK"]

    # Step 2: dedup retries. Only 'attempt_id' dedup is sound across both
    # retry and fan-out; 'request_id' collapses fan-out samples wrongly.
    if policy["dedup"] == "attempt_id":
        seen: dict = {}
        for c in billable:
            key = c.get("attempt") if c.get("attempt") is not None else c["request_id"]
            # keep the last attempt of each logical invocation (the one whose
            # usage reflects the final provider state)
            seen[key] = c
        counted = list(seen.values())
    elif policy["dedup"] == "none":
        counted = billable
    else:
        raise TokenAggregationInvariantError(
            f"unsupported dedup policy {policy['dedup']!r}; request_id dedup "
            "is unsound for fan-out — use attempt_id or none"
        )

    total_in = sum(c["input_tokens"] for c in counted)
    total_out = sum(c["output_tokens"] for c in counted)

    if total_in < 0 or total_out < 0:
        raise TokenAggregationInvariantError(
            "negative token total; child usage tuple is corrupt"
        )
    return {
        "input_tokens": total_in,
        "output_tokens": total_out,
        "aggregation_policy": policy["dedup"],
        "children_counted": len(counted),
    }


def enforce_turn_budget(agent_span: dict, budget: int) -> None:
    """Enforce budget on the leaf-authoritative total, never on an
    undeclared parent rollup."""
    if "gen_ai.usage.aggregation_policy" not in agent_span:
        raise TokenAggregationInvariantError(
            "parent agent span has no declared aggregation_policy; "
            "refusing to enforce budget on an unsound derived total"
        )
    if agent_span["gen_ai.usage.input_tokens"] > budget:
        raise TokenAggregationInvariantError(
            f"turn budget exceeded: {agent_span['gen_ai.usage.input_tokens']} "
            f"> {budget} under policy {agent_span['gen_ai.usage.aggregation_policy']}"
        )