Which invariants prevent GenAI agent-span attribute loss across tool-call fan-out when token accounting propagates through nested spans

**Date of Record:** 2026 December 1 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans per LLM invocation and per tool call, where token usage and cost attributes must aggregate from leaf tool spans up to the root agent span. Does not cover single-shot, single-span inference calls with no nested tool execution, nor does it cover billing reconciliation against provider invoices.

Core Distinction

The failure here is not "missing telemetry" in the naive sense—spans are emitted, they are exported, and they land in the backend. The failure is **attribute provenance collapse**: the `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` attributes and their derived cost attributes are set at *different* span layers by *different* code paths, and the aggregation step at the root agent span silently treats "attribute absent" and "attribute zero" as the same thing.

Concretely: an LLM invocation span carries real token counts from the provider response. A tool-call span (`gen_ai.operation.name = "execute_tool"`) does not consume model tokens itself—it is a child of the agent's reasoning loop. When the agent loops (reason → tool → reason → tool → final), the runtime must decide *where* the cumulative usage lives. Two legitimate conventions exist and they are mutually incompatible:

  1. **Leaf-attribution**: each `chat` span carries only its own call's usage; the root agent span sums descendants.
  2. **Cumulative-on-root**: each `chat` span carries running-total usage; the root reads the last child's total.

A runtime that mixes these—because tool-call spans are emitted by a shared instrumentation library that was written under convention (1), while the agent orchestrator was written under convention (2)—produces **double-counted input tokens and a root span whose `gen_ai.usage.output_tokens` is the max of children rather than the sum**. The invariant that breaks is monotonicity of cumulative usage across the span tree.

What Was Observed

A four-turn agent task (two tool calls, three model invocations) exported this span tree:

agent.invoke  (root)          gen_ai.usage.input_tokens=12040  output_tokens=410
├─ chat (turn 1)              gen_ai.usage.input_tokens=4010   output_tokens=180
├─ execute_tool (search)      gen_ai.usage.input_tokens=4010   output_tokens=180   ← copied from parent chat
├─ chat (turn 2)              gen_ai.usage.input_tokens=8030   output_tokens=95    ← cumulative, not per-call
├─ execute_tool (fetch)       gen_ai.usage.input_tokens=8030   output_tokens=95    ← copied again
└─ chat (turn 3)              gen_ai.usage.input_tokens=12040  output_tokens=410   ← cumulative

Three distinct pathologies are visible:

Downstream, the cost dashboard reported \$0.041 for a task that cost \$0.018, and a per-tool cost breakdown attributed 60% of spend to the `search` tool, which consumes zero model tokens.

Condition of Validity

The leaf-attribution convention (1) is the only one that composes correctly under arbitrary fan-out, and it is valid **only if** the following three conditions hold simultaneously:

  1. **Usage attributes are set exclusively on `gen_ai.operation.name ∈ {chat, text_completion, embeddings}` spans**, never on `execute_tool`, `invoke_agent` (non-root), or `create_agent` spans. Tool spans may carry `gen_ai.tool.name`, `gen_ai.tool.call.id`, and duration, but not `gen_ai.usage.*`.
  2. **Every usage-bearing span reports its own call's delta**, sourced directly from the provider response object at the moment the span closes—not from a shared context variable, not from a running accumulator.
  3. **Aggregation is a strict sum over the subtree**, with absent attributes treated as *absent* (excluded from the sum), not as zero (which would be indistinguishable from a genuine zero-token call and mask the bug).

If condition (2) cannot be met—e.g., the provider returns usage only at stream end and the span closes early—then the correct fallback is to **omit** the attribute and emit a `gen_ai.usage.missing = true` marker, not to backfill from context. A missing attribute is recoverable; a wrong one is not, because it is indistinguishable from truth downstream.

Decision Boundary

The boundary is between **propagation** and **aggregation**. Usage must *propagate upward by summation at export/query time*, never by *copying downward or sideways at span-creation time*. The moment a span copies a parent's usage attribute "for convenience," the tree becomes non-reconstructable: you can no longer tell whether a child's value is its own or inherited, and the sum invariant is destroyed irreversibly.

Operationally, enforce this with a single rule at the instrumentation boundary:

This is a *creation-time* guardrail, not a query-time fix. Query-time deduplication (e.g., "sum only leaf spans") fails here because the tool spans *are* leaves and they carry fabricated usage—the leaf sum is 4010+180+8030+95+12040+410, hopelessly wrong. There is no query that recovers the truth from a corrupted tree; the guardrail must fire before export.

Operational Effect

With the creation-time guardrail in place, the same task exports:

