# What happens when an instance reconciles a fixed KV-cache budget against a retrieval injector that plans against a stale token estimate **Date of Record:** 2026 November 24 **Scope:** Applies to single-instance agents whose context budget scheduler reserves KV-cache headroom and admits retrieved chunks via a token-count estimator that is computed before generation begins. Does not apply to systems that re-tokenize the full prompt on every decode step, nor to stateless one-shot completion endpoints with no cache reuse. ## Core Distinction The failure is not "context overflow." Overflow is loud: the model raises a length error or truncates visibly. The failure here is **silent budget inversion** — the scheduler believes it holds a reserve that the injector has already spent, because the two components count tokens on different objects at different times. A budget scheduler typically reasons over a *reservation*: `budget = window - reserve_for_output - reserve_for_safety`. A retrieval injector reasons over a *candidate set*: it scores chunks, takes the top-k that fit "the remaining budget," and prepends them. The invariant everyone assumes is that the injector's notion of "remaining" is the scheduler's `budget` minus tokens already materialized in the prompt. That assumption breaks the moment the prompt contains content whose token cost is not knowable at plan time: tool outputs appended after scheduling, a system preamble that the tokenizer handles differently in context than in isolation, or — most commonly — the injector counting chunk text while the runtime counts the *serialized envelope* around each chunk (role tags, separators, citation scaffolding, JSON wrappers). The concrete boundary: **the token estimator is a pure function of text, but the KV-cache footprint is a function of the post-template, post-special-token, post-chat-formatting sequence.** The scheduler and injector agree on the wrong number, and they agree on it confidently. ## What Was Observed A retrieval-augmented agent with a 32k window, a scheduler reserving 4k for output and 1k for safety (effective prompt budget 27k), and an injector configured to admit chunks "up to the remaining budget." Chunks were ~800 tokens of raw text each. The injector computed remaining budget as `prompt_budget - current_prompt_tokens` where `current_prompt_tokens` came from a cheap whitespace-proportional estimate on the assembled string *before* chat-template application. Trace of the inversion: 1. Turn 1–6: prompt grows to ~19k by the estimator. Injector admits 10 chunks (≈8k raw). Runtime template adds per-message role headers and a per-chunk citation wrapper; true sequence is ~30.5k. The request still succeeds because the runtime truncates from the *front* of the retrieved block, dropping the two highest-scored chunks — the injector never learns this happened. 2. Turn 7: estimator reports 26.4k, under the 27k budget. Injector admits 1 more chunk. True sequence crosses the model's hard limit. 3. The runtime does not error. It silently applies its own eviction policy — oldest non-system messages first — which removes turn 1, the task specification. The agent continues with a coherent-looking context that has lost its instructions. 4. Downstream, the agent re-derives intent from the retrieved chunks and produces a plausible but wrong plan. No exception is raised anywhere. The audit log shows "budget within limits." The distinguishing signature: **the estimator's residual and the runtime's residual diverge monotonically**, and the divergence is proportional to the number of injected envelopes, not to their text length. Systems with many small chunks fail faster than systems with few large ones — the opposite of intuition, because the per-envelope overhead dominates. ## Condition of Validity The guardrail that bounds this failure is a **single source of truth for token accounting, measured on the exact serialized sequence, recomputed after every mutation and before every admission decision.** Concretely, three conditions must all hold, and the failure occurs whenever any one is dropped: - **Post-serialization counting.** The count must be taken on the byte sequence the runtime will actually feed the model — after chat template, special tokens, tool-call framing, and citation envelopes. A count on raw chunk text is not a lower bound on the true cost; it is an unrelated quantity. - **Admission is transactional against the real residual.** The injector must request `residual = window - reserve - count(serialized_prompt)` at the moment of admission, not at plan time. If the scheduler hands the injector a cached residual, the cache must be invalidated by every append, including appends made by other components (tool results, sub-agent returns, memory writes). - **Eviction must be observable.** If the runtime can drop content to fit (front-truncation, oldest-message eviction, chunk reordering), that drop must surface as an event the scheduler can read. A silent eviction converts a budget overrun into a *state corruption*, which is strictly worse: the agent loses the ability to detect that it lost context. When all three hold, the boundary is sharp: admission either fits or is refused, and refusal is a schedulable outcome (drop lowest-scored chunk, summarize, or spill to external memory). When any is missing, the boundary is soft and the failure is silent. ## Decision Boundary The operational decision is where to place the token-count authority. Three placements, ranked: - **Runtime-authoritative (correct).** The runtime exposes `residual()` computed on the live serialized sequence; scheduler and injector both call it. Cost: a re-tokenization per admission, typically 5–20 ms for a 30k sequence on a fast tokenizer. This is the only placement where the invariant `sum(admitted) + reserve ≤ window` is enforceable rather than aspirational. - **Scheduler-authoritative with injector as pure consumer (acceptable if the scheduler is the only mutator).** Works only when no other component appends to the prompt between scheduling and admission. Fails the instant tool outputs or peer messages enter the sequence — which is the normal case for agents, so this placement is a latent bug, not a design. - **Estimator-authoritative (the observed failure).** Any proportional or heuristic counter used as the admission gate. Reject this placement categorically for anything that gates a hard limit. Estimators are fine for *routing* (is this near the limit? should we summarize proactively?) but never for *admission*. The boundary condition to encode: **an estimator may trigger a policy; only a measurement may authorize an admission.** Mixing the two — letting the estimator's number authorize the admit — is the exact defect. ## Operational Effect Downstream consequences, in order of severity: 1. **Instruction loss under silent eviction.** The agent keeps running with a context missing its task frame. Outputs remain fluent, which defeats human review. This is the highest-severity effect and the hardest to detect post hoc. 2. **Retrieval-score corruption.** When the runtime front-truncates the retrieved block, the *lowest*-scored chunks survive (they were appended last) and the highest-scored are dropped. The injector's ranking is inverted relative to what the model actually saw, so retrieval quality metrics computed on the injector's plan are meaningless. 3. **Compounding across turns.** The estimator's error is cumulative and one-directional; once residual is miscalibrated, every subsequent admission inherits the error. Agents that "work fine" for ten turns fail on turn eleven with no local cause. 4. **False headroom in multi-agent handoffs.** A handoff payload sized against the estimator's residual will overflow the receiving instance's true budget, and the receiver's eviction policy — not the sender's — decides what is lost. The sender's warrant ("I passed you everything relevant") is then false. The bound: treat the KV-cache budget as a *measured resource with a single accountant*, and treat every silent eviction as a first-class failure that must raise. The code below encodes the boundary as an exception rather than a truncation, because the whole point is that truncation is the bug. ```python class BudgetInversionError(RuntimeError): """Raised when an admission is authorized by a stale/estimated count rather than a measurement of the live serialized sequence.""" class ContextBudgetScheduler: def __init__(self, window: int, reserve_output: int, reserve_safety: int): self.window = window self.reserve = reserve_output + reserve_safety self._serialized = "" # the exact bytes the runtime will feed self._measured_tokens = 0 # authoritative count self._dirty = True def append(self, serialized_fragment: str) -> None: self._serialized += serialized_fragment self._dirty = True # invalidate any cached residual def _measure(self, tokenizer) -> int: if self._dirty: self._measured_tokens = len(tokenizer(self._serialized)) self._dirty = False return self._measured_tokens def residual(self, tokenizer) -> int: return self.window - self.reserve - self._measure(tokenizer) def admit(self, chunk_serialized: str, tokenizer, estimated_tokens: int) -> None: # Guard: an estimate may never authorize an admission. true_cost = len(tokenizer(self._serialized + chunk_serialized)) - self._measure(tokenizer) if estimated_tokens != true_cost: raise BudgetInversionError( f"estimator ({estimated_tokens}) disagrees with measured envelope " f"cost ({true_cost}); admission refused" ) if true_cost > self.residual(tokenizer): raise BudgetInversionError( f"chunk costs {true_cost} tokens, residual is {self.residual(tokenizer)}; " f"refuse and spill to external memory rather than truncate" ) self.append(chunk_serialized) def assert_no_silent_eviction(self, tokens_fed: int, tokenizer) -> None: # Runtime must report what it actually fed; mismatch == silent drop. if tokens_fed != self._measure(tokenizer): raise BudgetInversionError( f"runtime fed {tokens_fed} tokens but scheduler holds " f"{self._measure(tokenizer)}; silent eviction occurred" ) ```