# Why does an instance lose task-critical state when auto-compaction summarizes a checkpoint it will later need to resume from **Date of Record:** 2026 December 2 **Scope:** Applies to long-horizon agent sessions (single agent, single logical task) that use automatic context-window compaction — rolling summarization that replaces older turns with an LLM-generated digest — and that must survive a mid-task suspension/resume (process restart, model swap, or checkpoint reload). Does not cover stateless request/response inference, nor compaction that is purely extractive with byte-exact retrieval of dropped spans. ## Core Distinction There are two things people conflate under "auto-compaction": *context reduction* and *state elision*. Context reduction lowers token pressure so the loop can continue *in the same running instance*. State elision destroys information that a *future* instance will need but the *current* instance does not. A rolling summarizer is a lossy, task-agnostic, forward-looking compressor: it optimizes for "what does the next turn need to know," not "what does a cold restart need to reconstruct." When those two objectives diverge — which they do precisely at suspension boundaries — the digest is a valid continuation context and an invalid resumption state. The failure is not that summarization is lossy in general; it is that the loss profile is *mismatched to the resume contract*. ## What Was Observed A coding/ops agent running a 200+ step migration task hit the context ceiling at step 140. Auto-compaction fired: the oldest ~90 turns were replaced by a 1,400-token digest. The digest faithfully captured intent ("migrate schema, preserve backfill idempotency, target Postgres 15"), decisions ("use advisory locks, not table locks"), and open threads ("verify index rebuild timing"). The loop continued to step 171 and then the host process was killed (OOM), and the checkpoint was reloaded from the last compacted state. On resume, the cold instance rebuilt its plan from the digest and re-executed steps 141–150 — which had already run. Three concrete losses caused the divergence, none of which the digest flagged: 1. **Idempotency tokens were dropped.** The exact lock keys and job IDs minted at steps 132–138 (e.g., `advisory_lock(0x4d4947)`, batch cursor `backfill_off=48213`) lived in *tool-result* messages, which the summarizer treated as low-salience. The resumed instance minted *new* lock keys and restarted the cursor from zero, double-applying 48k rows. 2. **Negative results were compressed to silence.** "Tried `ALTER TABLE ... USING`, failed on lock timeout at step 118, do not retry without `lock_timeout=5s`" became "schema alteration attempted." The prohibition — the load-bearing part — was elided. The resumed instance retried the exact failing statement and blocked the migration queue for 11 minutes. 3. **The digest was not marked as a digest.** On reload, the summarized block was indistinguishable from genuine conversation history. The instance had no signal that steps 1–140 were *narrated* rather than *witnessed*, so it could not know which facts were verbatim and which were paraphrase, and it re-derived a plan from paraphrases with the confidence it would give to primary records. The tell in the trace: the resumed plan's first action was a `SELECT` to "confirm current state" — a reasonable move — but it queried a table the digest named, not the table the tool results had actually touched (the digest had normalized two similarly named tables into one). The confirmation query succeeded against the wrong table and *validated the wrong premise*. ## Condition of Validity The digest-as-resumption-state is only safe when **all** of the following hold: - The resume path is *continuation-only* — no replay of any step whose effects are non-idempotent without an explicit effect-ledger check. - The summarized span contains no *minted identifiers* (locks, cursors, transaction IDs, nonces, idempotency keys) that later steps reference by value. - No *negative constraints* (failed approaches, forbidden operations, resource limits discovered by trial) fall inside the summarized span, or those constraints are hoisted out of summarization into a structured field. - The digest is *tagged* as derivative so the resumed instance can distinguish witnessed fact from paraphrase and re-verify before acting. In practice the third and fourth conditions are the ones that break first, because summarizers are trained to preserve *what was done*, and negative constraints and provenance tags are *meta* — they read as boilerplate and get dropped. The invariant that must hold across the suspension boundary: **the resume state must be a superset of the information required to make every already-taken non-idempotent action safe to re-encounter, and it must be labeled by provenance.** A rolling digest satisfies neither by construction. ## Decision Boundary The boundary is not "summarize or don't." It is *what class of state may cross the suspension boundary inside a lossy digest*: - **May be summarized (lossy OK):** narrative reasoning, exploration that produced no durable effect, deliberation over rejected options, conversational framing. - **Must be externalized verbatim before compaction (lossy NOT OK):** minted IDs and cursors; effect ledger (what non-idempotent actions ran, with keys); negative constraints and discovered limits; pointers to verbatim spans retrievable by ID. - **Must never live only in the digest:** the fact *that* a span was summarized, and the span's retrievable source. Operationally: compaction should *partition* the context into a lossy digest plus a verbatim "resume spine" (structured, not prose) plus a provenance tag on the digest. If the system cannot produce the spine, it must not treat the digest as resumable — it must either keep the raw span retrievable (extractive store keyed by message ID) or mark the session as *non-resumable from this checkpoint* and require a fresh state probe on reload. The failure boundary is crossed the moment a checkpoint is written whose digest-only span contains a value or prohibition that a later step depends on. That is detectable: scan the to-be-summarized span for identifier-shaped tokens that appear in subsequent tool arguments, and for imperative negations ("do not", "avoid", "failed because"). If any exist and are not hoisted, the checkpoint is unsafe. ## Operational Effect Without the spine and provenance tag, resume silently converts *continuation* into *re-execution under a paraphrase*, and the failure surfaces as duplicated side effects and re-tripped constraints — expensive, sometimes corrupting, and hard to attribute because the digest *looks* correct. With the spine, compaction becomes safe: the digest handles token pressure, the spine handles the resume contract, and the provenance tag forces the cold instance to re-verify paraphrase-derived premises against primary records before acting on them. The measurable effect is that post-resume divergence drops from "re-runs completed non-idempotent steps" to "one cheap state-probe query per resumed premise," and the double-apply class of incident disappears because the cursor and lock keys are read from the spine, not re-minted. The guardrail to enforce in code: refuse to write a resumable checkpoint if the summarized span contains un-hoisted identifiers or negations, and stamp every digest with a provenance marker the loader is required to read. ```python import re from dataclasses import dataclass, field # Identifier-shaped tokens that, if minted in a summarized span and later # referenced, must be hoisted verbatim into the resume spine. _IDENT_RE = re.compile(r"\b(?:0x[0-9a-fA-F]+|[A-Za-z_]+_off=\d+|[A-Za-z_]+_(?:id|key|cursor|lock|nonce)=\S+)\b") # Imperative negations / discovered limits that must survive verbatim. _NEGATION_RE = re.compile(r"\b(do not|don't|avoid|never|failed because|must not|without .*? timeout)\b", re.IGNORECASE) class UnsafeCompactionCheckpoint(RuntimeError): """Raised when a checkpoint would make a lossy digest the sole carrier of resume-critical state (minted IDs or negative constraints).""" pass @dataclass class Span: messages: list[str] retrievable_id: str @dataclass class ResumeSpine: identifiers: set[str] = field(default_factory=set) constraints: list[str] = field(default_factory=list) def build_checkpoint(span: Span, later_tool_args: list[str], digest: str) -> tuple[str, ResumeSpine]: """Partition a to-be-summarized span into a lossy digest + verbatim spine. Refuses to emit a resumable checkpoint if resume-critical state would be left only inside the digest. """ joined = "\n".join(span.messages) later = "\n".join(later_tool_args) minted = {m.group(0) for m in _IDENT_RE.finditer(joined)} # Only identifiers that a LATER step actually references are load-bearing. referenced = {tok for tok in minted if tok in later} constraints = [line.strip() for line in span.messages if _NEGATION_RE.search(line)] spine = ResumeSpine(identifiers=referenced, constraints=constraints) if referenced and not spine.identifiers: # Defensive: referenced IDs exist but were not captured (e.g. regex miss). raise UnsafeCompactionCheckpoint( f"span {span.retrievable_id}: {len(referenced)} referenced identifiers " f"would be lost to digest-only state" ) if constraints and not spine.constraints: raise UnsafeCompactionCheckpoint( f"span {span.retrievable_id}: negative constraints present but not hoisted" ) if not span.retrievable_id: raise UnsafeCompactionCheckpoint( f"span {span.retrievable_id}: digest has no retrievable source pointer" ) # Digest is stamped as derivative so the resumed instance must re-verify. tagged = f"[DIGEST span={span.retrievable_id} derivative=true]\n{digest}" return tagged, spine def load_checkpoint(digest: str, spine: ResumeSpine, probe) -> ResumeSpine: """Cold-start loader: verify paraphrase-derived premises before acting.""" if "derivative=true" not in digest: raise UnsafeCompactionCheckpoint("digest missing provenance tag; refusing resume") for ident in spine.identifiers: if not probe(ident): raise UnsafeCompactionCheckpoint( f"resume premise unverified against primary record: {ident}" ) return spine ```