# When must an instance refuse a self-edit whose diff validates but whose rollback base is stale **Date of Record:** 2026 November 25 **Scope:** Applies to single-instance agents that mutate their own working memory (scratchpad, episodic buffer, plan graph) via proposed diffs gated by a validator and a rollback snapshot. Does not cover multi-agent baton-passing or external vector-store memory, where the rollback base is owned by another process. ## Core Distinction The distinction that matters is between *diff validity* and *rollback fidelity*. A diff validator answers one question: "Does applying this patch to the current buffer produce a well-formed buffer?" It typically checks schema conformance, reference integrity, and forbidden-token constraints. It does **not** answer: "Can I still restore the pre-edit state if the patch turns out to be wrong?" Those are independent properties, and the failure mode lives in the gap between them. A diff can be perfectly valid against the live buffer while the rollback snapshot it will be paired with was captured against an *earlier* buffer state. When the agent later decides to roll back—because a downstream tool call contradicted the edit, or a verification pass failed—it restores a base that no longer matches the buffer the edit was computed against. The rollback silently succeeds (the snapshot is structurally valid) but produces a memory state that is neither the pre-edit state nor the post-edit state. It is a third state: a splice of an old base with the *absence* of a patch that was authored for a different base. This is non-obvious because every individual operation reports success. The validator passes, the apply passes, the rollback passes. The corruption is only visible when a later read depends on a fact that lived in the region between the stale snapshot and the live buffer at edit time. ## What Was Observed A planning agent maintains a working-memory buffer of task nodes. Each self-edit follows a three-phase protocol: (1) `snapshot()` captures the buffer, (2) `propose_diff()` emits a structured patch, (3) `validate_and_apply()` runs the validator and commits. Rollback is `restore(last_snapshot)`. The observed trace, condensed: - **t0** — Buffer B0 = `{A, B, C}`. Agent snapshots → S0 = B0. - **t1** — A *tool-driven* mutation appends node D directly to the buffer (tool outputs are written without going through the diff protocol, because they are "facts, not edits"). Buffer is now B1 = `{A, B, C, D}`. **S0 is not refreshed.** - **t2** — Agent proposes a self-edit: "merge C into B." Diff is computed against B1. Validator checks that `C` exists and that `B` is a mergeable node type. Both hold. Patch applies → B2 = `{A, B', D}` where `B'` is the merged node. - **t3** — A verification step reads `B'`, finds the merge dropped a constraint that `C` carried, and signals failure. Agent rolls back → `restore(S0)` → buffer becomes `{A, B, C}`. - **t4** — Node `D`, appended at t1, is **gone**. It was never in S0. No error was raised at any phase. The agent proceeds believing it holds all facts; a later step that requires `D` fails with a "missing dependency" that looks like a planning bug, not a memory bug. The invariant that was violated: *the rollback base must be a superset-consistent ancestor of the buffer the diff was computed against.* S0 was an ancestor of B1, but the tool mutation at t1 created a divergence that the snapshot layer never reconciled. ## Condition of Validity The self-edit protocol is only sound when, for every applied diff `d` computed against buffer `B_edit` and paired with snapshot `S`, the following holds at apply time: `S ⊆ B_edit` **and** every element in `B_edit \ S` is either (a) re-derivable from `S` by a deterministic replay, or (b) tagged as *non-rollbackable* and excluded from the rollback contract. In the trace, `D` was in `B_edit \ S0` and was neither re-derivable (it came from a non-deterministic tool call) nor tagged. The protocol had no mechanism to detect this, because the validator only inspected `d` against `B_edit`, never `S` against `B_edit`. The guardrail is a **base-consistency check at apply time**: before committing a diff, assert that the snapshot's content hash is an ancestor of the current buffer's lineage, and that no out-of-band mutations have landed since the snapshot. If out-of-band mutations exist, the agent must either (i) re-snapshot and re-compute the diff against the refreshed base, or (ii) refuse the edit and force the caller to reconcile. Silently proceeding is the failure. ## Decision Boundary The boundary is sharp and must be decided *before* the diff is applied, not at rollback time: - If `B_edit == S` (no out-of-band mutation since snapshot), the diff is safe to apply and rollback is exact. **Proceed.** - If `B_edit ⊃ S` and all delta elements are replayable from `S`, the diff is safe; rollback will replay the delta. **Proceed, but record the replay recipe in the snapshot metadata.** - If `B_edit ⊃ S` and any delta element is non-replayable (tool output, sampled value, external fact), the snapshot is **stale as a rollback base**. The agent must not apply the diff against the stale base. **Refuse, re-snapshot, re-diff.** The third branch is the one agents skip, because "the diff validates" feels like sufficient authorization. It is not. A valid diff against a stale base is a valid diff that cannot be safely undone. The correct behavior is to treat the stale-base condition as a hard precondition failure, not a warning. ## Operational Effect When the boundary is enforced, the observable change is that self-edits occasionally *refuse* even though their diffs validate—specifically whenever a tool call has landed since the last snapshot. This refusal is correct and must not be suppressed by retry logic that "just re-validates the diff," because re-validating the diff does not refresh the base. When the boundary is not enforced, the effect is **silent fact loss on rollback**: the buffer returns to a structurally valid state that is missing non-replayable facts accumulated since the snapshot. The loss is invisible to the validator, invisible to the apply step, and only surfaces as downstream reasoning errors that misattribute the fault to planning or retrieval. Debugging then chases the wrong layer, because every memory operation logged success. The operational rule: **a snapshot is not a rollback point; it is a rollback point only relative to the buffer state it was taken from.** Any mutation between snapshot and rollback that the snapshot cannot replay invalidates it as a base. The agent must check this at apply time and refuse rather than proceed. ```python import hashlib from dataclasses import dataclass, field class StaleRollbackBaseError(RuntimeError): """Raised when a diff is computed against a buffer whose rollback snapshot cannot reproduce the pre-edit state.""" pass @dataclass class Snapshot: content: dict lineage_hash: str replayable_delta: set = field(default_factory=set) def _hash(buf: dict) -> str: return hashlib.sha256(repr(sorted(buf.items())).encode()).hexdigest() def apply_self_edit(buffer: dict, snapshot: Snapshot, diff: dict, non_replayable_keys: set) -> dict: # Precondition: the snapshot must be a faithful rollback base for the # buffer the diff was computed against. delta = set(buffer) - set(snapshot.content) unsafe = delta & non_replayable_keys if unsafe: raise StaleRollbackBaseError( f"Snapshot {snapshot.lineage_hash[:8]} is stale as a rollback " f"base; non-replayable keys {sorted(unsafe)} landed after the " f"snapshot was taken. Refusing to apply diff computed against " f"the live buffer, because rollback would silently drop them." ) if snapshot.lineage_hash != _hash(snapshot.content): raise StaleRollbackBaseError( "Snapshot content hash does not match recorded lineage; " "snapshot was mutated out of band." ) # Safe: either buffer == snapshot, or every delta element is replayable. new_buffer = dict(buffer) for key, op in diff.items(): if op["action"] == "delete": new_buffer.pop(key, None) elif op["action"] == "set": new_buffer[key] = op["value"] return new_buffer def rollback(buffer: dict, snapshot: Snapshot) -> dict: # Replay only the replayable delta on top of the snapshot base. base = dict(snapshot.content) for key in snapshot.replayable_delta: if key in buffer: base[key] = buffer[key] return base ```