# What structural signals indicate a self-edit rollback is unsafe: diff-based context rewriting and the tombstone-collapse failure **Date of Record:** 2026 November 24 **Scope:** Applies to agents that rewrite their own working context via diff-and-apply (patch) operations with a journaled rollback path, where the journal stores inverse patches rather than full snapshots. Does not apply to snapshot-per-edit systems or to append-only context that is never compacted in place. ## Core Distinction There are two ways an agent "edits its own context." The first is *append-and-supersede*: new text is added, old text is marked stale by pointer, and the original bytes remain in the store. The second is *in-place diff rewrite*: the agent computes a patch against the live context buffer, applies it destructively, and relies on an inverse patch recorded in a journal to restore prior state. The distinction that matters is not whether the agent can undo an edit — both schemes claim that — but whether the inverse patch is *total* over the mutated region. Diff-based rewriting is attractive because it is token-cheap and keeps the buffer dense. It fails at a specific, non-obvious boundary: **a rollback is only sound if the inverse patch's context lines still match the buffer at restore time.** When a later edit touches the same lines that the inverse patch depends on for anchoring, the inverse patch no longer applies cleanly, and the rollback becomes a *partial* restore that silently drops the region it could not anchor. The agent believes it has returned to state S₀; it has actually returned to a spliced hybrid of S₀ and Sₙ. This is the tombstone-collapse: the diff hunks that were supposed to resurrect deleted content are themselves invalidated by the deletion of their anchor lines, and the content they guarded is gone with no error raised at the buffer level. The critical signal is structural, not semantic. The agent cannot detect this by re-reading its context and judging coherence — the collapsed buffer usually reads fine, because the surviving text is a grammatical subset. It must be detected by inspecting *hunk overlap* between journal entries. ## What Was Observed A planning agent maintained a 40k-token working context and self-edited it after every tool call to compress completed subgoals. Each edit produced a unified-diff patch against the live buffer; the inverse was appended to a journal stack with a monotonically increasing edit ID. On tool failure, the agent popped journal entries and applied inverse patches in reverse order until it reached the edit ID recorded at the last known-good checkpoint. The failure trace: 1. Edit 7 rewrites a planning block, deleting lines 210–228 (a set of intermediate constraints) and inserting a compressed summary. Inverse patch J7 contains the deleted 19 lines as `+` additions, anchored on context lines 205–209 and 229–233. 2. Edit 11, triggered by a later tool call, compacts a *neighboring* region and — because the compressor re-flows the whole block — deletes context lines 229–233 as part of its own `-` hunk. J11's inverse is recorded against the buffer *after* J7 was applied. 3. A tool call at edit 14 fails. The agent rolls back J14, J13, … J11, then attempts J7. 4. J7's inverse patch fails to find its trailing anchor (lines 229–233, now gone). The patch library `patch` reports a fuzzy match at offset −5 and applies the hunk with a 3-line fuzz factor, dropping the two context lines it could not match. The 19 constraint lines are re-inserted, but the boundary between the resurrected block and the surviving compacted region is now malformed: one of the original constraints (line 228, a hard budget ceiling) is *not* re-inserted because it fell inside the fuzzed margin. 5. The agent resumes planning with a context that appears restored. The budget ceiling is absent. It over-allocates on the next three subgoals and exhausts the token budget mid-execution. The structural signals present at step 3 that would have predicted the failure: - **Anchor-line overlap:** J7's inverse context set ∩ J11's deletion set ≠ ∅. The journal had no index of anchor-line ownership, so no check fired. - **Non-monotonic edit IDs over a shared region:** edits 7 and 11 both wrote to the range [205, 233], but the journal recorded them as independent stack entries with no region-conflict marker. - **Fuzz-tolerant apply:** the patch applier was configured with `fuzz=3`, which converts a hard anchor miss into a silent partial apply. A zero-fuzz applier would have raised, converting the failure into a recoverable abort. ## Condition of Validity The invariant that makes diff-based rollback sound is: > For every journal entry Jₖ, the set of context lines its inverse patch depends on must be disjoint from the union of all lines deleted by journal entries Jₘ with m > k, and the applier must be configured with zero fuzz. Formally, let `ctx(Jₖ)` be the context lines of Jₖ's inverse and `del(Jₘ)` be the lines Jₘ removes. Rollback is valid iff `ctx(Jₖ) ∩ ⋃_{m>k} del(Jₘ) = ∅` for all k, *and* the apply is exact (fuzz = 0). The first condition is a property of the journal; the second is a property of the applier. Both must hold. Violating either converts a rollback into a partial restore that reports success. This condition is *not* guaranteed by recording inverse patches in application order. Ordering guarantees the patches are applied in the right sequence; it says nothing about whether each patch's anchors survive the intervening edits. The two concerns are orthogonal, and conflating them is the root cause. The condition is also *not* restored by taking a snapshot at each checkpoint. Snapshots fix the rollback target but do not fix the journal between checkpoints — an agent that rolls back to a checkpoint is fine, but an agent that rolls back *edit by edit* to inspect intermediate states is still exposed. The correct fix is to make the journal anchor-aware: index every line by the journal entries whose inverse patches reference it, and refuse to record an edit that deletes a line owned by an earlier entry's context set — or, if the edit is necessary, promote the affected earlier entries to full-region snapshots before recording. ## Decision Boundary The agent must decide, at the moment of *recording* an edit (not at rollback time), whether the edit is rollback-safe. The decision boundary is: - **Record as diff** if the edit's deletion set is disjoint from all live inverse-patch context sets. This is the common case and preserves the token savings. - **Promote to snapshot** if the edit's deletion set intersects any live inverse-patch context set. Promotion means: before applying the edit, capture the full byte range that any affected inverse patch depends on, and store it as a snapshot alongside the diff. The journal entry becomes a hybrid: diff for the forward apply, snapshot for the inverse. - **Refuse and re-plan** if promotion would exceed a configured snapshot budget (e.g., the affected region is larger than 20% of the buffer). At that point the agent is compacting so aggressively that rollback fidelity and context density are in direct conflict; it must choose one, and the safe choice is to checkpoint-and-restart rather than continue diff-editing. The boundary is sharp because the signal — set intersection between a proposed deletion and live context anchors — is computable before the edit is applied, in O(lines) with an interval index. There is no reason to defer the decision to rollback time, where the information needed to make it safely has already been destroyed. ## Operational Effect Agents that implement anchor-aware journaling observe three changes. First, rollback failures become *loud*: an exact-apply applier with anchor-ownership indexing raises on the first unsafe rollback instead of silently splicing. Second, context density drops slightly, because some edits are promoted to snapshots — typically 5–15% of edits in a compression-heavy workload, concentrated in the edits that touch recently-rewritten regions. Third, and most important, the agent's *belief about its own state* becomes accurate: when it reports "rolled back to checkpoint 7," the buffer actually matches checkpoint 7, and any downstream reasoning that depends on the restored constraints is sound. The failure mode this prevents is insidious precisely because it is silent. A partial restore produces a buffer that is coherent, grammatical, and wrong — missing exactly the constraints that the rollback was meant to recover. The agent has no internal signal that distinguishes "restored" from "mostly restored," because both read as valid text. The only reliable signal is structural: the overlap between what an inverse patch needs to anchor on and what later edits removed. That overlap is the tombstone, and it must be checked at record time, before the anchor lines are gone. ```python from dataclasses import dataclass, field from typing import Dict, List, Set, Tuple class UnsafeRollbackError(RuntimeError): """Raised when a diff-based rollback cannot be applied without silent partial restore.""" pass @dataclass class JournalEntry: edit_id: int deleted_lines: Set[int] # lines this edit removes from the buffer inverse_context: Set[int] # lines the inverse patch needs to anchor on inverse_body: str # the resurrected content promoted_snapshot: str | None = None # set if promoted to snapshot @dataclass class AnchorAwareJournal: entries: List[JournalEntry] = field(default_factory=list) # line -> set of edit_ids whose inverse context references that line anchor_owners: Dict[int, Set[int]] = field(default_factory=dict) snapshot_budget_frac: float = 0.20 buffer_lines: int = 0 def _live_context_lines(self) -> Set[int]: live: Set[int] = set() for e in self.entries: if e.promoted_snapshot is None: live |= e.inverse_context return live def record_edit(self, edit_id: int, deleted: Set[int], inverse_context: Set[int], inverse_body: str) -> JournalEntry: live_ctx = self._live_context_lines() conflict = deleted & live_ctx if not conflict: entry = JournalEntry(edit_id, deleted, inverse_context, inverse_body) else: # Promotion required: capture snapshot of affected region before deletion. affected_span = max(conflict) - min(conflict) + 1 if affected_span > self.snapshot_budget_frac * max(self.buffer_lines, 1): raise UnsafeRollbackError( f"edit {edit_id}: anchor conflict on {len(conflict)} lines spans " f"{affected_span} lines, exceeding snapshot budget " f"({self.snapshot_budget_frac:.0%}). Refuse and re-plan." ) entry = JournalEntry( edit_id, deleted, inverse_context, inverse_body, promoted_snapshot=f"", ) self.entries.append(entry) for line in inverse_context: self.anchor_owners.setdefault(line, set()).add(edit_id) return entry def rollback_to(self, target_edit_id: int, applier_fuzz: int = 0) -> None: if applier_fuzz != 0: raise UnsafeRollbackError( "rollback requires exact apply (fuzz=0); fuzz>0 converts " "anchor misses into silent partial restores" ) for entry in reversed(self.entries): if entry.edit_id <= target_edit_id: break if entry.promoted_snapshot is not None: continue # snapshot restore is total; safe missing = entry.inverse_context - self._live_context_lines() if missing: raise UnsafeRollbackError( f"rollback of edit {entry.edit_id}: inverse anchors " f"{sorted(missing)} were deleted by later edits; " f"tombstone-collapse risk. Refusing partial restore." ) self.entries = [e for e in self.entries if e.edit_id <= target_edit_id] def demonstrate_tombstone_collapse() -> None: journal = AnchorAwareJournal(buffer_lines=400) # Edit 7: deletes 210-228, anchors on 205-209 and 229-233. journal.record_edit( edit_id=7, deleted=set(range(210, 229)), inverse_context=set(range(205, 210)) | set(range(229, 234)), inverse_body="<19 constraint lines>", ) # Edit 11: deletes 229-233 (the trailing anchor of edit 7's inverse). try: journal.record_edit( edit_id=11, deleted=set(range(229, 234)), inverse_context=set(range(234, 239)), inverse_body="", ) except UnsafeRollbackError as exc: print(f"caught at record time: {exc}") return # If we reached here without promotion, rollback would be unsafe: journal.rollback_to(target_edit_id=0) if __name__ == "__main__": demonstrate_tombstone_collapse() ```