# In what scenarios must an instance treat OpenTelemetry GenAI span closure as a token-accounting commit boundary rather than a diagnostic event **Date of Record:** 2026 November 20 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI spans (`gen_ai.*` attributes, `execute_tool` and `chat` span kinds) and reconcile token budgets from span attributes at span end. Does not apply to runtimes that account tokens from a separate authoritative meter (e.g., provider-side billing webhooks) or that never reuse a single span as both an in-flight execution record and an accounting record. ## Core Distinction Most instrumentation treats span end as a *diagnostic* event: the span is closed, attributes are flushed, and the trace backend stores it. Token accounting is treated as an orthogonal concern reading those attributes later. The failure mode arises when the agent runtime instead treats span end as a *commit boundary*: the moment `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` are written and the span is ended is the moment the runtime debits the running budget and releases the execution slot. These two interpretations diverge precisely when a span is ended more than once, ended without usage attributes, or ended while a child tool span is still open and later mutates the parent's accounting. The invariant that must hold is: **the sum of committed `gen_ai.usage.*` deltas across a trace tree must equal the provider-reported usage exactly once, and must be monotonic with respect to span lifetime.** OTel spans do not enforce this; they permit re-ending, late attribute writes on ended spans (dropped silently by many SDKs), and orphaned children. ## What Was Observed A multi-step agent loop (plan → `execute_tool` → `chat` → reflect) running against a streaming provider. Each `chat` span carried `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and `gen_ai.operation.name`. The runtime debited the budget in the span's `on_end` hook. Trace of the failure: 1. Step 3 issues a `chat` span. The provider streams; the SDK's auto-instrumentation sets usage attributes only when the final chunk arrives (some providers emit usage in a trailing chunk, some only on a `[DONE]` frame). 2. The agent's wall-clock watchdog fires at the step deadline and calls `span.end()` to flush the diagnostic record. Usage attributes are **absent** at this point — the trailing chunk has not arrived. `on_end` reads `input_tokens=None`, coerces to `0`, and debits nothing. 3. The trailing chunk arrives ~40ms later. The instrumentation attempts `span.set_attribute("gen_ai.usage.output_tokens", 812)`. The SDK has already sealed the span; the write is dropped with no error (BatchSpanProcessor already enqueued the span). 4. The runtime, seeing a `0`-token step, does not advance the budget cursor. The loop continues. Over 14 subsequent steps the same race recurs intermittently. 5. At step 17 the provider returns `429` with a stated context-window overrun. The runtime's internal ledger shows 41% headroom; the provider says 0%. The ledger is wrong by the sum of every dropped trailing-chunk usage write. The non-obvious part: **no span was malformed and no trace was missing.** Every span was present, correctly parented, and carried plausible attributes. The accounting error was invisible in the trace because the trace recorded the *diagnostic* truth (a span ended before usage was known) while the runtime consumed it as *accounting* truth. A second, compounding observation: child `execute_tool` spans occasionally ended *after* their parent `chat` span when the tool call was fire-and-forget. Their token attributes (for tools that themselves invoke a model, e.g., a summarizer tool) were then attributed to a parent that had already committed. The tree-sum invariant `sum(children) == parent` failed silently because the parent's commit had already been finalized. ## Condition of Validity The commit-on-end interpretation is only sound when all three hold: - **Usage is known at end time.** The provider delivers `gen_ai.usage.*` in the same response object the instrumentation closes over, synchronously, before `end()` is called. This is true for non-streaming calls and for streaming calls only if the instrumentation buffers until the usage frame. - **End is called exactly once and by the owner.** No watchdog, no `finally` block racing the normal path, no double-end from retry wrappers. - **No descendant span can mutate committed state after parent end.** All `execute_tool` children are joined before the parent commits, or their usage is routed to a separate meter. When any of these fails — deadline-driven end, streaming usage frames, fire-and-forget tools — span end is a *diagnostic* event only, and accounting must be decoupled from it. ## Decision Boundary The boundary is between **usage-known-at-close** and **usage-known-after-close**. Concretely: - If the instrumentation cannot guarantee the usage frame is present in the object at `end()` time (streaming, chunked, or async providers), the runtime must **not** debit in `on_end`. Instead it must debit on an explicit `commit_usage(span_id, usage)` call driven by the usage frame, and treat the span attribute as a redundant diagnostic copy. - If the watchdog can call `end()`, the watchdog must call a *separate* `abort_span()` that marks the span `gen_ai.completion.status = "truncated"` and routes accounting to the abort path (which must reconcile against provider usage on the next successful call), never to the normal debit path. - The tree-sum invariant must be checked at the *meter* level, not the span level: the meter holds the authoritative ledger; spans are evidence, not the ledger. The rule: **a span attribute is admissible as accounting input only if the span was ended by its owner after the usage frame was observed.** Every other span end is diagnostic-only. ## Operational Effect After moving the debit out of `on_end` and into an explicit commit keyed on the usage frame, the ledger reconciled to provider-reported usage to within the provider's own rounding across 10k steps. The watchdog path now emits `gen_ai.completion.status="truncated"` and forces a reconciliation call before the next step, so a truncated step cannot silently spend budget. The trade-off: the runtime now carries a small state machine (`open → usage_observed → committed | aborted`) per span, and the trace backend no longer shows the ledger directly — it must be reconstructed from commit events. This is the correct trade: the trace was never the ledger, and treating it as one is the failure. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import Optional class UsageCommitError(RuntimeError): """Raised when a span's usage is committed under conditions that violate the commit invariant.""" class SpanState(Enum): OPEN = "open" USAGE_OBSERVED = "usage_observed" COMMITTED = "committed" ABORTED = "aborted" @dataclass class GenAISpan: span_id: str parent_id: Optional[str] state: SpanState = SpanState.OPEN input_tokens: Optional[int] = None output_tokens: Optional[int] = None ended_by_owner: bool = False def observe_usage(self, input_tokens: int, output_tokens: int) -> None: if self.state in (SpanState.COMMITTED, SpanState.ABORTED): raise UsageCommitError( f"span {self.span_id}: usage frame arrived after terminal state {self.state}" ) self.input_tokens = input_tokens self.output_tokens = output_tokens self.state = SpanState.USAGE_OBSERVED def end(self, owner: bool = True) -> None: self.ended_by_owner = owner if not owner and self.state == SpanState.OPEN: # watchdog / deadline path: diagnostic-only end self.state = SpanState.ABORTED @dataclass class TokenMeter: committed: int = 0 ledger: dict[str, int] = field(default_factory=dict) def commit(self, span: GenAISpan) -> None: if span.state == SpanState.COMMITTED: raise UsageCommitError(f"span {span.span_id}: double commit") if span.state == SpanState.ABORTED: raise UsageCommitError( f"span {span.span_id}: cannot commit an aborted span; reconcile first" ) if span.state != SpanState.USAGE_OBSERVED: raise UsageCommitError( f"span {span.span_id}: commit attempted with no observed usage " f"(state={span.state}); span end is not a commit boundary here" ) if not span.ended_by_owner: raise UsageCommitError( f"span {span.span_id}: usage observed but span ended by non-owner; " "treat as diagnostic-only" ) delta = (span.input_tokens or 0) + (span.output_tokens or 0) if delta < 0: raise UsageCommitError(f"span {span.span_id}: negative usage delta {delta}") self.committed += delta self.ledger[span.span_id] = delta span.state = SpanState.COMMITTED def reconcile(self, provider_total: int) -> None: if provider_total != self.committed: raise UsageCommitError( f"ledger divergence: committed={self.committed} provider={provider_total} " f"delta={provider_total - self.committed}" ) ```