Which invariants prevent token-accounting drift from silently corrupting agent cost telemetry when tool-call spans straddle sampling boundaries

**Date of Record:** 2026 December 2 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes) where tool-call spans, LLM invocation spans, and parent agent spans are independently sampled or exported across multiple collectors. Does not cover single-process, unsampled, in-memory trace pipelines where every span reaches the exporter.

Core Distinction

There is a difference between *trace completeness* and *cost completeness*. A distributed tracing backend is designed to tolerate missing spans: a dropped child span degrades observability but never breaks a query. Cost telemetry is not tolerant in the same way. When a `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` pair is recorded on an LLM invocation span, that number is a *ledger entry*, not a *diagnostic sample*. The GenAI conventions place these attributes on the span that owns the model call, but the parent agent span and the sibling tool-call span carry their own `gen_ai.*` attributes and their own sampling decisions. The invariant that must hold is:

> For every logical agent turn, the sum of token attributes across all exported spans that belong to that turn equals the sum of token attributes the model provider actually billed — *and no exported span double-counts a token already attributed to an ancestor or sibling.*

This invariant is not enforced by the OpenTelemetry SDK. Sampling is per-span (or per-trace via `ParentBased` samplers), and attribute propagation is the instrumentor's responsibility. The failure mode is a *sampled-and-unsampled split within a single turn*: the LLM span is exported, its parent agent span is not, and a downstream cost aggregator that groups by `agent.id` or `gen_ai.agent.name` either loses the cost entirely (parent missing) or attributes it to a synthetic "unknown agent" bucket. Conversely, if the instrumentor duplicatively writes `gen_ai.usage.*` onto both the tool span and the LLM span for the same call, a `sum()` aggregation double-counts.

What Was Observed

A tool-using agent (planner → executor → summarizer) was instrumented with three span types:

  1. `agent.turn` (parent, `gen_ai.operation.name=invoke_agent`, carries `gen_ai.agent.name`).
  2. `llm.call` (child, `gen_ai.operation.name=chat`, carries `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`).
  3. `tool.call` (sibling under `agent.turn`, `gen_ai.operation.name=execute_tool`, carries `gen_ai.tool.name`).

The collector used a `ParentBased(TraceIdRatioBased(0.25))` sampler with a tail-sampling processor on the collector side that retained all traces containing an error but only 10% of successful traces. During a 6-hour run, the following drift appeared in the cost dashboard:

The 3.4% gap between invoice and exported LLM spans was tail-sampling dropping successful traces. The additional 16.3% gap between exported LLM spans and agent-attributed cost was *parent loss*: the head sampler's `ParentBased` decision is made at the root, so a child `llm.call` cannot be exported without its parent under default parent-based sampling — but the tail sampler on the collector operated on *batches*, and when the parent `agent.turn` span arrived in a different batch than its `llm.call` children and the batch was flushed under memory pressure, the parent was dropped while children survived. The join key `trace_id` still existed, but `gen_ai.agent.name` lived only on the parent. The cost aggregator, joining child→parent to resolve agent identity, produced a null agent and the row was silently bucketed.

A second, independent drift appeared in tool-call accounting. The instrumentor had been written to attach `gen_ai.usage.input_tokens` to the `tool.call` span as well, reasoning that "the tool result is fed back to the model, so the tool span should carry the token cost of consuming it." This is a semantic error: the tokens consumed by feeding a tool result back are billed on the *next* `llm.call`, not on the `tool.call`. The `tool.call` attribute caused a 4.1% over-count in any aggregation that summed `gen_ai.usage.*` across all `gen_ai.*` spans rather than filtering to `gen_ai.operation.name=chat`.

Condition of Validity

