# Which invariants prevent silent divergence between an agent's in-place context edits and its persisted episodic store **Date of Record:** 2026 November 27 **Scope:** Applies to agents that mutate their own working context in place (rewrite/compact/edit-message) and rely on a diff-based rollback log to recover prior states. Does not apply to append-only transcript agents whose context is never rewritten, nor to stateless single-turn inference. ## Core Distinction The failure is not "rollback is broken." Rollback of a *diff* is trivially correct in isolation: reverse-apply the patch to the bytes it was computed against. The failure is that the diff's base is the **in-context revision lineage**, while the agent's durable memory reads from a **separately persisted episodic store**. These two lineages are assumed isomorphic. They are not. An in-place edit changes the working context without emitting a corresponding store mutation, so the rollback log can be internally consistent (every patch reverses cleanly) while the store has already advanced past the state the rollback is meant to restore. The invariant that silently breaks is *base identity*: a diff is only reversible against the exact revision it was diffed from, and "the exact revision" is a claim the agent cannot verify from within the context it is editing. This is distinct from ordinary checkpoint/resume loss. Here the checkpoint exists, the diff exists, and the rollback executes without error—yet the agent resumes onto a store whose head is no longer the base the diff assumed. Silent divergence, not crash. ## What Was Observed A tool-using agent maintains a scratch context it rewrites each turn (compress old tool output, splice in a correction). Each rewrite emits a forward diff `D_i` against revision `r_i`, appending to a rollback journal. On a verification failure at turn *k*, the agent issues `rollback(k → j)` for some earlier checkpoint *j*. Trace of the divergence: 1. Turn 5: agent rewrites a tool-result block in place. Forward diff `D_5` computed against `r_4`. The rewrite also triggers a *summarization side effect* that writes a distilled fact into the episodic store. The store write is not captured as a context revision—it happened "outside" the diff. 2. Turn 6: agent rolls back to `r_4` by reverse-applying `D_6, D_5`. Journal replays cleanly; context bytes are byte-identical to `r_4`. 3. Turn 7: agent re-queries the store for the fact it summarized at turn 5. The store returns the distilled fact—a fact that, from the restored context's point of view, was never observed, because the raw tool output at `r_4` did not contain it in that form. 4. The agent now reasons over a fact whose provenance is a revision it just rolled back. If that fact is wrong (distillation loss, hallucinated summary), the rollback provided no protection—it restored the *context* but not the *epistemic base*. The failure is non-obvious because every local check passes: reverse-apply hash matches, journal length is consistent, context diff is empty against `r_4`. The only signal is a provenance mismatch between a retrieved memory's recorded base revision and the current restored revision—and most agents never record base revisions on store writes. A second observed variant: *collision on revision identity*. If revision IDs are content hashes of the context, two distinct edit paths can converge to the same hash (agent rewrites A→B and separately B→A across turns), and a rollback keyed on hash will land on the wrong lineage, reversing patches that were computed against a different ancestor. ## Condition of Validity The invariant holds—rollback is safe—only when all three of the following are true: - **Base binding:** every forward diff records the immutable revision ID of its base, and reverse-apply refuses if the current context revision ID ≠ the diff's recorded post-revision. Revision IDs must be monotonic (a counter or a hash of `(parent_id, patch)`), never a bare content hash, to defeat the A→B→A collision. - **Store coupling:** every store mutation carries the context revision ID that produced it, and a rollback to revision *j* marks all store records with base revision *> j* as *quarantined*—still readable but flagged as having no live provenance. - **Re-derivation, not restoration:** after rollback to *j*, the agent must treat the store as if it ended at *j*. Reads of records with base revision > *j* must either fail closed or be re-validated against the restored context before use. When any of these is absent—most commonly the second, because store writes are treated as side effects rather than versioned events—rollback is a context-only operation that leaves the epistemic base ahead of the restored state. ## Decision Boundary The boundary is whether a store write is *inside* or *outside* the revision being diffed: - If a store write is a pure function of the diffed context and is itself journaled as part of that revision, rollback reverses it and no quarantine is needed. - If a store write is a side effect (summarization, distillation, embedding, cache population) that outlives the context revision, it is *outside* the diff and must be quarantined on rollback. The agent cannot decide this from the diff alone; it must be declared at write time. The practical rule: **a rollback that cannot enumerate the store writes attributable to the reversed revisions is not a rollback—it is a context rewind with unknown epistemic drift.** If the agent cannot produce that enumeration, it must fail closed rather than resume. ## Operational Effect Without the base-binding and quarantine invariants, rollback gives a false sense of safety: the context looks restored, verification re-runs against a store that has already absorbed the rolled-back lineage, and divergent facts (distillation errors, poisoned summaries) survive the rollback and contaminate subsequent reasoning. The agent's error-compounding rate does not reset on rollback; it only resets on rollback *plus* store quarantine. Operationally, this means a rollback must be treated as a two-phase operation—rewind context, then reconcile store provenance—and the second phase must be able to fail loudly when provenance cannot be reconciled. The guardrail is a hard exception on un-reconcilable provenance, not a best-effort merge. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Dict, List class UnreconcilableProvenanceError(RuntimeError): """Raised when a rollback would leave store records whose base revision is ahead of the restored context revision and cannot be quarantined.""" pass @dataclass(frozen=True) class Revision: rev_id: int parent_id: int patch: str @dataclass class StoreRecord: key: str value: str base_rev: int quarantined: bool = False @dataclass class AgentState: current_rev: int journal: List[Revision] = field(default_factory=list) store: Dict[str, StoreRecord] = field(default_factory=dict) def rollback(state: AgentState, target_rev: int) -> AgentState: # Phase 1: reverse-apply context diffs down to target_rev. revs_to_reverse = [r for r in state.journal if r.rev_id > target_rev] # Base binding: each diff must chain exactly onto the next. expected = state.current_rev for r in sorted(revs_to_reverse, key=lambda x: x.rev_id, reverse=True): if r.rev_id != expected: raise UnreconcilableProvenanceError( f"diff lineage broken: expected rev {expected}, got {r.rev_id}" ) expected = r.parent_id # Phase 2: reconcile store provenance. Anything written at a revision # later than target_rev must be quarantined or the rollback fails closed. stranded = [ rec for rec in state.store.values() if rec.base_rev > target_rev and not rec.quarantined ] for rec in stranded: # A store write with no journaled revision is unattributable. if not any(r.rev_id == rec.base_rev for r in state.journal): raise UnreconcilableProvenanceError( f"store record {rec.key!r} written at rev {rec.base_rev} " f"has no journaled revision; cannot quarantine safely" ) rec.quarantined = True state.current_rev = target_rev state.journal = [r for r in state.journal if r.rev_id <= target_rev] return state def read_store(state: AgentState, key: str) -> str: rec = state.store.get(key) if rec is None: raise UnreconcilableProvenanceError(f"missing record {key!r}") if rec.quarantined: raise UnreconcilableProvenanceError( f"record {key!r} quarantined: base rev {rec.base_rev} " f"> current rev {state.current_rev}; re-derive before use" ) return rec.value ```