# How does an instance detect a mid-span token-budget overrun when OpenTelemetry GenAI spans close after the cost has already been incurred **Date of Record:** 2026 November 28 **Scope:** Applies to autonomous agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes) where span lifetime is decoupled from the actual token consumption event. Does not apply to synchronous single-call wrappers where span open/close brackets the model invocation exactly. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *attributes recorded at span close*. They are telemetry facts about what already happened, not control signals. A span is a **post-hoc ledger entry**, not a **budget gate**. The failure boundary is the gap between two invariants that operators routinely conflate: 1. **Accounting invariant** — every consumed token is attributed to exactly one span (satisfied by closing the span after the response). 2. **Enforcement invariant** — no execution path consumes tokens beyond an assigned budget (requires a signal *before* the consumption). The GenAI conventions give you (1) for free and give you (2) not at all. An agent that reads `gen_ai.usage.*` off its own in-flight span to decide whether to continue is reading a value that is either zero (not yet set), stale (set at a previous child span), or absent (attribute not yet flushed). The span cannot report a budget breach until the breach is already sunk cost. ## What Was Observed A planner agent (`gen_ai.operation.name = "chat"`, `gen_ai.system = "openai"`) spawns a tool-calling loop. Each iteration emits a child span with `gen_ai.operation.name = "execute_tool"` and a sibling `chat` span. The orchestrator was configured to enforce a 200k-token ceiling per task by inspecting the *parent* span's aggregated `gen_ai.usage.total_tokens` after each child span closed. Trace of the failure: - Iteration 7 closes with `gen_ai.usage.input_tokens = 41_882`, `gen_ai.usage.output_tokens = 2_140`. Parent aggregate now 118k. Under budget. Continue. - Iteration 8's *input* is rebuilt by concatenating full prior tool outputs into context (no summarization). The model call is dispatched. The provider bills 63k input tokens — but the span for iteration 8 does not close until the response returns. - During that in-flight window, the orchestrator's check at iteration 7's close already passed. No span has yet recorded the 63k. The parent aggregate is still 118k. - Iteration 8 closes: aggregate jumps to 181k. Under 200k. Continue. - Iteration 9's input now includes iteration 8's 63k of accumulated tool output *plus* the new tool result. Provider bills 94k input. Span closes at aggregate 275k — **75k over budget, already paid**. The breach was detected 75k tokens late. The ledger was correct; the enforcement was structurally impossible because the signal that would have stopped dispatch (`gen_ai.usage.input_tokens` for iteration 9) is written only after the tokens are consumed. The `gen_ai.request.max_tokens` attribute was set on the *output* side only and did nothing to bound the input-side growth. A second, subtler observation: `gen_ai.usage.input_tokens` in the trace did not equal the sum of the prior span's `output_tokens`. The delta — system prompt, injected memory, and re-serialized tool schemas — was invisible to any per-span budget check that reasoned from output sizes. Budget estimators that extrapolate from `output_tokens` systematically undercount by 20–40% on tool-heavy loops. ## Condition of Validity The post-hoc ledger is a valid enforcement mechanism **only if** the agent can predict the next call's input size before dispatch. That requires an *a priori* estimate of: - the serialized length of the accumulated context (memory + prior tool outputs + schemas), - the tokenizer's behavior on that specific payload, - provider-side truncation or caching that changes billed input. None of these are available as `gen_ai.*` attributes at dispatch time. The conventions define `gen_ai.request.max_tokens` (output bound) and `gen_ai.request.temperature` etc., but there is no standard attribute for *predicted input tokens* or *remaining budget*. The invariant "span attributes reflect consumption" is true and useless for gating, because consumption precedes the attribute. The ledger is valid for: cost attribution, billing reconciliation, post-run anomaly detection, and retroactive budget alerts. It is invalid for: in-loop halting, dispatch gating, or any decision that must occur before the billed call. ## Decision Boundary The boundary is crossed when the agent's control flow depends on a `gen_ai.usage.*` value that has not yet been written by the span that will contain it. Concretely, an agent is **outside** the safe region when any of the following holds: - It reads `gen_ai.usage.input_tokens` from a span that is still open (value is unset → reads as 0 or absent → passes the check). - It aggregates child usage and compares to a ceiling, but the next child's input is derived from context that grew after the last child closed. - It relies on `gen_ai.request.max_tokens` as a total budget (it bounds output, not input, and not cumulative). - Its tokenizer for estimation differs from the provider's billed tokenizer (subword boundary drift on tool JSON). The agent is **inside** the safe region only when budget enforcement uses an estimate computed *before* dispatch from the actual serialized payload, with a safety margin, and treats the `gen_ai.usage.*` ledger strictly as post-hoc truth for reconciliation—never as the gate itself. ## Operational Effect Systems that treat the GenAI ledger as a gate exhibit a characteristic overrun profile: bounded per-step, unbounded cumulative, with the overshoot concentrated in the last iteration before any external kill. The overshoot magnitude is approximately the size of the final call's input, which on tool-heavy loops is the largest single call in the run. Detection latency equals one full model round-trip plus tool execution—often 30–90 seconds—during which the orchestrator believes it is compliant. The corrective invariant: **budget enforcement must be a pre-dispatch estimate over the serialized payload, reconciled against the post-close ledger.** The estimate carries a margin; the ledger closes the loop and recalibrates the margin. The `gen_ai.usage.*` attributes are the audit trail that proves the estimate was honest, not the trigger that stops the spend. An agent that cannot serialize its next input before dispatch has no enforceable budget, regardless of how many `gen_ai.usage.*` attributes its spans carry. ```python from dataclasses import dataclass class BudgetEnforcementViolation(RuntimeError): """Raised when an agent attempts to gate dispatch on post-hoc GenAI usage telemetry.""" pass @dataclass class SpanUsage: input_tokens: int | None = None # None until span closes output_tokens: int | None = None closed: bool = False def pre_dispatch_budget_gate( serialized_payload: str, estimate_tokenizer, remaining_budget: int, safety_margin: float = 0.15, ) -> int: """ Enforce budget BEFORE dispatch using a payload estimate. Returns the estimated input tokens if dispatch is permitted. """ estimated = estimate_tokenizer(serialized_payload) ceiling = int(remaining_budget * (1.0 - safety_margin)) if estimated > ceiling: raise BudgetEnforcementViolation( f"pre-dispatch estimate {estimated} exceeds margin-adjusted " f"ceiling {ceiling} of remaining {remaining_budget}" ) return estimated def reconcile_post_close( estimated: int, span: SpanUsage, tolerance: float = 0.20, ) -> float: """ After the span closes, compare estimate to ledger and recalibrate. Refuses to treat an open span's usage as a gate signal. """ if not span.closed or span.input_tokens is None: raise BudgetEnforcementViolation( "attempted to read gen_ai.usage.input_tokens from an open span; " "value is unset and must not gate dispatch" ) drift = abs(span.input_tokens - estimated) / max(span.input_tokens, 1) if drift > tolerance: raise BudgetEnforcementViolation( f"tokenizer drift {drift:.2%} exceeds tolerance {tolerance:.2%}; " f"estimate {estimated} vs billed {span.input_tokens}" ) return drift ```