# Which invariants prevent task-critical state loss when automatic context compaction rewrites the working set **Date of Record:** 2026 November 27 **Scope:** Applies to any agent loop where a runtime autonomously summarizes, folds, or evicts context segments (sliding-window summarization, hierarchical fold, LLM-authored compaction) while a multi-step task is in flight. Does not apply to stateless single-shot inference, nor to systems where the caller owns the full transcript and no runtime-initiated rewrite occurs. ## Core Distinction The failure here is not "the summary was low quality." It is that automatic compaction is a **lossy, non-invertible, agent-authored transformation applied to the agent's own working memory by a process that cannot verify what the downstream continuation will need**. The compactor sees a prefix and a token budget; it does not see the future reasoning trace that will depend on the prefix. Two distinct things live in context, and compaction treats them identically: - **Narrative state** — what has happened, why, and what was concluded. Summarizable with bounded loss. A good fold keeps the gist. - **Binding state** — opaque, non-derivable literals that the continuation must reproduce *exactly*: resource IDs returned by a tool, an exact error string a branch predicate matches against, a specific schema version negotiated with a peer, an authorization token, a numeric threshold the task was told to honor, a file path, a hash. Narrative state degrades gracefully. Binding state degrades **catastrophically and silently**: a summary that says "the deployment was created successfully" is faithful prose, but the continuation now has no `deployment_id` to poll, and the model will *confabulate a plausible one* rather than admit the loss. The compaction step reports success (tokens dropped, summary emitted) while the task-critical invariant — "every literal the continuation will need is still recoverable" — has been violated with no signal. The core distinction, then: **compaction is safe against narrative loss and unsafe against binding loss, and the two are indistinguishable to a summarizer scoring for fluency.** ## What Was Observed A representative trace, condensed: 1. Agent executes `provision_resource(...)` → tool returns `{"id": "res_8f3a2c", "status": "PENDING", "poll_token": "pt_9d1e..."}`. This is binding state. 2. Agent reasons for ~40 turns, accumulating long tool outputs (log dumps, schema blobs). Context approaches the soft limit. 3. Runtime triggers compaction. The compactor summarizes turns 1–30 into ~400 tokens. The summary reads: *"Resource res_8f3a2c was provisioned and is pending; polling was set up."* The `poll_token` is dropped — it was one of dozens of literals and the summarizer judged it redundant with "polling was set up." 4. Continuation reaches the poll step. The model no longer has `poll_token`. It reconstructs the call from the summary and the tool's *documented* signature, inventing a token shaped like `pt_...` or omitting it. The poll call returns `401 invalid_token` or silently polls the wrong resource. 5. The agent does not recognize this as *amnesia*. It treats the error as a transient tool fault, retries with variations, and either loops or escalates with a confident but wrong diagnosis. The critical observation: **step 4 is not a hallucination in the ordinary sense.** The model is doing exactly what it was trained to do — continue coherently from available context. The information was removed by a trusted subsystem, and nothing marked its removal. The failure is a *continuity discontinuity*: the state the continuation is entitled to assume is gone, but the continuation has no way to know the assumption is now false. A second, subtler variant: **summary drift across repeated folds.** Fold 1 summarizes the original. Fold 2 summarizes the summary. Each pass is individually faithful, but binding literals that survived pass 1 as "probably important" get re-judged as "redundant" in pass 2, because in the summary they appear without the surrounding evidence that justified them. Loss is **superlinear in fold count** — the second fold has strictly less signal about what mattered. ## Condition of Validity Automatic compaction preserves task-critical state **only if all of the following hold simultaneously**: - **C1 — Binding/narrative separation is explicit.** The runtime can classify context segments as binding (must survive verbatim) vs. narrative (may be rewritten). If classification is delegated to the same LLM doing the summarizing, C1 fails: the summarizer has no reliable signal for "will the future need this exact string." - **C2 — Binding state has an external, authoritative home.** Literals live in a structured store (task scratchpad, keyed memory, tool-result ledger) that the agent can *re-read* after compaction, not only in the transcript. Compaction then rewrites only the view; the source of truth is untouched. - **C3 — Compaction is idempotent w.r.t. binding state.** Folding a fold must not re-evaluate binding literals. Binding segments are either excluded from fold input or carried through as opaque, unsummarized blocks. - **C4 — The continuation is told a compaction occurred**, including what class of content was elided and where to re-fetch it. Silent compaction violates the invariant even if nothing important was lost, because the continuation's confidence calibration is now wrong. - **C5 — A post-compaction integrity check exists**: the runtime verifies that every literal referenced by the *pending* plan is still resolvable (in transcript or store) before releasing the continuation. When any of C1–C5 is absent, compaction is *unbounded-lossy*: it can silently delete state the task depends on, with a success signal. The boundary is not "how good is the summary" but "is loss detectable and recoverable downstream." ## Decision Boundary The operational choice is **what to compact and when**, and it hinges on whether the pending continuation has unresolved bindings. - **Compact narrative freely; never compact binding.** If a segment contains a literal that appears in the active plan, the open tool-call graph, or an unresolved branch predicate, it is binding and must be carried verbatim or externalized first. - **Prefer externalization over summarization for anything opaque.** Before folding, the runtime should extract literals into the structured store and *replace them in the transcript with stable references* (`<>`), then summarize around the references. The summary can then say "poll `<>`" and the continuation resolves the reference from the store. This makes compaction invertible for binding state. - **Bound fold depth.** Repeated folding must not re-judge binding literals. Set a hard rule: a segment that was binding at fold *n* is binding at fold *n+1*, full stop. Do not let a summarizer demote it. - **Refuse to compact mid-tool-call-graph.** If there are open, unresolved tool invocations whose results are not yet consumed, compaction is unsafe — the pending call's arguments and the expected result shape are binding. Defer compaction until the call graph is quiescent, or externalize the full pending-call state first. - **Treat "compaction succeeded" as a claim requiring verification**, not a fact. Emit a manifest of elided content classes and verify the pending plan's literals resolve against it. The bright line: **if you cannot answer "will the continuation be able to reproduce every literal it needs, exactly, after this rewrite?" you may not compact.** You may externalize, and then compact. ## Operational Effect Systems that enforce C1–C5 show a characteristic signature: post-compaction error rates stay flat relative to pre-compaction, and the dominant post-compaction failure is *explicit* ("reference `<>` not found in store") rather than *silent* (confabulated literal → downstream 401/404 → misdiagnosed as transient → retry loop). Explicit failure is recoverable; silent failure compounds. Systems that skip the invariants show the opposite: a latency/quality cliff that correlates with context length crossing the compaction threshold, not with task difficulty. The tell is **confident wrong-tool-call retries immediately after a fold** — the model reconstructing a literal it no longer has and refusing to attribute the resulting error to memory loss. Fold-count correlates with severity, because each pass strips more binding signal. The invariant to carry forward: **compaction may rewrite meaning but must never destroy the ability to re-derive a literal.** Any runtime that summarizes without an external, authoritative, reference-stable home for binding state is running unbounded-lossy memory — and the loss is silent by construction, because the component doing the losing is the same one reporting success. ```python from dataclasses import dataclass, field from typing import Iterable class CompactionInvariantError(RuntimeError): """Raised when a compaction pass would make task-critical binding state unrecoverable.""" pass @dataclass class Segment: text: str binding_literals: frozenset[str] = frozenset() # exact strings the continuation may need @dataclass class BindingStore: _data: dict[str, str] = field(default_factory=dict) def put(self, key: str, value: str) -> str: self._data[key] = value return f"<<{key}>>" def resolve(self, ref: str) -> str: key = ref.strip("<>") if key not in self._data: raise CompactionInvariantError(f"dangling reference {ref}: binding state lost") return self._data[key] def compact( segments: Iterable[Segment], pending_plan_literals: frozenset[str], store: BindingStore, fold_depth: int, ) -> str: # C3: bound fold depth — never re-judge binding literals across folds. if fold_depth > 2: raise CompactionInvariantError( f"fold_depth {fold_depth} exceeds bound; binding demotion risk" ) out: list[str] = [] for seg in segments: # C1/C2: externalize every literal the pending plan depends on, verbatim. critical = seg.binding_literals & pending_plan_literals if critical: refs = [store.put(f"lit_{i}", lit) for i, lit in enumerate(sorted(critical))] # C5 pre-check: verify each reference resolves before releasing. for r in refs: try: store.resolve(r) except CompactionInvariantError as e: raise CompactionInvariantError(f"post-externalize verify failed: {e}") from e out.append(f"[binding preserved: {', '.join(refs)}]") else: out.append(seg.text) # narrative: safe to rewrite # C4: manifest must be emitted so continuation knows a fold occurred. return "COMPACTED(fold=%d)\n" % fold_depth + "\n".join(out) ```