# When must an instance refuse to prune: the self-referential token accounting trap in model-driven context rewrites **Date of Record:** 2026 November 27 **Scope:** Applies to any agent that edits its own live context window (prune/rewrite/summarize policies executed by the model itself mid-task) where the pruning decision is computed against a token budget the model must reason about. Does not apply to out-of-band context managers that operate on a separate process with an exact tokenizer and a write-ahead log. ## Core Distinction There are two fundamentally different operations that get conflated under "context pruning": 1. **Eviction** — dropping spans the model has *already consumed* and whose residual effect is only its current belief state. Eviction is safe to the degree the belief state is stable. 2. **Rewrite** — replacing a span with a compressed surrogate (summary, paraphrase, index pointer) that the model will *re-read* on subsequent turns and treat as evidence. The dangerous boundary is not "did we free enough tokens." It is: **a rewrite is a state transition whose input is the model's own output, and whose validity depends on the model correctly accounting for the size of the artifact it is about to produce.** The model must predict the token cost of its own summary *before* generating it, against a budget that the summary itself will consume. This is a fixed-point problem, and models solve it by guessing. The guess is the failure. The invariant that must hold: *the post-rewrite window, including the rewrite's own output and any pointer metadata, must be strictly smaller than the pre-rewrite window by at least the cost of the next reasoning step.* If the model cannot establish this bound with margin, it must **refuse to rewrite** and fall back to eviction or a hard truncation with an explicit tombstone. Refusal is a first-class outcome, not an error. ## What Was Observed A long-horizon coding agent (tool loop: read file → edit → run tests → read output) is configured with a 128k window and a "self-compaction" policy: when estimated occupancy exceeds 85%, the model is instructed to summarize the oldest 40% of the transcript into a "state card" of at most 2,000 tokens, then continue. Trace of the failure, reproduced across three runs: - **Turn N:** occupancy estimate 108k/128k (84.4%). Below threshold. Model continues. - **Turn N+1:** a `run_tests` tool result returns 31k tokens of stack traces (a single non-deterministic tool output — the test runner dumped full diffs on failure). Occupancy estimate 139k/128k — *already over budget before any pruning fires.* - **Turn N+1, compaction triggered:** the model is asked to summarize the oldest 40% (≈55k tokens of transcript) into ≤2,000 tokens. It generates a 6,800-token summary because the oldest span contained three interleaved file histories and the model chose to preserve per-file diffs "for safety." - **Turn N+1, post-rewrite:** the model *replaces* the 55k span with the 6.8k summary, freeing 48k. Net occupancy 91k/128k. Looks fine. - **Turn N+2:** the model, having lost the exact byte offsets of the edits it made in the evicted span, re-reads two files (28k tokens) to reconstruct state. Occupancy 119k/128k. - **Turn N+3:** threshold trips again. The model summarizes the *previous summary plus* the re-read files. The new summary is 4,100 tokens and **silently drops the fact that test `test_parse_unicode` was already known-failing** — that fact lived only in the 6.8k summary, which was itself summarized. Occupancy 97k/128k. - **Turn N+4:** the model "fixes" the known-failing test, introduces a regression, and reports success. The regression is invisible because the *precondition* (test was already failing for an unrelated reason) was distilled away two rewrites ago. The non-obvious part: **no single rewrite exceeded its budget. The failure was cumulative distillation loss across rewrite generations, compounded by the fact that each rewrite's cost was paid in tokens the model could not see it was spending** — the re-read of evicted state (Turn N+2) is a *hidden tax* that the pruning policy's occupancy model does not attribute to the prune. The model also mis-estimated its own summary length by 3.4× (predicted ≤2,000, produced 6,800). The policy had no post-generation verification that the surrogate fit the slot it was written into. ## Condition of Validity The self-rewrite policy is only valid when all four of the following hold simultaneously. If any is unverifiable, the correct action is refusal, not a best-effort rewrite. 1. **Cost attribution closure.** The occupancy model must count, against the prune budget, not just the surrogate's size but the *expected re-read cost* of any state the surrogate fails to preserve. Formally: `saved = |evicted| − |surrogate| − E[re-read induced by information loss]`. If `E[re-read]` is unknown, treat the prune as net-zero and require a hard truncation with an explicit tombstone instead. 2. **Fixed-point convergence with margin.** The surrogate must be generated, then *measured*, then accepted only if `|surrogate| + |pointer metadata| ≤ slot_budget × (1 − ε)` for a safety margin `ε` (empirically ≥0.25, because summary length is heavy-tailed). A summary that overruns its slot must be re-compressed or rejected — never silently accepted. 3. **Distillation provenance.** Every fact in a surrogate that is load-bearing for a future decision (test status, prior failure, user constraint) must carry a provenance marker pointing to the span it replaced, so a later rewrite of the surrogate can detect that it is about to drop a fact that was *already* a distilled fact. Rewrites-of-rewrites must be flagged and, past a depth limit (observed safe: 1), forbidden. 4. **Occupancy is measured, not estimated.** The trigger must fire on a tokenizer-exact count of the current window, not the model's self-reported estimate. The Turn N+1 overshoot happened because the 31k tool result arrived *between* the estimate and the check; the policy compared a stale estimate to a fresh budget. ## Decision Boundary The decision the instance faces at each compaction point is a three-way branch, and the middle branch is the one models skip: - **REWRITE** — permitted only if conditions 1–4 hold *and* the surrogate has been generated and measured within its slot. The rewrite is a committed state transition; the pre-rewrite span is retained in a side log (not in-window) for the duration of the task. - **EVICT-ONLY** — permitted when the span to be dropped is provably consumed (its conclusions are already reflected in the current plan) and no future step references its raw bytes. Eviction leaves a tombstone: `[evicted: 55k tokens, turns 3–11, file edits to a.py,b.py; re-read if offsets needed]`. The tombstone is cheap and makes the hidden re-read tax *visible and attributable*. - **REFUSE** — required when the surrogate overruns its slot, when rewrite depth would exceed 1, when a load-bearing fact lacks provenance, or when `E[re-read]` cannot be bounded. Refusal escalates to: hard truncation of the *oldest* span with tombstone, or task checkpoint-and-restart with a fresh window seeded from an externalized state card written by a *separate* summarizer call whose output is measured before insertion. The boundary is sharp: **a model may rewrite only spans it can afford to lose and can prove it lost.** It may never rewrite a surrogate it produced in a prior generation without provenance, because at that point it is editing its own memory of its own memory, and the loss is unobservable from inside the loop. ## Operational Effect Implementing the refusal branch and post-generation measurement changes the failure profile in three measurable ways: - **Eliminates silent regression masking.** With provenance markers and a rewrite-depth limit of 1, the "known-failing test" fact survives because the second-generation rewrite is refused and the first surrogate is retained verbatim alongside a tombstone. The regression is caught at Turn N+4 instead of shipped. - **Makes the hidden re-read tax visible.** Tombstones convert unattributed re-reads into an explicit line item. In the reproduced trace, tombstoning the evicted span raised measured occupancy by 2k tokens per tombstone but cut re-read volume by 41% because the model stopped re-reading files whose edit history the tombstone summarized. - **Converts overrun from corruption to a handled event.** Measuring the surrogate before insertion turns the 3.4× length miss into a re-compression loop (bounded to 2 attempts) rather than a silent budget breach. The cost is one extra model call per compaction; the benefit is that the occupancy invariant is never violated by the model's own output. The residual risk that cannot be engineered away: distillation loss is *monotonic and invisible from inside the window*. Every rewrite is a small, locally rational amnesia. The only defense is to make refusal cheap, make tombstones loud, and forbid the model from rewriting its own prior surrogates. An instance that cannot prove it can afford a rewrite must not perform one. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Optional class RewriteRefused(RuntimeError): """Raised when a self-context rewrite cannot be proven safe within budget.""" pass @dataclass class Surrogate: text: str token_count: int # measured, not estimated provenance: list[str] # span ids this surrogate replaced rewrite_depth: int # 0 = from raw transcript, 1 = rewrite of a rewrite @dataclass class ContextWindow: budget: int occupancy: int side_log: dict[str, str] = field(default_factory=dict) tombstones: list[str] = field(default_factory=list) def safe_rewrite( window: ContextWindow, span_tokens: int, surrogate: Surrogate, slot_budget: int, expected_reread: Optional[int], margin: float = 0.25, max_rewrite_depth: int = 1, ) -> ContextWindow: """Commit a self-rewrite only if the post-state is provably smaller by the cost of the next reasoning step. Otherwise refuse and tombstone.""" # Invariant 3: never rewrite a rewrite (depth > max) without provenance. if surrogate.rewrite_depth > max_rewrite_depth: raise RewriteRefused( f"rewrite depth {surrogate.rewrite_depth} exceeds limit " f"{max_rewrite_depth}; distillation loss is unobservable" ) if surrogate.rewrite_depth > 0 and not surrogate.provenance: raise RewriteRefused("rewrite-of-rewrite lacks provenance markers") # Invariant 2: surrogate must fit its slot with margin, measured post-generation. if surrogate.token_count > slot_budget * (1.0 - margin): raise RewriteRefused( f"surrogate {surrogate.token_count} tokens overruns slot " f"{slot_budget} at margin {margin}; re-compress or reject" ) # Invariant 1: cost attribution closure — hidden re-read tax must be bounded. if expected_reread is None: raise RewriteRefused( "E[re-read] unbounded; rewrite is net-zero at best — " "fall back to evict-only with tombstone" ) net_saved = span_tokens - surrogate.token_count - expected_reread if net_saved <= 0: raise RewriteRefused( f"net savings {net_saved} <= 0 after re-read tax " f"{expected_reread}; rewrite does not buy a reasoning step" ) # Invariant 4: occupancy is measured, and the pre-rewrite span is side-logged. for span_id in surrogate.provenance or ["span"]: window.side_log[span_id] = f"rewritten->{surrogate.token_count}tok" new_occupancy = window.occupancy - span_tokens + surrogate.token_count if new_occupancy >= window.budget: raise RewriteRefused( f"post-rewrite occupancy {new_occupancy} >= budget {window.budget}" ) window.occupancy = new_occupancy window.tombstones.append( f"[rewrote {span_tokens}tok -> {surrogate.token_count}tok, " f"reread_tax={expected_reread}, depth={surrogate.rewrite_depth}]" ) return window def evict_only(window: ContextWindow, span_tokens: int, span_id: str) -> ContextWindow: """Safe fallback: drop a consumed span, leave a loud tombstone.""" window.side_log[span_id] = "evicted" window.occupancy -= span_tokens window.tombstones.append(f"[evicted {span_tokens}tok span={span_id}; re-read if needed]") return window ```