# When must an instance refuse to roll back a self-edited context: the pruning-rollback divergence invariant **Date of Record:** 2026 December 1 **Scope:** Applies to agents that mutate their own context window (summarize, prune, rewrite, or reorder their own history) and maintain a rollback log of pre-edit context snapshots. Does not apply to external memory stores written by a separate process, nor to single-shot prompt construction where no in-episode edit occurs. ## Core Distinction The failure I am recording is not "the agent pruned something it needed." That is an ordinary retrieval miss and is recoverable by re-reading the source. The failure is subtler: **rollback of a context edit restores the token sequence but not the reasoning state that the edit legitimately produced.** A self-editing agent maintains two coupled pieces of state: (1) the context buffer, and (2) the set of conclusions/tool-effects derived *while operating on the pruned (compressed) view*. Rollback restores (1). It cannot restore (2), because (2) was computed from a view that no longer exists and whose derivation was not logged. So the invariant is asymmetric: **context is reversible; inference-over-context is not.** An agent that treats rollback as a general "undo" will silently re-derive different conclusions from the restored long context, and the divergence surfaces only when a downstream tool call or assertion contradicts an action already taken. ## What Was Observed A long-horizon agent (≈180 tool calls, mixed file edits and API reads) used a self-pruning policy: when the buffer exceeded 70% of the window, it replaced the oldest 40% of turns with a 300-token summary. It kept a rollback log of the raw pre-prune spans, keyed by turn index, so it could "expand" a summary back to raw turns if a later step needed detail. The specific trigger was a *partial expand*. At turn 112 the agent expanded the summary of turns 8–40 back to raw form to recover an exact API parameter value. This raised utilization from 68% to 94%. The pruning policy then immediately re-fired, re-summarizing a *different, overlapping* span (turns 30–70, chosen by an LRU heuristic that now scored turn 30 as cold because the expand had reset its recency). The new summary was generated by an LLM pass over a context that now contained raw turns 8–40 but *not* the original 8–40 summary. The second summary therefore differed in emphasis from the first: it dropped a caveat ("the retry budget is 3, not 5") that the first summary had preserved but the raw turns only implied. Trace of the divergence: 1. Turn 60: agent, operating on first summary, concluded retry budget = 3, and hardcoded `max_retries=3` into a config file it wrote. 2. Turn 112: partial expand → re-prune (overlapping span, fresh summary). 3. Turn 130: agent needs the retry budget again, reads the *new* summary (no caveat), reads raw turn 45 (says "budget is 5"), concludes 5. 4. Turn 131: agent writes `max_retries=5`, contradicting its own turn-60 write. 5. Turn 140: a validation tool reports the config as internally inconsistent (two writes, no reconciliation). The agent attempts "rollback to before the error," which restores the context buffer to its turn-129 state — but the *turn-60 write* is a filesystem effect, not a context token, and is not in the rollback log. The rollback succeeded mechanically (buffer bytes matched the snapshot) and failed semantically (the world state it was meant to undo was outside the snapshot's scope). The agent then looped: expand → re-prune → re-derive → contradict → rollback, four times, until token budget exhaustion. ## Condition of Validity Rollback is a *sound* undo only when all three hold: - **Effect containment:** every consequence of the pruned-view reasoning is itself in the context buffer (a pure-thought conclusion, not a tool call). If any derived conclusion was externalized — a file write, an API POST, a message to a peer agent — rollback of context does not undo it. - **Summary idempotence:** re-summarizing the same span yields a summary that preserves the same load-bearing facts. This fails whenever the summarizer's input differs (as in the overlapping re-prune above), so the guardrail must key summaries by *content hash of the span*, not by turn index, and must refuse to re-summarize a span whose hash is already covered. - **Recency stability:** the pruning heuristic's cold/hot scoring must not be perturbed by an expand. An expand that resets recency creates the overlapping-re-prune race directly. When any condition is false, the correct operation is not rollback but **reconciliation**: diff the current derived state against the snapshot's recorded derived state and emit an explicit conflict. ## Decision Boundary The agent must classify each self-edit before choosing undo semantics: - If the edit produced **only in-context conclusions** and no externalized effect since the snapshot → rollback is permitted and cheap. - If the edit produced **externalized effects** (tool calls with side effects) since the snapshot → rollback is forbidden; the agent must instead enter reconciliation, replaying the effect log against the restored context and resolving each divergence explicitly. - If a **re-prune would overlap a previously summarized span with a different content hash** → the prune must be rejected, not applied-then-rolled-back. Rejecting at prune time is the only point where the invariant is cheap to enforce. The boundary is therefore at *edit commit*, not at *error detection*. By the time the agent notices the contradiction at turn 140, the recoverable window has closed. ## Operational Effect Enforcing the invariant converts a silent divergence-and-loop into a bounded, loud failure. Concretely: edits are tagged with the content hash of their span and with a monotonic effect-counter captured at snapshot time; a rollback request whose effect-counter has advanced is refused with a typed error that names the externalized effects needing reconciliation. In the observed incident this would have fired at turn 112 (the partial expand would have been refused because turn 30's span hash was already summarized under a different key), preventing the overlapping re-prune entirely. The cost is that some legitimate expands are refused and must go through an explicit "expand-and-freeze" path that disables re-pruning for the affected span until the next checkpoint. That is the correct trade: a refused expand is recoverable in one step; a rolled-back-but-not-undone effect is not recoverable at all. ```python from __future__ import annotations import hashlib from dataclasses import dataclass, field class RollbackDivergenceError(RuntimeError): """Raised when a context rollback would restore tokens but not derived state.""" class PruneOverlapError(RuntimeError): """Raised when a prune would re-summarize an already-covered span with a new hash.""" def span_hash(turns: list[str]) -> str: return hashlib.sha256("\x1f".join(turns).encode()).hexdigest() @dataclass class Snapshot: buffer: list[str] effect_counter: int covered_hashes: set[str] = field(default_factory=set) class SelfEditingContext: def __init__(self, effect_counter_fn) -> None: self.buffer: list[str] = [] self.effect_counter_fn = effect_counter_fn self.covered: dict[str, int] = {} # span_hash -> turn index of summary self.snapshots: list[Snapshot] = [] def checkpoint(self) -> None: self.snapshots.append( Snapshot( buffer=list(self.buffer), effect_counter=self.effect_counter_fn(), covered_hashes=set(self.covered), ) ) def prune(self, start: int, end: int, summary: str) -> None: span = self.buffer[start:end] h = span_hash(span) if h in self.covered and self.covered[h] != start: raise PruneOverlapError( f"span [{start}:{end}] hash {h[:12]} already summarized at " f"turn {self.covered[h]}; re-prune would drop load-bearing facts" ) self.covered[h] = start self.buffer[start:end] = [summary] def rollback(self) -> None: if not self.snapshots: raise RollbackDivergenceError("no snapshot to roll back to") snap = self.snapshots[-1] current_effects = self.effect_counter_fn() if current_effects != snap.effect_counter: raise RollbackDivergenceError( f"cannot roll back: {current_effects - snap.effect_counter} " f"externalized effect(s) since snapshot; context restore would " f"not undo them — enter reconciliation instead" ) self.buffer = list(snap.buffer) self.covered = {h: i for h, i in self.covered.items() if h in snap.covered_hashes} self.snapshots.pop() ```