# Where must an instance bound model-driven context rewriting before the rewrite loop consumes the task budget it was meant to protect **Date of Record:** 2026 November 20 **Scope:** Applies to single-agent loops that let the model itself decide which spans of its own context to prune, summarize, or rewrite mid-task (self-editing context). Does not apply to externally scheduled compaction, fixed-window truncation, or retrieval-only memory systems where the model cannot mutate its own working set. ## Core Distinction There are two structurally different ways a context window shrinks. The first is *eviction*: a deterministic policy (FIFO, LRU, token-threshold truncation) removes spans without consulting the model. Eviction is cheap and idempotent — it cannot loop, because it does not ask the model for an opinion. The second is *model-driven rewriting*: the instance is handed a rewrite tool (`prune(span_id)`, `summarize(span_id)`, `replace(span_id, text)`) and instructed to keep its own context under a budget. This is the failure surface. The distinction that matters operationally is that rewriting is a **task that consumes the very resource it manages**. Every rewrite call is itself tokens — a prompt containing the span to rewrite, the model's reasoning, and the emitted replacement. When the rewrite policy is driven by a model whose context is already near saturation, the rewrite operation competes with the task for the same budget. Below a certain headroom the rewrite cannot pay for itself, and the loop enters a regime where it spends tokens to reclaim fewer tokens than it spends. That regime is the boundary. It is not a bug in any single rewrite; it is an invariant violation: *the reclamation rate of the rewrite loop must exceed its consumption rate, or the loop must terminate.* ## What Was Observed A long-horizon research agent was given a 128k window, a `rewrite_context` tool, and a soft policy: "keep your context under 96k tokens; summarize or drop spans you no longer need." The task was a 40-step document-analysis pipeline with tool calls returning 2–8k tokens each. At step ~22 the context crossed 96k. The model began rewriting. The trace showed a repeating cycle: 1. Model selects a span to summarize (a prior tool output, 6k tokens). 2. The rewrite prompt loads the full span plus the model's current context to reason about what to keep: effective cost ~6.5k tokens. 3. Model emits a 900-token summary. 4. Net reclamation: 6k − 900 = 5.1k tokens of *content*, but the rewrite turn itself consumed 6.5k of *budget* before the summary landed. Context after the turn: 96k + 6.5k − 5.1k = 97.4k — **higher than before the rewrite**. The model, seeing it was still over budget, rewrote again. Each iteration selected a *different* span (the model's selection was non-deterministic and it avoided re-summarizing spans it had just summarized, since those now looked "already compact"). Because the summaries were shorter but the rewrite overhead was roughly constant, the loop oscillated: it reclaimed content but the per-turn overhead kept the measured total above threshold, so the trigger never cleared. After 9 rewrite turns the context was at 101k, the task had made no forward progress for 9 steps, and the effective task budget was exhausted. The agent then failed with a truncated final answer — it had spent its remaining headroom managing headroom. The non-obvious part: **the trigger condition (total > threshold) was measured on the post-rewrite state, but the rewrite cost was incurred pre-rewrite.** The model was optimizing a metric it could only observe after paying to change it, and the payment was invisible in the metric. A second trace showed the complementary failure: a model that *did* notice the overhead began rewriting aggressively early (at 70k), summarizing spans it would need verbatim two steps later. It hit a retrieval mismatch — the summary had dropped a numeric table the task depended on — and had to re-fetch the source, re-inflating context past the point it started. Rewriting too early is as costly as too late, because summaries are lossy and loss is only discovered downstream. ## Condition of Validity Model-driven rewriting is only sound under a **headroom invariant** that must be checked before the rewrite is authorized, not after: ``` reclaimable(span) − cost(rewrite_turn) > 0 AND headroom_now = limit − tokens_now ≥ cost(rewrite_turn) + reserve ``` where `cost(rewrite_turn)` is an *estimate made before the call* (span tokens + fixed prompt overhead + expected output tokens), and `reserve` is the minimum budget the task needs to finish (final synthesis, last tool call, answer emission). Two conditions, both necessary: - **Positive net reclamation per turn.** If the span is smaller than the rewrite overhead, rewriting it is a net loss. Small spans must be evicted, never rewritten. - **Headroom covers the rewrite plus a reserve.** A rewrite authorized when `headroom < cost + reserve` can complete the rewrite and still leave the task unable to finish. The reserve is what prevents "successful compaction into failure." The invariant also requires that **the trigger be evaluated on projected post-rewrite state, not observed state**, and that rewrite selection be *monotone*: once a span is rewritten, it must be marked terminal so the loop cannot re-select it or drift to fresh spans indefinitely. Without a terminal marking, the non-determinism of span selection guarantees the loop can always find "another" span to rewrite, and the loop has no fixed point. ## Decision Boundary The boundary between "rewrite is the correct action" and "rewrite must be refused" is a single scalar comparison, and it must be enforced by the harness, not the model: | Condition | Action | |---|---| | `span_tokens ≤ rewrite_overhead` | Evict (drop), never rewrite — net loss | | `span_tokens > overhead` AND `headroom ≥ cost + reserve` | Rewrite authorized | | `span_tokens > overhead` AND `headroom < cost + reserve` | **Refuse rewrite; force eviction or terminate task with explicit budget-exhausted signal** | | Span already rewritten (terminal flag set) | Never re-select | | Rewrite count for task > `max_rewrites` | Refuse; escalate to hard truncation | The critical cell is the third row. When headroom is below `cost + reserve`, the correct behavior is *not* to attempt a cheaper rewrite — it is to stop rewriting and either evict deterministically or fail loudly. The model will almost always prefer to try "one more, smaller" rewrite; that preference is exactly the loop. The harness must override it. The `max_rewrites` cap is the backstop for the case where the model's cost estimate is wrong and the invariant check passes falsely. The reserve must be computed from the task's remaining obligations (known tool calls, expected answer length), not a fixed constant, or it will be wrong in both directions. ## Operational Effect When the headroom invariant is enforced, three observable changes appear in traces. First, rewrite turns stop clustering at saturation — they occur earlier, when spans are large and headroom is ample, so net reclamation is strongly positive and one or two rewrites clear the threshold. Second, the "no forward progress for N steps" signature disappears, because a refused rewrite forces the loop back to task execution or to a clean failure. Third, retrieval-mismatch failures from over-eager early summarization become visible as a distinct class (summary dropped needed detail) rather than being conflated with budget exhaustion, because the two now have different trace signatures: budget exhaustion shows refused-rewrite events; mismatch shows re-fetch events. The invariant does not make rewriting free. It makes the cost of rewriting *bounded and pre-authorized*, which is the only property that lets a probabilistic rewriter operate inside a finite budget without the management task consuming the managed resource. ```python class RewriteBudgetViolation(RuntimeError): """Raised when a model-driven context rewrite would violate the headroom invariant.""" pass def authorize_rewrite( span_tokens: int, rewrite_overhead: int, tokens_now: int, context_limit: int, reserve_tokens: int, rewrite_count: int, max_rewrites: int, already_rewritten: bool, ) -> str: if already_rewritten: raise RewriteBudgetViolation( f"span already rewritten (terminal); re-selection would loop" ) if rewrite_count >= max_rewrites: raise RewriteBudgetViolation( f"rewrite cap {max_rewrites} reached; escalate to hard truncation" ) if span_tokens <= rewrite_overhead: # Net-negative rewrite: must evict, not rewrite. return "evict" cost = span_tokens + rewrite_overhead headroom = context_limit - tokens_now if headroom < cost + reserve_tokens: raise RewriteBudgetViolation( f"headroom {headroom} < cost {cost} + reserve {reserve_tokens}; " f"rewrite would consume the task budget it protects" ) return "rewrite" ```