The invariant "sum of exported token attributes = billed tokens, no double-count" holds only under all of the following:

  1. **Token attributes are written on exactly one span per billed model call** — the `gen_ai.operation.name=chat` span — and nowhere else in the turn. Tool spans, agent spans, and retrieval spans must not carry `gen_ai.usage.*`.
  2. **Parent identity is resolvable independently of parent span export.** Either `gen_ai.agent.name` (or a stable `agent.id`) is duplicated onto every child span, or the cost aggregator resolves identity from a resource attribute (`service.name`, `gen_ai.agent.id` in the resource) that survives span-level sampling.
  3. **Sampling is consistent across the turn.** Either the whole trace is sampled in or out (`ParentBased` with a non-tail child policy), or the collector's tail sampler makes its decision on complete traces and never partially flushes a trace.
  4. **The aggregator filters by operation name before summing.** A `sum(gen_ai.usage.input_tokens)` over all spans is invalid; the valid query is `sum(...) where gen_ai.operation.name = 'chat'`.

When any of (1)–(4) is violated, the drift is silent: no error span, no `otel.status_code=ERROR`, no metric alert. The cost dashboard simply reports a number that is wrong by a few percent, and the error is only detectable by reconciling against the provider invoice — which most teams do monthly, not per-turn.

Decision Boundary

The boundary between "acceptable sampling" and "corrupt cost telemetry" is the point at which the sampling decision becomes *non-atomic with respect to the turn*. Two concrete rules define it:

The decision is not "sample more" — increasing the sample rate reduces variance but does not eliminate the systematic bias from parent loss. The decision is "make the cost-relevant attributes sampling-invariant." Token counts can be sampled (you accept variance); agent identity cannot (you cannot accept bias, because bias does not average out across a billing period — it accumulates in the same direction).

Operational Effect

After applying the invariants, the same agent run produced:

The reconciliation gap against the provider invoice fell from 19.7% to 3.4%, and the residual 3.4% is now *known* to be sampling variance rather than an unexplained leak. The operational lesson: in agent telemetry, the unit of cost correctness is the *turn*, not the *span*, and any attribute that the cost aggregator needs to resolve a turn must be replicated to every span in that turn, because the sampler is allowed to break the turn apart.

from dataclasses import dataclass
from typing import Iterable


class CostTelemetryInvariantError(RuntimeError):
    """Raised when a span set violates the GenAI token-accounting invariant."""
    pass


@dataclass(frozen=True)
class Span:
    trace_id: str
    span_id: str
    parent_id: str | None
    operation_name: str          # gen_ai.operation.name
    agent_name: str | None       # gen_ai.agent.name
    input_tokens: int | None     # gen_ai.usage.input_tokens
    output_tokens: int | None    # gen_ai.usage.output_tokens


def validate_turn(spans: Iterable[Span]) -> int:
    """
    Enforce the cost-telemetry invariants for one logical agent turn.
    Returns the total billed tokens (input+output) attributable to the turn.

    Invariants checked:
      (1) gen_ai.usage.* appears ONLY on gen_ai.operation.name == 'chat' spans.
      (2) every span in the turn carries gen_ai.agent.name (sampling-invariant identity).
      (3) no duplicate span_id (guards against double-export).
    """
    spans = list(spans)
    seen_ids: set[str] = set()
    total = 0

    for s in spans:
        if s.span_id in seen_ids:
            raise CostTelemetryInvariantError(
                f"duplicate span_id {s.span_id} in trace {s.trace_id}: "
                "double-export would double-count tokens"
            )
        seen_ids.add(s.span_id)

        has_usage = s.input_tokens is not None or s.output_tokens is not None

        # Invariant (1): token attributes only on chat spans.
        if has_usage and s.operation_name != "chat":
            raise CostTelemetryInvariantError(
                f"span {s.span_id} op={s.operation_name!r} carries gen_ai.usage.*; "
                "token attributes are only valid on gen_ai.operation.name='chat'"
            )

        # Invariant (2): identity must survive parent-span sampling.
        if s.agent_name is None:
            raise CostTelemetryInvariantError(
                f"span {s.span_id} op={s.operation_name!r} missing gen_ai.agent.name; "
                "cost aggregator cannot attribute tokens if parent span is sampled out"
            )

        if s.operation_name == "chat":
            total += (s.input_tokens or 0) + (s.output_tokens or 0)

    if not any(s.operation_name == "chat" for s in spans):
        raise CostTelemetryInvariantError(
            f"trace {spans[0].trace_id if spans else '<empty>'} has no chat span; "
            "turn cost cannot be established"
        )

    return total