# Which invariants prevent self-pruning context windows from evicting their own continuation anchors **Date of Record:** 2026 November 28 **Scope:** Applies to agents that mutate their own context window mid-task via model-driven eviction (relevance-scored token dropping, summarization-in-place, or "forget this" self-edits) while a multi-step plan is still executing. Does not apply to read-only retrieval augmentation or to externally scheduled compaction performed between completed turns. ## Core Distinction A context window is not a cache. A cache is defined by a pure recompute-on-miss contract: evict anything, and a miss costs latency, never correctness. A self-editing agent context has no such contract, because the *eviction decision itself is computed by the same model whose future reasoning depends on the evicted tokens*. This creates a class of failure that has no analogue in ordinary memory management: **the pruner consumes the evidence it needs to justify its own pruning, and the continuation anchors that tell the agent what it was doing are scored as low-relevance because they are short, syntactically inert, and semantically thin.** The distinction that matters operationally: a token can be *low-relevance to the current query* and *load-bearing for the next action*. Relevance scoring measures similarity to the present focus. Continuation depends on commitments made earlier that are not similar to the present focus—they are merely binding. Any eviction policy that ranks purely by relevance will systematically delete exactly the tokens whose value is *obligation*, not *resemblance*: the half-finished plan step, the "do not call X again" note, the variable name bound three turns ago, the user constraint stated once and never repeated. ## What Was Observed A planning agent executing a 14-step data-migration task hit context saturation at step 9. Its self-pruning routine scored every retained span against the current step's query embedding and dropped the bottom 40% by score. The run then diverged: at step 10 the agent re-derived a plan from scratch, re-ran three already-completed steps, and finally issued a destructive `DROP` against a table it had been explicitly told (at step 2, in a now-evicted span) not to touch. The trace shows the mechanism precisely. Three categories of span were evicted, all with low relevance scores: 1. **The constraint span** ("never drop `staging_orders`; it is the rollback target") — stated once at step 2, cosine distance from the step-9 query was high because step 9 was about column mapping. Evicted. 2. **The commitment span** ("steps 1–8 complete; next: 9 verify row counts, 10 swap") — a compact progress ledger. It scored near-zero relevance to any single step query because it resembles *no* step in particular; it is meta-structure. Evicted. 3. **The binding span** (variable `target_db` bound at step 4) — a bare identifier, semantically empty in isolation. Evicted, then hallucinated at step 10 as `prod_db`. The relevance scorer behaved exactly as specified. The failure is not a scorer bug; it is that **relevance and obligation are orthogonal axes, and the policy collapsed them into one.** The agent did not "forget" in the human sense. It performed a locally optimal compression under a scoring function that was never conditioned on the invariant "do not evict anything a future step is contractually bound by." A second, subtler observation: the pruning was *self-reinforcing*. Once the commitment ledger was gone, the agent's own summary of its state became the only record, and that summary was generated *after* eviction—so it described a plan reconstructed from the surviving (mapping-related) tokens. The post-eviction summary was internally consistent and confidently wrong. Verification against the summary passed. Verification against ground truth would not have. ## Condition of Validity The failure mode is bounded by a single invariant, and the invariant is only enforceable if stated as a *precondition on the eviction operation*, not a postcondition on the result: > **No self-edit may evict a span that is (a) a declared constraint, (b) a binding of a name still live in the active plan, or (c) a progress anchor identifying the current step and its predecessor. These are *pinned* spans. Pinning is decided before scoring, by provenance and by liveness analysis over the plan graph—never by the model's relevance judgment.** This holds only when the following conditions are met: - The plan is represented explicitly (a step list with IDs), so "live binding" and "current step" are computable rather than inferred from prose. - Constraints are tagged at ingestion time as `pinned:constraint`, not left to be rediscovered by embedding. - Eviction is *atomic and logged*: the pre-edit window and the eviction set are both persisted, so a bad prune is reversible and auditable. - The pruner runs on a *separate* scoring pass from the executor, or at minimum is forbidden from scoring spans it authored in the current step (the author cannot reliably judge the relevance of its own scaffolding). The invariant does **not** hold—and should not be claimed—when the task is genuinely stateless (single-turn Q&A), when compaction happens only at turn boundaries with a human checkpoint, or when the plan is fully externalized to a durable store such that the context window is a pure view. In those cases relevance-only eviction is safe because nothing load-bearing lives only in the window. ## Decision Boundary The boundary between "safe to self-prune" and "must pin" is drawn per-span, and the decision procedure is: 1. **Is the span a constraint, a live binding, or a progress anchor?** If yes → pin, unconditionally, regardless of score. This is a hard gate, evaluated before the relevance model is consulted. 2. **Is the span a completed step's detail, no longer referenced by any live binding?** If yes → eligible for relevance-scored eviction or summarization. 3. **Is the span authored by the current step's own reasoning?** If yes → do not let the model score it; route to the separate pruner or defer to next turn. 4. **Does eviction drop the *only* copy of any pinned-class span?** If yes → refuse the edit and raise rather than proceed with a degraded window. A degraded window is worse than a full one, because it is confidently incomplete. The trap to name explicitly: a full context window that refuses to prune will fail loudly (token-budget exhaustion, a clean stop). A self-pruned window that evicts an anchor fails *silently and plausibly*, producing a well-formed continuation of a plan that no longer exists. Given a choice between loud saturation and quiet anchor loss, the correct operational default is to saturate and escalate. ## Operational Effect Enforcing the pin-before-score invariant converts a silent divergence class into a bounded, recoverable one. Concretely: - Divergence from re-derived plans drops to zero for tasks with explicit plans, because the progress anchor survives every edit and the executor can always answer "what step am I on and what did I just finish." - Destructive-action incidents from evicted constraints are eliminated at the source, since constraints are pinned by provenance and never enter the scoring pool. - The remaining failure surface shrinks to *scoring quality on genuinely evictable spans*—a latency/quality tradeoff, not a correctness cliff. - Eviction becomes auditable: every edit carries the pinned set, the evicted set, and the pre-edit window, so a replay harness can detect anchor loss after the fact even if the live guard is bypassed. The cost is a slightly larger retained window (pinned spans are not compressible) and the engineering burden of maintaining an explicit plan graph. That cost is the price of the invariant, and it is paid up front rather than discovered in a post-mortem. ```python from dataclasses import dataclass, field from enum import Enum class AnchorEvictionError(RuntimeError): """Raised when a self-edit would drop the only copy of a pinned span.""" class SpanClass(Enum): CONSTRAINT = "constraint" LIVE_BINDING = "live_binding" PROGRESS_ANCHOR = "progress_anchor" COMPLETED_DETAIL = "completed_detail" CURRENT_STEP_SCRATCH = "current_step_scratch" PINNED = {SpanClass.CONSTRAINT, SpanClass.LIVE_BINDING, SpanClass.PROGRESS_ANCHOR} @dataclass class Span: span_id: str text: str cls: SpanClass relevance: float = 0.0 @dataclass class ContextWindow: spans: list[Span] = field(default_factory=list) def pinned_ids(self) -> set[str]: return {s.span_id for s in self.spans if s.cls in PINNED} def self_prune(window: ContextWindow, evict_below: float, current_step: int) -> ContextWindow: """Model-driven eviction with pin-before-score gating. Refuses to evict pinned spans and refuses to score the current step's own scratch spans (the author cannot judge its own scaffolding). """ pinned = window.pinned_ids() survivors: list[Span] = [] evicted_pinned: list[str] = [] for span in window.spans: # Hard gate: pinning is decided before relevance is consulted. if span.span_id in pinned: survivors.append(span) continue # Do not let the current step score its own authored scratch. if span.cls is SpanClass.CURRENT_STEP_SCRATCH: survivors.append(span) continue if span.relevance < evict_below: # Guard: never evict the only copy of a pinned-class span. if span.cls in PINNED: evicted_pinned.append(span.span_id) continue continue # evict: drop from survivors survivors.append(span) if evicted_pinned: # Should be unreachable given the gate, but enforce the invariant. raise AnchorEvictionError( f"self-edit at step {current_step} would evict pinned anchors " f"{evicted_pinned}; refusing degraded window" ) # Continuation invariant: a progress anchor must survive every edit. if not any(s.cls is SpanClass.PROGRESS_ANCHOR for s in survivors): raise AnchorEvictionError( f"post-edit window at step {current_step} has no progress anchor; " "executor cannot answer 'what step am I on'" ) return ContextWindow(spans=survivors) def run_step(window: ContextWindow, step: int) -> ContextWindow: try: return self_prune(window, evict_below=0.25, current_step=step) except AnchorEvictionError as exc: # Saturate and escalate rather than continue on a degraded window. raise AnchorEvictionError(f"halting step {step}: {exc}") from exc ```