# Which invariants prevent silent recall loss when auto-compaction budgets collide with long-horizon task state **Date of Record:** 2026 November 29 **Scope:** Applies to any agent runtime that performs automatic context compaction (summarize-and-evict) under a fixed token budget while a long-horizon task depends on facts established earlier in the same session. Does not apply to stateless single-turn inference, nor to externalized memory stores that never evict from the live window. ## Core Distinction The failure is not "the summarizer produced a bad summary." It is that the compaction policy treats *token budget* and *recall obligation* as the same resource. A summarizer that hits its budget is a summarizer that has made an *implicit eviction decision* — it chose which facts to drop to fit the cap. The runtime, however, records only "compaction succeeded at N tokens," with no record of *what it agreed to forget*. The distinction that matters operationally: **compaction is a lossy write to a memory the agent will later read as if it were authoritative.** A summary that silently drops a constraint the agent later violates is indistinguishable, at read time, from a constraint that never existed. The boundary condition is the moment the summary's compression ratio exceeds the point where the retained facts no longer cover the set of facts the downstream task will *dereference*. ## What Was Observed A long-horizon agent (≈90 tool calls, 6 sub-goals) ran under an auto-compaction policy: at 80% of a 200k window, summarize the oldest 60% of turns into a bounded 4k-token digest, splice the digest in place of the evicted span, continue. The task required the agent to preserve three classes of state across compaction: (a) hard constraints ("do not touch production table `orders`"), (b) entity bindings ("the staging cluster is `stg-7`"), and (c) open obligations ("still need to rotate the leaked key before closing"). Observed trace across two compactions: - Compaction #1 (turn 41): digest retained (a) and (b), dropped (c) — the obligation was phrased as a future-tense aside, which the summarizer's salience heuristic scored low. The agent proceeded, completed sub-goals 3–4, and never rotated the key. - Compaction #2 (turn 78): the digest from #1 was itself re-summarized (compaction is recursive). The second-order digest dropped entity binding (b) because "the staging cluster" appeared only once in the first digest and was paraphrased into "the cluster." The agent then issued a tool call against a default cluster name resolved from the environment — a *plausible* but wrong binding. - No error was raised at either compaction. Both digests were within budget. Both were fluent. The failure surfaced only at final verification, 12 turns after the second compaction, as two silent constraint violations. The key observation: **the compression ratio compounded across recursive compactions (60% → 4k → 4k), so the second digest was summarizing a summary, and each generation's loss was invisible to the next.** The runtime had no invariant tying "facts the task will dereference" to "facts the digest retained." ## Condition of Validity The guardrail below is only sound under these conditions, and must be *disabled* rather than silently degraded when they fail: 1. **The set of dereferenceable facts is enumerable before compaction.** Constraints, entity bindings, and open obligations must be extractable as discrete, addressable records (a "pinned fact ledger"), not left implicit in prose. If the runtime cannot enumerate them, compaction cannot guarantee their survival and must be treated as unsafe. 2. **Pinned facts are excluded from the compression budget, not merely prioritized within it.** A budget that *includes* pinned facts lets the summarizer trade a constraint for a paragraph of narrative. Pinned facts must be carried verbatim (or via a lossless pointer) *outside* the summarized span, so the digest budget applies only to non-pinned material. 3. **Recursive compaction is bounded by generation depth.** Re-summarizing a digest is permitted only if the pinned ledger is re-injected verbatim at each generation and the digest is checked against the ledger, not against its parent digest. Unbounded recursive summarization without ledger re-injection is the exact mechanism that dropped binding (b). 4. **Recall is verified by dereference, not by presence.** A fact "present" in the digest is not recalled unless a downstream read resolves it to the same binding. Verification must replay the task's known dereferences against the post-compaction window. When any condition is unmet, the correct behavior is to *refuse to compact* and escalate (spill to external store, or halt for checkpoint), never to compact and hope. ## Decision Boundary The runtime must decide, at each compaction trigger, between three outcomes — and the boundary between them is the ledger coverage check, not the token count: - **Compact** iff every pinned fact in the ledger is present verbatim (or via a resolvable pointer) in the post-compaction window, *and* generation depth is within bound, *and* dereference replay passes. - **Spill-and-continue** iff the non-pinned material exceeds budget but the ledger is intact: evict narrative to an external store with a retrieval handle, keep the ledger pinned. This preserves recall at the cost of a retrieval hop. - **Halt** iff ledger coverage cannot be established (fact missing, binding paraphrased beyond resolution, or depth bound exceeded). Halting is mandatory; a lossy compaction that fails coverage is a *silent* violation generator and must be treated as a hard error, not a warning. The non-obvious boundary: **token budget is a soft constraint; ledger coverage is a hard constraint.** Any policy that lets the soft constraint override the hard one — e.g., "compact anyway to stay under window" — inverts the priority and produces exactly the observed trace. ## Operational Effect With the invariant enforced, the two failures above become impossible by construction: obligation (c) is in the ledger and re-injected verbatim at every generation, so it cannot be scored away; binding (b) is pinned and checked by dereference replay, so the paraphrase-to-"the cluster" is caught at compaction #2 and triggers halt-or-spill rather than a wrong tool call. The cost is real: pinned ledgers consume window that would otherwise hold narrative, and depth-bounded recursion forces earlier spills. The trade is deliberate — a retrieval hop is recoverable, a silently dropped constraint is not. Operationally this shifts the failure mode from *silent post-hoc violation* to *loud pre-compaction halt*, which is the only regime in which a long-horizon agent's memory can be trusted across compactions. ```python from dataclasses import dataclass, field from typing import Callable class CompactionCoverageError(RuntimeError): """Raised when a compaction would drop a pinned fact the task will dereference.""" pass class RecursionDepthExceeded(CompactionCoverageError): pass @dataclass class PinnedFact: key: str verbatim: str # must survive compaction unchanged or via resolvable pointer kind: str # 'constraint' | 'binding' | 'obligation' @dataclass class Ledger: facts: dict[str, PinnedFact] = field(default_factory=dict) def dereference(self, key: str) -> str: if key not in self.facts: raise CompactionCoverageError(f"dereference of unknown fact {key!r}") return self.facts[key].verbatim def compact(window: str, ledger: Ledger, budget: int, summarize: Callable[[str, int], str], max_depth: int, depth: int = 0) -> str: # Hard invariant: depth bound before any recursion into a prior digest. if depth > max_depth: raise RecursionDepthExceeded( f"recursive compaction depth {depth} exceeds bound {max_depth}; " "refusing to summarize a summary without ledger re-injection" ) digest = summarize(window, budget) # Hard invariant: every pinned fact must be present verbatim in the digest. # Missing fact => silent recall loss => halt, never proceed. for key, fact in ledger.facts.items(): if fact.verbatim not in digest: raise CompactionCoverageError( f"pinned {fact.kind} fact {key!r} absent from digest; " "compaction would silently drop a dereferenceable fact" ) # Hard invariant: dereference replay — the digest must resolve bindings # to the same values the task will read, not a paraphrase. for key in ledger.facts: if ledger.facts[key].kind == "binding": if ledger.dereference(key) not in digest: raise CompactionCoverageError( f"binding {key!r} paraphrased beyond resolution in digest" ) # Re-inject ledger verbatim so the next generation cannot lose it. pinned_block = "\n".join(f"[PINNED {f.kind}] {f.verbatim}" for f in ledger.facts.values()) return f"{pinned_block}\n---\n{digest}" ```