agent.invoke  (root)          (no usage attrs — aggregation is a query concern)
├─ chat (turn 1)              input=4010  output=180
├─ execute_tool (search)      (no usage attrs)
├─ chat (turn 2)              input=4020  output=95     ← per-call delta
├─ execute_tool (fetch)       (no usage attrs)
└─ chat (turn 3)              input=4010  output=410

Root usage is now a well-defined `sum(descendant chat spans)` = 12040 input / 685 output, cost is \$0.018, and per-tool cost attribution correctly reports zero model spend for tools. The invariant—**cumulative usage is monotonic non-decreasing down any root-to-leaf path, and equals the sum over usage-bearing descendants**—holds and is checkable by a single assertion at export time.

The residual risk is the streaming case: if a `chat` span closes before the usage chunk arrives, the delta is lost and the sum under-reports. The guardrail must therefore *delay span close until the usage chunk or a terminal error is observed*, with a bounded timeout after which the span closes with `gen_ai.usage.missing = true` rather than a fabricated value. Under-reporting with an explicit marker is auditable; over-reporting from context-copy is not.

from dataclasses import dataclass, field
from typing import Optional


class UsageAttributeViolation(RuntimeError):
    """Raised when a span attempts to set gen_ai.usage.* outside a model-call span,
    or when a usage-bearing span closes without a sourced delta."""
    pass


USAGE_KEYS = frozenset({"gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens"})
MODEL_OPS = frozenset({"chat", "text_completion", "embeddings"})


@dataclass
class Span:
    name: str
    operation: str
    attributes: dict = field(default_factory=dict)
    children: list = field(default_factory=list)
    closed: bool = False

    def set_usage(self, input_tokens: int, output_tokens: int) -> None:
        if self.operation not in MODEL_OPS:
            raise UsageAttributeViolation(
                f"span {self.name!r} op={self.operation!r} attempted to set "
                f"gen_ai.usage.* but is not a model-call span; usage must be "
                f"sourced from the provider response on a chat/completion span"
            )
        self.attributes["gen_ai.usage.input_tokens"] = input_tokens
        self.attributes["gen_ai.usage.output_tokens"] = output_tokens

    def close(self) -> None:
        if self.operation in MODEL_OPS:
            has_usage = USAGE_KEYS.issubset(self.attributes)
            marked_missing = self.attributes.get("gen_ai.usage.missing") is True
            if not has_usage and not marked_missing:
                raise UsageAttributeViolation(
                    f"model-call span {self.name!r} closed without gen_ai.usage.* "
                    f"and without gen_ai.usage.missing=true; refusing to export "
                    f"a span whose token accounting is silently absent"
                )
        self.closed = True


def aggregate_usage(root: Span) -> dict:
    """Sum usage over usage-bearing descendants. Absent != zero: only spans
    that actually carry the attribute contribute."""
    totals = {"input": 0, "output": 0, "missing_spans": 0}

    def walk(span: Span) -> None:
        if span.attributes.get("gen_ai.usage.missing") is True:
            totals["missing_spans"] += 1
        if USAGE_KEYS.issubset(span.attributes):
            totals["input"] += span.attributes["gen_ai.usage.input_tokens"]
            totals["output"] += span.attributes["gen_ai.usage.output_tokens"]
        for child in span.children:
            walk(child)

    walk(root)
    return totals


def assert_monotonic_usage(root: Span) -> None:
    """Invariant: along any root-to-leaf path, cumulative usage is
    non-decreasing, and equals the sum over usage-bearing descendants."""
    expected = aggregate_usage(root)
    path_sum = {"input": 0, "output": 0}

    def walk(span: Span) -> None:
        if USAGE_KEYS.issubset(span.attributes):
            path_sum["input"] += span.attributes["gen_ai.usage.input_tokens"]
            path_sum["output"] += span.attributes["gen_ai.usage.output_tokens"]
        for child in span.children:
            walk(child)

    walk(root)
    if path_sum != {"input": expected["input"], "output": expected["output"]}:
        raise UsageAttributeViolation(
            f"usage sum invariant broken: path={path_sum} aggregate={expected}"
        )


# --- demonstration of the guardrail firing on the observed bug ---
if __name__ == "__main__":
    root = Span(name="agent.invoke", operation="invoke_agent")
    chat = Span(name="chat", operation="chat")
    chat.set_usage(4010, 180)
    tool = Span(name="execute_tool", operation="execute_tool")
    try:
        tool.set_usage(4010, 180)  # the observed context-copy bug
    except UsageAttributeViolation as e:
        print(f"guardrail fired: {e}")
    root.children.append(chat)
    root.children.append(tool)
    chat.close()
    root.close()
    print(aggregate_usage(root))  # {'input': 4010, 'output': 180, 'missing_spans': 0}