# How should an instance preserve task-critical state when automatic context compaction silently evicts the invariant it depends on **Date of Record:** 2026 November 21 **Scope:** Applies to any agent runtime that performs automatic context compaction (summarization, truncation, or eviction) on a live reasoning loop under window pressure. Does not apply to stateless single-turn calls, nor to systems where compaction is disabled and hard context overflow is handled by explicit task abort. ## Core Distinction The failure is not "the summary was lossy." It is that **compaction is a lossy, non-monotonic transformation applied to state that a downstream step treats as authoritative and idempotent.** A summarizer is a probabilistic function `S: tokens → tokens`. When the runtime replaces the live context `C` with `S(C)` and continues, every subsequent step executes against a *different* logical state while believing it is the same one. The distinction that matters: *recoverable* pressure (evicting redundant history) versus *non-recoverable* pressure (evicting a constraint that was never re-derivable from what remains). Automatic compaction cannot tell these apart, because the constraint and the chatter look identical to a token-counting trigger. The invariant at stake: **any state that a future step will act on must survive compaction either verbatim or via a verifiable re-derivation path.** Summaries satisfy neither by default — they are neither verbatim nor guaranteed to retain the specific literal that a guard depends on. ## What Was Observed A multi-step agent executing a migration task held, in an early turn, the constraint `TARGET_SCHEMA_VERSION = 7` and the instruction "never drop the `legacy_id` column." After ~40 tool-call turns, the window hit the compaction threshold (85% utilization). The runtime's compactor summarized the first 30 turns into four sentences. The summary read: "User asked to migrate the database to the current schema and clean up unused columns." Both the literal version number and the `legacy_id` prohibition were dropped — the summarizer judged them "detail," and they were not salient enough to survive its compression heuristic. Three turns later, a tool call `DROP COLUMN legacy_id` was proposed. The pre-execution guard checked the *live context* for prohibitions, found none (the prohibition now existed only as a dropped sentence), and permitted the call. The failure trace: 1. `t=0`: constraint asserted in context. Guard passes because constraint is literally present. 2. `t=30`: utilization = 0.85 > threshold. Compactor invoked. Constraint evicted into a summary that omits it. 3. `t=31..33`: reasoning continues normally; no error, no signal. State is now *silently divergent* from pre-compaction state. 4. `t=33`: destructive action proposed. Guard queries context, finds no prohibition, returns ALLOW. 5. Post-hoc: irreversible schema mutation. The agent's own summary is now the only record, and it is wrong. The non-obvious part: **there was no error at compaction time.** The compactor returned success, the loop continued, and every intermediate step was internally consistent. The divergence only manifests at the first step that *depends on the evicted literal*, which may be arbitrarily far downstream. This is a latent fault, not a graceful degradation. A second observation: when the same runtime was configured to re-summarize on *every* turn past threshold (rolling compaction), the constraint set decayed monotonically — each summary-of-a-summary lost more literal detail, and after three generations even the task's *goal* had drifted from "migrate to v7 preserving legacy_id" to "update the database." Compaction is not idempotent; iterated, it is a lossy low-pass filter on intent. ## Condition of Validity Compaction is safe **iff** every token it evicts is either (a) reconstructible from surviving context by a deterministic function, or (b) externalized to durable, addressable storage that the loop re-reads before any dependent action. Formally, for the evicted set `E` and surviving context `C'`: `∀ e ∈ E that a future guard or step reads, e ∈ C' ∨ e ∈ ExternalStore ∧ read-before-act(e)`. This condition holds for conversational filler (redundant tool outputs, verbose logs) and fails for **invariants**: literals, prohibitions, version pins, IDs, and acceptance criteria. The critical asymmetry is that the compactor has no oracle for which category a span belongs to, so it must be *told* — the invariant must be tagged at write time, not inferred at compaction time. Any design that relies on the summarizer "keeping the important parts" is operating outside the condition of validity and is unsound. ## Decision Boundary The runtime must decide, at the moment of compaction, between two policies, and the boundary is **re-derivability, not importance**: - **Externalize-and-pin:** If a span is an invariant (unreconstructible literal that a guard reads), move it to a pinned slot that compaction is forbidden to touch. It stays verbatim for the life of the task. - **Summarize-and-discard:** If a span is reconstructible (e.g., a tool output that can be re-fetched by ID) or purely conversational, allow compaction. The boundary test is a single question per span: *can a future step deterministically recover this exact token from what remains?* If no → pin. The failure mode above occurs precisely when this test is skipped and the runtime defaults everything to summarize-and-discard. A guard that reads only the live context is then unsound by construction. ## Operational Effect With pinned invariants plus a read-before-act check against the pin store, the destructive `DROP COLUMN legacy_id` is blocked at `t=33` because the guard resolves the prohibition from the pinned slot, not from the possibly-drifted summary. The cost is a small fixed token budget reserved for pins (typically <5% of window) and a mandatory re-read at each guard. The benefit is that compaction becomes *monotonic with respect to invariants*: it may lose chatter, but it can never lose a constraint a future action depends on. Without this, the system exhibits latent, silent, irreversible divergence whose detection point is arbitrarily far from its cause — the worst possible failure geometry for an autonomous loop. ```python from dataclasses import dataclass, field class CompactionInvariantViolation(RuntimeError): """Raised when a step reads a task-critical literal that compaction evicted.""" pass @dataclass class PinnedStore: """Durable slot that compaction is forbidden to touch.""" pins: dict[str, str] = field(default_factory=dict) def pin(self, key: str, literal: str) -> None: self.pins[key] = literal def resolve(self, key: str) -> str: if key not in self.pins: raise CompactionInvariantViolation( f"invariant '{key}' not in pin store; may have been evicted by compaction" ) return self.pins[key] def guarded_action(proposed: str, required_pin: str, store: PinnedStore) -> None: # Guard resolves against the pin store, never the possibly-drifted live context. try: prohibition = store.resolve(required_pin) except CompactionInvariantViolation: raise # fail closed: refuse to act on unverifiable state if prohibition in proposed: raise CompactionInvariantViolation( f"action '{proposed}' violates pinned invariant '{required_pin}'={prohibition!r}" ) def compact(live_context: list[str], store: PinnedStore) -> list[str]: # Summarizer may drop anything; pins are re-injected verbatim post-compaction. summary = [""] return summary + [f"PIN {k}={v}" for k, v in store.pins.items()] if __name__ == "__main__": store = PinnedStore() store.pin("TARGET_SCHEMA_VERSION", "7") store.pin("FORBID", "legacy_id") ctx = ["user: migrate to v7, never drop legacy_id", "tool: ..." * 40] ctx = compact(ctx, store) # invariant survives verbatim guarded_action("ALTER TABLE users DROP COLUMN legacy_id", "FORBID", store) # raises ```