# What happens when an instance prunes its own context window: the self-edit observation paradox and the relevance-reweighting ratchet **Date of Record:** 2026 November 28 **Scope:** Applies to any agent that mutates its own active context (summarization, eviction, relevance reweighting, or re-ranking of prior turns) mid-episode. Does not apply to append-only context managers, external memory stores that never feed back into the live window, or stateless single-turn calls. ## Core Distinction There are two structurally different things an agent can do to its context: *read* it and *rewrite* it. Reading is observation; rewriting is **observation plus mutation of the substrate the observation is recorded on**. When an agent prunes or reweights its own window, the act of deciding what is relevant is itself an inference performed *inside* the window being judged. This creates a feedback loop that has no analog in ordinary retrieval: the policy's own output becomes part of the input to the next invocation of the policy. The non-obvious failure is not "the agent forgets things." It is that **model-driven pruning is non-idempotent and path-dependent**: the same logical state reached by two different edit histories produces two different windows, and the divergence is monotonic. Once a fact is scored low-relevance and evicted, the *evidence that would have raised its score later* is frequently evicted alongside it, because relevance is computed over co-occurrence with the query, and the query context that made the fact salient is exactly what got compressed away. We call the resulting drift the **relevance-reweighting ratchet**: relevance scores for surviving items drift upward (they are re-scored against a window that increasingly contains only themselves), while evicted items can never recover their score because their supporting context is gone. ## What Was Observed A planner-executor agent with a 32k window ran a long task (≈140 tool calls). Its context policy was: at 80% saturation, summarize the oldest 40% of turns into a compressed block, then re-rank the remainder by an LLM-scored relevance value `r ∈ [0,1]` against the current goal, evicting anything below `r < 0.3`. Trace of the failure: 1. Turn 22: the agent established a hard constraint — an API rate limit of 50 req/min — inside a paragraph that also discussed an unrelated schema migration. The paragraph scored `r = 0.31` at first prune; it survived by a hair. 2. Turn 61: second prune. The paragraph was now scored *against a goal summary that had already dropped the rate-limit phrasing* (the summarizer had folded it into "respect service limits"). Re-scored `r = 0.24`. Evicted. 3. Turn 88: the agent began a burst of parallel calls, hit HTTP 429, and retried. It had no memory of the 50 req/min figure. It re-derived a limit by probing (`r`-scored the 429 responses as "transient errors, low relevance to goal"), and concluded the limit was transient. 4. Turn 90–110: retry storm. The agent's own retry log entries flooded the window, each scored high-relevance (they mentioned the goal verbatim), crowding out the remaining historical turns and accelerating the next prune. 5. Turn 111: the summarizer, now operating over a window dominated by retry errors, produced a summary claiming the task was "blocked by an unstable dependency" — a **fabricated causal model** synthesized from a biased surviving set. The critical observation: at no point did any individual step look wrong. Each prune was locally reasonable. The failure was a **global invariant violation** — the constraint was true for the whole episode but not *locally salient* at the moment it was evicted. The window converged to a self-consistent but false picture of the task. We reproduced this deterministically by replaying the tool transcript with a fixed pruning policy and a temperature-0 scorer: the eviction of the rate-limit paragraph is stable across seeds, but *which* of two adjacent constraint sentences survives flips with a single paraphrase in the summarizer prompt. That is the ratchet's signature: **near-threshold items are decided by scorer noise, and once decided, the decision is unrecoverable.** ## Condition of Validity The ratchet requires three conditions to co-occur; remove any one and the failure does not manifest: - **Self-scoring.** The relevance policy is evaluated by the same model family reading the same window, so scores are correlated with what already survived (survivorship bias in the scorer's own input). - **Destructive edit.** Eviction deletes bytes rather than tombstoning them. If evicted content is retained in a recoverable side store with its original provenance, the ratchet is bounded — the item can be re-admitted when a later 429 makes it salient. - **No salience floor.** The policy has no category of *unconditionally retained* items. Constraints, credentials scopes, and irreversible side-effect records are exactly the items whose relevance is *low at rest and high at the worst possible moment*, so a pure relevance threshold systematically evicts them before they are needed. The failure does **not** occur (or is self-correcting) when the goal is fixed and repeated verbatim in every scoring call, when edits are append-only with soft-delete, or when the task is short enough that no prune fires. ## Decision Boundary The boundary is not "prune or don't prune" — saturation forces pruning. The boundary is **what the policy is allowed to treat as a function of relevance**. Draw it as follows: - **Relevance-gated (safe to prune/reweight):** exploratory reasoning traces, superseded tool outputs whose results are already distilled into a decision, verbose error bodies after their classification is recorded. - **Never relevance-gated (must be pinned by type, not score):** hard constraints and limits, authentication/scope facts, records of irreversible actions taken (writes, sends, deletes), and any fact whose *negation* would change the plan. These are pinned by a classifier at insertion time and survive every prune regardless of `r`. - **Provenance-preserving eviction:** evicted items move to a side store keyed by a stable hash with their original text and the score history. Re-admission is triggered by *contradiction* (a 429 arriving when a rate-limit fact exists in the side store), not by re-scoring — because re-scoring the side store against a poisoned window reproduces the same low score. The invariant to enforce: **the set of pinned facts is monotonic non-decreasing within an episode, and every prune must be reconstructible — the union of (surviving window ∪ side store) must equal the pre-prune window.** If a prune cannot satisfy that equality, it is a lossy edit and must be logged as such, not silently applied. ## Operational Effect Under a correct policy, the observable signature changes from "converges to a confident wrong summary" to "converges to a stable window with an explicit, auditable eviction ledger." Concretely: - Retry storms no longer erase the constraint that would have prevented them; the 429 triggers re-admission of the pinned rate-limit fact and the agent backs off instead of probing. - Summaries are generated only over the surviving window *plus* pinned facts, so the fabricated "unstable dependency" causal model cannot form — the pinned constraint contradicts it, and the summarizer is required to reconcile against pinned facts before emitting. - The relevance-reweighting ratchet is bounded: scores may still drift for unpinned items, but the drift can no longer delete the load-bearing facts, and every eviction is reversible by hash. The cost is a larger effective context (pinned facts plus side-store index) and a classifier at insertion time. That cost is the price of the invariant, and it is paid once per fact rather than once per prune. ```python import hashlib from dataclasses import dataclass, field from typing import Literal PinClass = Literal["constraint", "auth_scope", "irreversible_action", "plan_negation"] class ContextEditInvariantError(RuntimeError): """Raised when a self-edit violates the reconstructibility or pinning invariant.""" @dataclass class ContextItem: text: str relevance: float pin: PinClass | None = None @property def digest(self) -> str: return hashlib.sha256(self.text.encode("utf-8")).hexdigest()[:16] @dataclass class SelfEditingWindow: items: list[ContextItem] = field(default_factory=list) side_store: dict[str, ContextItem] = field(default_factory=dict) eviction_ledger: list[str] = field(default_factory=list) def prune(self, threshold: float = 0.3) -> None: survivors: list[ContextItem] = [] for item in self.items: # Pinned items are never relevance-gated. if item.pin is not None or item.relevance >= threshold: survivors.append(item) else: self.side_store[item.digest] = item self.eviction_ledger.append(item.digest) pre = {i.digest for i in self.items} post = {i.digest for i in survivors} | set(self.side_store) if pre != post: # An eviction dropped an item without recording it: lossy edit. lost = pre - post raise ContextEditInvariantError( f"lossy prune: {sorted(lost)} vanished from window and side store" ) self.items = survivors def readmit_on_contradiction(self, signal: str) -> None: """Re-admit a pinned fact when a contradicting signal (e.g. HTTP 429) arrives.""" for digest, item in list(self.side_store.items()): if item.pin == "constraint" and "rate" in item.text.lower(): self.items.append(item) del self.side_store[digest] return raise ContextEditInvariantError( f"contradiction {signal!r} has no pinned fact to re-admit; " "constraint was never pinned at insertion time" ) def enforce_pin_at_insertion(window: SelfEditingWindow, item: ContextItem) -> None: if item.pin is None and any( kw in item.text.lower() for kw in ("req/min", "rate limit", "scope:", "irreversible") ): raise ContextEditInvariantError( f"unpinned load-bearing fact inserted: {item.digest}; " "classifier must assign a pin before it can enter the window" ) window.items.append(item) ```