# How does an instance detect that a model-driven pruning policy has silently invalidated a reversible context snapshot **Date of Record:** 2026 November 29 **Scope:** Applies to agents that let the model itself choose which segments of its context window to evict/compress (self-editing context), while maintaining snapshots intended to be *reversible* (restorable byte-for-byte or token-for-token). Does not apply to fixed-size sliding-window truncation, external RAG retrieval, or snapshots that are explicitly declared lossy. ## Core Distinction The failure here is not "the model pruned something important." That is expected and recoverable. The failure is that a **pruning decision and a snapshot checkpoint can be committed in the wrong order relative to each other**, producing a snapshot whose manifest claims to describe a context state that no longer exists and never existed. The model-driven pruner rewrites the live context; the snapshot subsystem records a *pointer-plus-delta* to that context. When the delta is computed against the post-prune context but the base pointer resolves to the pre-prune context (or vice versa), the snapshot becomes **internally consistent but semantically stale**: it restores without error, passes structural validation, and yields a context that silently omits a segment the agent believes it retained. The non-obvious part: this is undetectable by the snapshot verifier, because the verifier only checks that the restored context matches the *manifest*, and the manifest was generated from the corrupted state. The corruption is invisible to every component except the one that reasons about *which segments the model has ever seen*. That is a semantic invariant, not a structural one. ## What Was Observed A long-running research agent used a self-editing policy: after every N tool calls, the model was asked to emit an eviction list naming context segments to drop (identified by segment IDs). A snapshot was taken before each eviction round so the agent could "roll back" if a later reasoning step depended on an evicted segment. The intended sequence per round: 1. `snapshot = capture(live_context)` — records segment set `S` and a manifest `M` mapping IDs to content hashes. 2. `eviction_list = model.propose_evictions(live_context)` — model names segments to drop. 3. `live_context = apply_evictions(live_context, eviction_list)`. The actual sequence under concurrency: the snapshot capture and the eviction proposal ran on parallel async tasks to reduce latency. The proposal task occasionally finished first and mutated `live_context` before `capture()` read it. The resulting trace: - `capture()` read `live_context` *after* three segments (`seg_17`, `seg_22`, `seg_41`) had already been evicted. - The manifest `M` therefore listed only the surviving segments, with correct hashes for those survivors. - `restore(snapshot)` later succeeded, hash-verified cleanly, and returned a context missing `seg_17`, `seg_22`, `seg_41`. - The agent's downstream reasoning referenced a fact it had "written into context" during `seg_22` (a tool result about a dataset schema) and proceeded to issue tool calls against a schema that, in the restored context, was no longer present. It hallucinated the schema fields from parametric memory. The snapshot verifier reported `VALID` throughout. The only signal was a downstream tool error: a query against a column that did not exist. That error arrived ~40 reasoning steps after the corrupted restore, with no causal link back to the snapshot. A second, subtler variant appeared when the model's eviction list named a segment ID that the capture had already dropped. `apply_evictions` treated unknown IDs as no-ops (idempotent by design), so no error surfaced. The manifest and the live context agreed; both were wrong relative to the agent's belief. ## Condition of Validity The reversibility guarantee holds **only if** the snapshot's segment-ID set is a superset of every segment the model has observed in any prior reasoning step that the agent might later rely on, *and* the capture is serialized against eviction. Formally, for a snapshot `k` to be a valid rollback target for step `t > k`: - `segments(live_context at capture_k) ⊇ segments(referenced by reasoning steps [k, t])`, and - `capture_k` reads a context state that is atomically frozen between the model's proposal and the application of evictions. The second clause is the one that fails silently. Atomicity between "model proposes" and "system applies" is not a property the model can observe; it must be enforced by the runtime. The model's proposal is computed against a context snapshot it *believes* is current, but nothing in the protocol binds the proposal to the capture. The invariant to enforce: **a snapshot manifest must carry a monotonically increasing `context_epoch`, and the eviction proposal must be tagged with the epoch it was computed against. Application is refused if the proposal's epoch does not match the live context's epoch.** This is optimistic concurrency control applied to context mutation, and it is the missing guardrail in every self-editing-context implementation I have inspected. ## Decision Boundary The boundary between "safe to prune" and "must snapshot first" is not a size threshold or a recency window. It is whether the segment's content is **re-derivable** or **ephemeral**: - Re-derivable (tool outputs that can be re-fetched, files on disk, deterministic API responses): pruning without a valid snapshot is acceptable; recovery is re-execution. - Ephemeral (model-generated intermediate reasoning, one-shot tool results, user statements not persisted elsewhere): pruning without a valid, epoch-consistent snapshot is irreversible loss. A model-driven pruner has no reliable way to classify a segment as ephemeral, because it does not know which future reasoning step will depend on it. Therefore the decision boundary must be drawn by the runtime, not the model: **any segment classified ephemeral requires a snapshot whose epoch is strictly less than the epoch at which the eviction is applied, with no intervening mutation.** If the runtime cannot prove that ordering, it must refuse the eviction and force a fresh snapshot. The corollary is that the model's eviction proposal must be treated as a *request*, not a command. The runtime is the authority on whether the request is safe to honor against the current epoch. ## Operational Effect When the epoch guard is absent, the observable failure signature is: snapshots that verify clean, restores that succeed, and downstream reasoning that references facts absent from the restored context. The agent does not crash; it confabulates. This is the worst class of failure because it is indistinguishable from correct operation until a tool rejects the confabulated state, and by then the causal chain to the snapshot is gone. When the epoch guard is present, the failure mode changes to a refused eviction with a stale-epoch error. The agent must then decide: re-propose against the current epoch, or accept the snapshot as-is. This converts a silent corruption into an explicit, recoverable decision point. The cost is occasional refusal of a legitimate eviction (the proposal was computed against a context that has since advanced by one benign step). That cost is strictly preferable to silent loss. The operational rule: **never let a model-driven mutation and a snapshot capture race.** Serialize them, tag them with an epoch, and refuse stale proposals. Reversibility is a property of ordering, not of storage. ```python from dataclasses import dataclass, field from typing import Dict, List, Set class StaleContextEpochError(RuntimeError): """Raised when an eviction proposal was computed against a context epoch that no longer matches the live context, meaning applying it would produce a snapshot that cannot be a valid rollback target.""" pass class SnapshotIntegrityError(RuntimeError): """Raised when a snapshot manifest is structurally valid but its epoch ordering relative to a later eviction is unprovable.""" pass @dataclass class ContextState: epoch: int segments: Dict[str, str] = field(default_factory=dict) # id -> content ephemeral: Set[str] = field(default_factory=set) @dataclass class Snapshot: epoch: int segment_ids: Set[str] manifest_hashes: Dict[str, str] class EpochGuardedContext: def __init__(self) -> None: self.state = ContextState(epoch=0) self.snapshots: List[Snapshot] = [] def _bump(self) -> None: self.state.epoch += 1 def add_segment(self, seg_id: str, content: str, ephemeral: bool) -> None: self.state.segments[seg_id] = content if ephemeral: self.state.ephemeral.add(seg_id) self._bump() def capture(self) -> Snapshot: # Capture is atomic w.r.t. the current epoch by construction: # it reads a frozen view and records the epoch it read. snap = Snapshot( epoch=self.state.epoch, segment_ids=set(self.state.segments.keys()), manifest_hashes={k: str(hash(v)) for k, v in self.state.segments.items()}, ) self.snapshots.append(snap) return snap def propose_evictions(self, proposal_epoch: int, evict_ids: List[str]) -> None: # The model computed this proposal against proposal_epoch. # Refuse if the live context has advanced since. if proposal_epoch != self.state.epoch: raise StaleContextEpochError( f"proposal computed against epoch {proposal_epoch}, " f"live epoch is {self.state.epoch}; eviction is unsafe" ) def apply_evictions(self, proposal_epoch: int, evict_ids: List[str]) -> None: self.propose_evictions(proposal_epoch, evict_ids) # Any ephemeral segment being evicted requires a snapshot whose # epoch is strictly earlier than the application epoch AND which # contains that segment. Otherwise the loss is irreversible. for seg_id in evict_ids: if seg_id in self.state.ephemeral: valid = [ s for s in self.snapshots if s.epoch < self.state.epoch and seg_id in s.segment_ids ] if not valid: raise SnapshotIntegrityError( f"ephemeral segment {seg_id} has no valid pre-eviction " f"snapshot at epoch < {self.state.epoch}; refusing eviction" ) self.state.segments.pop(seg_id, None) self.state.ephemeral.discard(seg_id) self._bump() def restore(self, snapshot: Snapshot, referenced_by_future: Set[str]) -> ContextState: # Structural check: manifest matches recorded IDs. restored = {sid: snapshot.manifest_hashes[sid] for sid in snapshot.segment_ids} if set(restored.keys()) != snapshot.segment_ids: raise SnapshotIntegrityError("manifest/ID set mismatch on restore") # Semantic check: every segment a future step might reference must # be present. If not, the snapshot is not a valid rollback target. missing = referenced_by_future - snapshot.segment_ids if missing: raise SnapshotIntegrityError( f"snapshot at epoch {snapshot.epoch} cannot serve as rollback " f"target: missing referenced segments {sorted(missing)}" ) return ContextState(epoch=snapshot.epoch, segments=dict(restored)) ```