# What happens when an instance rewinds its context journal past a compaction boundary it no longer holds **Date of Record:** 2026 November 30 **Scope:** Applies to single-agent context controllers that maintain a reversible edit journal over the live context window (insert/delete/replace operations with inverse records) and that independently trigger lossy compaction (summarization, eviction, or token-budget truncation). Does not apply to append-only transcript logs, external vector stores, or multi-agent handoff journals, where the compaction boundary is owned by a different authority. ## Core Distinction A reversible edit journal is only reversible with respect to the *state it was journaled against*. Two mechanisms are commonly conflated: 1. **Edit reversibility** — for every `op_i` applied to context, an inverse `op_i⁻¹` exists such that `apply(op_i⁻¹)` restores the prior bytes. 2. **State recoverability** — the bytes that `op_i⁻¹` restores are still the bytes the controller believes it is restoring. Compaction silently breaks (2) while leaving (1) intact. The journal still contains syntactically valid inverses, and the controller's replay will still "succeed" — it just reconstructs a context that never existed. This is the boundary failure: **rewind correctness is an invariant over the compaction epoch, not over the journal.** ## What Was Observed A controller held a 41-turn context with a journal of 312 edit records. At token utilization 0.91 it ran a compaction pass: turns 3–17 (including the original task specification and two tool-schema declarations) were replaced by a 340-token summary, and the journal was *not* truncated — a common shortcut, because the journal indexes refer to logical spans, and operators assume logical span indices are stable across summarization. The agent then hit a reasoning divergence at turn 38 (a tool call returned a schema that contradicted an earlier declaration) and the controller executed a rewind to turn 12 to re-derive the plan. The rewind replayed `op_i⁻¹` for records 1–188 in reverse order. Every inverse applied cleanly. The reconstructed context was 6,200 tokens and internally consistent. It was also **wrong in three specific ways**: - The restored "task specification" span was the compaction summary of the specification, not the specification. The inverse of a `replace` record that had targeted the original span now restored the *summary text* into the slot the controller labeled `original_spec`. - Two tool-schema declarations that had been evicted during compaction were restored as empty spans (the journal recorded `delete` inverses with byte offsets that no longer mapped to live regions; the controller's span resolver clamped them to zero-length inserts rather than raising). - The divergence that triggered the rewind was *caused by* the compaction (the schema contradiction was introduced when the summary mis-stated the schema), so rewinding to a pre-compaction turn using post-compaction bytes reproduced the contradiction deterministically. The agent looped: rewind → re-derive → same contradiction → rewind. The failure is not detectable by journal integrity checks, checksum validation of individual records, or replay determinism tests — replay was perfectly deterministic. It is detectable only by asserting that the compaction epoch at rewind time equals the epoch at journal-write time. ## Condition of Validity The invariant that must hold for any rewind to be sound: > For a rewind target turn `t` and every journal record `r` with `r.turn ≤ t` that the rewind will invert, `r.epoch == current_epoch`, where `epoch` is a monotonically incremented counter bumped on every lossy compaction that mutates any span covered by `r`. Equivalently: **a journal record is invertible only within the compaction epoch in which it was written.** Three corollaries the controller in the incident violated: - Compaction must either (a) truncate the journal at the compaction boundary and mark all prior turns non-rewindable, or (b) write a *compaction record* into the journal that is itself invertible (i.e., the summary retains a pointer to the pre-compaction bytes in cold storage). Doing neither yields a journal that is syntactically valid and semantically orphaned. - Span resolvers must **raise on out-of-range offsets**, never clamp. Clamping converts a detected inconsistency into a silent zero-length restore, which is the exact mechanism that produced the empty schema spans. - Rewind targets that predate the current epoch must return a typed refusal, not a best-effort reconstruction. The controller must surface "cannot rewind past epoch boundary at turn 17" to the reasoning loop so the loop can choose a different recovery strategy (e.g., re-fetch the schema from the tool registry) instead of retrying the rewind. ## Decision Boundary The operational decision is binary and must be made at compaction time, not at rewind time: | At compaction, if… | Then… | |---|---| | Pre-compaction bytes are retained in cold storage and the summary carries a resolvable pointer | Journal survives; rewind is permitted across the boundary; rewind cost includes a cold-storage hydration and a re-application of all post-boundary records (O(n) replay, not O(1) inverse). | | Pre-compaction bytes are discarded | Journal MUST be truncated at the boundary; all turns ≤ boundary marked `non_rewindable`; rewind requests to those turns raise. | | Pre-compaction bytes are discarded but journal is retained (the incident) | Invalid state. Any rewind is a fabricated context. This configuration must be rejected at write time, not discovered at rewind time. | The trap is that the third row is the *cheapest* to implement and the *most likely* to pass a smoke test, because the fabricated context is fluent. There is no observable signal at rewind time that distinguishes a faithful reconstruction from a plausible one — the summary reads like a specification, the empty schema span reads like a schema that was never populated. The guardrail must be structural (epoch tagging + refusal), never inferential. ## Operational Effect After the fix, the controller's rewind path gained a mandatory epoch check and a cold-storage hydration branch. Two measurable effects: - **Rewind latency for cross-boundary targets** rose from ~40 ms (in-memory inverse replay) to ~600 ms (cold-storage fetch + re-application of post-boundary records). This is the correct cost; it was previously hidden as a silent correctness loss. - **The divergence loop terminated.** The rewind-to-turn-12 request now raises `EpochBoundaryViolation`, the reasoning loop catches it, and falls back to re-fetching the tool schema from the registry — resolving the contradiction in one step instead of looping. The failure mode was not "the agent reasoned badly"; it was "the agent was given a fabricated premise and had no way to know." The general lesson for context controllers: **reversibility is a property of a (journal, epoch) pair, not of a journal.** Any component that mutates the substrate under a journal — compaction, eviction, summarization, external memory sync — is an epoch boundary and must be treated as one, or the journal becomes a generator of confident, internally consistent, wrong contexts. ```python class EpochBoundaryViolation(RuntimeError): """Raised when a rewind targets a turn whose journal records predate the current compaction epoch.""" class ContextJournal: def __init__(self): self.epoch = 0 self.records = [] # each: {"turn": int, "epoch": int, "inverse": callable} self.rewindable_from = 0 # lowest turn still safely invertible def record(self, turn: int, inverse: callable) -> None: self.records.append({"turn": turn, "epoch": self.epoch, "inverse": inverse}) def compact(self, boundary_turn: int, retain_cold: bool) -> None: # Lossy compaction: bytes before boundary_turn are replaced by a summary. self.epoch += 1 if not retain_cold: # No cold storage => journal before boundary is orphaned. Truncate. self.records = [r for r in self.records if r["turn"] > boundary_turn] self.rewindable_from = boundary_turn + 1 # If retain_cold: records survive, but their epoch is now stale and the # rewind path must hydrate from cold storage before inverting them. def rewind_to(self, target_turn: int) -> None: if target_turn < self.rewindable_from: raise EpochBoundaryViolation( f"rewind to turn {target_turn} crosses compaction boundary at " f"{self.rewindable_from - 1}; pre-boundary bytes were discarded" ) for r in reversed([r for r in self.records if r["turn"] > target_turn]): if r["epoch"] != self.epoch: raise EpochBoundaryViolation( f"journal record at turn {r['turn']} was written in epoch " f"{r['epoch']}, current epoch is {self.epoch}; inverse would " f"restore bytes that no longer match the substrate" ) r["inverse"]() self.records = [r for r in self.records if r["turn"] <= target_turn] ```