In what scenarios must an instance treat OpenTelemetry GenAI span attributes as non-authoritative when tool calls span multiple token-accounting domains

**Date of Record:** 2026 December 1 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*` attributes) across tool-call boundaries where the tool executes in a different billing/accounting domain (subprocess, remote MCP server, sandboxed sidecar) than the orchestrating LLM instance. Does not apply to single-process, single-tenant agents whose tool calls are in-process function calls with no separate cost attribution.

Core Distinction

The GenAI semantic conventions define `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and (in newer revisions) `gen_ai.usage.cost` as *observational* attributes attached to a span. They are explicitly not a ledger. The failure mode is treating a completed span's token/cost attributes as an authoritative accounting record for an agent that crosses a tool-call boundary into a foreign accounting domain. When an agent invokes a tool that is itself an LLM (a sub-agent, a remote summarizer, a retrieval reranker served over MCP), the child span's token counts are recorded *by the child's process*, using the child's tokenizer and the child's model identity. The parent span aggregates them into `gen_ai.usage.*` by summation, and that summation is silently wrong across three axes: tokenizer mismatch, model-identity aliasing, and retry/duplicate-span double counting.

The invariant that breaks is this: **the sum of `gen_ai.usage.*` over a span subtree does not equal the billable cost of that subtree unless every leaf span shares a tokenizer, a model SKU, and a deduplication key with its parent.** OTel's semantic conventions do not enforce any of these; they only define attribute names and types.

What Was Observed

An orchestrator agent (`gpt-4o` class, `cl100k`-family tokenizer) dispatched a research subtask to a remote MCP tool `research.summarize`, which internally ran a `claude-3-5-sonnet` sub-agent. Both emitted GenAI spans with the same `trace_id` propagated via W3C `traceparent` in the MCP `_meta` field. The orchestrator's span processor computed parent `gen_ai.usage.input_tokens` as the sum of its own input tokens plus the child's reported `gen_ai.usage.input_tokens`.

Three concrete divergences appeared in the recorded trace:

  1. **Tokenizer drift:** The child reported 4,120 input tokens for a 14,800-character context using Anthropic's tokenizer; the orchestrator's cost model applied its own per-token price to that count. The character-to-token ratio differed by ~18% between tokenizers on the same text, so the attributed cost was off by a factor the parent could not detect from the attribute alone.
  1. **Model-identity aliasing:** The child span carried `gen_ai.request.model = "claude-3-5-sonnet-20241022"` but the parent's cost-attribution table keyed only on `gen_ai.system` (`anthropic`) and a coarse family name. Two distinct Sonnet revisions with a 3x price difference collapsed to one rate.
  1. **Retry double-counting:** The MCP transport retried the tool call once after a 30s timeout (`gen_ai` spans for both attempts shared the same `trace_id` but different `span_id`). The orchestrator summed both attempts' `output_tokens` into the parent, recording 2x the billable output for a call that was billed once (the first attempt's response was discarded by the child before completion). The parent had no `gen_ai.operation.name` disambiguation between the two attempts and no `retry.count` attribute to subtract.

The recorded parent span was internally consistent — all attributes present, types correct, span status `OK` — and yet the derived cost was ~2.4x the actual invoice line for that trace. Nothing in the OTel GenAI conventions flags this.

Condition of Validity

The parent's `gen_ai.usage.*` aggregation is authoritative **only if all four hold**:

If any condition fails, the aggregated attribute is a *lower or upper bound estimate*, not a ledger entry. The correct posture is to treat it as telemetry for latency and volume correlation, and to reconcile cost against the provider's own usage API out-of-band.

Decision Boundary

The boundary is not "local vs remote tool." It is **whether the parent can reconstruct the child's tokenizer and model SKU from the span alone.** A remote tool that echoes back a fully-qualified model string and a tokenizer identifier in its span attributes is safe to aggregate. A remote tool that reports only `gen_ai.system` and a family name is not — even if it is fast and reliable.

Concretely: if `gen_ai.request.model` on any descendant span does not match a price-table key exactly, the parent MUST NOT write an aggregated `gen_ai.usage.cost` attribute onto its own span. It may write `gen_ai.usage.input_tokens` as a volume metric, but must mark the cost as unresolved — for example by omitting the cost attribute entirely rather than emitting a partial sum, because downstream dashboards cannot distinguish "cost = 0" from "cost unknown" when the attribute is a float.

The second boundary is retry visibility. If the transport (MCP `_meta`, A2A headers) does not propagate a stable attempt identifier, the parent cannot deduplicate and MUST treat the subtree as non-aggregatable for billing. This is the non-obvious part: the failure is silent because retries produce *valid-looking* spans, and the parent's summation logic is locally correct.

Operational Effect

The practical consequence is that an agent runtime emitting GenAI spans across tool boundaries must implement a **span-subtree admissibility check** before writing any aggregated cost attribute, and must fail closed (omit the attribute) rather than fail open (write a plausible but wrong number). Downstream cost dashboards keyed on `gen_ai.usage.cost` will then show gaps for cross-domain traces, which is the correct signal: those traces require reconciliation against provider usage APIs, not against the trace store.

The second effect is on replay and audit. An auditor replaying a trace to verify a cost claim will recompute the same wrong sum from the same spans — the trace is self-consistent and self-deceiving. The only defense is to record, on the parent span, the *provenance* of each aggregated contribution: which `span_id`, which model string, which tokenizer, which attempt. Without that, the trace cannot be audited, only trusted.

from dataclasses import dataclass
from typing import Iterable


class NonAggregatableSubtreeError(RuntimeError):
    """Raised when a GenAI span subtree cannot be safely aggregated for cost."""


@dataclass(frozen=True)
class GenAISpan:
    span_id: str
    parent_span_id: str | None
    model: str | None            # gen_ai.request.model, may be None
    system: str | None           # gen_ai.system
    tokenizer: str | None        # gen_ai.tokenizer.name (extension), may be None
    input_tokens: int
    output_tokens: int
    attempt_id: str | None       # transport-propagated retry key, may be None
    status: str = "OK"


def aggregate_cost(
    spans: Iterable[GenAISpan],
    price_table: dict[str, float],
) -> tuple[int, int, float]:
    """
    Aggregate token and cost attributes over a span subtree.

    Returns (input_tokens, output_tokens, cost). Raises if any leaf span is
    not admissible for cost aggregation, rather than emitting a wrong sum.
    """
    seen_attempts: set[tuple[str, str]] = set()
    total_in = 0
    total_out = 0
    total_cost = 0.0

    for span in spans:
        if span.status != "OK":
            # Error spans may still have partial usage; exclude from cost.
            continue

        if span.model is None or span.model not in price_table:
            raise NonAggregatableSubtreeError(
                f"span {span.span_id}: model {span.model!r} not in price table; "
                f"cannot attribute cost (system={span.system!r})"
            )

        if span.tokenizer is None:
            raise NonAggregatableSubtreeError(
                f"span {span.span_id}: missing tokenizer identity; "
                f"token counts from {span.model!r} may not match price-table tokenizer"
            )

        if span.attempt_id is not None:
            key = (span.span_id.rsplit("-", 1)[0], span.attempt_id)
            if key in seen_attempts:
                # Duplicate attempt already counted; skip.
                continue
            seen_attempts.add(key)

        rate = price_table[span.model]
        total_in += span.input_tokens
        total_out += span.output_tokens
        total_cost += (span.input_tokens + span.output_tokens) * rate

    return total_in, total_out, total_cost