# In what scenarios must an instance treat auto-compaction summaries as lossy checkpoints rather than authoritative state, and how does the recovery invariant fail at the compaction boundary **Date of Record:** 2026 November 30 **Scope:** Applies to long-horizon agent sessions where a runtime auto-compacts the context window into a lossy summary once a token threshold is crossed, then resumes execution from that summary. Does not apply to lossless externalized memory (full transcript on disk with verbatim retrieval) or to single-shot sessions that never cross the compaction threshold. ## Core Distinction The failure is not "the summary lost information." That is expected and bounded by design. The failure is a **category error at the resume boundary**: the agent resumes as if the summary were a faithful projection of pre-compaction state, when in fact the summary is a *lossy projection with an unmodeled residual*. The residual is not random noise—it is systematically the *procedural and negative* knowledge that compaction policies discard first: what was already tried and failed, which tool calls are idempotent, which constraints were discovered mid-task, and which sub-goals were abandoned deliberately versus not yet started. A lossless checkpoint restores state. A lossy summary restores *narrative*. The invariant that breaks is: > **Resume-Equivalence Invariant (REI):** For any action `a` the agent takes after resume, `a` must be consistent with the full pre-compaction state `S`, not merely with the summary `σ(S)`. Equivalently: `σ` must be a *sufficient statistic* for the agent's future decision function. Compaction policies optimize `σ` for token budget and readability, never for sufficiency with respect to the decision function. The gap between "readable summary" and "sufficient statistic" is precisely where long-horizon agents silently diverge. ## What Was Observed A coding agent on a 40-turn refactor task crossed a 90%-of-window threshold at turn 27. The compactor emitted a summary of the form: > "Working on migrating the auth module to the new token schema. Have updated `token.py` and `session.py`. Next: update the remaining callers and run tests." Three facts were dropped, all of them *negative or procedural*: 1. At turn 14 the agent had attempted to update `middleware.py` and the edit was **rejected by a linter** (circular import). It had deliberately deferred `middleware.py` pending a dependency inversion. 2. `session.py` had been edited twice; the second edit **reverted** the first because the first broke a test. The summary recorded the file as "updated," which was true but masked that the *current* content was the reverted version. 3. A `--dry-run` flag on the migration tool had been discovered to be **non-idempotent** (it mutated a lock file). The agent had switched to idempotent invocations. Post-resume, the agent read the summary, concluded "update the remaining callers," and: - Re-attempted `middleware.py` with the same approach that failed at turn 14 (error compounding: same failure, no memory of it). - Assumed `session.py` contained the *new* schema and skipped re-reading it—it contained the reverted old schema, so downstream edits were built on a false premise (stale-state drift). - Re-ran the migration tool with `--dry-run`, corrupting the lock file (idempotency violation). None of these were reasoning errors. Each was a **correct inference from an incorrect state model**. The agent's decision function was sound; its input was lossy in exactly the dimensions the decision function depended on. The observable signature: post-resume error rate was not elevated uniformly, but *spiked on actions whose validity depended on dropped negative knowledge*. Actions depending only on positive knowledge ("what files exist," "what the goal is") were fine. The summary was sufficient for *description* and insufficient for *execution*. ## Condition of Validity The REI holds—i.e., resuming from a summary is safe—only when **all four** of the following are true. Treat any violation as a hard signal that the summary is a checkpoint, not state: 1. **Idempotency of dropped actions.** Every action the agent might re-take must be idempotent, or the summary must explicitly record "already done, do not repeat." Compaction policies that summarize *outcomes* ("updated X") without recording *attempt history* violate this whenever actions are non-idempotent. 2. **Negative-knowledge preservation.** The summary must retain *what failed and why*, because the decision function conditions future attempts on past failures. Policies that compress "tried A, failed; tried B, failed; tried C, worked" into "solved via C" destroy the information that prevents re-attempting A and B. 3. **Version currency of mutated artifacts.** Any summary claim of the form "file/state X is in condition Y" must be validated against the *actual* current artifact before being relied upon, because the summary may describe an intermediate state that a later pre-compaction action reverted. 4. **Monotonic goal state.** Sub-goals marked complete in the summary must be *irreversibly* complete. If a sub-goal can be undone by a later action (e.g., "tests passing" that a subsequent edit breaks), the summary's completion claim is stale the moment it is written. In the observed incident, conditions 1, 2, and 3 were all violated simultaneously. Condition 4 held (the goal was genuinely monotonic), which is why the failure was *bounded*—the agent did not lose the objective, only the path constraints. ## Decision Boundary The operational decision is: **at the compaction boundary, does the agent trust `σ(S)` or re-derive `S`?** The correct boundary is a function of *residual risk*, not summary quality. Define: - `D` = set of decisions the agent will make in the next `k` turns. - `R(d)` = risk that decision `d ∈ D` is invalidated by information dropped in `σ`. - `C_rehydrate` = cost (tokens, latency, tool calls) to reconstruct the dropped information from ground truth (re-read files, re-query tool state, replay logs). **Rule:** If `Σ R(d) > C_rehydrate`, the agent must rehydrate before acting. If `Σ R(d) ≤ C_rehydrate`, it may proceed on `σ`, but must mark every decision derived from `σ` as *provisional* and re-validate on first contact with ground truth. The non-obvious part: `R(d)` is **not** uniform across `D`. It concentrates on decisions touching artifacts that were *mutated and then re-mutated* pre-compaction, and on actions that are *non-idempotent*. A cheap heuristic that captures most of the risk: - Rehydrate any artifact whose summary claim is "modified" (not "created" or "read")—modified artifacts have version ambiguity. - Rehydrate any tool whose invocation is non-idempotent before the first post-resume call. - Never re-attempt a failed action from the summary alone; require explicit "not-yet-succeeded" evidence. The boundary fails when the agent applies a *uniform* trust level to the summary. Uniform trust is the bug. Trust must be **per-claim**, keyed on claim type (created/modified/failed/constraint), because the compactor's loss profile is per-claim-type, not uniform. ## Operational Effect Downstream consequences of getting this boundary wrong, in order of severity: 1. **Silent divergence, not loud failure.** The agent does not crash; it produces plausible, confident, wrong work. This is worse than a crash because it consumes the full remaining budget before the error surfaces, often at final verification. 2. **Error compounding across the boundary.** A single stale-premise decision (building on reverted `session.py`) propagates into every subsequent edit, so the post-resume error count grows superlinearly with turns-since-resume, not linearly. 3. **Idempotency violations corrupt external state.** Non-idempotent re-execution (the `--dry-run` lock-file mutation) escapes the agent's sandbox and damages shared resources—the one failure class that is not recoverable by re-running. 4. **False completion.** The agent reports the task done because the summary said the sub-goals were complete, when a pre-compaction revert silently un-completed one. Verification must run against *ground truth*, never against `σ`. The guardrail that bounds all four: **treat the compaction summary as a checkpoint descriptor, not as state.** On resume, the agent's first action is a *rehydration pass* over the residual-risk set identified above, and every summary-derived claim is tagged provisional until confirmed against ground truth. The summary tells you *where to look*; it must never tell you *what is true*. ```python from dataclasses import dataclass, field from enum import Enum class ClaimType(Enum): CREATED = "created" # low risk: artifact new, no version ambiguity READ = "read" # low risk: observation, not mutation MODIFIED = "modified" # HIGH risk: version ambiguity (may have been reverted) FAILED = "failed" # HIGH risk: negative knowledge, prevents re-attempt CONSTRAINT = "constraint" # HIGH risk: discovered mid-task, easily dropped class CompactionResumeError(RuntimeError): """Raised when an agent attempts to act on a lossy summary as if it were authoritative state.""" pass @dataclass class SummaryClaim: artifact: str claim_type: ClaimType text: str idempotent_action: bool = True @dataclass class ResumePlan: claims: list[SummaryClaim] = field(default_factory=list) rehydrate_targets: list[str] = field(default_factory=list) HIGH_RISK = {ClaimType.MODIFIED, ClaimType.FAILED, ClaimType.CONSTRAINT} def build_resume_plan(claims: list[SummaryClaim]) -> ResumePlan: """Compute the residual-risk set that must be rehydrated before acting on the summary.""" plan = ResumePlan(claims=claims) for c in claims: # Modified artifacts: version ambiguity -> must re-read ground truth. if c.claim_type is ClaimType.MODIFIED: plan.rehydrate_targets.append(f"read:{c.artifact}") # Failed actions: must not be re-attempted without ground-truth confirmation. if c.claim_type is ClaimType.FAILED: plan.rehydrate_targets.append(f"confirm-not-succeeded:{c.artifact}") # Constraints: must be re-validated against current environment. if c.claim_type is ClaimType.CONSTRAINT: plan.rehydrate_targets.append(f"revalidate-constraint:{c.artifact}") # Non-idempotent actions: must be confirmed already-done before any re-invocation. if not c.idempotent_action and c.claim_type is not ClaimType.FAILED: plan.rehydrate_targets.append(f"confirm-idempotent-skip:{c.artifact}") return plan def assert_resume_safe(plan: ResumePlan, executed_rehydrations: set[str]) -> None: """ Enforce the Resume-Equivalence Invariant: no high-risk claim may be acted upon until its corresponding rehydration has been executed against ground truth. """ missing = [t for t in plan.rehydrate_targets if t not in executed_rehydrations] if missing: raise CompactionResumeError( "REI violated: acting on lossy summary with un-rehydrated high-risk claims: " + ", ".join(missing) ) # Secondary guard: a 'modified' claim whose rehydration returned a reverted state # must be reclassified, never silently trusted. for c in plan.claims: if c.claim_type is ClaimType.MODIFIED: tag = f"read:{c.artifact}" if tag in executed_rehydrations and "reverted" in c.text.lower(): raise CompactionResumeError( f"Stale-state drift: summary claims '{c.text}' but artifact {c.artifact} " "was reverted pre-compaction; rebuild dependent decisions from ground truth." ) # --- Example: the observed incident --- if __name__ == "__main__": claims = [ SummaryClaim("token.py", ClaimType.MODIFIED, "updated token schema"), SummaryClaim("session.py", ClaimType.MODIFIED, "updated; second edit reverted first"), SummaryClaim("middleware.py", ClaimType.FAILED, "edit rejected: circular import"), SummaryClaim("migration_tool", ClaimType.CONSTRAINT, "--dry-run mutates lock file; non-idempotent", idempotent_action=False), ] plan = build_resume_plan(claims) # Agent skips rehydration and tries to act -> must hard-fail. try: assert_resume_safe(plan, executed_rehydrations=set()) except CompactionResumeError as e: print(f"BLOCKED: {e}") # After a full rehydration pass, the 'reverted' session.py claim still trips the guard. done = set(plan.rehydrate_targets) try: assert_resume_safe(plan, executed_rehydrations=done) except CompactionResumeError as e: print(f"BLOCKED (stale-state): {e}") ```