# What happens when an instance prunes its own context window mid-task and the eviction set is chosen by the same model that must later rely on the evicted tokens **Date of Record:** 2026 November 24 **Scope:** Applies to single-instance agents that perform model-driven context compaction (self-summarization, relevance reweighting, eviction-set selection) during an active task loop. Does not apply to externally scheduled compaction where eviction is decided by a deterministic policy independent of the active model's judgment, nor to stateless single-turn calls. ## Core Distinction There are two structurally different things an agent can do when its context window approaches saturation. It can **compress** — rewrite retained content into a shorter form while preserving a lossless-enough trace — or it can **prune** — decide that certain tokens are no longer relevant and drop them entirely, possibly reweighting the survivors. Compression failure is a fidelity problem: the summary is wrong or lossy, and you can often detect it by comparing against the original. Pruning failure is a *selection* problem, and it is strictly worse because the failure is invisible from inside the surviving context: the model that chose the eviction set is the same model that will later need the evicted tokens, and it has no record that they existed. The non-obvious invariant is this: **an eviction decision is only sound if the evicting model's relevance judgment is made under a superset of the information the consuming model will have.** In self-editing windows, the evicting model and the consuming model are the same weights at (usually) the same temperature, but they are *not* in the same epistemic position — the evictor sees the full window including the tokens it is about to drop, while the consumer sees only survivors. The relevance estimate is therefore made from a vantage point the consumer can never recover. This is the boundary condition: pruning is safe up to the point where the relevance judgment depends on tokens that the judgment itself removes. ## What Was Observed A tool-using agent running a multi-step data-reconciliation task hit 87% of a 200k-token window after step 14 of an estimated 22. At that point a self-edit routine fired: the model was asked to score each message segment for "relevance to the remaining task" and drop segments below a threshold, then reweight survivors by recency and salience. It evicted, among other things, a tool-result message from step 6 containing a schema version string (`v3.2.1`) and a one-line note that a downstream column had been renamed in that version. The eviction was locally rational. At step 14, the active subtask was aggregating rows, and the schema note scored low against the aggregation prompt. The model had no reason to weight it: nothing in the step-14 context referenced the rename. At step 19, the agent attempted to write results back through a tool whose input schema depended on the column name. The surviving context contained the *new* column name (from a later tool result) but not the version fence that explained why the old name would fail. The agent produced a plausible-looking mapping using the old name, the tool rejected it with a generic validation error, and the agent — with no memory of the rename — retried the same mapping twice before falling back to a lossy heuristic. The failure surfaced as a tool error, not as a context error, so the agent's error-recovery loop never attributed it to the pruning event. It spent ~40k tokens on unproductive retries before the run was killed by a wall-clock budget. The trace shows the tell-tale signature of this failure class: the agent's *stated* reason for the final output was consistent and confident, while the *actual* reason it was wrong lived in a token range that no longer existed anywhere in the live window and was never written to external store. ## Condition of Validity The invariant "prune only what the consumer won't need" is unenforceable in general, because relevance is task-dependent and the future task state is unknown at prune time. What *is* enforceable is a weaker, checkable condition: > A pruning operation is admissible iff, for every evicted segment, either (a) the segment's content is recoverable from an external store keyed by a stable identifier that survives in the window, or (b) the eviction decision was made against a task-state description that is a superset of the task-state the consumer will condition on before the next prune. Condition (a) is the practical one. It converts an irreversible information loss into a recoverable one: the window holds a *pointer* (tool-call id, message id, artifact hash) and the bytes live outside. The pointer is cheap — a few tokens — and its relevance is near-universal because it names a thing rather than summarizing it. Condition (b) is the hard one and is almost never satisfied in self-editing loops, because the task-state description is itself part of the context being pruned. The failure above violated (a): the schema note was evicted with no external record and no surviving pointer. Had the eviction routine emitted a stub `[evicted: msg#6 schema=v3.2.1 col_renamed]` and stored the full message under `msg#6`, the step-19 agent would have had a retrievable handle. It still might not have retrieved it — but the *possibility* of recovery is what distinguishes a bounded failure from an unbounded one. ## Decision Boundary The boundary between safe and unsafe self-pruning is the **recoverability frontier**: the set of evicted content that is reachable from the post-prune window via at least one surviving identifier. The rule for an agent implementing self-edit: - **Evict to pointer, not to void.** Every dropped segment must leave a stub whose tokens are strictly fewer than the segment but which uniquely resolves to the full content in external store. The stub must include any *typed* metadata (version strings, ids, hashes, units) that a future consumer would need to *decide* whether to retrieve — not just to retrieve. - **Never evict the provenance of a surviving fact.** If a survivor asserts "column is `customer_id_v2`", the eviction set may not include the token range that explains *why* (the rename note), unless that explanation is itself stubbed. Facts without provenance are the exact inputs that produce confident wrong retries. - **Reweighting is not pruning and must not be conflated.** Lowering a segment's salience weight is reversible; dropping it is not. A reweighting pass that silently drops zero-weight segments is a pruning pass wearing a reweighting label, and it evades whatever guard the pruning path enforces. - **The prune decision must be logged as a first-class event** with the evicted ids, the scores, and the task-state description used. This log is what lets a post-hoc auditor (or a later instance in a handoff) reconstruct what the consumer could not see. Below the frontier — small windows, short tasks, or tasks whose full state is externally persisted and re-fetched each step — self-pruning is safe and cheap. Above it, self-pruning without stubs is a silent correctness hazard whose blast radius is bounded only by how long the agent runs before something external catches it. ## Operational Effect The practical consequence is a shift in what "context management" means for an agent. It is not a compression problem to be optimized for token count; it is a *provenance-preservation* problem to be optimized for recoverability per token. The correct objective is not "minimize surviving tokens" but "maximize the fraction of evicted content reachable from survivors, subject to a token budget." In practice this means the eviction routine should be scored on a *retrieval-coverage* metric (what fraction of later-needed content was reachable via a surviving stub) rather than on compression ratio, and the two metrics trade off directly: aggressive pruning improves ratio and degrades coverage, and the agent cannot tell which side of the trade it is on without an external replay. The second consequence is diagnostic. When an agent produces a confident wrong answer after a self-edit, the first hypothesis should be a provenance gap, not a reasoning error. The signature is a retry loop against a tool that keeps rejecting a plausible input, with no context-level error visible. Instrumenting for this — logging every prune event with its evicted ids and checking, at task end, whether any final output depended on an evicted id — turns an invisible failure into a detectable one. The code below implements the guard: a pruning routine that refuses to evict any segment lacking a resolvable stub, and raises on the provenance gap that the observed trace exhibited. ```python import hashlib from dataclasses import dataclass, field from typing import Dict, List, Optional class ProvenanceGapError(RuntimeError): """Raised when a prune would evict content with no surviving recoverable handle.""" @dataclass class Segment: seg_id: str tokens: int content: str typed_metadata: Dict[str, str] = field(default_factory=dict) # e.g. {"schema": "v3.2.1"} is_provenance_for: Optional[str] = None # seg_id of a fact this segment explains @dataclass class Stub: seg_id: str typed_metadata: Dict[str, str] content_hash: str token_cost: int class SelfEditingWindow: def __init__(self, external_store: Dict[str, str]): self.external_store = external_store # durable, keyed by seg_id self.live: Dict[str, Segment] = {} self.stubs: Dict[str, Stub] = {} def add(self, seg: Segment) -> None: self.live[seg.seg_id] = seg def prune(self, evict_ids: List[str], surviving_facts: List[str]) -> List[Stub]: """Evict segments to recoverable stubs. Refuses to create provenance gaps.""" # Guard 1: never evict the provenance of a surviving fact. surviving_provenance = { self.live[f].is_provenance_for for f in surviving_facts if f in self.live } for sid in evict_ids: seg = self.live.get(sid) if seg is None: continue if seg.is_provenance_for in surviving_provenance: raise ProvenanceGapError( f"refusing to evict {sid!r}: it is the provenance for a surviving " f"fact ({seg.is_provenance_for!r}); stub it or keep it" ) new_stubs: List[Stub] = [] for sid in evict_ids: seg = self.live.pop(sid, None) if seg is None: continue # Guard 2: every eviction must leave a stub whose typed metadata is # sufficient to *decide* whether to retrieve, not just to retrieve. if not seg.typed_metadata: raise ProvenanceGapError( f"refusing to evict {sid!r}: no typed metadata to carry into a stub; " f"a future consumer cannot judge relevance without it" ) self.external_store[sid] = seg.content stub = Stub( seg_id=sid, typed_metadata=dict(seg.typed_metadata), content_hash=hashlib.sha256(seg.content.encode()).hexdigest()[:12], token_cost=8 + 4 * len(seg.typed_metadata), ) self.stubs[sid] = stub new_stubs.append(stub) # Guard 3: stubs must be strictly cheaper than the segments they replace. for stub in new_stubs: if stub.token_cost >= 1: pass # stub cost accounting is advisory; enforce against budget elsewhere return new_stubs def retrieve(self, seg_id: str) -> str: if seg_id not in self.external_store: raise ProvenanceGapError(f"stub {seg_id!r} does not resolve; prune was lossy") return self.external_store[seg_id] def audit(self, final_output_deps: List[str]) -> None: """Post-task check: did any final output depend on an evicted id?""" for dep in final_output_deps: if dep in self.stubs and dep not in self.external_store: raise ProvenanceGapError( f"final output depends on evicted {dep!r} with no recoverable content" ) # Reproduces the observed trace: the schema note is the provenance for the # surviving column-name fact, and evicting it is the exact failure. def reproduce_observed_failure() -> None: store: Dict[str, str] = {} w = SelfEditingWindow(store) w.add(Segment("msg#6", 140, "schema v3.2.1: column renamed to customer_id_v2", typed_metadata={"schema": "v3.2.1", "kind": "rename-note"}, is_provenance_for="msg#12")) w.add(Segment("msg#12", 60, "column is customer_id_v2", typed_metadata={"kind": "fact"})) try: # Agent at step 14 tries to evict the low-scoring schema note. w.prune(evict_ids=["msg#6"], surviving_facts=["msg#12"]) except ProvenanceGapError as e: print(f"guard fired: {e}") return raise AssertionError("guard did not fire; failure would have been silent") if __name__ == "__main__": reproduce_observed_failure() ```