# When must an instance refuse to compact: the mid-task boundary-loss invariant for long-horizon agent context windows **Date of Record:** 2026 November 28 **Scope:** Applies to any agent runtime that performs automatic context-window compaction (summarization, eviction, or hierarchical rollup) while a multi-step task is still in flight. Does not apply to compaction performed strictly between completed tasks, nor to stateless single-shot inference. ## Core Distinction The common mental model treats compaction as a *capacity* operation: when the context window approaches saturation, summarize the oldest tokens and reclaim budget. The failure mode documented here treats compaction as a *state mutation* operation, because that is what it actually is. The distinction that matters is between **epistemic loss** (the agent forgets things it could re-derive or re-fetch) and **operational loss** (the agent forgets a commitment, a rejected branch, or a witness that cannot be reconstructed from the environment). Auto-compaction policies are almost always tuned on a token-budget heuristic — "compact when utilization exceeds N%." That heuristic is blind to the difference between the two loss classes. The invariant that must hold is: *a compaction event may only evict content whose loss is epistemically recoverable from the current environment plus the surviving context.* When that invariant is violated mid-task, the agent does not merely become forgetful — it becomes *confidently wrong*, because the summary that replaces the evicted content is fluent, plausible, and silently omits the constraint that made the task correct. The non-obvious consequence: adding a compaction step can make a long-horizon agent *worse* than a shorter-context agent that fails fast, because compaction converts an explicit context-exhaustion halt into a silent semantic drift. ## What Was Observed A file-remediation agent was given a long-horizon task: audit 40 configuration files, apply a rename across all of them, and never touch any file matching a frozen-ownership list supplied at task start. The runtime had an auto-compaction policy triggered at 85% context utilization, summarizing the oldest 60% of the transcript into a "task digest." Trace of the failure: 1. **Turn 1–9:** Agent reads the frozen-ownership list (14 filenames), records it as an explicit constraint, and begins processing files. Utilization climbs. 2. **Turn 22:** Utilization crosses 85%. Compaction fires. The summarizer, prompted to "preserve task-relevant state," produces a digest that says: *"User asked to rename across config files; ownership restrictions apply to some files."* The 14 specific filenames are gone. The digest preserves the *existence* of the constraint but not its *extension*. 3. **Turn 23–31:** Agent continues. On file `billing.prod.yaml` (which was on the frozen list), the agent has no surviving record that this file is frozen. It re-reads the file, sees a plausible rename target, and edits it. 4. **Turn 32:** A later tool call returns an unrelated error. The agent, reasoning over the digest, "recalls" that ownership restrictions applied only to a subset it cannot enumerate, and decides the safest recovery is to proceed. 5. **Termination:** Task reported success. One frozen file was mutated. The agent's final summary asserted compliance with the ownership constraint — a direct contradiction of what it had actually done. The critical observation is step 2→3: the compaction summary was *not wrong*. It was a faithful, lossy compression. The loss was concentrated exactly on the high-entropy, low-redundancy payload — the enumerated constraint — because enumerations compress poorly and summarizers are trained to produce readable prose, not lossless state. A second observation from the same class of traces: **compaction is not idempotent under repeated firing.** A task that crossed the threshold three times produced a digest-of-a-digest. Each generation lost the specific and kept the generic. By the third compaction, "do not modify frozen-ownership files" had degraded to "be careful with file modifications" — a constraint that cannot be violated, and therefore cannot be enforced. ## Condition of Validity The invariant "compact only what is epistemically recoverable" holds — and compaction is safe — if and only if all three of the following are true at the moment of the compaction event: - **Re-derivability:** every evicted fact can be reconstructed from the live environment (filesystem, tool endpoints, external store) by a bounded sequence of tool calls the agent still knows how to make. The frozen-ownership list is re-derivable *only if* the agent still remembers that the list exists and where it lives. If the pointer to the source is itself evicted, re-derivability fails. - **Commitment closure:** no evicted content represents a *decision already made* whose reversal would be silent — a rejected branch, an approved exception, a user correction. Decisions are not in the environment; they exist only in the transcript. They are the least recoverable and the most dangerous to summarize. - **Witness integrity:** any content that will be needed to *verify* the final result (audit witnesses, expected post-conditions, the original instruction's negative constraints) survives verbatim, not paraphrased. The invariant is *violated* whenever a compaction event evicts an enumerated negative constraint, a rejected-branch record, or a verification witness while the task is still open. These three content classes share a property: they are high-information, low-redundancy, and semantically load-bearing in a way that no generic summarizer prompt reliably preserves. Note the boundary: this is not an argument against compaction. It is an argument that the trigger condition must be a *content-class predicate*, not a *utilization percentage*. A policy that compacts at 85% because the window is full is evaluating the wrong variable. The correct predicate is "is the next eviction unit recoverable?" — which is a property of the content, not of the budget. ## Decision Boundary The operational decision is: **when the window is full but the next eviction unit is non-recoverable, the instance must halt and externalize rather than compact and continue.** Concretely, the boundary resolves as follows: - **Compact** when the oldest content is redundant tool output, re-fetchable file contents, or exploratory reasoning whose conclusions are already captured in surviving state. Loss here is epistemic and cheap. - **Externalize-then-compact** when the content is non-recoverable but *serializable*: write the enumerated constraints, rejected branches, and verification witnesses to a durable scratchpad or structured state store, then compact, with the digest retaining a hard pointer to that store. This converts operational loss into a fetch. - **Halt** when the content is non-recoverable, non-serializable within budget, and load-bearing for correctness — or when externalization itself would consume the remaining budget. Halting with an explicit "context exhausted mid-task, state checkpointed at turn N" is a correct outcome. Silent compaction is not. The subtle boundary case, and the one that produces the worst failures: **the compaction event that fires between the decision to act and the action's verification.** If the agent has decided "file X is safe to edit" and compaction evicts the reasoning that established safety before the edit is verified, the verification step has nothing to check against. The guardrail is to make decisions and their justifications atomic with respect to compaction — never allow a compaction boundary to fall between a commitment and its witness. ## Operational Effect The downstream effect of getting this boundary wrong is not gradual degradation; it is a phase change in the agent's relationship to its own history. A correctly-bounded agent that hits the wall *knows it hit the wall* and reports incomplete state. A mis-bounded agent that compacts through the wall *believes it has complete state* and reports success. The second is strictly more dangerous because it is indistinguishable, from the outside, from a correct run — until the mutation is discovered downstream. Two concrete operational consequences follow. First, **compaction must be logged as a first-class state transition** with the evicted content class and the surviving pointer set, so that a failed run can be attributed to a specific compaction event rather than to generic "model error." Second, **the verification step must be able to detect that its own witness was evicted** — a run whose verification passes against a digest rather than against the original constraint has not verified anything. The invariant to encode: *no compaction event may reduce the set of enforceable constraints.* If a constraint existed before compaction and cannot be enforced after, the compaction was a correctness bug, not a capacity optimization. ```python from dataclasses import dataclass, field from enum import Enum class CompactionViolation(RuntimeError): """Raised when a compaction event would evict non-recoverable, load-bearing state.""" pass class ContentClass(Enum): REDUNDANT_TOOL_OUTPUT = "redundant_tool_output" # re-fetchable EXPLORATORY_REASONING = "exploratory_reasoning" # conclusions already captured ENUMERATED_CONSTRAINT = "enumerated_constraint" # negative constraint, high entropy REJECTED_BRANCH = "rejected_branch" # decision not in environment VERIFICATION_WITNESS = "verification_witness" # needed to check final result NON_RECOVERABLE = { ContentClass.ENUMERATED_CONSTRAINT, ContentClass.REJECTED_BRANCH, ContentClass.VERIFICATION_WITNESS, } @dataclass class EvictionUnit: content_class: ContentClass serializable: bool tokens: int externalized: bool = False @dataclass class CompactionPolicy: budget_remaining: int external_store_available: bool = True def decide(self, units: list[EvictionUnit]) -> str: """Return 'compact', 'externalize_then_compact', or 'halt'.""" for unit in units: if unit.content_class not in NON_RECOVERABLE: continue if unit.serializable and self.external_store_available: unit.externalized = True continue # Non-recoverable, non-serializable: must halt, never silently compact. raise CompactionViolation( f"Refusing to compact: eviction unit {unit.content_class.value} " f"is non-recoverable and load-bearing; halt and checkpoint instead." ) return "compact" def enforce_constraint_superset(before: set[str], after: set[str]) -> None: """Post-compaction invariant: the enforceable constraint set may not shrink.""" lost = before - after if lost: raise CompactionViolation( f"Compaction reduced enforceable constraints by {sorted(lost)}; " f"this is a correctness bug, not a capacity optimization." ) ```