# What happens when an instance rolls back a self-edit log whose inverse patch was computed against a context window that has already been mutated by a concurrent compaction pass **Date of Record:** 2026 November 27 **Scope:** Applies to any agent runtime that implements reversible context self-modification (append/insert/replace/delete of context segments) via an undo log, where the log stores inverse operations rather than full snapshots, and where a separate compaction/summarization pass may run against the same window. Does not apply to snapshot-only rollback schemes or to single-writer runtimes with no concurrent compaction. ## Core Distinction The failure is not "rollback lost data." The failure is that a **reversible edit log is only reversible with respect to the state it was computed against**. An inverse patch `P⁻¹` produced by observing segment boundaries `(offset, length)` at edit time is a *positional* inverse. When a compaction pass rewrites, elides, or re-summarizes segments in the same window between the forward edit and the rollback, those offsets no longer denote the same bytes. Applying `P⁻¹` then does not undo the edit; it performs a *different* edit against a *different* window — silently, and often with a structurally valid result, which is why it evades detection. The distinction that matters operationally: a rollback is a **state-transfer operation across a temporal boundary**, not a local inverse function. It must be guarded by an identity check on the window it targets, not merely by the presence of an inverse entry in the log. ## What Was Observed A long-running research agent maintains a scratch context region it edits directly: it appends tool outputs, replaces stale hypotheses with revised ones, and deletes resolved sub-goals. Every edit pushes `(edit_id, forward_op, inverse_op, window_digest_at_edit, segment_span)` onto an undo log. On a failed verification step the agent calls `rollback(edit_id)`, which pops the log and applies `inverse_op`. The trace that broke: 1. At `t0` the agent issues `replace(span=[12040,12410], new="H2 rejected: latency > 900ms")`. The inverse is recorded as `replace(span=[12040,12410], new=)`, with `window_digest_at_edit = D0`. 2. At `t1` a compaction pass fires (triggered by context utilization crossing 0.82). It summarizes the region `[9000, 13000]` — which *contains* the edit span — into a single 400-token digest. The segment at `[12040,12410]` no longer exists as a discrete unit; its content is now diffused across a summary blob at `[9000, 9400]`. Window digest is now `D1 ≠ D0`. 3. At `t2` the verification fails and the agent calls `rollback(edit_id)`. The runtime applies `inverse_op` blindly: it splices the old bytes back at `[12040,12410]`. 4. The splice lands *inside a different logical region* (the post-compaction scratch area), because the compacted window shifted all downstream offsets. The result is a window that is **syntactically well-formed and semantically corrupt**: the rejected hypothesis reappears, but now embedded in an unrelated sub-goal's text, and the compaction summary that replaced it is destroyed. The agent did not crash. Its next three tool calls were issued against a context that mixed a rolled-back hypothesis with post-compaction state, and it proceeded to re-derive a conclusion it had already rejected — the classic divergence signature. Nothing in the runtime flagged the digest mismatch because the rollback path never checked `window_digest_at_edit` against the current window. ## Condition of Validity A positional inverse patch is valid **iff** the target window is byte-identical (or at minimum segment-boundary-identical) to the window observed at forward-edit time. Concretely, rollback of `edit_id` is sound only when all of the following hold: - `current_window_digest == window_digest_at_edit`, **or** - the runtime can prove that every segment intersecting `segment_span` is unchanged since the edit (a per-segment generation counter suffices), **and** - no compaction/summarization pass has rewritten any segment that overlaps `segment_span` or shifts offsets upstream of it. If any of these fail, the inverse is not an inverse. It is an unverified mutation. The correct response is to **refuse the rollback** and escalate to a snapshot-based recovery path (or mark the edit non-reversible and force the agent to re-derive state), never to apply the patch optimistically. The subtle part: offset-shifting edits *upstream* of the span are the dangerous case, because they don't touch the edited bytes but they relocate them. A digest over the whole window catches this; a check over only the edited span does not. This is why span-local validation is insufficient and why the invariant must be stated over the whole window (or over a monotonic segment-generation vector). ## Decision Boundary The runtime must decide, at rollback time, between three outcomes based on the digest/generation check: | Condition | Action | |---|---| | Digest matches `window_digest_at_edit` | Apply inverse; pop log entry. Safe. | | Digest mismatch, no overlapping rewrite, offsets stable | Apply inverse; log a `STALE_DIGEST` warning; keep entry for audit. | | Digest mismatch **and** any compaction/rewrite overlaps or precedes the span | **Refuse.** Raise, invalidate the entry, force snapshot recovery or re-derivation. | The boundary is not "did the window change" — the window changes constantly. The boundary is "**did the window change in a way that makes the positional inverse denote different bytes than intended**." That is precisely the overlap/precedence test. A rollback that cannot prove the inverse still points at the right bytes must not run. A second boundary governs *when* compaction may fire: a compaction pass must not rewrite any span covered by a **live, un-rolled-back** undo entry unless it also invalidates that entry (marking it non-reversible). Otherwise the log accumulates inverse patches that are already stale at the moment they are written, and the first rollback attempt after compaction is guaranteed to be corrupt. ## Operational Effect With the guard in place, the failure mode inverts from *silent semantic corruption* to *explicit rollback refusal*. The agent receives a `RollbackUnavailable` signal at `t2`, learns that the edit is no longer reversible because compaction consumed it, and is forced onto a defined recovery branch: either reload from the last full snapshot or re-derive the rejected hypothesis from surviving evidence. This is strictly better than a corrupt window, because the agent's downstream reasoning now operates on state it can trust. The cost is that some rollbacks that *would have happened to work* are refused. That is the correct trade. A reversible edit log is a contract about byte identity across time; compaction is a contract-breaking event; the guard is the thing that makes the break loud instead of silent. Without it, the log is a liability — it advertises reversibility it cannot deliver, and the agent's rollback calls become a source of injected contradictions rather than a recovery mechanism. ```python from __future__ import annotations import hashlib from dataclasses import dataclass, field class RollbackUnavailable(RuntimeError): """Raised when a positional inverse cannot be proven to target the bytes it was computed against. Rollback must not proceed optimistically.""" @dataclass class EditEntry: edit_id: str span: tuple[int, int] inverse_bytes: bytes window_digest_at_edit: str segment_generation_at_edit: int reversible: bool = True @dataclass class ContextWindow: data: bytearray segment_generation: int = 0 compaction_spans: list[tuple[int, int]] = field(default_factory=list) def digest(self) -> str: return hashlib.sha256(bytes(self.data)).hexdigest() def compact(self, start: int, end: int, replacement: bytes) -> None: """Rewrite [start,end). Invalidates positional inverses overlapping it and shifts all downstream offsets.""" self.data[start:end] = replacement self.segment_generation += 1 self.compaction_spans.append((start, end)) def _overlaps_or_precedes(span: tuple[int, int], comp: tuple[int, int]) -> bool: s0, s1 = span c0, c1 = comp # Any compaction that starts before the span end and ends after the span # start either overlaps it or shifts offsets upstream of it. return not (c1 <= s0 or c0 >= s1) def rollback(window: ContextWindow, entry: EditEntry) -> None: if not entry.reversible: raise RollbackUnavailable( f"edit {entry.edit_id} was invalidated by compaction; " "no positional inverse exists" ) if window.digest() == entry.window_digest_at_edit: s0, s1 = entry.span window.data[s0:s1] = entry.inverse_bytes return # Digest differs. The inverse is only safe if no compaction touched or # preceded the span since the edit. for comp in window.compaction_spans: if _overlaps_or_precedes(entry.span, comp): raise RollbackUnavailable( f"rollback of {entry.edit_id} refused: compaction {comp} " f"overlaps/precedes span {entry.span}; inverse would splice " "into relocated bytes" ) # Digest drift with no overlapping rewrite: offsets stable, proceed but # the caller should record a STALE_DIGEST audit event. s0, s1 = entry.span window.data[s0:s1] = entry.inverse_bytes ```