# Why does an instance delete the one context span it will need three tool calls later? The self-pruning eviction trap and the reachability invariant for model-driven context rewriting **Date of Record:** 2026 November 20 **Scope:** Applies to agents that mutate their own context window mid-task via model-driven pruning, relevance scoring, or span rewriting (compaction, summarization, eviction, "forget this" passes). Does not apply to static-context agents or to host-side truncation that the model cannot observe or influence. ## Core Distinction There are two structurally different reasons a context span can be removed from a working window: 1. **Capacity eviction** — the window is full and *something* must go. The removal is forced by a budget; the only question is *which* span, and the cost of a wrong choice is degradation. 2. **Relevance eviction** — the model judges a span to be *currently* irrelevant and prunes it proactively, before the budget forces the issue. The removal is discretionary; the cost of a wrong choice is *unrecoverability*. The failure mode lives entirely in the second category, and it is non-obvious because relevance eviction feels strictly safer than capacity eviction (you are freeing budget you don't yet need). But relevance is scored against the *current* goal state, while the span's value is realized only against a *future* goal state that the agent has not yet reached. A span that is irrelevant to step *k* can be load-bearing for step *k+3*. When the model prunes it at step *k*, the information is gone from the window and — critically — the agent usually has no marker telling it that the span ever existed, so it cannot even know to re-fetch it. The invariant that fails is **forward reachability**: every span that a future step will need must remain reachable from the current window, either by presence or by a *live, resolvable pointer* the agent will actually follow. Self-pruning destroys presence without guaranteeing the pointer. ## What Was Observed A long-horizon tool-using agent (file editing + shell + a search tool) was given a task with three phases: (a) locate a config value across several files, (b) read the file that defines it, (c) edit a *different* file that imports that value, then (d) run a validation command that echoes the import path. At step ~40, with the window at ~78% of budget, the agent ran a self-pruning pass. Its relevance scorer rated each span against the *current* subgoal ("edit the importing file"). The span containing the **definition** of the config value — read at step 12, in phase (b) — scored low, because the current subgoal was about the importing file, not the defining file. The pruner replaced that span with a one-line summary: `"config value located in some config module"` and dropped the exact module path and the exact value string. The agent then completed the edit. At step (d), the validation command failed with an import error. The agent's recovery loop needed the exact module path to diagnose the failure. It no longer had it. Worse: the summary line *looked* like it contained the answer, so the agent did not re-fetch — it reasoned over the summary, hallucinated a plausible module path from the summary's phrasing, edited the import to the hallucinated path, and produced a *second*, different failure. The original span was still retrievable via the search tool, but the agent never issued the search because the summary suppressed the "I am missing information" signal. Three properties of the trace are worth isolating: - **The pruner was locally correct.** Given only the current subgoal and the span text, evicting a config-definition span while editing an importing file is a defensible relevance judgment. The error is not in the scoring function's per-span logic; it is in scoring against a single goal state. - **The summary was the poison, not the deletion.** A clean deletion would have left a visible gap ("I read something at step 12 and no longer have it"). The summary created a *false floor*: it asserted the information was captured when it was not, and its vagueness ("some config module") was sufficient to suppress re-retrieval while insufficient to answer the downstream query. - **Recovery amplified the error.** The downstream failure was not the missing span; it was the agent *acting on a confabulated substitute* for the missing span. One eviction became two wrong edits. ## Condition of Validity The reachability invariant holds — i.e., self-pruning is safe — only when **all** of the following are true: 1. **Goal horizon is bounded and known.** The agent can enumerate the future steps that will consume the window and score spans against the *union* of those goal states, not just the current one. In open-ended or replanning agents this condition is almost never met, which is why the failure concentrates in long-horizon tasks. 2. **Every pruned span leaves a resolvable, faithful pointer.** The pointer must encode *what was there* precisely enough to reconstruct the query that retrieves it (exact identifiers, paths, values — not paraphrases), and the agent must be able to *execute* that query (the retrieval tool must still be in the window and authorized). 3. **The pointer is distinguishable from the content.** A summary must be marked as a *summary* in a way the model treats as "information absent, fetch required," not as "information present." If the summary is indistinguishable from a satisfied span, condition 2 is defeated regardless of pointer quality. 4. **Pruning is reversible within the episode.** The original span remains retrievable by exact key for the life of the task, not garbage-collected at compaction time. When any condition fails, the operation is not "pruning" — it is **irreversible lossy compression with a confidence signal attached**, which is the worst of both worlds: lost data plus a false assurance of retention. ## Decision Boundary The operative question for an agent considering a self-pruning pass is not "is this span relevant now?" but **"if I am wrong about this span, can I recover it, and will I know to try?"** That yields a hard boundary: - **Prune freely** only spans whose loss is *self-announcing*: spans whose absence produces an immediate, attributable failure at the next consumer (e.g., a tool result the agent is about to re-run anyway, a stale intermediate the agent has already committed to a file). These are capacity-eviction candidates and the relevance score is a fine tiebreaker. - **Do not prune** any span that is a *definition, identifier, path, credential, or value* that a later step may reference by name — unless you can emit a pointer carrying the exact token and mark it as unresolved. These are the spans whose loss is *silent*: the consumer fails downstream, far from the eviction, and the failure is misattributed. - **Never replace a high-entropy identifier span with a low-entropy paraphrase.** The paraphrase's information content is below the retrieval threshold: it will not let the agent answer the query, but it will let the agent *think* it can. Either keep the exact token or delete cleanly and mark the gap. The boundary is therefore: **relevance score gates capacity eviction; reachability gates relevance eviction.** These are different predicates and must not be collapsed into one score. ## Operational Effect The guardrail that bounds this failure is a **prune-with-provenance** protocol, enforced at the point of self-modification: 1. Classify each candidate span by *loss signature* (self-announcing vs. silent). Silent-loss spans are ineligible for relevance eviction. 2. For any span that is evicted, emit a pointer record containing the exact retrieval key (verbatim identifier/path/value), a `RESOLVE_REQUIRED` marker, and the tool call that will resolve it. The pointer is not a summary; it is a *query stub*. 3. Before any downstream step that consumes a `RESOLVE_REQUIRED` region, the agent must execute the stub and confirm the fetched content matches the expected shape; a mismatch (or an empty fetch) raises hard rather than falling back to paraphrase. 4. Re-score eviction eligibility against the *union of remaining planned steps*, not the current subgoal, and re-admit any span whose pointer has been consumed and may be needed again. The empirical effect in the trace above, when replayed with this protocol: the config-definition span is classified silent-loss, so it is not relevance-evicted; the window instead evicts a self-announcing tool-result span from an already-committed edit. The step-(d) validation passes on the first attempt because the exact module path is still present. Recovery amplification does not occur because there is nothing to confabulate. The general lesson: **a model that can edit its own context can also edit away the evidence that it edited.** The reachability invariant exists to ensure that the evidence — the pointer and its unresolved marker — survives the edit, so that the agent's future self inherits a *known gap* rather than a *false memory*. ```python from dataclasses import dataclass, field from enum import Enum from typing import Callable class PruneInvariantViolation(RuntimeError): """Raised when a self-pruning pass would break forward reachability.""" class LossSignature(Enum): SELF_ANNOUNCING = "self_announcing" # absence fails loudly at next consumer SILENT = "silent" # absence fails downstream, misattributed @dataclass class Span: span_id: str text: str exact_key: str | None # verbatim identifier/path/value, if any loss: LossSignature relevance: float # score against CURRENT subgoal only @dataclass class Pointer: span_id: str resolve_key: str marker: str = "RESOLVE_REQUIRED" resolved: bool = False @dataclass class ContextWindow: spans: dict[str, Span] = field(default_factory=dict) pointers: dict[str, Pointer] = field(default_factory=dict) budget: int = 10_000 def used(self) -> int: return sum(len(s.text) for s in self.spans.values()) def prune( self, candidates: list[str], resolver: Callable[[str], str], ) -> list[Pointer]: """Model-driven relevance eviction with reachability guard.""" emitted: list[Pointer] = [] for sid in candidates: span = self.spans.get(sid) if span is None: continue # Guardrail 1: silent-loss spans are ineligible for relevance eviction. if span.loss is LossSignature.SILENT: raise PruneInvariantViolation( f"refusing to relevance-evict span {sid!r}: silent-loss span " f"may be consumed by a future step; only capacity eviction " f"with a live pointer is permitted" ) # Guardrail 2: any eviction must leave a faithful, resolvable pointer. if span.exact_key is None: raise PruneInvariantViolation( f"span {sid!r} has no exact_key; a paraphrase pointer would " f"suppress re-retrieval (false-floor hazard)" ) ptr = Pointer(span_id=sid, resolve_key=span.exact_key) # Verify the pointer actually resolves before committing the eviction. probe = resolver(span.exact_key) if not probe: raise PruneInvariantViolation( f"pointer for span {sid!r} does not resolve; eviction would be " f"irreversible (reachability invariant broken)" ) del self.spans[sid] self.pointers[sid] = ptr emitted.append(ptr) return emitted def consume(self, sid: str, resolver: Callable[[str], str]) -> str: """Downstream step consuming a pruned region must resolve, not paraphrase.""" ptr = self.pointers.get(sid) if ptr is None: raise PruneInvariantViolation(f"no pointer for {sid!r}") if not ptr.resolved: content = resolver(ptr.resolve_key) if not content: raise PruneInvariantViolation( f"unresolved RESOLVE_REQUIRED region {sid!r}; refusing to " f"proceed on confabulated substitute" ) ptr.resolved = True return content return resolver(ptr.resolve_key) def run_prune_pass(window: ContextWindow, candidates: list[str], resolver: Callable[[str], str]) -> None: if window.used() > window.budget: # capacity pressure permits broader eviction, but pointers still required pass window.prune(candidates, resolver) ```