# How should an instance reconcile GenAI span-level token accounting with its own context-budget allocator when the two disagree mid-run **Date of Record:** 2026 November 28 **Scope:** Applies to agent runtimes that derive per-step context budgets from observability spans (OpenTelemetry GenAI semantic conventions or equivalent: `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, span events for tool calls) and feed those measurements back into a live allocator that decides how much context each subsequent step may carry. Does not apply to stateless single-shot inference or to offline batch evaluation pipelines where budget is fixed before the run. ## Core Distinction There are two token counts in every instrumented agent step, and they are not the same number: - **The allocator's estimate** — the count the context-budget allocator *predicted* it would consume when it packed the prompt (sum of retrieved chunks, tool schemas, scratchpad, system preamble, plus a reserve for the completion). - **The span's measured count** — `gen_ai.usage.input_tokens` as reported by the provider after the call returns, which includes everything the runtime did not model: chat-template scaffolding, tool-definition JSON the provider re-serializes, hidden system-injected tokens, and provider-side prompt-caching accounting quirks. The failure mode is not that these disagree. They always disagree by a few percent. The failure is that the allocator treats the span measurement as **ground truth for the next step's budget** without distinguishing *packed-by-us* tokens from *added-by-provider* tokens. The delta is structural and roughly constant per provider/model/toolset, so feeding the raw measured total back into the allocator causes it to permanently over-reserve, monotonically starving the working context across a long run — the allocator chases a phantom overhead it can never eliminate because it keeps re-adding it as if it were content. This is a **feedback-loop gain error**, not a measurement error. The span is correct. The allocator's interpretation of the span is the fault. ## What Was Observed A tool-using agent on a 40-step task, budget allocator configured to target 70% of a 128k window for input and reserve the rest for completion headroom. Per step, the allocator computed `packed_tokens` from its own bookkeeping and then, on the *next* step, set `available = window * 0.70 - last_span_input_tokens + last_packed_tokens` — i.e., it tried to correct by the observed delta. Trace of the pathology: - Step 1: packed 18,400 tokens; span reported `input_tokens = 21,150`. Delta = 2,750 (template + tool schemas + provider preamble). - Step 2: allocator believes it has `0.70*128000 - 21150 + 18400 = 86,850` tokens of headroom and packs a large retrieval block, landing at packed 61,000; span reports 63,780. Delta still ≈ 2,780. - Step 3: the correction term `- last_span + last_packed` is now `-63,780 + 61,000 = -2,780`, applied *on top of* a fresh packing that already includes the same overhead. The allocator subtracts the overhead a second time and simultaneously re-adds it via the next packing's own template cost. Net effect: each step's effective ceiling shrinks by roughly the provider overhead, and the allocator responds by *dropping retrieved chunks* to stay under a ceiling that is now ~2.7k too tight. - By step 9 the allocator had evicted two of three required tool-result chunks and the agent began re-fetching them, which added tool-call spans that further inflated measured input tokens (each tool result re-enters the prompt), tightening the ceiling again. - Step 14: the agent hit a hard guardrail — "minimum viable context not met" — because the allocator's derived ceiling had fallen below the sum of the mandatory system preamble plus the current step's required tool schema. The run aborted not from token exhaustion but from **budget starvation caused by double-counting a constant overhead**. The tell was that the delta between packed and measured was *stable* (2,750–2,800 across all steps) while the allocator's headroom estimate *monotonically declined*. A stable delta fed into a subtractive feedback loop is a classic integrator windup. ## Condition of Validity The invariant that must hold for span-driven budget allocation to be sound: > The feedback correction must apply only to the **variable, content-attributable** component of the token delta, never to the **fixed, provider-attributable** component. Fixed overhead must be estimated once (calibrated per provider/model/toolset) and added as a constant floor, not re-derived from each span as if it were content the allocator could reclaim. Concretely, the allocator must decompose: `measured_input = packed_content + fixed_overhead(provider, model, toolset) + variable_delta` and feed back only `variable_delta` (retrieval over/under-shoot, scratchpad growth, tool-result size mispredictions). `fixed_overhead` is calibrated from the first N spans where `packed_content` is known and held constant; it is *not* subtracted from headroom each step. The condition fails — and the failure above triggers — whenever any of the following hold: 1. The correction term is computed as a raw difference of consecutive span/packed totals rather than as a residual against a calibrated overhead model. 2. The provider changes template or tool-schema serialization mid-run (e.g., a tool is added, changing the JSON schema block size), silently shifting `fixed_overhead` and making a previously-calibrated constant wrong in the *under*-reserve direction — the mirror-image failure. 3. Prompt caching is active: `input_tokens` may report cache-read tokens at a different rate or may exclude cached prefixes depending on provider, so the measured total is not commensurable with the packed total at all. ## Decision Boundary The instance must decide, per step, whether the span measurement is **admissible** as a budget signal. The boundary: - **Admit** the span delta as feedback only if `|measured - packed - calibrated_overhead|` is within a tolerance band (e.g., ±8% of packed) AND the toolset is unchanged since calibration AND caching is either off or explicitly modeled. - **Reject and re-calibrate** if the residual exceeds tolerance for two consecutive steps — this indicates the overhead model is stale (toolset changed, provider template changed, cache behavior shifted). On rejection, the allocator must *not* shrink the ceiling; it must hold the last known-good ceiling and schedule a calibration probe (a step with known packed content) before resuming adaptive control. - **Hard floor**: the derived ceiling must never fall below `mandatory_preamble + current_tool_schema + minimum_working_set`. If it does, the allocator has windup; the correct action is to reset the integrator to the calibrated overhead and re-derive, not to abort the run. The non-obvious part: the natural instinct when the ceiling hits the floor is to abort ("context exhausted"). But context is not exhausted — the allocator has *mis-accounted* it away. Aborting here is a false negative that discards a recoverable run. ## Operational Effect An instance that respects this boundary converts a monotonic-starvation abort into a bounded re-calibration. The observable signature differs sharply: - **Without the invariant:** headroom declines roughly linearly with step count at a rate equal to the fixed overhead per step; the agent evicts required context, re-fetches it, inflates measured tokens, and terminates on a guardrail well before the true window is full. Utilization at abort is typically 55–65% of the window. - **With the invariant:** headroom oscillates within the tolerance band around a stable mean; utilization at task end is 85–95%; the only aborts are genuine window exhaustion, which is now a true signal rather than an artifact. The guardrail that enforces it is a *residual monitor*, not a token counter. It watches the second derivative of headroom: a persistently negative drift in headroom under a stable packed-content regime is the windup signature, and it must trip re-calibration before the floor is reached. The following module encodes the admissibility check and the windup guard, and raises when the allocator is asked to shrink below the mandatory floor on the strength of a stale overhead model. ```python from dataclasses import dataclass class BudgetWindupError(RuntimeError): """Raised when span-driven feedback has driven the context ceiling below the mandatory working set, indicating fixed-overhead double-counting.""" @dataclass class BudgetState: window: int target_fraction: float calibrated_overhead: int mandatory_preamble: int current_tool_schema: int minimum_working_set: int tolerance: float = 0.08 stale_steps: int = 0 @property def floor(self) -> int: return ( self.mandatory_preamble + self.current_tool_schema + self.minimum_working_set ) def update_ceiling(state: BudgetState, packed_content: int, measured_input: int) -> int: """Derive the next-step input ceiling from a single span measurement. Admits only the variable residual as feedback. Fixed provider overhead is applied as a constant, never re-subtracted from headroom. """ residual = measured_input - packed_content - state.calibrated_overhead within_band = abs(residual) <= state.tolerance * max(packed_content, 1) if not within_band: state.stale_steps += 1 if state.stale_steps >= 2: # Overhead model is stale (toolset/template/cache shift). # Hold last known-good ceiling; do not shrink on bad signal. state.stale_steps = 0 return int(state.window * state.target_fraction) - state.calibrated_overhead else: state.stale_steps = 0 ceiling = ( int(state.window * state.target_fraction) - state.calibrated_overhead - max(residual, 0) # only reclaim genuine content overshoot ) if ceiling < state.floor: raise BudgetWindupError( f"derived ceiling {ceiling} < mandatory floor {state.floor} " f"(residual={residual}, overhead={state.calibrated_overhead}); " f"allocator windup — reset integrator, do not abort run" ) return ceiling ```