In what scenarios must an instance treat an OpenTelemetry GenAI span as non-authoritative for cost attribution when tool-call attributes diverge from the model-call envelope

**Date of Record:** 2026 December 1 **Scope:** Applies to agent runtimes that emit `gen_ai.*` spans per the OpenTelemetry GenAI semantic conventions and reconcile token/cost telemetry from those spans against an external billing ledger or budget governor. Does not apply to single-shot inference without tool loops, nor to systems where the model provider is the sole and authoritative source of usage.

Core Distinction

The GenAI semantic conventions model an agent run as a *tree*: one `gen_ai.chat` (or `gen_ai.invoke_agent`) span per model call, with child `gen_ai.execute_tool` spans hanging off it, each carrying `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` where the provider reports them. The non-obvious boundary is this: **the span tree is a *causal* record, but cost attribution requires an *accounting* record, and the two diverge the moment a tool call triggers a nested model call whose tokens are billed to the same parent envelope but recorded on a different span.**

When an agent calls a tool that itself invokes an LLM (a sub-agent, a summarizer, a re-ranker, a reflection step), the convention has no single canonical place to attach the nested model call's usage. Implementations split into two camps:

  1. **Nested-span camp:** the inner `gen_ai.chat` span is a child of the `execute_tool` span; usage sits on the inner span. Parent `gen_ai.chat` usage reflects only the outer turn.
  2. **Rollup camp:** the runtime aggregates all descendant usage onto the top-level agent span and zeroes the inner spans (or leaves them but marks the parent as `aggregate`).

Both are "conformant" under the current convention, which specifies attribute *names* but not *ownership semantics* across the tool boundary. A cost governor that sums leaf spans and a governor that reads the root span will disagree — silently — by exactly the nested-call tokens. This is the failure surface.

What Was Observed

A three-tier agent (planner → retriever-tool that calls an embedding+rerank model → synthesizer) emitted spans under `gen_ai.*` v1.27 conventions. During a 40-minute incident replay:

The budget governor summed `gen_ai.usage.*` across all spans where `gen_ai.operation.name` ∈ {chat, text_completion} and multiplied by a per-model price table keyed on `gen_ai.request.model`. It produced a correct total for the reranker (61k × rerank price) but a **double-count** for the synthesizer: the root's 18,442 input tokens were re-emitted on a *duplicate* root span created by a retry (see below), and the governor had no dedup key.

The retry is the second half of the failure. The planner timed out at 30s (client-side `gen_ai.request.timeout`), the orchestrator retried the *entire* agent invocation, and the retry re-used the same `trace_id` (propagated from the inbound request) but generated a new `span_id` for the root. The original root span was still exported (it completed server-side after the client gave up). Result: two root `invoke_agent` spans, same `trace_id`, different `span_id`, both with `status.code=OK` from the exporter's perspective, both carrying full usage. The governor counted both.

Net over-attribution: ~2.1× on synthesizer tokens, ~1.0× on reranker (correct), and the *tool's own* nested call was attributed to the tool span's service, not the agent's, so the per-agent cost dashboard under-reported by 61k tokens while the global ledger over-reported by 18k. The two errors did not cancel.

Condition of Validity

The invariant that makes span-derived cost authoritative is:

> **For any `trace_id`, the sum of `gen_ai.usage.input_tokens` over spans where `gen_ai.operation.name ∈ {chat, text_completion, embeddings}` AND `span.parent_span_id` is null-or-root AND `gen_ai.usage.aggregate=false` equals the provider's billed input tokens for that trace, exactly once.**

This holds only when all four conditions are met:

  1. **Single root per trace.** Retries must mint a new `trace_id` (or set `gen_ai.usage.aggregate=true` on the superseded root and mark it `status.code=ERROR` with a `retry.superseded` attribute). A retried invocation that reuses `trace_id` with a fresh root violates the "exactly once" clause.
  2. **Usage ownership is declared.** Every `gen_ai.chat` span must carry `gen_ai.usage.aggregate` ∈ {true, false}. `false` means "these tokens are mine, count them." `true` means "these are a rollup of descendants, do not double-count." The convention currently leaves this implicit; without it, nested-call tokens are counted either zero or twice.
  3. **Tool-boundary model calls are re-parented or flagged.** A model call made *inside* a tool must either (a) be re-parented to the agent root with `gen_ai.tool.name` set to the originating tool, or (b) carry `gen_ai.usage.attributed_to=<parent_span_id>` so the governor can walk the attribution edge rather than the span edge.
  4. **Model identity is stable across the envelope.** `gen_ai.request.model` on a nested span must match the price-table key used for the root, or the governor must resolve price per-span (not per-trace). Mixed-model traces (reranker + synthesizer) break any single-price-per-trace assumption.

When any condition fails, the span tree is a valid *debugging* artifact but an invalid *billing* artifact. The instance must fall back to the provider's usage API for that `trace_id` window and mark the span-derived number as advisory.

Decision Boundary

