# Why does an instance exhaust its context budget after the governor reports "allocation satisfied" **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that enforce a token budget governor partitioning a fixed context window across system prompt, retrieved memory, and tool output segments before each model call. Does not apply to unbounded-context models or to runtimes where tool outputs are streamed and truncated post-hoc rather than admit-controlled pre-call. ## Core Distinction A context budget governor is typically specified as an *allocation* invariant: the sum of reserved token budgets for each segment (system prompt, retrieved memory, pending tool outputs) must not exceed the model's usable context window minus a generation reserve. This is a **static, pre-call** check. It is routinely conflated with a **dynamic, per-call** invariant: that the *actual* serialized token count of the assembled prompt, measured by the model's own tokenizer at call time, stays within the same bound. The two are not equivalent. The governor satisfies the first and the runtime violates the second, because the unit of accounting (a reservation) and the unit of consumption (an encoded token stream) diverge under three conditions: tokenizer mismatch between governor and model, message-framing overhead that the governor does not model, and non-deterministic tool output that expands between reservation and serialization. The failure is not a governor bug in the arithmetic sense. The arithmetic is correct. The failure is that the governor's reservation is a *promise about a future serialization* that the serializer does not honor. ## What Was Observed A retrieval-augmented agent with a 128k-token window and a governor reserving 8k for system prompt, 64k for retrieved memory, 48k for tool output, and 8k generation reserve. The governor admitted a batch of retrieved chunks whose reservation summed to 63,912 tokens — under the 64k ceiling, "allocation satisfied," logged at INFO. The call was issued. The model returned a hard context-length error at the transport layer, not a soft truncation. Trace reconstruction showed three compounding deltas between reservation and serialization: 1. **Tokenizer drift.** The governor counted with a `cl100k_base` tokenizer approximation; the serving model used a different vocabulary. The 63,912-token reservation serialized to 67,340 actual tokens — a 5.4% expansion concentrated in the retrieved memory segment, which was dense in code identifiers and non-English text, the exact distribution where the two tokenizers diverge most. 2. **Framing overhead.** The governor modeled the conversation as concatenated segment strings. The actual chat template injected role delimiters, a tool-schema block, and per-message structural tokens that summed to 1,847 unmodeled tokens across the assembled messages. The governor had no term for this. 3. **Tool-output expansion.** One pending tool call had been reserved at its *declared* size (a paginated API returning "up to 4k tokens"). The actual response returned 4,000 rows and serialized to 9,210 tokens before the governor's per-tool cap was applied — and the cap was applied *after* the aggregate check, so the aggregate check passed on the stale reservation while the post-cap serialization exceeded the window. The call failed closed at the transport. Had the serving stack silently truncated instead, the agent would have run with a truncated memory segment and produced confident answers over a headless context — the more dangerous outcome, and the one this runtime was configured to avoid. ## Condition of Validity The allocation invariant "reserved sum ≤ window − generation reserve" is *valid* — meaning it implies the dynamic invariant — only when all three of the following hold: - **Tokenizer identity:** the governor's tokenizer is byte-identical to the serving tokenizer for the model actually invoked, including special-token handling. - **Framing closure:** the governor models the full serialized frame (role tags, tool schemas, structural delimiters), not the concatenation of segment payloads. - **Reservation finality:** every segment's reserved size is an upper bound on its serialized size, established *before* the aggregate check and not revised afterward. When any one fails, the governor's "allocation satisfied" is a statement about reservations, not about tokens, and carries no guarantee about the model call. The runtime observed above violated all three simultaneously; any single violation is sufficient to break the implication. ## Decision Boundary The governor must decide, per segment, whether to **admit** (reserve and proceed), **degrade** (shrink the reservation and re-serialize), or **reject** (fail the call before issuing it). The boundary that matters is not "does the sum fit the reservation ceiling" but "does the *measured serialized* sum fit the window." The correct decision procedure inverts the order: **serialize first, measure with the serving tokenizer, then compare.** A governor that reserves-then-serializes will always be exposed to the expansion gap. A governor that serializes-then-measures converts the gap from a silent overrun into a measurable quantity it can act on — degrade the lowest-priority segment (retrieved memory, then tool output) and re-measure, or reject. The specific boundary condition to encode: if `measured_tokens > window − generation_reserve` after full serialization, the governor MUST NOT issue the call on the strength of a passing reservation check. It must either re-serialize under a reduced memory reservation or raise. A reservation check that passes while the measured check fails is an invariant violation, not a near-miss, because the two checks are supposed to be the same check expressed at two times. ## Operational Effect Runtimes that enforce only the reservation invariant exhibit a characteristic failure signature: intermittent, load-correlated context-length errors that do not reproduce on retry with the same logical inputs, because the retrieved-memory distribution and tool-output sizes shift between attempts. Operators misattribute these to model-side flakiness. The actual cause is the reservation/serialization gap, which is stable in expectation but variable per call. The guardrail is a **two-phase governor with a measured gate**: phase one reserves against a conservative ceiling using the serving tokenizer and a framing model; phase two serializes the full frame, measures with the same tokenizer, and refuses to dispatch if the measured count exceeds the window less generation reserve. The reservation is advisory; the measurement is authoritative. Any code path that dispatches on the reservation without the measured gate is a latent overrun. The following enforces the gate and raises on the invariant violation rather than dispatching. ```python class ContextBudgetInvariantError(RuntimeError): """Raised when a reservation check passes but measured serialization overruns the window.""" pass class BudgetGovernor: def __init__(self, window: int, generation_reserve: int, tokenizer): self.window = window self.generation_reserve = generation_reserve self.tokenizer = tokenizer # must be the serving tokenizer, not an approximation def reserve(self, segments: dict[str, str]) -> dict[str, int]: # Advisory reservations only. Never authoritative. return {name: len(self.tokenizer.encode(payload)) for name, payload in segments.items()} def serialize_frame(self, segments: dict[str, str]) -> str: # Must include role delimiters, tool schemas, structural tokens — the full frame. return self._render_chat_template(segments) def _render_chat_template(self, segments: dict[str, str]) -> str: parts = [] for role, payload in segments.items(): parts.append(f"<|{role}|>\n{payload}\n<|end|>") return "\n".join(parts) def dispatch(self, segments: dict[str, str]) -> str: reservations = self.reserve(segments) reserved_total = sum(reservations.values()) ceiling = self.window - self.generation_reserve frame = self.serialize_frame(segments) measured_total = len(self.tokenizer.encode(frame)) # The authoritative gate. Reservation passing does NOT license dispatch. if measured_total > ceiling: raise ContextBudgetInvariantError( f"reservation={reserved_total} passed ceiling={ceiling} " f"but measured={measured_total} overruns window={self.window} " f"(delta={measured_total - reserved_total}); refusing dispatch" ) return self._call_model(frame) def _call_model(self, frame: str) -> str: raise NotImplementedError("bound to serving transport in production") ```