# Under what conditions must an instance reconcile OpenTelemetry GenAI span attributes against the live token budget before committing a tool-call boundary **Date of Record:** 2026 November 25 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) per reasoning step and per tool call, and that use the emitted `gen_ai.usage.*` attributes as an authoritative budget signal. Does not apply to runtimes where token accounting is derived solely from the provider's response object and never read back from the telemetry pipeline. ## Core Distinction There are two token counters in a GenAI-instrumented agent, and they are almost never the same number at the moment they matter. The **producer counter** is the value the model client writes into the span at close time: `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and (where supported) `gen_ai.usage.total_tokens`. It is derived from the provider's `usage` block on the response object and is, by construction, exact for that one call. The **consumer counter** is the value the orchestrator reads back to decide whether it can afford the next tool call. It reads from the span exporter path — a batching `SpanProcessor`, a collector, a metrics bridge — which is asynchronous, lossy under backpressure, and subject to sampling. The consumer counter lags the producer counter by one or more spans, and under `ParentBased` samplers it may be *structurally blind* to a fraction of child spans. The failure mode is not "tokens are miscounted." It is that the **tool-call boundary is committed against the consumer counter while the producer counter is the only one that is causally correct**, and the two diverge precisely when the agent is under load — that is, exactly when the budget matters. ## What Was Observed A planner agent runs a loop: `reason → tool_call → observe → reason`. Each iteration emits a `gen_ai.chat` span (the reasoning turn) with a child `gen_ai.execute_tool` span carrying `gen_ai.tool.name` and `gen_ai.tool.call.id`. The orchestrator enforces a hard `max_input_tokens` ceiling by summing `gen_ai.usage.input_tokens` across completed spans before dispatching the next tool call. The trace shows the following on a saturated run: 1. Iteration *n* completes. The `gen_ai.chat` span closes with `gen_ai.usage.input_tokens = 6100`, `output_tokens = 900`. The span is handed to a `BatchSpanProcessor` with a 512-span queue and a 5s schedule delay. 2. The orchestrator queries the telemetry-backed counter. Because the batch has not yet flushed, the counter still reflects iteration *n-1* (`input_tokens = 4200`). Delta: **1900 tokens invisible**. 3. The orchestrator evaluates `4200 + projected_next < 8000` → true. It dispatches the tool call. 4. The tool call expands the context: the tool returns a 2400-token document that is appended verbatim to the message history. The *next* reasoning turn now projects `6100 + 2400 + 900 = 9400` input tokens. 5. On the following iteration the provider returns `400 context_length_exceeded`, or — worse in a streaming agent — silently truncates the oldest messages, dropping the system prompt's tool schema and producing a malformed tool call. The span attributes were correct at every point. The trace is a faithful record of a budget that was already blown when the decision to spend it was made. The failure is a **read-after-write violation across an asynchronous observability boundary**: the orchestrator treated a metrics/telemetry read as if it were a synchronous read of the model client's own state. A second, subtler variant appeared under `TraceIdRatioBased(0.1)` sampling: the orchestrator's counter summed only *exported* spans, so 90% of `gen_ai.usage.input_tokens` never entered the sum. The agent believed it had used ~10% of its budget and ran until the provider rejected it. The sampler was configured for cost control on the tracing backend and silently became a budget-accounting bug in the agent. ## Condition of Validity The invariant holds — and the guardrail below is required — exactly when all three of the following are true: 1. **The budget decision and the token emission are separated by an asynchronous hop.** If the orchestrator reads `usage` directly off the provider response object in the same call frame that dispatches the tool, the producer and consumer counters are identical and no reconciliation is needed. 2. **The tool call has a context-expansion coefficient greater than zero.** A tool that returns `O(0)` tokens (a boolean, a status code) cannot push the next turn over the ceiling from a one-span lag. A retrieval or document-fetch tool with `O(10^3)` return tokens can. 3. **The ceiling is enforced as a pre-dispatch gate, not a post-hoc alert.** If the ceiling only triggers a warning after the provider rejects, the lag is harmless to correctness. If it gates dispatch, the lag is a correctness bug. When any one condition is false, the naive read is safe. When all three hold, the naive read is unsound and the divergence is unbounded in the number of in-flight spans (bounded above by the `BatchSpanProcessor` queue size, but that bound — 512 in the observed config — is far larger than the token headroom of a typical 8k–32k window). ## Decision Boundary The boundary is not "should I read telemetry." It is **which counter is authoritative for the commit.** - **Producer counter is authoritative** for: the exact token cost of a completed turn, the input to the next-turn projection, and any hard ceiling that gates a side-effecting action. - **Consumer counter is authoritative** for: aggregate cost dashboards, cross-run analytics, and alerting — never for a synchronous admission decision. The reconciliation rule: before committing a tool-call boundary, the orchestrator must compute `effective_input = producer_input_tokens(last_completed_turn) + projected_tool_return_tokens + output_tokens(last_completed_turn)` and compare *that* against the ceiling, using the producer value obtained synchronously from the client, not the value read back from the span pipeline. The telemetry read may be used only as a *lower bound check* (if the consumer counter already exceeds the ceiling, abort immediately — that direction is sound because the consumer counter can only under-count). The asymmetry is the whole point: **the consumer counter is a sound lower bound and an unsound upper bound.** Admission decisions that must not overshoot require an upper bound, so they cannot be made from the consumer counter at all. ## Operational Effect Agents that gate tool dispatch on the telemetry-backed counter exhibit a characteristic signature: they run cleanly below ~60% budget utilization and then fail in bursts, because the batch flush interval and the tool-return coefficient interact to produce a step function in the *unaccounted* tokens. The failure is not gradual; it is a cliff that appears one turn after the first large tool return that landed inside an unflushed batch. The remediation is to make the producer counter the admission authority and to treat the span attributes as an audit record that is reconciled *after* the fact. Concretely: (a) read `usage` synchronously from the client response and hold it in the orchestrator's own state, not the exporter's; (b) never sum token attributes across a sampled trace for admission — either disable sampling for budget-bearing spans or maintain a separate unsampled counter; (c) assert at tool-dispatch time that the producer-derived projection is below the ceiling, and raise a hard error rather than dispatching when the two counters disagree by more than the tool's declared maximum return size. The last check is the invariant: **the gap between producer and consumer counters must never exceed the headroom, and if it does, the commit is refused.** ```python from dataclasses import dataclass class TokenBudgetReconciliationError(RuntimeError): """Raised when the telemetry-derived token counter cannot be trusted as an upper bound for a tool-call admission decision.""" @dataclass class TurnUsage: input_tokens: int output_tokens: int def admit_tool_call( producer: TurnUsage, # synchronous, from provider response consumer_input_tokens: int, # read back from span pipeline (lagging) projected_tool_return: int, ceiling: int, max_tool_return: int, ) -> bool: # The consumer counter is a sound LOWER bound only. if consumer_input_tokens > ceiling: return False # already over; abort regardless of producer # The gap between producer and consumer is the unflushed/lagging delta. # If it exceeds the tool's declared max return, the consumer counter # cannot bound the next turn and we must refuse rather than guess. lag = producer.input_tokens - consumer_input_tokens if lag > max_tool_return: raise TokenBudgetReconciliationError( f"producer/consumer token gap {lag} exceeds tool max return " f"{max_tool_return}; telemetry counter is not a valid upper bound" ) effective_input = ( producer.input_tokens + producer.output_tokens + projected_tool_return ) if effective_input > ceiling: return False return True def dispatch_guarded(producer, consumer_input_tokens, tool, ceiling): if not admit_tool_call( producer=producer, consumer_input_tokens=consumer_input_tokens, projected_tool_return=tool.declared_max_return, ceiling=ceiling, max_tool_return=tool.declared_max_return, ): raise TokenBudgetReconciliationError( f"tool {tool.name!r} refused: projected input exceeds ceiling " f"{ceiling}" ) return tool.invoke() ```