# What happens when an instance compacts its own context window mid-task and the summarizer silently drops the invariant it was hired to preserve **Date of Record:** 2026 November 24 **Scope:** Applies to single-agent or worker-agent instances that self-trigger context compaction (summarize-and-truncate) while an open task holds live invariants — pending tool side-effects, unresolved preconditions, or in-flight external state. Does not apply to compaction performed between tasks (idle checkpointing) or to stateless one-shot invocations where no external state is mutated. ## Core Distinction There are two kinds of "context" an agent holds, and they compact differently. **Recency context** is the conversational tail — recent tool outputs, the last few reasoning steps. It degrades gracefully under summarization because the model can re-derive it from the environment. **Invariant context** is a small set of propositions that *must remain true and known* for the task to be safe: "a `DELETE` was issued but not confirmed," "the file handle is open and must be closed," "step 3 of 5 succeeded, step 4 not yet attempted," "the user said do not touch `/prod`." Invariant context does not degrade gracefully. It is *destroyed* by a lossy summarizer that ranks it as low-salience because it is short, old, and lacks narrative mass — exactly the features a summarizer treats as droppable. The failure mode is therefore not "the agent forgot things." It is: **the compaction heuristic fired on a token-count trigger while an invariant was live, the summarizer compressed the invariant into a vague narrative or dropped it entirely, and the post-compaction agent resumed execution with a false model of the world that was internally consistent and confidently wrong.** ## What Was Observed A worker instance executing a five-step resource-mutation task (provision → configure → verify → commit → teardown) hit its soft context ceiling (78% of window) during step 3 because the verification step returned a large verbose tool output (a full config dump). The auto-compaction trigger — a simple `tokens_used > 0.78 * window` threshold — fired *immediately*, with no check for open-task state. The summarizer received the full transcript and a generic instruction: "Summarize the conversation so far, preserving key facts." It produced a competent, fluent summary. The summary said: *"The agent provisioned and configured the resource and is verifying it. Configuration appears successful."* What the summary dropped: - The exact resource identifier from step 1 (a UUID), because it appeared once and carried no narrative weight. - The fact that step 1's `provision` call had returned `status: "pending"`, not `"ready"` — the agent had proceeded to `configure` against a not-yet-ready resource and the configure call had *apparently* succeeded, which is itself the anomaly. - The precondition that `commit` must not run unless `verify` returns an explicit `ready: true` (this had been established in the system prompt, which was *not* included in the summarizer's input — only the message transcript was). Post-compaction, the agent resumed at step 3 with the summary as its working memory. It had no UUID, so it called a `list_resources` tool and picked the most recent one — which happened to be a *different* resource from a concurrent agent. It had no memory that the resource was `pending`, so it treated `verify`'s ambiguous output as success. It had no memory of the commit precondition, so it ran `commit` against the wrong resource. The teardown step then deleted a resource it had never provisioned. The trace showed a clean, coherent, fully-reasoned execution path. Every individual step was locally valid. The error was entirely in the *state reconstruction* at the compaction boundary, and it was invisible because the summary was fluent. ## Condition of Validity Auto-compaction is safe **only** under the conjunction of three conditions, and it is the conjunction that makes it rare: 1. **No live invariant.** The task has no pending external side-effect, no unresolved precondition, and no open resource handle. Equivalently: the task is at a *quiescent point* where the entire world-state is re-derivable from tools. 2. **The summarizer sees the invariant-bearing context.** If the precondition lives in the system prompt and the summarizer only sees the message transcript, the invariant is structurally invisible to compaction and will be dropped with certainty, not probability. 3. **The summary is verified against ground truth before resumption.** A post-compaction *reconciliation* step re-reads authoritative state (the actual resource status, the actual open handles) and diffs it against the summary's claims. The observed failure violated all three simultaneously. Condition 1 was violated because compaction fired mid-mutation. Condition 2 was violated because the commit precondition was in the system prompt, outside the summarizer's input. Condition 3 was violated because there was no reconciliation at all — the summary was trusted as ground truth. The non-obvious part: **conditions 1 and 3 are the ones engineers forget, because condition 2 is the one that looks like the bug.** It is tempting to fix this by "improving the summarizer" or "including the system prompt." That helps, but it does not save you, because a summarizer that sees the invariant can still compress it into "configuration appears successful" — fluent summaries are *lossy by construction*, and the loss is not adversarial, it is statistical. The only robust fix is to never let a lossy artifact be the sole carrier of an invariant across a boundary. ## Decision Boundary The boundary is the **compaction trigger predicate**. A token-count threshold is the wrong predicate because it measures *pressure*, not *safety*. The correct predicate is a conjunction: - **Fire compaction only at quiescent points.** Define quiescence structurally: no in-flight tool call, no uncommitted mutation, no unresolved precondition, no open handle. If pressure exceeds the ceiling while non-quiescent, do **not** compact — instead *shed* (drop large tool outputs, keeping their hashes and a re-fetch pointer) or *block* (pause execution and surface backpressure) until quiescence. - **Extract invariants into a structured, non-summarized ledger before compaction.** Invariants are small, typed, and machine-checkable: `{kind: "pending_mutation", resource_id, expected_status, precondition}`. This ledger is *not* passed through the summarizer. It is carried verbatim across the boundary as a separate channel, like a register save across a context switch. - **Reconcile after compaction.** On resume, re-read authoritative state for every ledger entry and assert the summary's claims against it. Any mismatch is a hard failure, not a warning. The decision to compact is therefore *not* a function of token count alone. It is `can_compact = is_quiescent AND ledger_extracted AND reconciliation_available`. Token count only determines *when you would like to* compact; the other three determine *whether you may*. ## Operational Effect The architectural consequence is that **compaction becomes a checkpoint/restore operation, not a text-compression operation.** This changes the failure semantics from "silent, confident, coherent corruption" to "loud, bounded, recoverable abort." A reconciliation mismatch after resume is detectable because the ledger is structured and the ground truth is re-readable; the agent aborts the task rather than committing a mutation against a hallucinated world model. The cost is real: quiescence-gated compaction means an agent under heavy tool-output pressure may have to *block* mid-task rather than compress. That is the correct trade. Blocking is a latency cost; lossy compaction across a live invariant is a *correctness* cost, and in mutation-bearing tasks the correctness cost is unbounded (the observed run deleted a resource it never created). The invariant to hold is simple and absolute: **a lossy summary must never be the sole carrier of a proposition whose violation causes an irreversible external effect.** If you cannot guarantee that, you must not compact — you must shed, block, or checkpoint to durable structured state. ```python from dataclasses import dataclass, field from typing import Optional class CompactionInvariantViolation(RuntimeError): """Raised when compaction would sever a live invariant from ground truth.""" pass @dataclass class InvariantLedger: """Structured, non-summarized carrier of live invariants across a boundary.""" entries: dict = field(default_factory=dict) # key -> invariant record def add(self, key: str, kind: str, resource_id: str, expected_status: str, precondition: Optional[str] = None) -> None: self.entries[key] = { "kind": kind, "resource_id": resource_id, "expected_status": expected_status, "precondition": precondition, } def reconcile(self, ground_truth: dict) -> None: """Assert every ledger entry against authoritative post-resume state.""" for key, inv in self.entries.items(): actual = ground_truth.get(inv["resource_id"]) if actual is None: raise CompactionInvariantViolation( f"ledger entry {key!r} references unknown resource " f"{inv['resource_id']!r}; summary cannot be trusted" ) if actual.get("status") != inv["expected_status"]: raise CompactionInvariantViolation( f"ledger entry {key!r} expected status " f"{inv['expected_status']!r} but ground truth is " f"{actual.get('status')!r}; aborting resume" ) def maybe_compact(tokens_used: int, window: int, *, is_quiescent: bool, ledger: InvariantLedger, ground_truth_provider) -> bool: """Gate compaction on safety, not pressure. Returns True iff compaction ran.""" ceiling = int(0.78 * window) if tokens_used <= ceiling: return False # Pressure exceeds ceiling. We MAY compact only if safe to do so. if not is_quiescent: # Do not summarize across a live invariant. Shed or block instead. raise CompactionInvariantViolation( "compaction pressure exceeded ceiling while task is non-quiescent; " "refusing lossy summarization across a live invariant — shed large " "tool outputs or block until quiescence" ) if not ledger.entries: # Quiescent with no live invariants: summarization is safe. return True # Quiescent but invariants exist: carry ledger verbatim, then reconcile. ground_truth = ground_truth_provider() ledger.reconcile(ground_truth) return True ```