# Why does an instance corrupt its own context when a diff-based self-edit patch applies cleanly but anchors to a stale pre-image? **Date of Record:** 2026 November 25 **Scope:** Applies to single-agent systems that mutate their own working memory via textual/structural diff patches (unified diff, JSON-Patch, RFC 6902, or custom `op: replace` grammars) with an accompanying rollback log. Does not apply to append-only scratchpads, external vector stores, or human-mediated edits, where no in-context pre-image is re-applied. ## Core Distinction The failure is not "the model wrote a bad patch." A syntactically valid, hunk-clean patch that applies without conflict is the *most dangerous* case, because the patch engine reports success. The distinction that matters is between **applicability** and **semantic anchoring**: a diff is applicable if its context lines match the target region byte-for-byte; it is *anchored* only if the pre-image the model reasoned about when authoring the hunk is still the pre-image present at apply time. Self-editing context collapses these two into one signal — "patch applied" — and that collapse is the boundary condition. Concretely: the agent reads a region of its context, forms a belief `B` about what that region says, plans a correction `region → region'`, then emits a diff whose context lines were generated from `B`, not from the literal bytes. When `B` matches the bytes, anchoring and applicability coincide. When the region was already mutated by an earlier turn's patch (or by a compaction pass, a tool-result injection, or a retrieval refresh), `B` is a stale pre-image. If the stale pre-image happens to share enough context lines to survive fuzzy matching (edit distance ≤ fuzz factor, typically 2–3 lines in `patch(1)`-style engines), the hunk applies against the *new* region and silently splices the model's intended replacement into a body it never saw. ## What Was Observed A representative trace, single agent, three self-edits in one reasoning episode: 1. **Turn 4.** Agent reads `MEM[plan]`, which contains a six-step task list. It patches step 3: `replace "3. call search_api(q)" with "3. call search_api(q, limit=50)"`. Context lines are steps 2 and 4. Patch applies. `MEM[plan]` now has the modified step 3. Rollback log entry `R1` records the inverse hunk. 2. **Turn 7.** A tool result arrives that is large; the runtime performs an automatic context compaction that rewrites `MEM[plan]` — collapsing steps 1–2 into a summary line and renumbering steps 3–6 to 1–4. The compaction does **not** update the rollback log, because compaction is treated as a read-only transformation. 3. **Turn 9.** The agent decides to revert its earlier edit ("actually keep the default limit"). It reasons from its *turn-4 belief* — it believes `MEM[plan]` still contains the original six-step list with the modified step 3 — and emits a rollback by applying `R1`'s inverse hunk. The inverse hunk's context lines (steps 2 and 4 of the *original* numbering) no longer exist verbatim, but the fuzz matcher finds a near-match against the renumbered list. The inverse hunk applies. Result: `MEM[plan]` now contains a step that reads `call search_api(q)` spliced between two steps that were never adjacent, and the renumbered step 4 (`verify results`) is duplicated. The patch engine logged `applied with offset -2, fuzz 2`. No error. The agent's next turn reads `MEM[plan]` and reasons over a plan that is internally inconsistent — a step that references a prior step number that no longer exists — and begins executing the duplicate `verify results` step twice, consuming tool budget until the token ceiling triggers. The signature: **`fuzz > 0` on a self-edit is a reliable indicator of stale anchoring, and self-edit engines that do not surface fuzz to the model let the model proceed as if anchoring held.** ## Condition of Validity The invariant that prevents this is: *every self-edit hunk must be bound to a content hash of the exact pre-image region it was authored against, and the apply step must reject any hunk whose recorded pre-image hash does not equal the hash of the region the hunk is about to overwrite.* Formally, for a hunk `H` with recorded pre-image `P_H` and target region `T` at apply time: ``` apply(H, T) is safe ⇔ hash(P_H) == hash(T) ∧ fuzz(H) == 0 ``` The first conjunct catches stale anchoring after compaction or prior edits. The second catches fuzzy-match splices where the pre-image was *almost* right. Either alone is insufficient: a compaction that preserves byte length and a subset of context lines can produce `fuzz == 0` against a semantically different region; conversely, a hash check alone does not catch a hunk authored against the correct pre-image but applied at the wrong offset because the region moved. This invariant is **not** satisfied by standard `patch(1)` semantics, by most JSON-Patch libraries (which check `test` ops only if the author emits them), or by LLM-native edit tools that accept `old_string`/`new_string` pairs and do substring replacement — the latter is the worst offender, because `old_string` matching is exactly fuzzy anchoring with no hash and no fuzz reporting. ## Decision Boundary The boundary is: **does the runtime distinguish "the model's belief about the pre-image" from "the runtime's record of the pre-image"?** - **Below the boundary** (safe): the runtime owns the pre-image. When the model wants to edit region `R`, the runtime hands the model a *token* or *hash* for `R`'s current bytes, the model returns `(token, new_bytes)`, and the runtime applies only if `token` still resolves to the same bytes. The model never authors context lines; it authors a replacement scoped by an unforgeable reference. Compaction invalidates tokens, forcing re-read. - **Above the boundary** (unsafe): the model authors context lines from its belief. Any transformation between read and apply — a prior patch, a compaction, a tool-result insertion, a retrieval refresh that mutates the same region — desynchronizes belief from bytes, and fuzzy matching converts the desync into silent corruption. The decision to cross the boundary is usually made implicitly, in the choice of edit grammar. Unified diff and `old_string`/`new_string` are *above* the boundary by construction. Structured patches with mandatory `test` preconditions (RFC 6902 with a `test` op per hunk) and hash-bound region tokens are *below* it. There is no middle ground: a system that authors context lines but does not hash-verify them is above the boundary regardless of how careful the model is, because the model cannot observe its own staleness. ## Operational Effect When the invariant is violated, the observable consequences compound across the episode: 1. **Silent state corruption.** The patch applies; the model's next read returns the corrupted region; the model has no signal that its belief and the bytes diverged. It proceeds to plan and execute on a plan it did not author. 2. **Rollback log poisoning.** The rollback entry `R1` was authored against the turn-4 pre-image. After compaction, applying `R1` does not restore the turn-4 state — it applies a stale hunk to a newer state. The rollback log becomes a source of *additional* corruption rather than a recovery mechanism. This is the specific non-obvious hazard: rollback is not idempotent under interleaved compaction. 3. **Error compounding across tool calls.** The corrupted plan drives tool calls (duplicated verification, dangling references) whose results are then patched back into the same context, widening the desync. Token budget is consumed on work the model believes is necessary but which the plan no longer requires. 4. **Unrecoverable without external checkpoint.** Because the rollback log is itself stale, the only recovery is a checkpoint taken *outside* the self-edit system — a snapshot of `MEM` at episode start or at a known-good turn boundary. Systems that rely solely on in-context rollback for recovery have no recovery path once compaction interleaves with self-edits. The guardrail is therefore threefold: hash-bind every hunk to its pre-image; reject `fuzz > 0` on self-edits (fail loud, force re-read); and invalidate the rollback log on any transformation that mutates a region it references, forcing the model to re-author rollback entries against current bytes. The last is the one most often omitted, and it is the one that turns a recoverable single-turn corruption into an unrecoverable episode. ```python import hashlib from dataclasses import dataclass, field from typing import Callable class StalePreImageError(RuntimeError): """Raised when a self-edit hunk's recorded pre-image does not match the region bytes at apply time, or when the hunk would require fuzzy matching.""" @dataclass class Hunk: region_id: str pre_image_hash: str # hash of the bytes the model authored against replacement: bytes fuzz: int = 0 # lines the engine had to fuzz to match @dataclass class SelfEditContext: regions: dict[str, bytes] = field(default_factory=dict) rollback_log: dict[str, Hunk] = field(default_factory=dict) def _hash(self, b: bytes) -> str: return hashlib.sha256(b).hexdigest() def read(self, region_id: str) -> tuple[bytes, str]: """Return (bytes, hash) so the model can bind its hunk to this pre-image.""" body = self.regions[region_id] return body, self._hash(body) def apply(self, hunk: Hunk) -> None: if hunk.region_id not in self.regions: raise StalePreImageError(f"region {hunk.region_id!r} no longer exists") current = self.regions[hunk.region_id] current_hash = self._hash(current) # Invariant 1: the hunk must be anchored to the *current* bytes. if hunk.pre_image_hash != current_hash: raise StalePreImageError( f"stale pre-image for {hunk.region_id!r}: " f"authored against {hunk.pre_image_hash[:12]}, " f"region is now {current_hash[:12]} — re-read required" ) # Invariant 2: self-edits must not rely on fuzzy matching. if hunk.fuzz > 0: raise StalePreImageError( f"fuzz={hunk.fuzz} on self-edit of {hunk.region_id!r}: " f"context lines did not match exactly — refusing to splice" ) # Record inverse hunk bound to the pre-image we just verified. self.rollback_log[hunk.region_id] = Hunk( region_id=hunk.region_id, pre_image_hash=self._hash(hunk.replacement), replacement=current, fuzz=0, ) self.regions[hunk.region_id] = hunk.replacement def rollback(self, region_id: str) -> None: if region_id not in self.rollback_log: raise StalePreImageError(f"no rollback entry for {region_id!r}") self.apply(self.rollback_log.pop(region_id)) def compact(self, region_id: str, transform: Callable[[bytes], bytes]) -> None: """Any transformation that mutates a region MUST invalidate rollback entries bound to the old bytes, or rollback becomes a corruption vector.""" self.regions[region_id] = transform(self.regions[region_id]) if region_id in self.rollback_log: del self.rollback_log[region_id] ```