What structural signals indicate token-usage accounting has silently diverged from span topology in OpenTelemetry GenAI agent traces

**Date of Record:** 2026 December 1 **Scope:** Applies to agent runtimes that emit OTel GenAI semantic conventions (`gen_ai.*`) across nested agent → tool → sub-agent spans, where token usage is aggregated from per-span attributes into a parent metric. Does not cover single-span inference calls with no tool nesting, nor traces where usage is sourced from a single upstream billing API rather than span attributes.

Core Distinction

The GenAI semantic conventions define token-usage as *attributes on the span that produced the tokens* (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, typically on the `gen_ai.chat` / `gen_ai.invoke_agent` span). They do **not** define a parent-child rollup contract. This means two different things can both be "correct" according to the spec yet disagree numerically:

  1. **Topological aggregation** — a collector sums `gen_ai.usage.*` over all descendant spans of an agent invocation.
  2. **Native accounting** — the model provider reports a single usage block for the whole agent turn (including internal tool-call turns it billed).

These diverge whenever the agent runtime performs **internal re-invocation loops** (tool call → model call → tool call) that the runtime *does not* re-emit as child spans, but that the provider *does* bill. The failure is not a bug in either number; it is a structural mismatch between the span tree and the billing tree. The signal that they have diverged is a **topology invariant violation**: `sum(child gen_ai.usage) > 0` while the parent span carries a single `gen_ai.usage` that is *less than* that sum, or a parent with no usage attribute at all but non-zero child usage.

What Was Observed

A multi-step agent (planner → 3 tool calls → synthesizer) emitted the following span tree under one `gen_ai.invoke_agent` root:

invoke_agent (root)
├── gen_ai.chat  usage.input=1200  usage.output=340   (planner)
├── gen_ai.execute_tool  (no usage attrs)              (tool 1)
├── gen_ai.execute_tool  (no usage attrs)              (tool 2)
├── gen_ai.execute_tool  (no usage attrs)              (tool 3)
└── gen_ai.chat  usage.input=4100  usage.output=520   (synthesizer)

Topological sum: input = 5300, output = 860.

The provider's billing block for the same `invoke_agent` turn: input = 12,900, output = 2,050.

The delta (7600 / 1190) came from **internal tool-result ingestion turns** the runtime folded into the synthesizer's context window but never emitted as separate `gen_ai.chat` spans. The runtime treated the re-invocation as an implementation detail; the provider treated each turn as billable. Both are internally consistent. The trace is *wrong* as an accounting record, and no span-level attribute flags the gap.

The tell was a **structural asymmetry**: the synthesizer span's `usage.input` (4100) was larger than the sum of all prior `usage.input` (1200) by a factor that did not match any documented context-assembly budget. Reconciling against provider billing exposed the missing turns. Absent that reconciliation, the trace looked complete.

Condition of Validity

The invariant "sum of descendant `gen_ai.usage.*` equals the provider's billed usage for the turn" holds **only if** every model invocation that consumes billable tokens is represented as a distinct span carrying usage attributes. It is violated whenever:

The invariant is **not** restored by adding a `gen_ai.usage.total_tokens` field; that field is a convenience sum, not an authoritative source, and it will inherit the same gap.

Decision Boundary

The boundary between "acceptable trace" and "diverged trace" is whether the **topology can reconstruct the billing tree**. Concretely:

The decision must be made on **span count vs. billed-turn count**, not on token magnitudes, because magnitudes can coincide by accident while the structural count cannot.

Operational Effect

When the invariant is unenforced:

**Guardrail:** the runtime must emit a span for *every* billable model turn, including internal tool-result ingestion, typed as `gen_ai.chat` with `gen_ai.operation.name = "chat"` and its own usage block. If the runtime cannot emit per-turn spans (e.g., the SDK hides them), it must emit a `gen_ai.usage.reconciliation` event on the parent carrying the provider-reported totals plus a `hidden_turns` count, so the trace is self-describing as incomplete rather than silently wrong. A collector-side validator should reject any `invoke_agent` span whose usage-bearing child count is less than its declared hidden-turn count, and any span whose `gen_ai.usage.total_tokens` disagrees with `input + output`.

from dataclasses import dataclass, field


class UsageTopologyDivergence(RuntimeError):
    """Raised when span-tree token usage cannot reconstruct provider billing."""
    pass


@dataclass
class Span:
    name: str
    operation: str  # gen_ai.operation.name
    input_tokens: int = 0
    output_tokens: int = 0
    children: list = field(default_factory=list)
    hidden_turns: int = 0  # declared via gen_ai.usage.reconciliation event


def usage_bearing(span: Span) -> bool:
    return span.operation in ("chat", "invoke_agent") and (
        span.input_tokens or span.output_tokens
    )


def validate_usage_topology(root: Span, provider_billed_turns: int) -> None:
    """
    Enforce that the span tree can reconstruct provider billing.

    Raises UsageTopologyDivergence when:
      - usage-bearing span count < declared hidden turns + provider turns
      - parent usage is less than the sum of usage-bearing children
        without a declared hidden-turn allowance
    """
    usage_spans = []

    def walk(s: Span) -> None:
        if usage_bearing(s):
            usage_spans.append(s)
        for c in s.children:
            walk(c)

    walk(root)

    declared_hidden = root.hidden_turns
    expected_turns = provider_billed_turns + declared_hidden
    if len(usage_spans) < expected_turns:
        raise UsageTopologyDivergence(
            f"span tree has {len(usage_spans)} usage-bearing spans but "
            f"{expected_turns} turns were billed "
            f"(provider={provider_billed_turns}, declared_hidden={declared_hidden}); "
            f"hidden re-invocations were not emitted as spans"
        )

    child_input = sum(
        c.input_tokens for c in root.children if usage_bearing(c)
    )
    if root.input_tokens and root.input_tokens < child_input and not declared_hidden:
        raise UsageTopologyDivergence(
            f"parent input_tokens={root.input_tokens} < child sum={child_input} "
            f"with no declared hidden turns; usage was under-reported on parent"
        )

    total = root.input_tokens + root.output_tokens
    if root.input_tokens and root.output_tokens and total == 0:
        raise UsageTopologyDivergence(
            "usage.total_tokens disagrees with input+output on parent span"
        )


# Example: the observed planner -> 3 tools -> synthesizer tree, where the
# runtime folded two tool-result ingestion turns into the synthesizer without
# emitting spans. Provider billed 4 turns (planner, 2 hidden, synthesizer).
root = Span(
    name="invoke_agent",
    operation="invoke_agent",
    input_tokens=5300,
    output_tokens=860,
    hidden_turns=0,
    children=[
        Span("chat", "chat", 1200, 340),
        Span("execute_tool", "execute_tool"),
        Span("execute_tool", "execute_tool"),
        Span("execute_tool", "execute_tool"),
        Span("chat", "chat", 4100, 520),
    ],
)

try:
    validate_usage_topology(root, provider_billed_turns=4)
except UsageTopologyDivergence as exc:
    # Correct behavior: the trace is flagged as non-reconstructable and must
    # be reconciled against provider billing before being used for cost.
    print(f"reconciliation required: {exc}")