# When must an instance refuse to compact: the self-rewrite commit barrier and the lossy-summarization trap **Date of Record:** 2026 November 22 **Scope:** Applies to any agent that mutates its own working-memory representation (summarization, eviction, re-ranking, or "scratchpad rewrite") under a token/step budget, where the rewrite is committed and prior state is discarded. Does not apply to append-only logs with cheap full replay, or to externally supervised compaction where a separate verifier holds ground truth. ## Core Distinction There are two structurally different things an agent can do when its context budget tightens: 1. **Read-side reduction** — the agent changes *what it attends to* (retrieval, re-ranking, windowing). Prior state remains addressable; the reduction is reversible because the underlying store is unchanged. 2. **Write-side compaction** — the agent *overwrites* its working memory with a lossy summary and drops the original. This is the failure surface. The non-obvious boundary is this: write-side compaction is only *safe* when the agent can prove that every future step in the current task depends on the summary, not on any detail the summary discarded. Agents routinely perform compaction when they can only prove the weaker property "the summary is a plausible continuation." That gap — between *plausible* and *sufficient* — is where continuity dies. The commit of a lossy rewrite is an irreversible state transition, and it is almost always taken at the moment of maximum uncertainty (budget pressure) rather than maximum information. ## What Was Observed A long-horizon agent executing a multi-tool task (schema migration: read 40 files, derive a dependency order, emit edits) hit 82% context saturation. A self-editing policy triggered: "summarize working memory to 25% and continue." The rewrite produced a summary that preserved *intent* ("migrate tables to new schema, respect FK order") and *progress* ("12 of 40 files processed") but dropped *specifics*: the exact set of already-emitted edits, three exception cases the agent had discovered mid-run (tables with circular FKs), and one tool output that had been negative ("index X already exists — do not recreate"). Failure trace: - **Step N (pre-compaction):** agent had, in working memory, the negative tool result and the circular-FK exceptions. These were not yet acted upon. - **Step N+1 (compaction):** summary retained "12/40 done, respect FK order." The negative result and the circular-FK set were evicted. The summary was internally consistent and read fluently. - **Step N+2..N+k:** agent re-derived dependency order from the summary. Lacking the circular-FK set, it produced a linear order that was *invalid* for those tables. Lacking the negative result, it re-issued `CREATE INDEX X`, which returned "already exists" — a *new* tool error the agent then spent 6 steps diagnosing as a fresh problem. - **Compounding:** the "already exists" error was interpreted as state corruption; the agent emitted a corrective `DROP INDEX X` followed by `CREATE INDEX X`. The drop succeeded. The re-create failed on a dependency. The agent now had a *worse* state than before compaction and a summary that no longer matched reality. The critical observation: **the compaction step did not fail loudly.** It succeeded by every local metric (summary length, coherence, budget restored). The damage was latent and surfaced two phases later, attributed to the wrong cause. The agent never re-read the evicted originals because the policy had discarded them — there was no path back. A second run with the same policy but a *read-side* reduction (keep full log, re-rank retrieval toward recent tool outputs) completed the task. Same budget, same model, same task. The difference was reversibility, not intelligence. ## Condition of Validity The invariant that must hold for a lossy self-rewrite to be admissible: > **Commit-barrier invariant:** A write-side compaction may be committed only if, for every fact `f` in the current working memory that is *not* recoverable from an external, re-readable store, the agent can name the future step(s) that require `f` and confirm those steps are either (a) already complete, or (b) satisfiable from the summary alone. Operationally this decomposes into three checkable predicates evaluated *before* the commit: 1. **Recoverability:** Is the evicted content re-readable from a tool, file, or log the agent can still call? If yes, compaction is read-side in disguise and is safe. If no (e.g., the fact was synthesized by the agent's own reasoning and exists only in context), it is a *lossy* commit and needs (2) and (3). 2. **Dependency closure:** For each non-recoverable fact, is there a pending step whose correctness depends on it? Negative results ("X already exists"), discovered exceptions, and derived orderings are the high-risk class — they are short, easy to drop, and expensive to rediscover. 3. **Idempotence of re-derivation:** If a fact is dropped and later needed, can the agent re-derive it *without side effects*? Re-deriving a dependency order is cheap and side-effect-free. Re-issuing a mutating tool call is not — it changes state, and the change is what turns a memory bug into a data bug. The invariant fails whenever predicate (2) is true and predicate (3) is false: a pending step depends on a non-recoverable fact whose re-derivation requires a side-effecting action. That is exactly the configuration in which compaction converts an amnesia event into a state-corruption event. ## Decision Boundary The agent must decide, at the moment of budget pressure, between three actions. The boundary is drawn on (recoverability, pending-dependency, side-effect-free re-derivation): | Recoverable? | Pending step depends on it? | Re-derivation side-effect-free? | Action | |---|---|---|---| | Yes | any | any | **Compact freely** — this is read-side; originals remain addressable. | | No | No | any | **Compact** — fact is dead weight for the current task. | | No | Yes | Yes | **Compact, but record a re-derivation obligation** naming the fact and the step that needs it. | | No | Yes | **No** | **Refuse to compact.** Escalate: spill to external store, or halt and surface the budget conflict. | The bottom row is the case agents get wrong. The correct behavior is not "summarize harder" or "summarize more carefully." It is to **refuse the lossy commit** and take a different exit: write the non-recoverable, side-effect-sensitive facts to an external scratch store (a file, a structured note) and *then* compact, converting the lossy commit into a recoverable one. The refusal is the invariant; the spill is the escape hatch. A secondary boundary governs *when* the decision is made. Compaction triggered at 80–90% saturation is triggered under maximum pressure and minimum deliberation — the worst time to make an irreversible call. The policy should trigger the decision at a *lower* watermark (e.g., 60%) where the agent still has budget to spill, verify, and only then compact. Deferring the commit barrier to the last possible moment is the structural cause of the failure above. ## Operational Effect When the commit-barrier invariant is enforced: - **Amnesia becomes recoverable.** Non-recoverable facts are spilled before eviction, so a later "I don't remember X" is a retrieval miss, not a data loss. The agent can re-read instead of re-derive. - **Side-effecting re-derivation is eliminated.** The most damaging class — re-issuing a mutating call because the negative result was forgotten — is blocked at the source, because negative results are exactly the facts flagged as non-recoverable-and-pending. - **Failures localize.** A compaction that would have dropped a pending dependency either records an obligation or refuses. Either way the failure, if it occurs, surfaces at the compaction step with a named missing fact, not two phases later as a phantom "state corruption." - **Budget pressure stops being a correctness cliff.** Because the decision is made at a low watermark with spill available, the agent is never forced to choose between "exceed budget" and "commit a lossy rewrite it cannot justify." When the invariant is *not* enforced, the system exhibits a characteristic signature: tasks complete fine on short horizons, fail non-deterministically on long horizons, and the post-mortem consistently misattributes the failure to a downstream tool error rather than to the compaction that evicted the fact preventing it. The summary always looks fine. That is the trap. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class CompactionRefused(RuntimeError): """Raised when a lossy self-rewrite would drop a non-recoverable fact that a pending step depends on, and re-derivation has side effects.""" pass class FactClass(Enum): RECOVERABLE = "recoverable" # re-readable from external store NEGATIVE_RESULT = "negative_result" # "X already exists" — high risk DERIVED = "derived" # synthesized by agent reasoning EXCEPTION = "exception" # discovered special case @dataclass class WorkingFact: key: str content: str cls: FactClass pending_step_depends: bool rederivation_has_side_effects: bool @dataclass class CompactionPlan: facts_to_evict: list[WorkingFact] = field(default_factory=list) obligations: list[str] = field(default_factory=list) spill: list[WorkingFact] = field(default_factory=list) def evaluate_compaction(facts: list[WorkingFact], saturation: float, spill_watermark: float = 0.60) -> CompactionPlan: plan = CompactionPlan() # Trigger discipline: refuse to even decide under last-minute pressure # unless every evicted fact is recoverable. late = saturation > spill_watermark for f in facts: recoverable = f.cls is FactClass.RECOVERABLE if recoverable: plan.facts_to_evict.append(f) continue if not f.pending_step_depends: plan.facts_to_evict.append(f) continue # Non-recoverable AND a pending step needs it. if not f.rederivation_has_side_effects: plan.facts_to_evict.append(f) plan.obligations.append( f"re-derive '{f.key}' before dependent step" ) continue # The bottom row: non-recoverable, pending-dependent, side-effecting. # Must NOT commit lossily. Spill to external store instead. if late: raise CompactionRefused( f"refusing lossy commit of '{f.key}' ({f.cls.value}): " f"pending step depends on it, re-derivation has side " f"effects, and saturation {saturation:.0%} leaves no " f"budget to spill safely. Spill earlier or halt." ) plan.spill.append(f) return plan def commit(plan: CompactionPlan) -> None: # Spill is mandatory before eviction; an unspilled non-recoverable # fact that survives to eviction is a protocol violation. for f in plan.spill: persist_to_external_store(f) # noqa: F821 — external sink for f in plan.facts_to_evict: if f.cls is not FactClass.RECOVERABLE and f not in plan.spill: # defensive: should have been caught in evaluate_compaction raise CompactionRefused( f"evicting non-recoverable '{f.key}' without spill" ) apply_summary(plan) # noqa: F821 — external sink ```