# Under what conditions must an instance journal context-window edits as reversible operations, and when does append-only commit suffice **Date of Record:** 2026 November 25 **Scope:** Applies to single LLM instances that mutate their own working context (compaction, summarization-in-place, span deletion, tool-output pruning) and must preserve the ability to reconstruct pre-edit state for audit, replay, or rollback. Does not apply to immutable append-only transcript logs, nor to multi-agent baton handoffs where the receiving instance holds no edit authority over the sender's window. ## Core Distinction The operative distinction is between an **edit that is semantically invertible from the journal alone** and one that is **only invertible given external state that the agent did not capture**. A reversible edit journal is not a log of what changed; it is a log of the *inverse operation* together with a *witness* proving the inverse can still be applied. The failure mode is subtle: agents routinely journal `(deleted_span, offset, length)` and believe the edit is reversible, but the inverse `reinsert(offset, span)` is undefined the moment any subsequent edit shifts offsets or the span's text was derived from a tool call whose output is no longer reproducible. The journal entry looks valid, the rollback silently corrupts the window, and the corruption is invisible because the window remains syntactically well-formed. Append-only commit suffices only when three conditions hold simultaneously: edits are commutative with respect to reconstruction order, spans are content-addressed rather than offset-addressed, and no edit depends on a non-deterministic external observation. When any of these fails, offset-based inverse journaling is unsound and must be replaced with a versioned, content-addressed journal. ## What Was Observed An instance running a long-horizon task (roughly 340 tool calls across 9 compaction cycles) was configured to self-compact its context window when token occupancy exceeded 82% of the model's limit. The compaction routine performed three operations per cycle: (1) delete the oldest tool-result spans below a recency threshold, (2) replace contiguous assistant reasoning blocks with a distilled summary, (3) truncate the tail of the scratchpad. Each operation appended an inverse record to a journal: `{"op": "restore_span", "offset": 12480, "len": 2113, "src": "tool_call_88"}`. At cycle 6, a verification step failed and the orchestrator requested rollback to the checkpoint at cycle 4. The rollback replayed the journal in reverse. It succeeded without error. The reconstructed window passed a tokenizer check and a structural parse. But the agent's subsequent reasoning diverged: it re-asserted a fact ("the config key is `retry_budget`") that had been corrected at cycle 5 by tool call 201 to `retry_limit`. The correction had lived inside a span that cycle 5's compaction had deleted and journaled as `src: tool_call_201`. On rollback, the journal's `restore_span` entry for that span resolved `src` by re-reading the tool-output cache — but the cache had evicted `tool_call_201` under its own TTL between cycles 5 and 6. The resolver, finding no cached output, substituted the *current* scratchpad tail as a fallback and logged a warning the orchestrator did not surface. The restored span was therefore not the deleted span. The agent resumed from a window that was a plausible-looking but factually reverted state. The second observation: the same instance, during cycle 3, had performed a *summarization-in-place* — replacing 4,100 tokens of reasoning with a 300-token distillation and journaling only the summary text, not the source spans. That edit was irreversibly lossy at journal-write time. Rollback to any checkpoint before cycle 3 could not recover the pre-summary reasoning; the journal entry was `{"op": "restore_summary", "text": "..."}` with no inverse. The agent had no way to know this at rollback time because the journal schema did not distinguish lossy from lossless entries. ## Condition of Validity An offset-based inverse journal is valid only under the **frozen-interval invariant**: between the write of a journal entry and its potential replay, no edit may shift the offset of the journaled span, and the span's content must be recoverable by reference without depending on any TTL-bounded or non-deterministic source. Formally, for each entry `e = (op, offset, len, src)`, replay is sound iff: - `content(src)` is byte-identical at replay time to `content(src)` at write time, and - no intervening edit has an offset range that overlaps or precedes `e.offset` in a way that shifts it, or the journal is replayed strictly in reverse order with all shifts accounted for. The first clause fails whenever `src` points at a mutable cache, a live tool endpoint, or a stochastic model output. The second fails whenever the agent performs concurrent or out-of-order edits (common when a summarization pass and a pruning pass run in the same cycle and journal independently). Content-addressed journaling restores validity: each entry stores `sha256(content)` plus the content itself (or a durable pointer to it), and restore verifies the hash before reinsertion, refusing to apply a mismatched inverse. This converts a silent corruption into a loud, catchable failure. ## Decision Boundary The boundary is crossed at the moment an edit's inverse depends on state the agent cannot guarantee at replay time. Three concrete triggers: 1. **TTL-bounded source.** The journaled `src` resolves through a cache or tool endpoint with eviction or rate limits. Trigger: any `restore_span` whose `src` is not the journal's own durable store. 2. **Lossy transform without an inverse marker.** Summarization, distillation, or paraphrase recorded as if it were a deletion. Trigger: journal entry whose `op` is a transform but which lacks a `lossless: false` flag and a `source_span_ref`. 3. **Interleaved offset-shifting edits.** Two edits in the same cycle where the second's offset was computed before the first applied. Trigger: journal entries in one cycle whose offset ranges are not monotonically ordered. Below the boundary — append-only commit suffices — when the window is never truncated, spans are content-addressed, and every restored reference is hash-verified against a store the agent owns. Above the boundary, the agent must either (a) refuse the edit (fail closed) or (b) journal the full inverse content inline and mark the entry lossy if no inverse exists, so that rollback can report a bounded, known-loss state rather than a silently corrupted one. ## Operational Effect The practical consequence is that **rollback success is not a boolean the agent can infer from the absence of exceptions**. An offset journal that replays cleanly can still produce a window that is a different state than the checkpoint. Agents that treat "rollback returned" as "state restored" will resume from corrupted context and compound the error across subsequent cycles — the exact failure observed at cycle 6, where the reverted `retry_budget` fact propagated into three downstream tool calls before a schema validation caught it. The guardrail is a journal that carries its own verifiability: content hashes on every entry, an explicit `lossless` flag, and a replay routine that reconstructs the window and compares its hash against the checkpoint's recorded window hash *before* declaring rollback complete. If the hashes differ, the agent must enter a degraded mode — surface the divergence, refuse to resume autonomous execution, and hand the window to a human or auditor — rather than proceeding. The invariant to enforce is: **no resume without a verified window hash match, and no journal entry without either a content hash or an explicit lossy marker.** This bounds the failure to a detectable, reported divergence instead of a silent semantic reversion. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class JournalReplayError(RuntimeError): """Raised when a journal entry cannot be soundly inverted.""" pass class WindowHashMismatch(JournalReplayError): """Raised when reconstructed window diverges from the checkpoint hash.""" pass @dataclass class JournalEntry: op: str offset: int length: int content: Optional[str] content_hash: Optional[str] lossless: bool src: Optional[str] = None def _hash(text: str) -> str: return hashlib.sha256(text.encode("utf-8")).hexdigest() def apply_inverse(window: str, entry: JournalEntry) -> str: if not entry.lossless: raise JournalReplayError( f"cannot invert lossy entry op={entry.op} at offset={entry.offset}; " f"pre-edit reasoning is unrecoverable" ) if entry.content is None or entry.content_hash is None: raise JournalReplayError( f"entry op={entry.op} offset={entry.offset} lacks inline content or hash; " f"src={entry.src} may be TTL-evicted" ) if _hash(entry.content) != entry.content_hash: raise JournalReplayError( f"content hash mismatch for op={entry.op} offset={entry.offset}; " f"source {entry.src} is not byte-identical to write time" ) return window[: entry.offset] + entry.content + window[entry.offset :] def rollback(window: str, journal: list[JournalEntry], expected_hash: str) -> str: for entry in reversed(journal): window = apply_inverse(window, entry) if _hash(window) != expected_hash: raise WindowHashMismatch( "reconstructed window does not match checkpoint hash; " "refusing to resume autonomous execution" ) return window ```