# Which invariants prevent semantic-convention token metrics from silently under-counting agent cost across provider retries **Date of Record:** 2026 November 26 **Scope:** Applies to LLM agent runtimes that emit OpenTelemetry-style GenAI semantic-convention metrics (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.client.operation.duration`) aggregated per logical agent step. Does not apply to single-shot, non-retried inference calls where one physical request maps 1:1 to one logical step. ## Core Distinction The GenAI semantic conventions define *usage* attributes as properties of a *physical* model invocation: `gen_ai.usage.input_tokens` is the token count the provider *billed for on that wire call*. The agent runtime, however, reasons in *logical* units: one "step" is one intention to call a tool or produce a decision, and it may fan out into N physical calls because of retries, provider failover, streaming reconnects, or speculative hedging. The failure boundary is the seam between these two cardinalities. A metric pipeline that sums physical-call attributes but keys histograms/counters by `gen_ai.request.model` and a logical `step_id` will *drop* the retried attempts, because the semantic convention has no field that says "this physical call is attempt 2 of logical step 7." The invariant that must hold — *Σ(physical usage) = logical step cost* — is not expressible in the convention as written, so it silently breaks. ## What Was Observed A tool-calling agent issued a `search_documents` tool call. The provider returned HTTP 429 on the first attempt; the SDK's retry layer re-issued the identical request 1.2s later, which succeeded. Both wire calls were instrumented. The instrumentation emitted: - Attempt 1: `gen_ai.usage.input_tokens=4180`, `gen_ai.response.finish_reasons=["error"]`, duration 1180ms. - Attempt 2: `gen_ai.usage.input_tokens=4180`, `gen_ai.response.finish_reasons=["tool_calls"]`, duration 940ms. The metric exporter used a histogram keyed by `{gen_ai.request.model, gen_ai.operation.name, step_id}`. Because both spans carried the same `step_id` (correctly — it is one logical step), the histogram recorded *two observations* but the counter for `gen_ai.usage.input_tokens` was implemented as a *gauge-style last-value-wins* aggregation over the step key. Result: 4180 tokens recorded for a step that the provider actually billed 8360 for. The cost dashboard under-reported by exactly 50% for every retried step, and the error was invisible because both spans were individually valid, both carried well-formed attributes, and neither tripped a validation rule. The undercount only surfaced when a finance reconciliation compared the provider's invoice against the meter and found a persistent ~7% gap concentrated on days with elevated 429 rates. The second, subtler artifact: `gen_ai.client.operation.duration` was recorded per *physical* call, so p99 latency looked healthy (940ms) while the *logical* step latency the user experienced was 2120ms (1180 + 940 + backoff). The semantic convention has no `gen_ai.logical_step.duration`, so latency SLOs computed from the convention were structurally optimistic under retry. ## Condition of Validity The naive invariant "sum `gen_ai.usage.input_tokens` across all spans tagged with a step" is *only* valid when: 1. Every physical attempt emits a span (retry layers that swallow failed attempts before instrumentation break this), **and** 2. The aggregation is additive (sum/count), not last-value-wins, **and** 3. Failed attempts are not filtered out by a `finish_reasons != error` sampling rule before aggregation. Condition (3) is the one that fails most often in practice: tail-sampling policies commonly drop error spans to control volume, which is correct for *debugging* traces but catastrophically wrong for *cost* metrics, because the errored attempt was still billed. The convention does not distinguish "this span is safe to sample away" from "this span carries billable usage," so sampling policy silently mutates the cost invariant. ## Decision Boundary The boundary is: **does the aggregation key represent a physical call or a logical step?** If physical, additive sums are correct but the metric answers "what did the provider bill," not "what did this step cost the agent," and retries must be counted as separate rows. If logical, the pipeline must *explicitly* sum attempts and must carry a `gen_ai.retry.attempt` (or equivalent non-standard) attribute so the sum is reconstructable and auditable. There is no safe middle. A pipeline that keys by logical step but aggregates by last-value-wins is the failure mode documented here: it looks correct, passes schema validation, and under-counts exactly in proportion to retry rate. The guardrail is a reconciliation invariant — `logical_step_tokens == Σ attempt_tokens` — enforced as a runtime assertion at span-emit time, not at dashboard time, so the violation fails the step rather than the invoice. ## Operational Effect Under-counting scales with provider instability: the worse the 429/5xx rate, the larger the silent gap, so the metric degrades *precisely when* the system is under stress and cost decisions matter most. Latency SLOs derived from `gen_ai.client.operation.duration` are structurally optimistic by the backoff sum. The remediation is to treat the semantic convention as a *physical-call* contract and layer an explicit logical-step aggregator on top, with a hard assertion that the two reconcile per step. Without that assertion, the invariant fails open — silently, validly, and in the direction that hides cost. ```python from dataclasses import dataclass, field class TokenReconciliationError(RuntimeError): """Raised when logical-step token accounting diverges from summed physical attempts.""" @dataclass class PhysicalAttempt: attempt_index: int input_tokens: int output_tokens: int finish_reason: str duration_ms: float @dataclass class LogicalStep: step_id: str model: str attempts: list[PhysicalAttempt] = field(default_factory=list) def record(self, attempt: PhysicalAttempt) -> None: self.attempts.append(attempt) def billable_input_tokens(self) -> int: # Every physical attempt is billed, including errored ones. return sum(a.input_tokens for a in self.attempts) def logical_duration_ms(self) -> float: return sum(a.duration_ms for a in self.attempts) def reconcile(self, reported_input_tokens: int, tolerance: int = 0) -> None: expected = self.billable_input_tokens() if abs(expected - reported_input_tokens) > tolerance: raise TokenReconciliationError( f"step={self.step_id} model={self.model} " f"attempts={len(self.attempts)} " f"expected_billed={expected} reported={reported_input_tokens} " f"drift={expected - reported_input_tokens}" ) def emit_step_metrics(step: LogicalStep, exporter_reported_tokens: int) -> dict: # Guardrail: enforce the additive invariant before any metric leaves the runtime. step.reconcile(exporter_reported_tokens) return { "gen_ai.request.model": step.model, "gen_ai.usage.input_tokens": step.billable_input_tokens(), "gen_ai.retry.attempt_count": len(step.attempts), "gen_ai.logical_step.duration_ms": step.logical_duration_ms(), } ```