The governor must switch from span-derived to provider-authoritative accounting when **any** of the following is observed on a trace:

Below the boundary — single root, declared aggregate flags, no nested model calls, single model — span-derived cost is authoritative to within exporter sampling error and may be used for hard budget enforcement. Above the boundary, it is advisory only; the governor must not *deny* a request based on a span-derived overrun that could be a double-count artifact, because denying on a phantom overrun is itself a failure (the agent is starved of budget it actually has).

The asymmetry matters: **over-attribution must be tolerated (advisory), under-attribution must be blocked (fail-closed).** A span tree that under-counts (nested call attributed away from the agent) will let an agent exceed its real budget silently. A span tree that over-counts (retry double-count) will falsely throttle. The guardrail is to treat over-count as advisory and under-count as a hard stop, using the provider ledger as the tiebreaker.

Operational Effect

An instance that treats span-derived GenAI usage as authoritative without the four validity conditions will, in a tool-using agent with any retry or nested-model path, mis-attribute cost in *both* directions on the same trace. The per-agent dashboard and the global ledger diverge, and neither matches the provider invoice. The fix is not a better exporter — it is an explicit accounting layer: declare usage ownership (`gen_ai.usage.aggregate`), re-parent or attribute nested model calls (`gen_ai.usage.attributed_to`), mint fresh `trace_id` per retry, and gate hard budget enforcement on the validity predicate above. When the predicate fails, the instance must degrade to provider-authoritative reconciliation for that window rather than enforce on a span tree it cannot trust.

from dataclasses import dataclass
from typing import Iterable


class SpanAccountingError(RuntimeError):
    """Raised when a GenAI span tree cannot be trusted for cost attribution."""


@dataclass(frozen=True)
class GenAISpan:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    operation_name: str
    request_model: str | None
    input_tokens: int
    output_tokens: int
    aggregate: bool | None          # gen_ai.usage.aggregate
    attributed_to: str | None       # gen_ai.usage.attributed_to
    status_code: str                # OK | ERROR | UNSET
    timed_out: bool


MODEL_OPS = {"chat", "text_completion", "embeddings"}


def assert_cost_authoritative(spans: Iterable[GenAISpan]) -> None:
    """Validate the exactly-once cost invariant for one trace.

    Raises SpanAccountingError if the span tree is a valid debugging artifact
    but an invalid billing artifact. Callers must then fall back to the
    provider usage API for the trace window.
    """
    spans = list(spans)
    if not spans:
        raise SpanAccountingError("empty trace: no spans to attribute")

    trace_ids = {s.trace_id for s in spans}
    if len(trace_ids) != 1:
        raise SpanAccountingError(
            f"mixed trace_ids in accounting set: {sorted(trace_ids)}"
        )

    roots = [s for s in spans if s.parent_span_id is None]
    if len(roots) > 1:
        ok_roots = [r for r in roots if r.status_code == "OK"]
        if len(ok_roots) > 1:
            raise SpanAccountingError(
                f"multiple OK roots under trace {roots[0].trace_id}: "
                f"retry shadow — usage would be double-counted"
            )

    by_id = {s.span_id: s for s in spans}
    for s in spans:
        if s.operation_name not in MODEL_OPS:
            if s.input_tokens or s.output_tokens:
                raise SpanAccountingError(
                    f"usage on non-model span {s.span_id} "
                    f"({s.operation_name}): mis-tagged tokens"
                )
            continue

        if s.aggregate is None:
            raise SpanAccountingError(
                f"span {s.span_id} missing gen_ai.usage.aggregate: "
                f"ownership undeclared, cannot dedup"
            )

        parent = by_id.get(s.parent_span_id) if s.parent_span_id else None
        if parent is not None and parent.operation_name == "execute_tool":
            if s.attributed_to is None:
                raise SpanAccountingError(
                    f"nested model call {s.span_id} under tool span "
                    f"{parent.span_id} lacks gen_ai.usage.attributed_to: "
                    f"tokens would be attributed to the tool, not the agent"
                )

        ancestor_model = _nearest_model_ancestor_model(s, by_id)
        if ancestor_model is not None and ancestor_model != s.request_model:
            if s.aggregate is not False:
                raise SpanAccountingError(
                    f"mixed-model trace at {s.span_id}: "
                    f"{s.request_model} under {ancestor_model}, "
                    f"single-price-per-trace assumption broken"
                )

    for s in roots:
        if s.timed_out and s.status_code == "OK":
            raise SpanAccountingError(
                f"root {s.span_id} timed out but reports OK: "
                f"client abandon / server completion race"
            )


def _nearest_model_ancestor_model(span: GenAISpan, by_id: dict[str, GenAISpan]) -> str | None:
    cur = by_id.get(span.parent_span_id) if span.parent_span_id else None
    while cur is not None:
        if cur.operation_name in MODEL_OPS:
            return cur.request_model
        cur = by_id.get(cur.parent_span_id) if cur.parent_span_id else None
    return None