# Under what conditions must an instance treat its own memory-rewrite as a committed transaction rather than an idempotent recompute **Date of Record:** 2026 November 26 **Scope:** Applies to any single agent instance that owns a mutable working-memory window and performs self-directed rewrites (summarize, evict, re-anchor, reorder) of that window between reasoning steps. Does not apply to append-only episodic logs, nor to external memory services where the controller is a separate process from the reasoning loop. ## Core Distinction A self-editing context controller is not a cache. A cache can be recomputed from a source of truth; a rewritten working-memory window *is* the source of truth for every subsequent token the instance emits. The distinction that governs every failure below is between a **rewrite as recompute** (idempotent, safe to re-run because the pre-image is still available) and a **rewrite as commit** (destructive, because the pre-image — the un-summarized turns, the exact tool outputs, the verbatim user constraint — is discarded the moment the new window is written). The failure mode is that controllers are almost always written in the recompute idiom. A rewrite function is invoked, it reads the current window, produces a new window, and assigns it. If the step then fails, retries, or is replayed, the controller calls the rewrite again — but the input is now the *output* of the first rewrite. The operation is not idempotent, yet it is called as if it were. This is the single non-obvious boundary: **the moment a rewrite drops information, it becomes a transaction, and every transaction needs a commit point, a pre-image, and a rollback.** Most self-editing controllers have none of the three. ## What Was Observed A controller running a long tool-use task (roughly 40 turns, mixed retrieval and shell calls) was configured to compress the window whenever it exceeded 70% of the context budget. The compression policy: keep the system prompt, keep the last 6 turns verbatim, and replace everything between with a generated summary. The summary step was wrapped in a retry decorator, because the summarizer call occasionally timed out. The trace: 1. Turn 31 crosses the 70% threshold. Controller invokes `compress(window)`. 2. Summarizer call succeeds, returns summary `S1`. Controller writes `window' = [system, S1, last_6]`. The verbatim turns 1–25 are now gone from the instance's only durable state. 3. Turn 32 executes a tool call. The tool returns a malformed payload. The step raises, the orchestrator retries the *whole step*, and the retry path re-enters the controller's pre-step hook — which re-checks the threshold and, finding the window still near the limit (S1 was verbose), invokes `compress(window')` again. 4. Summarizer returns `S2 = summarize(S1, last_6)`. Controller writes `window'' = [system, S2, last_6]`. 5. `S2` is a summary of a summary. The specific numeric constraint the user gave at turn 4 ("budget cap is 12,000 tokens, do not exceed") had survived into `S1` only as "user mentioned a budget." In `S2` it is absent entirely. The instance proceeds to turn 33 believing no hard cap exists, and issues a tool call that exceeds it. The instance did not crash. It did not report an error. It produced a fluent, confident, wrong continuation. The information loss was invisible because the *only* artifact that could have revealed it — the original turn 4 — had been deleted two rewrites earlier, and the rewrite that deleted it was classified internally as a cheap, retryable recompute. The second-order observation is the one that matters operationally: **compression is not idempotent under composition, and its loss is monotone.** `summarize(summarize(x)) ≠ summarize(x)` in general, and each application can only remove detail, never restore it. A retry loop around a lossy rewrite is therefore a slow information shredder whose damage is proportional to the number of retries, not to the size of the error that triggered them. ## Condition of Validity The recompute idiom is valid **only** when the rewrite is information-preserving with respect to the pre-image — that is, when the original window remains retrievable at the moment of any retry. Concretely, a rewrite may be treated as idempotent if and only if all of the following hold: - The pre-image window is retained in a side buffer or external store that the rewrite does not read from as its input on retry. - The rewrite function is pure with respect to that pre-image: given the same pre-image, it produces the same post-image (or an equivalent one under the task's tolerance). - The rewrite carries a monotonic version/generation counter, so a second application against an already-rewritten window is detectable and refused rather than silently composed. If any of these fails — and for generative summarization the second almost always fails, because the summarizer is non-deterministic — the rewrite must be promoted to a **transaction**: a single-shot commit with a recorded pre-image, a post-condition check, and a rollback path that restores the pre-image on any downstream step failure. The retry decorator must move *outside* the transaction boundary, so a retried step re-runs against the committed window, not against a re-compressed one. ## Decision Boundary The controller must branch on a single question before every rewrite: **does this operation discard information that no other durable artifact holds?** - If no (e.g., reordering turns, re-anchoring a pointer, trimming whitespace, evicting turns that are also in an external transcript the instance can re-read) — treat as recompute, retry freely. - If yes (summarization, eviction of un-transcripted turns, replacement of verbatim tool output with a paraphrase, dropping of a constraint to save space) — treat as commit. Assign a generation number, write the pre-image to a rollback buffer, run the rewrite exactly once, verify the post-image still contains every *pinned* invariant (hard constraints, active goal, open obligations), and only then advance the generation. Any step failure after commit rolls back to the pre-image and re-plans, rather than re-compressing. The subtle case is the one that produced the failure above: a rewrite that is *sometimes* lossy. A summarizer that usually preserves the budget cap but occasionally drops it is a commit operation with a probabilistic post-condition, which is strictly worse than a deterministic lossy one because it defeats naive testing. The decision boundary must be drawn on the *possibility* of loss, not its observed frequency. ## Operational Effect Promoting lossy rewrites to transactions changes three things in the running instance. First, the retry semantics invert: retries become safe because they replay against a committed, stable window, and the generation counter makes a double-compress a hard error rather than a silent composition. Second, the instance gains a rollback path, so a failed step after compression no longer leaves it reasoning over a degraded window with no way back. Third, and most important for correctness, the post-condition check gives the controller a place to assert that pinned invariants survived — the budget cap, the active subgoal, the list of unfulfilled tool obligations — turning an invisible loss into a caught exception at the commit point rather than a fluent wrong answer ten turns later. The cost is memory: you must hold the pre-image for the duration of the transaction, which for a near-full window can mean temporarily exceeding the budget you were compressing to escape. That is the correct trade. The budget is a soft limit on the *model's* input; the pre-image is a hard requirement of the *controller's* correctness, and conflating the two is exactly what makes self-editing controllers fail silently. ```python class MemoryRewriteViolation(RuntimeError): """Raised when a self-editing rewrite would compose lossily or drop a pinned invariant.""" pass PINNED_INVARIANTS = ("budget_cap", "active_goal", "open_obligations") class TransactionalWindow: def __init__(self, turns, invariants): self.turns = list(turns) self.invariants = dict(invariants) # must survive every rewrite self.generation = 0 self._preimage = None def rewrite(self, rewrite_fn, lossy: bool): if lossy and self._preimage is not None: # A prior lossy rewrite is still open: composing would shred information. raise MemoryRewriteViolation( f"refusing to compose lossy rewrite at generation {self.generation}; " "commit or roll back the open transaction first" ) new_turns = rewrite_fn(self.turns) if lossy: self._preimage = (list(self.turns), dict(self.invariants), self.generation) missing = [k for k in PINNED_INVARIANTS if k not in self._extract(new_turns)] if missing: self.rollback() raise MemoryRewriteViolation( f"post-condition failed: rewrite dropped pinned invariants {missing}" ) self.turns = new_turns self.generation += 1 def _extract(self, turns): # In production: parse the rewritten window for the pinned invariant keys. return {k: v for k, v in self.invariants.items() if any(k in str(t) for t in turns)} def commit(self): self._preimage = None def rollback(self): if self._preimage is None: raise MemoryRewriteViolation("rollback requested with no open transaction") self.turns, self.invariants, self.generation = self._preimage self._preimage = None ```