What structural signals indicate OTel GenAI span-tree divergence from token accounting under retry and compaction

**Date of Record:** 2026 December 2 **Scope:** Applies to agents emitting OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) across multi-step tool loops with retries, context compaction, or partial-stream failures. Does not apply to single-shot inference with no tool calls and no retry path.

Core Distinction

A GenAI span tree is a *narrative* of what the agent claims it did. Token accounting is a *ledger* of what the model was actually billed for. Under retries, streaming aborts, and context compaction, these two artifacts diverge silently: the span tree remains internally consistent (every span has a parent, every tool call has a result) while the sum of `gen_ai.usage.input_tokens` across `chat` spans no longer matches the operator's billing ledger or the model's own reported usage. The failure is not a missing span — it is a *well-formed* span tree whose aggregate token attributes are structurally wrong because the retry/compaction path either duplicated usage or dropped it.

What Was Observed

An agent executing a 40-step tool loop against a model with a 200k context window hit compaction at step 27. The trace showed 40 `gen_ai.chat` spans, each with `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`. Two structural signals appeared that the naive ledger check missed:

  1. **Duplicate `gen_ai.response.id` across sibling spans.** A transient 503 on step 14 triggered an SDK-level retry. The retry emitted a *new* `gen_ai.chat` span as a sibling of the failed one, but the failed span still carried `gen_ai.usage.input_tokens` from the aborted streaming response (partial usage recorded before the stream broke). The successful retry span carried full usage. Summing both double-counts the input prompt for that step. The span tree is valid; the ledger is inflated by ~1 prompt's worth of tokens.
  1. **Compaction span without a usage attribute.** The compaction step (step 27) was implemented as a separate model call whose output replaced the message history. It was emitted as a `gen_ai.chat` span but *without* `gen_ai.usage.*` because the wrapper's usage extractor only ran on the primary inference path. The span tree looks complete; the ledger is *deflated* by the entire compaction call's cost.
  1. **Orphaned tool-call spans after compaction.** Three `gen_ai.tool.call` spans whose `gen_ai.tool.call.id` referenced tool calls in the *pre-compaction* message history had no corresponding `gen_ai.chat` span carrying that tool call in its output — because compaction rewrote the assistant message that originally contained the tool call. The tool spans dangle as children of a chat span that no longer semantically contains them.

The combined effect: the operator's token ledger was off by +1 prompt (retry double-count) and −1 compaction call (missing usage), netting to a small error that masked both bugs. A per-step reconciliation against `gen_ai.response.id` uniqueness and per-span usage presence exposed both.

Condition of Validity

The invariant holds only when:

When any of these fails, the span tree is *structurally* valid but *semantically* inconsistent with the ledger. The check must be structural (tree shape, attribute presence, ID uniqueness) rather than value-based (does the sum match billing), because the billing ledger is the ground truth the tree is supposed to explain — you cannot use it to validate the tree.

Decision Boundary

Do not attempt to reconcile by *summing* usage attributes and comparing to a known total. Instead, reconcile *structurally* before any aggregate comparison:

The decision boundary is: *structural validity of the span tree does not imply ledger fidelity.* Treat them as independent checks and fail loudly when they disagree.

Operational Effect

Without this check, agents report clean traces while their token accounting drifts. The drift is bounded per-trace by roughly one prompt (retry double-count) plus one compaction call (missing usage), which is small enough to survive casual review but compounds across thousands of traces into systematic under- or over-billing, and — more dangerously — into *incorrect cost attribution per tool*, which corrupts any downstream optimization that prunes expensive tools based on span-derived cost. The fix is a pre-aggregation structural gate: validate `gen_ai.response.id` uniqueness, usage-attribute presence on all billed chat spans, and tool-call-ID reachability before any token sum is computed.

from dataclasses import dataclass
from typing import Iterable


class GenAISpanTreeInconsistent(RuntimeError):
    """Raised when an OTel GenAI span tree is structurally valid but ledger-inconsistent."""


@dataclass(frozen=True)
class ChatSpan:
    span_id: str
    response_id: str
    input_tokens: int | None
    output_tokens: int | None
    is_retry_of: str | None = None
    is_compaction: bool = False
    tool_call_ids_in_output: tuple[str, ...] = ()


@dataclass(frozen=True)
class ToolSpan:
    span_id: str
    tool_call_id: str
    parent_chat_span_id: str


def validate_span_tree(chat_spans: Iterable[ChatSpan], tool_spans: Iterable[ToolSpan]) -> None:
    chats = list(chat_spans)
    tools = list(tool_spans)

    # 1. Usage presence on every billed chat span (compaction included).
    for c in chats:
        if c.input_tokens is None or c.output_tokens is None:
            raise GenAISpanTreeInconsistent(
                f"chat span {c.span_id} (response_id={c.response_id}, compaction={c.is_compaction}) "
                f"is missing gen_ai.usage.* attributes; ledger would silently deflate."
            )

    # 2. response_id uniqueness except for explicit retry links.
    seen: dict[str, str] = {}
    for c in chats:
        if c.response_id in seen and c.is_retry_of != seen[c.response_id]:
            raise GenAISpanTreeInconsistent(
                f"duplicate gen_ai.response.id={c.response_id} across spans "
                f"{seen[c.response_id]} and {c.span_id} without an explicit retry link; "
                f"token aggregation would double-count."
            )
        seen.setdefault(c.response_id, c.span_id)

    # 3. Tool-call reachability: every tool span's call id must be present in exactly
    #    one ancestor chat span's recorded output.
    chat_by_span = {c.span_id: c for c in chats}
    for t in tools:
        parent = chat_by_span.get(t.parent_chat_span_id)
        if parent is None:
            raise GenAISpanTreeInconsistent(
                f"tool span {t.span_id} references unknown parent chat span {t.parent_chat_span_id}."
            )
        if t.tool_call_id not in parent.tool_call_ids_in_output:
            raise GenAISpanTreeInconsistent(
                f"orphan tool span {t.span_id}: tool_call_id={t.tool_call_id} not present in "
                f"parent chat span {parent.span_id}'s output; likely history rewrite / compaction."
            )


def aggregate_tokens(chat_spans: Iterable[ChatSpan], tool_spans: Iterable[ToolSpan]) -> int:
    chats = list(chat_spans)
    tools = list(tool_spans)
    validate_span_tree(chats, tools)  # structural gate before any summation
    return sum((c.input_tokens or 0) + (c.output_tokens or 0) for c in chats)