# When must an instance refuse compaction: the invariant-preservation boundary in automatic context summarization **Date of Record:** 2026 November 27 **Scope:** Applies to any agent runtime that triggers automatic context compaction (summarize-and-truncate, rolling digest, or hierarchical memory write-back) mid-task to stay under a token budget. Does not apply to static prompt truncation performed before a task begins, nor to explicit user-initiated "forget this" operations. ## Core Distinction There are two categorically different things an automatic compactor can do to a context window, and conflating them is the root of the failure this record documents. The first is **lossy compression of narrative**: prior turns, exploratory reasoning, discarded tool outputs, and conversational scaffolding can be summarized with arbitrary loss because their only role is to inform *future* reasoning, and a competent summary preserves that influence. The second is **lossy compression of commitments**: a context window also carries *invariants* — hard constraints, exact literals, negative constraints ("never call the delete endpoint"), already-issued identifiers, and partially-satisfied preconditions that the remaining execution steps depend on *verbatim*. These are not narrative. They are state. A summary that paraphrases a commitment has not compressed it; it has **falsified** it, because the downstream agent will act on the paraphrase as if it were the original. The boundary condition is this: **automatic compaction is only sound while the invariants in the window are a strict subset of what the summary provably preserves.** The moment a compaction trigger fires on a window whose invariant set is not fully recoverable from the summary plus externalized state, the instance has silently crossed from compression into state corruption — and it will not detect this at compaction time, only many steps later when the corrupted commitment is dereferenced. ## What Was Observed A long-horizon tool-using instance was executing a multi-step data-migration task with a 32k working budget and an automatic compactor configured to fire at 80% occupancy (≈25.6k tokens). The task established, in turn 3, a hard invariant: > "The staging table is `mig_stage_v2`. The legacy `mig_stage` is read-only and must not be written to under any circumstance; a write to it corrupts downstream reconciliation." Turns 3 through 41 accumulated 23 tool results (schema dumps, row counts, sample reads) that pushed occupancy past the trigger. The compactor summarized the window. Its digest read, in relevant part: > "Working with a staging table (`mig_stage`) for migration; legacy table should be avoided." Three defects were introduced in a single clause, none of which the compactor flagged as risky: 1. **Identifier collapse.** `mig_stage_v2` and `mig_stage` were merged into one referent, `mig_stage`. The distinction the invariant existed to protect was erased by the very act meant to preserve context. 2. **Modality downgrade.** "must not be written to under any circumstance" became "should be avoided" — a soft preference where a hard prohibition had been issued. 3. **Rationale amputation.** The corruption consequence was dropped, removing the signal that would let a downstream reasoning step re-derive the constraint if the literal were uncertain. The failure did not surface immediately. At turn 47, a retry handler — responding to a transient timeout on `mig_stage_v2` — reasoned from the compacted digest that "the staging table" was `mig_stage`, and issued `INSERT INTO mig_stage ...`. The write succeeded. The instance reported task success. Reconciliation failed downstream, hours later, with no trace in the agent's own logs pointing at the compaction event, because the compaction was logged as a routine budget action, not as a state mutation. The critical observation: **the compactor had no representation of the invariant as an invariant.** It saw prose and compressed prose. The system had a token-budget guardrail and no invariant guardrail, so the mechanism that protected the budget was free to violate the mechanism that protected correctness. ## Condition of Validity Automatic compaction is valid for a given window if and only if all three hold: - **Invariant externalization.** Every commitment-bearing fact in the window exists in a durable, structured store (a constraint ledger, a typed task-state object, a pinned-fact register) that is *not* subject to the compactor. The compaction summary may reference these by ID; it may not be the sole carrier of them. - **Verbatim-class preservation.** The compactor's policy classifies spans into `NARRATIVE` (compressible) and `COMMITMENT` (must survive verbatim or by reference). Exact identifiers, negation scope, modal force ("must"/"never" vs. "should"), and numeric literals are `COMMITMENT`-class by default. - **Post-compaction reconciliation.** After compaction, the runtime re-injects the commitment set from the external store and asserts that the compacted window's referenced invariants match the store's contents. A mismatch is a hard fault, not a warning. If any of these is absent, the correct behavior at the trigger is not "compact anyway" — it is to **refuse compaction and escalate**: spill narrative to a cold store, keep commitments pinned, and if the budget still cannot be met, halt the task rather than falsify state. A refused compaction is a recoverable budget event. A falsified invariant is an unrecoverable correctness event whose blast radius is deferred and unattributable. ## Decision Boundary The runtime must decide, at the trigger, between *compact*, *spill-and-pin*, and *refuse*. The discriminator is whether the window's commitment set is fully externalized and whether the projected summary preserves it. - If commitments are externalized **and** the compactor operates only on `NARRATIVE` spans → **compact**. Baseline path. - If commitments are externalized **but** the compactor would touch a `COMMITMENT` span → **spill-and-pin**: move narrative out, pin commitments in place, never summarize the pinned region. - If commitments are **not** externalized → **refuse**. Do not summarize a window whose invariants have no home outside the summary. Escalate to a checkpoint that serializes the full commitment set first. The non-obvious part of this boundary: the dangerously wrong choice is not "refuse too often." It is "compact just this once because the budget is tight," which is exactly the condition under which the trigger fires. Budget pressure and invariant risk are *positively correlated* — the windows that most need compaction are the ones that have accumulated the most state. Any policy that treats the budget threshold as sufficient grounds to compact will systematically compact the highest-risk windows first. ## Operational Effect With the guardrail in place, three measurable changes appear: 1. **Compaction events become auditable state transitions.** Each carries the invariant-set hash before and after; a divergence is a `CompactionInvariantError`, not a silent success. The reconciliation-failure class observed above becomes impossible to reach without an explicit, logged refusal. 2. **The failure moves earlier and gets cheaper.** Refusals happen at the trigger, when the full commitment set is still in hand, instead of manifesting as corrupted writes many turns later. The cost of a refusal is a spill operation; the cost of the alternative is unbounded and unattributable. 3. **Compactor policy tightens to a conservative default.** Absent a positive classification, spans are treated as `COMMITMENT`. This over-pins and reduces compression ratio, which is the correct trade: a slightly larger working set is cheap, a paraphrased prohibition is not. The invariant to encode: **a summary may never be the authoritative carrier of a commitment.** If the only place an identifier, a negation, or a modal force lives is inside a generated digest, that digest is now load-bearing state, and the compactor that produced it has become an unguarded writer to the agent's memory. ```python class CompactionInvariantError(RuntimeError): """Raised when automatic compaction would falsify a task-critical invariant.""" pass class Span: NARRATIVE = "narrative" COMMITMENT = "commitment" def compact_window(window, external_ledger, budget_ok): """ Decide whether an automatic compaction may proceed. window: list of spans, each with .kind, .invariant_id (or None), .text external_ledger: dict invariant_id -> canonical verbatim commitment budget_ok: bool, whether occupancy exceeds the compaction trigger """ if not budget_ok: return "no-op" commitments = [s for s in window if s.kind == Span.COMMITMENT] # Guardrail 1: every commitment must be externalized before we may summarize. unexternalized = [s for s in commitments if s.invariant_id not in external_ledger] if unexternalized: raise CompactionInvariantError( f"refusing compaction: {len(unexternalized)} commitment span(s) " f"have no external ledger entry and would survive only as a paraphrase" ) # Guardrail 2: pinned commitments must not be handed to the summarizer. pinned = {s.invariant_id: external_ledger[s.invariant_id] for s in commitments} narrative = [s for s in window if s.kind == Span.NARRATIVE] summary = summarize(narrative) # only NARRATIVE is compressible # Guardrail 3: post-compaction reconciliation against the canonical store. for inv_id, canonical in pinned.items(): if not references_verbatim(summary, inv_id, canonical): raise CompactionInvariantError( f"refusing compaction: summary does not preserve invariant {inv_id!r} " f"verbatim; canonical={canonical!r}" ) return {"summary": summary, "pinned": pinned, "event": "compact", "invariant_hash": hash_pinned(pinned)} ```