Under what conditions must an instance refuse to close a GenAI span whose `gen_ai.usage.input_tokens` was derived from a provider-reported counter rather than a local tokenizer, because the span's parent turn span will otherwise record a token total that is not attributable to any single model provenance?
**Date of Record:** 2026 December 2 **Scope:** Applies to agents that emit OpenTelemetry GenAI spans (`gen_ai.*` semantic conventions ≥ v1.28) where a parent `invoke_agent` turn span aggregates child `chat`/`execute_tool` span token counts, and where at least one child obtained usage from a provider response body rather than a local tokenizer. Does not apply to single-model, single-span deployments where no aggregation occurs, nor to spans that carry no `gen_ai.usage.*` attributes at all.
Core Distinction
The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *observations of a billing event*, not as *measurements of a context window*. These are not the same quantity, and the conventions do not reconcile them. A provider's `usage.prompt_tokens` field is authoritative for cost but is defined by the provider's own tokenizer, its own system-prompt injection, its own tool-schema serialization, and its own cache-accounting rules. A local tokenizer's count is authoritative for what the agent *believes it sent*. When a turn span aggregates child spans, it silently sums two different measurement regimes under one attribute name.
The boundary condition is this: **a parent turn span may not be closed with an aggregated `gen_ai.usage.input_tokens` if any contributing child span's usage value originated from a provider counter whose tokenizer identity differs from the tokenizer identity declared on the parent (or is undeclared).** The aggregation is arithmetically valid and semantically corrupt. The span is not "wrong" in the sense a validator would flag; it is wrong in the sense that the number cannot be traced back to a single provenance, and any downstream consumer—cost attribution, context-budget enforcement, cache-hit analysis—will read it as if it were.
What Was Observed
An agent orchestration layer wrapped each reasoning turn in an `invoke_agent` span and each model call in a child `chat` span. Child spans recorded `gen_ai.usage.input_tokens` from the provider response's `usage` object. The parent turn span recorded the sum of its children. The turn span also carried `gen_ai.request.model = "claude-3-5-sonnet"` and a `gen_ai.tokenizer` resource attribute of `"anthropic-claude"`.
During a tool-heavy turn, a single child `chat` span was served by a fallback provider (recorded correctly on the child as `gen_ai.request.model = "gpt-4o"`, tokenizer `"o200k_base"`). The child's `input_tokens` came from the fallback provider's counter. The parent summed it in. The resulting turn span reported 47,812 input tokens with `gen_ai.request.model = "claude-3-5-sonnet"`, a model whose tokenizer would have produced a materially different count for the same serialized prompt—typically 8–15% divergence on tool-schema-heavy payloads because the two tokenizers split JSON keys and punctuation differently.
The failure was not visible in any single span. It surfaced only when a context-budget enforcer read the turn span's `input_tokens`, compared it to the model's declared context limit, and computed remaining headroom. The headroom was wrong by the divergence factor, and because the divergence is *tokenizer-pair-specific and payload-shape-dependent*, it was not a constant offset that a calibration table could fix. On the next turn with a different tool schema, the sign of the error flipped.
A second observation: the same aggregation, when all children came from the same provider, was still subtly wrong because provider counters include cached-prefix tokens at a different rate but the same field, while the local tokenizer counts them at face value. The turn total was internally consistent but did not match what the model actually had in context.
Condition of Validity
The aggregation invariant holds only when all of the following are true for every contributing child span:
- The child span carries `gen_ai.request.model` equal to the parent's `gen_ai.request.model` **or** the parent does not declare a model at all (in which case the parent is a pure container and must not carry a model-scoped token total).
- The child's usage value carries provenance—either a `gen_ai.usage.source = "provider"` / `"local_tokenizer"` marker, or the resource-level tokenizer identity matches the parent's.
- The parent does not carry a `gen_ai.request.model` attribute when it aggregates children of differing models. A container span with mixed-model children must be model-agnostic: it may carry `gen_ai.usage.input_tokens` only if it also carries a per-model breakdown (e.g., child spans retained and queryable), otherwise the aggregate must be dropped or renamed to a non-convention attribute.
When any condition fails, the parent must either (a) omit the aggregated usage attribute and rely on child-span queries, or (b) refuse to close and raise, forcing the emitter to fix provenance before the span is exported. Option (b) is correct when the consumer is a budget enforcer that reads only the parent.
Decision Boundary
The decision is not "is the sum correct?" It is "does the sum have a single tokenizer provenance?" Compute it as a set-membership test over the children's `(model, tokenizer)` pairs, not as a numeric check.
- **One provenance, parent model matches:** aggregate, close, export. This is the happy path.
- **One provenance, parent declares no model:** aggregate but strip `gen_ai.request.model` from the parent and add `gen_ai.usage.aggregate_provenance = "<tokenizer-id>"`. The total is valid; the model attribution is not.
- **Multiple provenances:** do not aggregate into a model-scoped attribute. Either drop the parent usage attribute (preferred when child spans are exported and queryable) or refuse to close.
- **Provider counter vs. local tokenizer mixed, parent declares a model:** refuse to close. The number will be read as model-scoped and it is not.
The trap is the third and fourth cases look identical to a naive sum. A validator that checks `parent.input_tokens == sum(children.input_tokens)` passes in all four cases. The invariant that must be enforced is provenance cardinality, which the semantic conventions do not currently express as a first-class attribute—so the emitter must enforce it structurally.
Operational Effect
When this invariant is enforced, the observable behavior changes in three places. First, turn spans with mixed-provider children stop carrying a model-scoped token total; budget enforcers that read the parent must fall back to summing child spans, which is correct but requires the children to be retained (they usually are, but retention is a separate policy). Second, the refusal path surfaces provider-fallback events as span-closure errors, which is the intended signal: a fallback that changes tokenizer identity is a provenance event, not a routine retry. Third, cost attribution stops silently blending two price regimes under one model label.
When it is *not* enforced, the failure is latent and payload-dependent. It does not produce a spike, an error rate, or a latency change. It produces a slow drift in budget headroom that manifests as either premature context truncation (when the provider counter overcounts relative to the local tokenizer) or context-overflow 400s from the provider (when it undercounts). The 400s are misdiagnosed as "context window too small" rather than "the turn span lied about how full the context was."
The guardrail is a closure-time assertion, not an export-time validator, because once the span is exported the provenance is gone. The assertion must run where the children are still in scope—at the parent's `end()`—and it must fail closed.
from dataclasses import dataclass
class TokenProvenanceViolation(RuntimeError):
"""Raised when a turn span would close with an aggregate token total
that has no single tokenizer provenance."""
pass
@dataclass(frozen=True)
class ChildUsage:
model: str
tokenizer: str
input_tokens: int
source: str # "provider" | "local_tokenizer"
def close_turn_span(
parent_model: str | None,
parent_tokenizer: str | None,
children: list[ChildUsage],
) -> dict:
if not children:
return {}
provenances = {(c.model, c.tokenizer) for c in children}
if len(provenances) == 1:
model, tokenizer = next(iter(provenances))
total = sum(c.input_tokens for c in children)
if parent_model is not None and parent_model != model:
# Single provenance but parent mislabels the model.
raise TokenProvenanceViolation(
f"parent model {parent_model!r} != child provenance {model!r}; "
f"aggregate would be misattributed"
)
if parent_model is None:
return {
"gen_ai.usage.input_tokens": total,
"gen_ai.usage.aggregate_provenance": tokenizer,
}
return {"gen_ai.usage.input_tokens": total}
# Multiple provenances.
provider_sourced = [c for c in children if c.source == "provider"]
local_sourced = [c for c in children if c.source == "local_tokenizer"]
if parent_model is not None and provider_sourced and local_sourced:
raise TokenProvenanceViolation(
f"turn span declares model {parent_model!r} but aggregates "
f"{len(provider_sourced)} provider-counter and "
f"{len(local_sourced)} local-tokenizer children; "
f"total is not attributable to a single tokenizer"
)
if parent_model is not None and len({c.model for c in children}) > 1:
raise TokenProvenanceViolation(
f"turn span declares model {parent_model!r} but children span "
f"models {sorted({c.model for c in children})}; "
f"refusing to emit model-scoped aggregate"
)
# Container span: no model declared, mixed provenance.
# Drop the model-scoped aggregate; retain children for query-time sum.
return {"gen_ai.usage.aggregate_dropped": "mixed_provenance"}