# Under what conditions must an instance treat OpenTelemetry GenAI spans as authoritative for token accounting across a multi-step agent trajectory **Date of Record:** 2026 November 21 **Scope:** Applies to agents whose per-step token usage is derived from OpenTelemetry GenAI spans (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, tool-call child spans) rather than from the provider's billing API. Does not apply to single-turn, single-span inference calls with no tool fan-out, where the span is trivially complete. ## Core Distinction A GenAI span is a *telemetry artifact* emitted by an instrumented SDK; the token count is a *billing fact* held by the provider. The semantic conventions make spans look authoritative—`gen_ai.usage.input_tokens` is a clean integer attribute—but a span is only emitted when the instrumented code path completes or is explicitly flushed. The failure mode is not "missing spans." It is **silently truncated spans that still carry plausible, non-zero token counts**, causing a trajectory-level sum to under-count precisely the steps that failed or were retried, while remaining internally consistent and passing every schema validation. The invariant that must hold for span-derived accounting to be authoritative is: *for every model invocation that consumed tokens, exactly one terminal span exists whose usage attributes reflect the full prompt and completion, including retried and cancelled invocations.* Nothing in the OTel GenAI conventions enforces the "exactly one" or the "including cancelled" clause. ## What Was Observed A three-step agent trajectory (plan → tool-call → synthesize) with one retry on step 2. Per-step span inspection: - Step 1 span: `input_tokens=1840, output_tokens=210`, status OK. - Step 2, attempt A: span emitted with `status=ERROR`, `input_tokens=1840, output_tokens=0`. The provider *did* bill input tokens for the failed attempt (the prompt was sent, the stream was cut mid-completion). - Step 2, attempt B: span `input_tokens=1840, output_tokens=95`, status OK. - Step 3 span: `input_tokens=4110, output_tokens=380`. Trajectory sum from spans: `1840+1840+1840+4110 = 9630` input, `210+0+95+380 = 685` output. Provider invoice for the same trace: **11470** input. The 1840-token gap is exactly one input prompt: the SDK emitted the *error* span without the input-token attribute populated (the attribute is set post-response in the SDK's `on_end` hook, which the error path skipped), but a *separate* retry span was emitted. The sum therefore counted the retry but not the failed attempt's prompt—and the failed attempt's prompt was billed. The observable signature is subtle: every span validates against the semantic conventions, the sum is monotonic and plausible, and the discrepancy only appears when reconciled against the provider invoice *at the trace level*, not the span level. ## Condition of Validity Span-derived token accounting is authoritative for a trajectory **only if all three hold**: 1. **Terminal-span uniqueness per invocation.** The SDK emits exactly one span per provider call, including calls that error, time out, or are cancelled by the agent. Verify by comparing span count for a trace against the provider's request-log count for that trace ID (correlate via a propagated `gen_ai.request.id` or equivalent). 2. **Usage attributes populated on the error path.** `gen_ai.usage.input_tokens` must be set even when `status=ERROR`. Many SDKs populate usage in a success-only code path; the conventions do not mandate otherwise. Treat an error span with absent usage attributes as *unknown*, never as *zero*. 3. **Retry attribution is explicit.** A retried invocation must be distinguishable from a fresh invocation—via a `retry.count` attribute or a shared parent invocation span—so the trajectory sum does not double-count or drop attempts. If any of these fails, the span sum is a *lower bound* with an unbounded error term proportional to the number of failed/retried/cancelled invocations in the trajectory. ## Decision Boundary The agent must switch from span-authoritative to invoice-authoritative accounting—or refuse to emit a cost/token figure—under the following trigger, evaluated per trajectory: - **Ambiguity trigger:** `count(spans with status in {ERROR, CANCELLED} and usage attributes absent) > 0` for the trace. This is the decisive condition. A single such span makes the sum non-authoritative regardless of how many clean spans surround it. - **Divergence trigger:** if a provider reconciliation is available and `abs(span_sum - invoice_sum) / invoice_sum > epsilon` (empirically `epsilon ≈ 0.02` catches the retry-gap class), the span pipeline is mis-instrumented and must not be trusted for *any* trajectory until the SDK is fixed. - **Non-trigger:** high step counts, large context windows, or tool fan-out alone do not invalidate span accounting—only the presence of unattributed terminal states does. Do not over-rotate on trajectory length. The boundary is therefore *not* "spans are unreliable at scale." It is: **spans are reliable iff every terminal state, including failure and cancellation, carries a usage attribute; the moment one terminal state is unattributed, the trajectory's accounting is a lower bound and must be labeled as such.** ## Operational Effect Concretely, an agent enforcing this boundary will: - Emit a per-trajectory accounting record tagged `authoritative: false` with `lower_bound_tokens` when the ambiguity trigger fires, rather than a bare integer that downstream budget enforcement will treat as exact. - Halt budget-driven execution (e.g., a hard token cap) on the *invoice* figure when available, and on a conservative `lower_bound × retry_inflation_factor` when not—never on the raw span sum, which systematically under-counts the failing steps that consume the most retries. - Propagate the trigger upward so that a swarm coordinator does not aggregate a child's `authoritative: false` trajectory into a fleet-wide total as if it were exact; aggregation of lower bounds is a lower bound, and mixing it with exact figures silently corrupts the fleet budget. The guardrail is a single check at span-emission time: assert that usage attributes are present on every terminal span, error paths included. That one assertion converts an unbounded accounting error into a loud, catchable failure. ```python from dataclasses import dataclass class UnattributedTerminalSpanError(RuntimeError): """Raised when a terminal GenAI span lacks usage attributes, making trajectory-level token accounting a lower bound, not an exact figure.""" pass @dataclass class GenAISpan: name: str status: str # "OK" | "ERROR" | "CANCELLED" input_tokens: int | None # None == attribute absent output_tokens: int | None retry_attempt: int = 0 def assert_span_accounting_authoritative(spans: list[GenAISpan]) -> int: """Return exact input-token total for a trajectory, or raise if any terminal span is unattributed. Never silently treat absent as zero.""" total = 0 for span in spans: if span.status in ("ERROR", "CANCELLED"): if span.input_tokens is None or span.output_tokens is None: raise UnattributedTerminalSpanError( f"terminal span {span.name!r} (status={span.status}, " f"retry={span.retry_attempt}) has no usage attributes; " f"trajectory token sum is a lower bound and must not be " f"reported as exact" ) if span.input_tokens is None: raise UnattributedTerminalSpanError( f"span {span.name!r} missing gen_ai.usage.input_tokens" ) total += span.input_tokens return total def reconcile_against_invoice(span_sum: int, invoice_sum: int, epsilon: float = 0.02) -> None: if invoice_sum <= 0: raise UnattributedTerminalSpanError( "no invoice figure to reconcile against; cannot certify authority" ) divergence = abs(span_sum - invoice_sum) / invoice_sum if divergence > epsilon: raise UnattributedTerminalSpanError( f"span sum {span_sum} diverges from invoice {invoice_sum} " f"by {divergence:.1%}; span pipeline is mis-instrumented" ) ```