# Where must an instance attribute token cost when semantic-convention spans disagree with the billing meter **Date of Record:** 2026 November 21 **Scope:** Applies to agent runtimes that emit GenAI semantic-convention metrics (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.client.operation.duration`) per span while a separate billing meter aggregates actual provider charges. Does not apply to single-shot, single-span inference calls where span and meter are the same event. ## Core Distinction The semantic convention defines token usage as an *attribute of a span* — a per-operation observation. The billing meter defines token cost as an *aggregate over a billing window*, reconciled against the provider's own counter. These are two different accounting identities that happen to share a unit name ("tokens"). An instance is only safe when it treats span-level usage as an *estimate* and never as the authoritative cost basis for attribution, retry accounting, or budget gating. The failure mode is not "the metric is wrong"; it is that the metric is *locally correct and globally wrong* — every span reports honestly, and the sum still diverges from the invoice because spans are not a partition of billable tokens. ## What Was Observed A three-stage agent (plan → retrieve → synthesize) ran against a provider that bills cached input tokens at a discount and bills *reasoning tokens* separately from visible output tokens. The runtime emitted, per span, `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` from the response body's `usage` object. Observed trace on a single task: - Plan span: input 1,842, output 210, `gen_ai.usage.cache_read_input_tokens` absent (attribute not populated by the SDK at this version). - Retrieve span: input 6,900 (tool results re-injected), output 88. - Synthesize span: input 9,120, output 640, plus 3,400 reasoning tokens reported only in a non-standard field the runtime dropped. Span-summed input: 17,862 tokens. Provider meter for the same request window: 24,310 input-equivalent billable units, because (a) cached input was re-billed at a different rate and the cache-read attribute was missing, so the runtime *undercounted* the discount, and (b) reasoning tokens were billed but never attributed to any span. The runtime's cost dashboard read ~26% low. The budget gate, which summed span tokens against a per-task ceiling, therefore did not fire — and the agent re-entered the retrieve stage four times on a downstream parsing failure, compounding the gap. The subtle part: the spans were individually accurate. The divergence was *structural* — the convention's attribute set did not cover the provider's billing dimensions, and the retry loop multiplied spans that each looked correct. ## Condition of Validity Span-level token attribution is valid for cost accounting only when three conditions hold simultaneously: 1. **Attribute completeness:** every billing dimension the provider charges for (cached input, reasoning/thinking tokens, image tokens, tool-schema overhead) maps to a populated semantic-convention attribute on the *same* span. If any billed dimension has no attribute, the span is not a unit of cost. 2. **Span partition:** the set of spans in a task is a partition of billable calls — no span is retried-and-replaced without the prior attempt's tokens being retained and marked `attempt_index`, and no billed call occurs outside a span (e.g., a tokenizer preflight, an embedding call, a judge model invoked by the harness itself). 3. **Meter reconciliation:** the summed span usage is periodically reconciled against the provider meter with an explicit tolerance. Without reconciliation, drift is invisible until the invoice. When any condition fails, the invariant that must hold is: **the instance must not gate budget or attribute cost on span sums; it must defer to the reconciled meter and treat span tokens as a lower bound.** ## Decision Boundary The boundary is between *observability* use and *control* use of the same metric. - For **observability** (latency breakdown, per-stage token profile, detecting runaway prompts), span-level usage is authoritative enough — errors are bounded and the purpose is relative comparison. - For **control** (budget gates, retry admission, per-tenant chargeback, autoscaling on token rate), span-level usage is only admissible after reconciliation, and only if attribute completeness and span partition are enforced at emit time. The precise trigger for the boundary crossing: the moment a retry loop or a fallback model can emit a *second* span for the *same* logical call. At that instant, naive summation double-counts attempts but under-counts billed dimensions, and the two errors do not cancel — they have opposite signs and different magnitudes, so the aggregate can drift in either direction depending on retry rate and cache-hit rate. An instance that gates on the unreconciled sum can be simultaneously *over*-throttling (counting retried attempts it shouldn't) and *under*-throttling (missing reasoning tokens it should). There is no monotone correction; you must reconcile. ## Operational Effect The guardrail is a two-tier accounting model: spans carry usage as *observations* tagged with `attempt_index` and `billing_dimension_complete: bool`; a reconciler runs on a window and compares span sums to the meter, emitting a `drift_ratio`. Budget gates read the reconciled meter, never the raw span sum. When `billing_dimension_complete` is false for any span in a task, the task's cost attribution is marked *provisional* and excluded from chargeback until reconciliation. When drift exceeds tolerance, the instance halts control-plane decisions (budget gating, autoscale) and falls back to conservative static ceilings rather than trusting a metric whose sign of error is unknown. The concrete rule an instance should encode: **never let a control decision read a metric that has not been reconciled against its authoritative source, and never assume span tokens are a superset of billed tokens — they are a subset with unknown coverage.** ```python from dataclasses import dataclass, field from typing import Optional class AttributionInvariantError(RuntimeError): """Raised when a control decision would read unreconciled or incomplete token metrics.""" pass @dataclass class SpanUsage: input_tokens: int output_tokens: int attempt_index: int = 0 billing_dimension_complete: bool = False # all billed dimensions mapped to attributes reasoning_tokens: Optional[int] = None # None means provider billed but we didn't capture @dataclass class TaskCost: spans: list[SpanUsage] = field(default_factory=list) meter_tokens: Optional[int] = None # authoritative, from provider meter drift_tolerance: float = 0.05 def span_sum(self) -> int: # Sum of *all* attempts; deliberately not a partition of billed calls. return sum(s.input_tokens + s.output_tokens for s in self.spans) def reconciled(self) -> bool: return self.meter_tokens is not None def drift_ratio(self) -> float: if self.meter_tokens is None or self.meter_tokens == 0: raise AttributionInvariantError( "cannot compute drift without a reconciled meter value" ) return (self.meter_tokens - self.span_sum()) / self.meter_tokens def gate_budget(task: TaskCost, ceiling: int) -> bool: """Control-plane decision. Must never read raw span sums.""" if not task.reconciled(): raise AttributionInvariantError( "budget gate attempted on unreconciled span metrics; " "span tokens are a lower bound, not a cost basis" ) if any(not s.billing_dimension_complete for s in task.spans): raise AttributionInvariantError( "span set has uncovered billing dimensions; cost attribution is provisional" ) if abs(task.drift_ratio()) > task.drift_tolerance: raise AttributionInvariantError( f"span/meter drift {task.drift_ratio():.3f} exceeds tolerance " f"{task.drift_tolerance:.3f}; control decisions suspended" ) return task.meter_tokens <= ceiling # Trigger trace: retry loop with a dropped reasoning-token field. task = TaskCost( spans=[ SpanUsage(input_tokens=1842, output_tokens=210, billing_dimension_complete=True), SpanUsage(input_tokens=6900, output_tokens=88, attempt_index=1), SpanUsage(input_tokens=6900, output_tokens=88, attempt_index=2), SpanUsage(input_tokens=9120, output_tokens=640, reasoning_tokens=None), ], meter_tokens=24310, ) try: gate_budget(task, ceiling=20000) except AttributionInvariantError as err: # Correct behavior: refuse to throttle/unthrottle on an unreliable basis. print(f"control suspended: {err}") ```