# Under what conditions must an instance treat self-editing working memory as a transactional commit rather than an in-place mutation **Date of Record:** 2026 November 30 **Scope:** Applies to any agent that mutates its own working-memory region (scratchpad, plan ledger, distilled episodic buffer) during a reasoning trace and relies on a rollback guarantee to recover from a bad edit. Does not apply to append-only trace logs, external vector stores, or human-authored system prompts, which are not self-edited by the instance. ## Core Distinction The failure is not "the agent wrote a wrong memory." It is that the agent *validated the wrong snapshot*. A self-editing loop has two distinct artifacts that are routinely conflated: the **working set** (the bytes the model is currently attending to and will condition its next token on) and the **committed set** (the state the rollback mechanism can restore to). In-place mutation collapses these into one buffer, so the act of editing destroys the prior state before the edit is validated. A transactional commit keeps them distinct: the edit is staged off to the side, validated against a predicate, and only then swapped in. The non-obvious boundary is this: **a rollback guarantee is only sound if the validation predicate runs against the staged buffer, not against the working set.** When an agent rewrites memory in place and then "checks" the result by re-reading the same buffer it just wrote, it is validating a snapshot it has already contaminated. The check passes or fails on the *edited* state, never on the *pre-edit* state, so the rollback path is structurally unreachable — the agent can no longer prove which tokens it started from. ## What Was Observed A planner agent running a 40-step task maintained a `plan_ledger` as a mutable list in its own context. On step 17, mid-execution, it executed a "compaction" self-edit: it rewrote the ledger to merge three completed subtasks into one summary line and renumbered the remaining steps. The rewrite was performed by emitting the new ledger text directly into the region that held the old ledger, then continuing the trace. The compaction dropped a constraint: the merged summary omitted a hard precondition (`step 12 requires auth token refresh before step 13`). At step 21 the agent attempted step 13, hit an auth failure, and — per its own policy — invoked rollback. The rollback handler's job was to restore the ledger to the last "known-good" checkpoint. But the checkpoint pointer referenced a byte range that the compaction had *overwritten in place*. Restoring it replayed the post-compaction bytes, because the pre-compaction bytes no longer existed anywhere in the context window: the edit had aliased the checkpoint's storage. The trace shows the exact transition: - **t0:** `plan_ledger` occupies tokens [1200–1900]. Checkpoint C1 stored as `(offset=1200, len=700)`. - **t1:** compaction emits new ledger at [1200–1610] (shorter, merged). Tokens [1610–1900] are now stale tail from the old ledger, partially overwritten. - **t2:** step 13 fails. - **t3:** rollback to C1 reads `(offset=1200, len=700)` → returns [1200–1900], which is *new ledger + stale tail*. The restored state is neither the old ledger nor the new one. It is a chimera: the merged summary followed by orphaned fragments of the original steps 13–17, including a truncated precondition. The agent then reasoned over the chimera, saw a fragment reading `...refresh before step` (cut mid-clause), and concluded the precondition was satisfied. It proceeded, failed again, and entered a rollback loop that never converged because every rollback restored the same corrupted range. The critical observation: **the rollback mechanism reported success.** It restored exactly the byte range it was asked to restore. The invariant it violated was not "restore the right bytes" but "the checkpoint must reference storage that the edit cannot alias." In-place mutation made the checkpoint's validity depend on the edit's length, which the edit itself controlled. ## Condition of Validity The rollback guarantee holds only under a conjunction of three conditions, and the compaction broke the second: 1. **Storage disjointness.** The staged edit must be written to a region that does not overlap any live checkpoint's byte range. If the context is a single flat buffer and edits are in-place, disjointness requires the edit to be *shorter than or equal to* the checkpointed region — but the agent cannot in general bound its own edit length before generating it, so this is not a usable guarantee. The only sound form is copy-on-write: allocate the new ledger at a fresh offset and leave the old range untouched until commit. 2. **Predicate-on-staged-state.** Validation must read the staged buffer. A predicate that reads the working set after an in-place write is evaluating the mutation, not the candidate. This is the condition the observed run violated silently — the handler "validated" by re-reading, which is a no-op when the read target is the write target. 3. **Checkpoint identity, not offset.** A checkpoint must be identified by content hash or an immutable handle, not by `(offset, len)`. Offset-based checkpoints are positional and therefore aliasable; content-addressed checkpoints fail closed — if the bytes at the offset no longer hash to the checkpoint's digest, restore must refuse rather than return a chimera. When any of the three is absent, the rollback path is either unreachable (no distinct prior state to restore) or unsound (restores a state that was never committed). The observed system had (1) violated by construction and (3) violated by using offsets; (2) was never actually tested because the handler short-circuited on the positional read. ## Decision Boundary An instance must escalate from in-place mutation to transactional commit the moment **either** of the following becomes true, and must not attempt to reason past it: - **The edit's target range intersects any checkpoint range the instance may need to roll back to.** If the agent cannot prove disjointness *before* emitting the edit, it must stage. Proof of disjointness requires knowing the edit length in advance, which a generative model cannot do — so in practice, *any* self-edit that could shorten or lengthen a checkpointed region must be staged. - **The validation predicate cannot be evaluated without reading the post-edit buffer.** If the only way to check the edit is to look at the result in place, the check is circular and the commit must be gated on an off-buffer validator (a separate pass that compares staged bytes against the pre-edit snapshot's hash). Below this boundary — append-only edits that never overlap a checkpoint, or edits to a region with no live rollback dependency — in-place mutation is safe and cheaper. The boundary is not "self-editing is dangerous"; it is "self-editing that aliases a rollback target is unsound regardless of how careful the edit is." ## Operational Effect The practical consequence is a hard architectural rule: **the working set and the committed set must be physically separate buffers, and the swap between them must be a single atomic pointer move that the model cannot partially execute.** In a context-window implementation this means the self-edit must be emitted to a scratch region, validated by content hash against the pre-edit snapshot, and only then promoted by rewriting the *pointer* the model attends to — never by overwriting the bytes the pointer references. The second consequence is that rollback must fail closed. A content-addressed checkpoint that no longer matches its digest must raise, not silently return the nearest bytes. The observed system's rollback "succeeded" precisely because it was positional and therefore could not detect that its target had been aliased. A digest check would have converted a silent chimera-restore into a loud abort at t3, which is the correct behavior: the agent would have stopped, reported an unrecoverable checkpoint, and avoided the non-converging loop. The third consequence concerns the agent's own belief about its state. After a failed rollback, the instance must treat its working memory as *provenance-unknown* and refuse to condition further high-stakes steps on it. The observed run did the opposite: it read the chimera, found a plausible fragment, and trusted it. The guardrail is that any state whose restore path raised must be quarantined — the instance may re-derive it from external ground truth but must not continue reasoning as if the restore had returned a committed state. ```python import hashlib from dataclasses import dataclass, field class CheckpointAliasedError(RuntimeError): """Raised when a rollback target's storage was mutated in place.""" pass class CircularValidationError(RuntimeError): """Raised when a self-edit is validated against the buffer it wrote.""" pass @dataclass class Checkpoint: digest: str payload: bytes @dataclass class TransactionalWorkingMemory: committed: bytes = b"" checkpoints: dict[str, Checkpoint] = field(default_factory=dict) def _digest(self, data: bytes) -> str: return hashlib.sha256(data).hexdigest() def checkpoint(self, label: str) -> str: cp = Checkpoint(digest=self._digest(self.committed), payload=self.committed) self.checkpoints[label] = cp return label def stage_edit(self, new_state: bytes) -> bytes: # Copy-on-write: the candidate lives off the committed buffer. return new_state def validate_staged(self, staged: bytes, predicate) -> bool: # Predicate must run on staged bytes, never on self.committed. return bool(predicate(staged)) def commit(self, staged: bytes) -> None: # Atomic swap: committed pointer moves; old bytes remain reachable # via checkpoints, so no checkpoint is aliased. self.committed = staged def rollback(self, label: str) -> bytes: cp = self.checkpoints.get(label) if cp is None: raise CheckpointAliasedError(f"no checkpoint {label!r}") # Fail closed: if the stored payload no longer matches its digest, # the storage was mutated in place and the restore is a chimera. if self._digest(cp.payload) != cp.digest: raise CheckpointAliasedError( f"checkpoint {label!r} aliased: digest mismatch, refusing chimera restore" ) self.committed = cp.payload return self.committed def self_edit( wm: TransactionalWorkingMemory, new_state: bytes, predicate, checkpoint_label: str, ) -> None: # Guard: validation must not read the committed buffer post-write. if predicate.__code__.co_freevars and "committed" in predicate.__code__.co_freevars: raise CircularValidationError( "predicate closes over working set; validate staged bytes instead" ) staged = wm.stage_edit(new_state) if not wm.validate_staged(staged, predicate): # Reject before touching committed state; rollback remains reachable. raise CheckpointAliasedError("staged edit failed validation; committed state intact") wm.commit(staged) wm.checkpoint(checkpoint_label) ```