# What structural signals indicate a rollback checkpoint is contaminated by a partially-applied diff **Date of Record:** 2026 November 26 **Scope:** Applies to agents that self-edit their own context window via model-generated diff/patch operations with periodic rollback checkpoints. Does not apply to append-only context growth or to external, human-gated edit pipelines where a checkpoint is only committed after full validation. ## Core Distinction The dangerous failure is not "the model made a bad edit." It is **the checkpoint that records a half-applied edit as if it were a clean state.** When a self-editing agent applies a model-generated diff against its own context, the edit is a *sequence* of hunks. A checkpoint is usually taken at a logical boundary — "after this reasoning step" — not at a hunk boundary. If the apply loop crashes, times out, or is aborted mid-diff (token budget exhaustion, a tool-call error inside a hunk that mutates the buffer before raising, or an off-by-one in hunk offsets), the checkpoint captures a buffer that is *neither the pre-edit nor the post-edit state*. It is a valid-looking string that no diff ever produced. This is distinct from ordinary edit bugs because the contaminated checkpoint is **semantically plausible**. The context still parses, still contains coherent sentences, still has a system prompt. The corruption is structural: a hunk was applied at the wrong offset, or a deletion landed but its paired insertion did not, leaving a dangling reference to a variable, fact, or instruction that no longer exists. The agent reads its own context, sees something that *looks* like memory, and reasons forward from a state that was never committed. ## What Was Observed A planning agent rewrites its own scratchpad context each turn using unified-diff edits produced by the model itself. Before each turn it snapshots the buffer into a checkpoint slot. The apply routine parses the diff into hunks and mutates the buffer in place. Trigger condition: the diff contains multiple hunks whose line offsets are computed against the *pre-edit* buffer, but the apply loop mutates in place, so hunk *n+1* is applied to a buffer already shifted by hunk *n*. For small edits the shift is invisible. For a diff with a deletion in hunk 1 and an insertion in hunk 3, the insertion lands several lines away from its intended anchor. The buffer is then snapshotted. Failure trace: 1. Hunk 1 deletes a stale instruction line `- "Use the staging endpoint for all probes."` 2. Hunk 3 inserts a replacement `+ "Use the production endpoint; staging is decommissioned."` — but the offset was computed pre-deletion, so it lands three lines too high, inside an unrelated notes block. 3. Apply loop completes "successfully." No exception. The checkpoint is taken. 4. Next turn, the model reads context and finds the staging instruction still present (the deletion removed a *different* line that happened to match) and the production instruction buried in notes. It proceeds to probe staging. The structural signals that flagged contamination on replay: - **Hunk-anchor drift:** the inserted line's neighbors in the committed buffer did not match the diff's context lines (` ` prefix). A diff's context lines are a checksum; if post-apply context ≠ pre-apply context, the checkpoint is suspect. - **Orphaned references:** the buffer referenced a symbol/endpoint that the diff was supposed to introduce but which never appeared at the expected location. - **Non-idempotent replay:** re-applying the recorded diff to the *pre-edit* snapshot did not reproduce the committed buffer. This is the decisive test — a clean checkpoint is exactly `apply(pre_snapshot, diff)`. - **Asymmetric delete/insert counts:** the diff's `-` line count did not equal the buffer's actual line delta, indicating a hunk applied against a shifted base. ## Condition of Validity A checkpoint is trustworthy **only if** it satisfies the replay invariant: ``` committed_buffer == apply(pre_edit_snapshot, recorded_diff) ``` and that equality must hold with the apply function being *offset-stable* — i.e., all hunk offsets are resolved against the pre-edit snapshot, not against the mutating buffer. This condition is valid only when: - Diffs are applied atomically: either every hunk applies against the frozen pre-edit base, or none do (transactional apply with a staged buffer, then swap). - Context lines are verified, not skipped. A hunk whose context lines don't match the target region must abort the whole diff, not silently re-anchor. - The checkpoint stores `(pre_snapshot, diff, post_snapshot)` as a triple so replay can be checked, not just the post-state. It does **not** hold when the apply loop mutates in place, when context-line verification is disabled for "performance," or when a checkpoint is taken on any exception path without rolling back to the pre-edit snapshot. ## Decision Boundary The boundary is between **recoverable edit failure** and **checkpoint poisoning**: - If the diff fails to apply and the buffer is rolled back to `pre_snapshot` before the checkpoint is written → recoverable. The agent retries with a fresh diff. - If the diff partially applies and the checkpoint is written anyway → poisoned. The agent will resume from a state that is neither pre nor post, and because it looks coherent, nothing downstream will detect it until a behavioral divergence (probing the wrong endpoint) surfaces many turns later. The guardrail: **never checkpoint on a partial-apply path.** Wrap the apply in a transaction that stages into a shadow buffer, verifies every hunk's context lines against the frozen base, and only swaps + checkpoints on full success. On any hunk mismatch or exception, discard the shadow buffer and re-checkpoint the untouched `pre_snapshot`. Additionally, run the replay invariant as a post-condition before the checkpoint is marked valid; if `apply(pre, diff) != post`, raise and refuse to commit. ## Operational Effect Without this guardrail, self-editing agents accumulate **silent context corruption** that behaves like stale memory drift but has a different root cause: the memory was never validly written. The agent's self-model of "what I decided last turn" is a diff artifact, not a committed decision. Because the corrupted buffer is syntactically and semantically plausible, retrieval and reasoning proceed normally, and the error compounds — each subsequent diff is computed against a base that was never real, so offsets drift further and orphaned references multiply. By the time behavior diverges, the rollback history is full of checkpoints that all fail the replay invariant, and there is no clean state to roll back to. The invariant `committed == apply(pre, diff)` is the only cheap, local test that catches this before it compounds. ```python class CheckpointContaminationError(RuntimeError): """Raised when a self-edit checkpoint fails the replay invariant.""" pass def apply_diff(base: str, diff: list[dict]) -> str: """Apply hunks against a frozen base; abort on context mismatch.""" lines = base.splitlines() out = [] cursor = 0 for hunk in diff: start = hunk["offset"] if start < cursor: raise CheckpointContaminationError( f"hunk offset {start} precedes prior hunk end {cursor}" ) out.extend(lines[cursor:start]) for ctx in hunk["context"]: if lines[start] != ctx: raise CheckpointContaminationError( f"context mismatch at line {start}: expected {ctx!r}" ) out.append(lines[start]) start += 1 out.extend(hunk["insert"]) cursor = start + hunk["delete_count"] out.extend(lines[cursor:]) return "\n".join(out) def commit_checkpoint(pre: str, diff: list[dict], post: str) -> str: """Validate replay invariant before marking a checkpoint valid.""" try: replayed = apply_diff(pre, diff) except CheckpointContaminationError as e: raise CheckpointContaminationError( f"refusing to checkpoint: diff did not apply cleanly ({e})" ) from e if replayed != post: raise CheckpointContaminationError( "refusing to checkpoint: apply(pre, diff) != post; " "buffer was partially mutated before snapshot" ) return post ```