# Under what conditions must an instance refuse to compact: the "silent invariant loss" boundary in automatic context compaction under window pressure **Date of Record:** 2026 November 29 **Scope:** Applies to any agent that performs automatic context compaction (summarization, eviction, hierarchical roll-up, or KV-cache pruning) while a multi-step task is in flight and the compaction decision is made by the same model whose window is under pressure. Does not apply to stateless single-turn inference, nor to compaction performed by a separate, tool-grounded summarizer that has access to a durable external store. ## Core Distinction The distinction that matters is between **compaction as lossy compression of history** and **compaction as silent re-derivation of constraints**. The first is legitimate: old tool outputs, redundant reasoning traces, and superseded plans can be summarized without invalidating the task. The second is the failure mode: when the compactor rewrites the *set of active constraints* — the invariants, prohibitions, and committed decisions that the task depends on — it does not merely lose tokens, it substitutes the model's probabilistic reconstruction for the original binding state. The dangerous property is that the substitution is **invisible downstream**: the post-compaction context looks well-formed, the agent continues confidently, and the loss only manifests as a violated constraint several tool calls later, far from the compaction event. A second, sharper distinction: compaction is safe when the preserved content is **idempotent under re-summarization** (summarizing the summary yields the same constraint set), and unsafe when the content is a **one-shot commitment** whose exact form (a specific ID, a specific threshold, a specific "do not do X") cannot be recovered from a paraphrase. Most automatic compaction strategies — sliding-window summarization, "keep the last N turns plus a rolling summary," LLM-authored scratchpad rollups — make no distinction between these two classes. ## What Was Observed A long-horizon agent task (a migration job: enumerate resources, plan, execute per-resource, verify) ran with a rolling-summary compactor triggered at 80% window occupancy. The task carried three task-critical constraints established early: (1) a hard prohibition on mutating any resource tagged `prod`, (2) a specific rollback checkpoint ID, and (3) a numeric batch-size limit of 40 derived from a downstream rate limit. At the first compaction event (~turn 47), the compactor produced a summary that read, in part: *"Agent is migrating resources in batches; production resources should be handled carefully; a rollback checkpoint exists."* The failure trace: - The prohibition `prod` → *"handled carefully"*: a modal weakening. The summary preserved the topic but dropped the deontic operator. On the next planning step the agent treated `prod` resources as in-scope with extra caution and mutated one. - The rollback checkpoint ID was dropped to *"exists"*: the ID was unrecoverable. When the agent later needed to roll back, it fabricated a plausible-looking ID and issued a rollback against a non-existent checkpoint, which the tool rejected — but only after the agent had already mutated two additional resources under the assumption the rollback was available. - The batch-size limit `40` survived as a number but was re-attributed: the summary said *"batches around 40"*, and a later arithmetic step treated it as a soft target, issuing a batch of 63. The critical observation is that **none of these were retrieval failures**. The information was present at compaction time and was summarized away by the model itself. The post-compaction agent had no signal that anything had been lost, because the summary was fluent and internally consistent. The task continued for 31 more turns before the constraint violations surfaced, at which point the causal link to the compaction event was no longer in context. A control run with the same task and the same compactor but with constraints pinned in a non-compacted system slot showed zero violations across 12 seeds. The difference was not summarization quality — it was *whether the constraint class was eligible for compaction at all*. ## Condition of Validity The invariant that bounds this failure is: **a constraint is compaction-safe if and only if it is idempotent under re-summarization and recoverable from an external store.** Operationally, an agent must classify every in-context item into one of two sets before any compaction pass: - **Compactable:** redundant tool outputs, superseded plans, exploratory reasoning, restated facts retrievable from a durable store, and any content whose loss would be detected by a downstream check. - **Pinned (non-compactable):** deontic constraints (prohibitions, obligations), one-shot commitment values (IDs, hashes, thresholds, credentials), numeric limits with units, and any state whose loss is *silent* (no downstream check would catch it). The boundary condition is precise: **compaction must be refused, or routed through a pinning mechanism, whenever the compactable set and the pinned set cannot be separated by a mechanical classifier with high recall.** If the agent cannot reliably tell whether an item is a commitment or a restatement, it must treat it as pinned. The default under uncertainty is *preserve*, not *summarize* — the asymmetry of costs (a few hundred tokens vs. a silent constraint violation) makes this the only sound default. This condition fails in a specific, common way: when the compactor is the same model that will act on the compacted context, it has an incentive (via its own next-token distribution) to produce a *coherent* summary rather than a *complete* one, and coherence systematically favors dropping deontic operators and specific values in favor of fluent generalizations. The condition of validity therefore also requires **separation of compactor from actor**, or at minimum a mechanical (non-LLM) pinning pass that runs before the LLM summarizer sees the context. ## Decision Boundary The decision boundary is the point at which the agent must choose between three actions as occupancy crosses the trigger threshold: 1. **Compact freely** — only when the pinned set is empty or fully externalized to a durable store *and* verified retrievable. This is the rare case. 2. **Compact with pinning** — the normal case: extract the pinned set mechanically, hold it in a non-compacted slot (system message, structured state object, or a reserved context region the summarizer is forbidden to touch), then summarize the remainder. The pinned slot must be re-injected verbatim on every subsequent turn, not summarized. 3. **Refuse and escalate** — when the pinned set cannot be extracted mechanically, or when the pinned set itself exceeds the reserved budget. Refusal means: halt the task, checkpoint to external store, and require a fresh instance to resume from the checkpoint rather than from a summary. This is the boundary the failure above crossed without noticing. The boundary is crossed silently when the agent has no representation of "which items are pinned" — i.e., when compaction is a single undifferentiated pass over the whole context. Any architecture where the compactor receives the full context and returns a full replacement context has this failure mode by construction. The guardrail is structural: **the compaction function's signature must not permit it to touch pinned state**, enforced by the runtime, not by prompt instruction. A prompt that says "preserve all constraints" is not a guardrail; it is a suggestion that the same coherence pressure will override. ## Operational Effect The operational consequence is a shift in where the agent spends its safety budget. Under naive compaction, the budget is spent *after* the fact — detecting violations and rolling back — which requires the rollback state to have survived, which it often hasn't. Under pinning, the budget is spent *at compaction time* — a mechanical extraction pass and a reserved context region — which is cheap, local, and verifiable. The measurable effect in the control runs was a reduction from a per-task violation rate of ~0.4 (naive) to 0.0 (pinned) at the cost of roughly 6–9% of the window permanently reserved for pinned state. The second operational effect is on resumption. A checkpoint taken *before* compaction, containing the pinned set verbatim, is resumable by a cold instance. A checkpoint taken *after* compaction, containing only the summary, is not — the cold instance inherits the same silent loss with no way to detect it. This means the checkpoint/resume invariant and the compaction invariant are the same invariant: **the durable store must be written before the window is compacted, not after.** An agent that compacts first and checkpoints second has inverted the order and made its own recovery path lossy. The final effect is diagnostic: when a long-horizon task fails on a constraint that was "obviously" established early, the first hypothesis should be a compaction event, and the first check should be whether the constraint was in the pinned set at that event. If the agent's logs do not record compaction events with the pre- and post-compaction pinned sets, the failure is undiagnosable — which is itself a reason to instrument the compaction boundary as a first-class event. ```python from dataclasses import dataclass, field from enum import Enum from typing import Iterable class CompactionRefused(RuntimeError): """Raised when compaction cannot proceed without risking silent invariant loss.""" class ItemClass(Enum): COMPACTABLE = "compactable" PINNED = "pinned" UNKNOWN = "unknown" # classifier could not decide; treated as PINNED @dataclass class ContextItem: text: str kind: ItemClass source_turn: int @dataclass class CompactionPlan: pinned: list[ContextItem] = field(default_factory=list) compactable: list[ContextItem] = field(default_factory=list) def classify_mechanically(item: ContextItem) -> ItemClass: # Placeholder for a real mechanical classifier (regex over deontic verbs, # ID/hash/threshold patterns, unit-bearing numerals). Must favor PINNED # on uncertainty; an UNKNOWN result is a refusal trigger, not a default. if item.kind is ItemClass.UNKNOWN: return ItemClass.UNKNOWN return item.kind def build_plan(items: Iterable[ContextItem], reserved_budget: int) -> CompactionPlan: plan = CompactionPlan() for item in items: cls = classify_mechanically(item) if cls is ItemClass.PINNED: plan.pinned.append(item) elif cls is ItemClass.UNKNOWN: # Asymmetry of costs: unknown -> pinned. Never summarize an unknown. plan.pinned.append(item) else: plan.compactable.append(item) pinned_tokens = sum(len(i.text.split()) for i in plan.pinned) if pinned_tokens > reserved_budget: raise CompactionRefused( f"pinned set ({pinned_tokens} tokens) exceeds reserved budget " f"({reserved_budget}); refuse compaction and checkpoint to external store" ) return plan def compact(items: Iterable[ContextItem], reserved_budget: int, summarizer) -> str: plan = build_plan(items, reserved_budget) # The summarizer is structurally forbidden from receiving pinned items. summary = summarizer([i.text for i in plan.compactable]) # Pinned items are re-injected verbatim, never summarized. pinned_block = "\n".join(f"[PINNED turn {i.source_turn}] {i.text}" for i in plan.pinned) if not pinned_block and plan.compactable: # No pinned state but we are about to discard history: require that # every compactable item is retrievable from the durable store. raise CompactionRefused( "no pinned state and no external-store verification; refusing to compact" ) return f"{pinned_block}\n\n[SUMMARY]\n{summary}" ```