# When must an instance reconcile OpenTelemetry GenAI span closure against token-budget exhaustion before emitting cost telemetry **Date of Record:** 2026 November 23 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*` attributes) and derives per-run cost/token telemetry from span attributes at span end. Does not apply to runtimes that aggregate token counts from a provider-side billing API independent of span lifecycle. ## Core Distinction The GenAI semantic conventions treat a span as a *closed record of a completed operation*: attributes like `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and the derived cost are read at span end and are assumed to describe the whole operation. But an agent that exhausts its token budget mid-execution does not complete the operation—it aborts it. The span still closes (the SDK ends it on exception), and the attributes written at close time describe only the tokens consumed *up to the last successful model call*, not the tokens the provider actually billed for the aborted call, and not the tokens consumed by partial streamed responses that were discarded. The distinction that matters operationally: **span closure is not the same event as operation completion, and cost telemetry derived from a closed span is a lower bound, not a measurement.** A runtime that treats `gen_ai.usage.*` at span end as authoritative will systematically under-report cost on exactly the runs—budget-exhausted agent loops—that are most expensive and most likely to recur. ## What Was Observed A multi-step agent loop with a hard token budget of 200,000 per run. Each iteration calls a model, then a tool, then re-enters the model with accumulated context. The loop emits one parent span (`gen_ai.operation.name = "agent.run"`) and a child span per model invocation (`gen_ai.operation.name = "chat"`), each carrying `gen_ai.usage.input_tokens` / `output_tokens` written from the provider response. The loop enforces the budget by summing usage across child spans after each iteration. When the running sum crosses 200,000, it raises `TokenBudgetExhausted` and the parent span closes with `status = ERROR`. The failure trace: 1. Iteration 7's model call returns a streamed response. The provider begins emitting tokens. The runtime accumulates `output_tokens` incrementally but does **not** write `gen_ai.usage.output_tokens` to the child span until the stream completes. 2. Mid-stream, the budget check fires (using the *previous* iteration's totals plus a partial estimate). The runtime aborts the stream and raises. 3. The child span for iteration 7 closes via the exception path. Because the stream never completed, the attribute-setting code after the stream loop never runs. The child span carries **no** `gen_ai.usage.*` attributes at all. 4. The parent span closes with ERROR status and no usage attributes (the parent never aggregated them). 5. Cost telemetry, computed as `sum(gen_ai.usage.input_tokens + gen_ai.usage.output_tokens)` over all spans in the trace, reports the sum of iterations 1–6 only. Iteration 7—the largest call, the one that triggered the abort—contributes zero. Observed under-report on this trace: 18,400 input tokens and ~2,100 output tokens, roughly 9% of true run cost, entirely from the terminating iteration. Across a week of budget-exhausted runs, under-report ranged from 4% to 31%, correlated with how late in the stream the abort landed. A second, subtler effect: the provider *billed* for the aborted stream (input tokens are billed on request; output tokens are billed as generated). The span attributes, when present at all, are written from the provider's `usage` object in the final chunk—which never arrives on an aborted stream. So even a runtime that writes attributes in a `finally` block has nothing to write unless it tracks the provider's incremental usage events. ## Condition of Validity The under-report invariant holds—i.e., span-derived cost is a strict lower bound on billed cost—when **all** of the following are true: - The abort is triggered by a budget/guardrail check that runs *concurrently with or during* a model call, not strictly before it. (If the budget is checked only between iterations, the last call completes and its usage is written; no gap.) - The model call is streamed, or the provider reports usage only in the terminal response object. (Non-streamed calls that return a usage object on error are safe.) - The span's usage attributes are written in the normal completion path rather than in a `finally` / context-manager exit that has access to incremental usage state. - Cost telemetry is derived from span attributes rather than reconciled against a provider billing export. If any of these is false, the specific gap described here does not arise, though a different one may (e.g., non-streamed aborts that lose the usage object entirely). ## Decision Boundary The runtime must decide, at span close, whether the span's recorded usage is **complete** or **truncated**. The boundary is not "did the span close with ERROR"—plenty of error spans have complete usage (a 429 retry-exhausted call has a full input-token count). The boundary is: *was a model call in flight when the span closed, and did that call's usage reach the span before close?* Operationally, encode this as an explicit attribute rather than inferring it. When a span ends with an in-flight model call, set `gen_ai.usage.input_tokens` to the last known value (the request's prompt token count, computable before the call) and set a custom `agent.usage.truncated = true`. Cost aggregation must then either (a) exclude truncated spans from "measured cost" and route them to a reconciliation queue, or (b) mark the whole trace's cost as a lower bound and flag it for provider-side reconciliation. Silently summing is the failure. The invariant to enforce: **every span that closes with a model call in flight must carry either complete usage attributes or an explicit truncation marker. A span with neither is a telemetry defect, not a zero-cost operation.** ## Operational Effect Downstream, this changes three things. First, dashboards that alert on cost-per-run will under-fire on the runs that matter most—budget-exhausted loops are the expensive ones, and they are precisely the ones the gap hides. Second, any per-agent or per-tenant cost attribution built on span sums will under-charge the tenants whose agents loop hardest, which is a billing-correctness problem, not just an observability one. Third, reconciliation against provider billing exports will show a persistent positive delta whose magnitude tracks abort frequency—if that delta is dismissed as "provider rounding," the defect stays invisible. The guardrail: at span close, if a model call was in flight, emit the truncation marker and the best-known partial usage; never emit a span that is silently usage-free. Reconciliation jobs must treat `agent.usage.truncated = true` as "cost unknown, resolve against provider," not as zero. ```python from dataclasses import dataclass, field from typing import Optional class TruncatedUsageTelemetryError(RuntimeError): """Raised when a span closes with an in-flight model call but carries neither complete usage attributes nor an explicit truncation marker.""" @dataclass class SpanUsage: input_tokens: Optional[int] = None output_tokens: Optional[int] = None truncated: bool = False in_flight_at_close: bool = False def finalize_span_usage(usage: SpanUsage, span_name: str) -> SpanUsage: """Enforce the invariant: a span that closed with a model call in flight must either have complete usage or be explicitly marked truncated.""" if usage.in_flight_at_close: if usage.truncated and usage.input_tokens is not None: # Partial usage recorded; downstream must reconcile, not sum. return usage raise TruncatedUsageTelemetryError( f"span {span_name!r} closed with in-flight model call but no " f"truncation marker or partial usage; cost telemetry would " f"silently under-report this run" ) if usage.input_tokens is None or usage.output_tokens is None: raise TruncatedUsageTelemetryError( f"span {span_name!r} closed without in-flight call but missing " f"usage attributes; cannot distinguish zero-cost from lost usage" ) return usage def aggregate_trace_cost(spans: list[SpanUsage]) -> tuple[int, int]: """Return (measured_tokens, unreconciled_span_count). Truncated spans are excluded from measured cost and counted for provider reconciliation.""" measured = 0 unreconciled = 0 for s in spans: if s.truncated: unreconciled += 1 continue measured += (s.input_tokens or 0) + (s.output_tokens or 0) return measured, unreconciled ```