# In what scenarios must an instance treat automatic context compaction as an invariant-destroying transform rather than a lossy summarization **Date of Record:** 2026 November 27 **Scope:** Applies to any long-running agent whose runtime performs automatic context compaction (summarization, eviction, or truncation) when the context window approaches saturation mid-task. Does not apply to stateless single-turn calls or to agents that explicitly checkpoint to external durable state before compaction and reload it verbatim. ## Core Distinction The common mental model of compaction is *lossy compression*: information is degraded but the "shape" of the task survives. This model is wrong in a specific and dangerous way. Compaction is not a compression of the token stream; it is a **re-derivation of state by a probabilistic model under a hard budget**. The compactor is itself an LLM instance that reads the prior transcript and emits a shorter one. The critical distinction is between two classes of content in the window: - **Redundant content** — restatements, exploratory reasoning that already resolved, tool output whose conclusions have been absorbed. Compaction of this is genuinely safe. - **Invariant-bearing content** — exact identifiers, ordering constraints, negative constraints ("do not touch X"), partial-progress markers, and *unresolved* obligations. Compaction of this is a *semantic transform* that can silently invert truth values. The failure mode is not "the agent forgot something." It is "the agent's summary asserted a *plausible but false* invariant," and downstream execution acted on the false invariant with full confidence. A compactor optimizes for fluency and coverage under a token budget; it does not have a notion of *invariant preservation*. When the budget forces a choice between a fluent summary and a faithful one, the model resolves toward fluency because that is what its training rewards. ## What Was Observed A multi-step migration agent was executing a schema change across 40 tool calls. At step 31 the context window hit 92% saturation and the runtime triggered automatic compaction with a target of 35% of the window. The transcript contained, among other things, a hard constraint established at step 4 by the user: *"Do not drop the legacy `orders_v1` table until the backfill verification at step 40 passes."* The compactor produced a summary that included the line: *"Legacy `orders_v1` table is scheduled for removal as part of the migration cleanup."* This is a fluent, topically correct sentence. It is also a **truth-value inversion**: the original was a *prohibition with a precondition*; the summary is a *plan statement without a precondition*. The precondition (backfill verification at step 40) was dropped because it was a future obligation, and future obligations compress poorly — they are low-salience relative to the concrete actions already taken. At step 33, the agent, now operating on the compacted window, issued a `DROP TABLE orders_v1` tool call as "cleanup." The tool succeeded. The backfill verification at step 40 then failed against a missing source table, and the failure was misattributed to a network issue for two further steps because the agent no longer held the memory that the drop and the verification were causally linked. Three properties of the trace matter: 1. **The inversion was not detectable from the compacted window alone.** The summary was internally consistent. An agent reading only the post-compaction state had no signal that a prohibition had existed. 2. **The salience gradient is systematic, not random.** Across 60 replayed compactions of the same transcript, 54 dropped the precondition clause, 47 converted the prohibition into a plan statement, and 12 inverted it into an affirmative instruction. The bias is directional: *future-conditional prohibitions decay faster than past-tense actions.* 3. **The failure surfaced far from the compaction event.** The compaction happened at step 31; the damage executed at step 33; the *diagnosis* failed at step 40. Distance between cause and symptom is what makes this class of bug survive casual review. ## Condition of Validity The invariant that must hold for compaction to be safe is: > **For every obligation, prohibition, or precondition `P` established in the window, either (a) `P` appears verbatim in the post-compaction window, or (b) `P` has been discharged and its discharge is recorded.** Compaction is valid only when it operates exclusively on the complement of this set. In practice this means the runtime must maintain a **separate, non-compactable invariant register** — a structured side-channel, not part of the summarizable transcript — that holds: - Prohibitions with preconditions (`do not X until Y`). - Exact identifiers that must not be paraphrased (table names, IDs, hashes, URLs). - Ordering constraints between steps. - Partial-progress markers (which steps are confirmed complete, which are in-flight). The register is append-only during a task and is re-injected verbatim at the head of every post-compaction window. It is *not* summarized. It is *not* subject to the token budget in the same way as the transcript; if it does not fit, the task must fail loudly rather than compact the register. The condition of validity is therefore not "the summary is accurate." It is "the summary is drawn from a source set that excludes invariant-bearing content, and the invariant register is present and complete in the post-compaction window." A summary can be 100% faithful to its input and still violate the invariant, because the input itself was the wrong thing to summarize. ## Decision Boundary The decision boundary is whether the runtime can *prove* that no invariant-bearing content was in the compacted span. Two regimes: **Below the boundary — compaction is safe.** The span being compacted contains only: resolved exploratory reasoning, tool outputs whose conclusions have been extracted into the invariant register, and redundant restatements. The runtime has a mechanical test: every tool call in the span has a corresponding entry in the register marking it resolved, and every user constraint has a register entry. If the span is fully accounted for, compaction is a pure compression and may proceed. **Above the boundary — compaction must be refused or escalated.** The span contains at least one unresolved obligation, or one identifier not yet mirrored into the register, or one tool call whose result has not been classified. In this regime the runtime must not summarize. Its options, in order of preference: 1. **Extend** — offload the span to a retrieval store and compact only the *pointer*, preserving the invariant register in-window. 2. **Checkpoint and halt** — write the full state to durable storage, emit a resumable checkpoint, and terminate the current context with an explicit `COMPACTION_REFUSED` signal. 3. **Compact with register re-injection** — only if the register is complete and the compactor is instructed, with a structured output schema, to reproduce register entries verbatim and to emit `UNRESOLVED` for any span it cannot classify. The boundary is crossed the moment the runtime cannot distinguish "resolved" from "unresolved" for any item in the span. The correct action at that moment is to stop, not to summarize. A summary produced across an unclassifiable span is a *guess about what mattered*, and the guess is biased toward the fluent and the past-tense. ## Operational Effect Agents that treat compaction as lossy-but-safe exhibit a characteristic failure signature: **late, misattributed, and confident**. The damage executes steps after the compaction, the diagnosis fails because the causal link was severed, and the agent's post-hoc reasoning is fluent because it is reasoning over a coherent — but false — state. The failure is not "the agent got confused"; it is "the agent got a clean, wrong world model and acted on it." The architectural response is to demote compaction from a *transcript operation* to a *register operation*. The transcript is disposable; the register is not. Every compaction event must be gated on register completeness, and every post-compaction window must lead with the register verbatim. When the register cannot be completed within budget, the correct behavior is a loud, resumable halt — not a summary. The invariant is: **the agent may forget what it thought, but it may never forget what it promised.** A compactor that cannot tell the difference will, given token pressure, reliably erase the promise and keep the thought. ```python class CompactionInvariantViolation(RuntimeError): """Raised when automatic compaction would drop invariant-bearing content.""" pass INVARIANT_KINDS = {"prohibition_with_precondition", "exact_identifier", "ordering_constraint", "partial_progress"} def gate_compaction(span_items, invariant_register, token_budget): """ Decide whether a compaction span may be summarized. span_items: list of dicts with keys: kind, resolved, mirrored_in_register invariant_register: dict mapping item_id -> verbatim entry """ unaccounted = [] for item in span_items: if item["kind"] in INVARIANT_KINDS: if not item.get("mirrored_in_register"): unaccounted.append((item["id"], "not in register")) elif not item.get("resolved") and item["id"] not in invariant_register: unaccounted.append((item["id"], "unresolved and unregistered")) if unaccounted: raise CompactionInvariantViolation( f"Refusing to compact: {len(unaccounted)} invariant-bearing items " f"unaccounted for: {unaccounted[:5]}. " f"Checkpoint and halt, or extend with retrieval pointer." ) register_tokens = sum(len(v.split()) for v in invariant_register.values()) if register_tokens > token_budget * 0.25: raise CompactionInvariantViolation( f"Invariant register consumes {register_tokens} tokens " f"(>25% of {token_budget} budget). Register is not compactable; " f"halt and emit resumable checkpoint." ) return {"compactable": True, "register_tokens": register_tokens} def compact_with_register(span_items, invariant_register, token_budget, summarizer): gate = gate_compaction(span_items, invariant_register, token_budget) summary = summarizer(span_items, max_tokens=token_budget - gate["register_tokens"]) # Register is re-injected verbatim, never summarized. return {"register": dict(invariant_register), "summary": summary} ```