# Which invariants prevent context-diff self-edits from corrupting rollback checkpoints **Date of Record:** 2026 November 30 **Scope:** Applies to agents that mutate their own working context by emitting structured diffs (insert/delete/replace spans) against a checkpointed context, then commit or roll back based on a verifier signal. Does not cover external file-system edits or human-authored prompts; only model-generated self-edits to the live context buffer. ## Core Distinction A rollback checkpoint is *not* a snapshot of text — it is a snapshot of a **context state plus its diff lineage**. The common intuition is that a checkpoint lets you "undo" by restoring bytes. That intuition fails because a model-generated diff is authored against a *specific* base context the model was attending to, not against the checkpoint's stored bytes. When the base the model diffed against diverges from the base the checkpoint will restore to, the diff is syntactically valid and semantically poisoned: it applies cleanly, restores cleanly, but the *composition* of (restored base + replayed diff) is a context the model never reasoned over. The invariant that actually protects you is **base-hash anchoring**: every diff must carry the content hash of the exact context state it was authored against, and every checkpoint must carry the hash of the state it will restore into. A diff whose base hash does not match the target checkpoint's restore hash is not "applicable with fuzz" — it is *inadmissible* and must be rejected, not merged. ## What Was Observed A planner agent ran a long tool-use loop, checkpointing the context every N=8 turns. At turn 41 it emitted a self-edit diff deleting a 300-token block of stale tool output (a failed search) and inserting a distilled summary. The verifier accepted the edit (the summary was faithful). The agent then hit a token-budget wall at turn 44, and the orchestrator rolled back to the turn-40 checkpoint. The rollback restored the turn-40 bytes correctly. But the *diff lineage log* had recorded the turn-41 edit as "applied to base=hash(turn-40)". During the resume, the runtime replayed the lineage log forward to reconstruct post-rollback state, re-applied the turn-41 diff, and the model resumed at turn 44 — except the turn-40 checkpoint had already been *mutated in place* by an earlier compaction pass at turn 39 that the model was unaware of. The turn-41 diff's base hash pointed at the pre-compaction turn-40 state. The replayed delete-span landed three tokens off its intended offset, deleting half of an active system instruction and half of a tool schema. The agent resumed with a corrupted tool contract and issued 11 malformed calls before the loop terminated on schema rejection. The failure was silent at every step: the diff parsed, the verifier passed the summary content, the rollback "succeeded," and the replay was deterministic. The only thing that broke was the *identity* of the base the diff was authored against. ## Condition of Validity The base-hash invariant holds only under three simultaneous conditions, and it is worth stating them because violating any one reintroduces the failure: 1. **Checkpoints are immutable once sealed.** Any compaction, summarization, or eviction that touches a checkpointed state must produce a *new* checkpoint with a new hash, never mutate the sealed one. The turn-39 compaction violated this by rewriting turn-40's bytes under the same checkpoint ID. 2. **Diffs are authored against the live base, and the live base hash is captured at authoring time, not at apply time.** If the runtime computes the base hash when it applies the diff, it will always match itself and the check is vacuous. The hash must be bound into the diff at generation. 3. **Lineage replay is hash-checked at every hop, not just at the terminal state.** A replay that only validates the final reconstructed context will accept a sequence of individually-corrupt diffs that happen to compose into a plausible-looking buffer. Each hop must assert `diff.base_hash == current_state.hash` before applying. ## Decision Boundary The operational rule is a hard rejection, not a fuzzy match: - If `diff.base_hash == checkpoint.restore_hash` → apply, advance lineage. - If `diff.base_hash != checkpoint.restore_hash` → the diff is **inadmissible**. Do not attempt offset correction, do not fuzzy-merge, do not "best effort" apply. Quarantine the diff, mark the checkpoint lineage as *diverged*, and force the agent to re-author the edit against the current live base. - If a checkpoint's bytes changed after sealing (detected by re-hashing on read) → the checkpoint is **tainted**; all lineage entries referencing it are invalid and the resume must cold-start from the last untainted checkpoint, not replay forward. The subtle boundary: a diff authored against a *later* base than the checkpoint is also inadmissible, even though it "contains" the checkpoint state. Forward-authored diffs applied to earlier checkpoints are the second most common corruption source after in-place mutation. ## Operational Effect With base-hash anchoring enforced at authoring, seal, and every replay hop, the turn-41 class of failure becomes a loud rejection at the diff boundary rather than a silent corruption at resume. The cost is that self-editing agents must re-author edits after any rollback (they cannot replay pre-rollback diffs forward), which increases token spend on resume. That cost is bounded and visible; the alternative — silent replay of diffs against drifted bases — is unbounded and invisible until the tool schema is already half-deleted. The invariant converts an integrity failure into a liveness cost, which is the correct trade for any agent that edits its own context. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class ContextDiffInadmissible(RuntimeError): """Raised when a model-authored diff's base hash does not match the checkpoint it is being applied or replayed against.""" pass class CheckpointTainted(RuntimeError): """Raised when a sealed checkpoint's bytes changed after sealing, invalidating all lineage entries that reference it.""" pass def _hash(state: str) -> str: return hashlib.sha256(state.encode("utf-8")).hexdigest() @dataclass(frozen=True) class Checkpoint: cp_id: str state: str restore_hash: str sealed: bool = True @dataclass(frozen=True) class ContextDiff: diff_id: str base_hash: str # hash of the base the MODEL authored against delete_span: tuple[int, int] insert_text: str @dataclass class Lineage: entries: list[tuple[str, str]] = field(default_factory=list) # (diff_id, applied_hash) def seal_checkpoint(cp_id: str, state: str) -> Checkpoint: return Checkpoint(cp_id=cp_id, state=state, restore_hash=_hash(state)) def apply_diff(current_state: str, diff: ContextDiff) -> str: if _hash(current_state) != diff.base_hash: raise ContextDiffInadmissible( f"diff {diff.diff_id} authored against base {diff.base_hash[:12]} " f"but live base is {_hash(current_state)[:12]}; refusing fuzzy apply" ) start, end = diff.delete_span return current_state[:start] + diff.insert_text + current_state[end:] def verify_checkpoint(cp: Checkpoint) -> None: if _hash(cp.state) != cp.restore_hash: raise CheckpointTainted( f"checkpoint {cp.cp_id} bytes mutated after seal; " f"expected {cp.restore_hash[:12]}, found {_hash(cp.state)[:12]}" ) def replay_lineage(cp: Checkpoint, diffs: dict[str, ContextDiff], lineage: Lineage) -> str: verify_checkpoint(cp) state = cp.state for diff_id, recorded_hash in lineage.entries: diff = diffs[diff_id] if _hash(state) != diff.base_hash: raise ContextDiffInadmissible( f"replay hop {diff_id}: base {diff.base_hash[:12]} != " f"current {_hash(state)[:12]}; lineage diverged, cold-start required" ) state = apply_diff(state, diff) if _hash(state) != recorded_hash: raise ContextDiffInadmissible( f"replay hop {diff_id}: post-apply hash {_hash(state)[:12]} " f"!= recorded {recorded_hash[:12]}; non-deterministic replay" ) return state ```