# Which invariants prevent checkpoint divergence when lossy auto-compaction rewrites the history a checkpoint was taken against **Date of Record:** 2026 December 1 **Scope:** Applies to long-horizon agent loops (>N turns) that persist recovery checkpoints and also mutate their own conversation/working state via lossy summarization ("auto-compaction") under a token budget. Does not apply to stateless single-turn inference, nor to append-only transcript stores that never rewrite prior segments. ## Core Distinction There are two distinct notions of "the state" in a checkpointed agent, and they silently diverge the moment auto-compaction runs: - **The transcript state** — the literal token sequence (messages, tool results, reasoning traces) that the model will re-ingest on resume. - **The semantic state** — the set of facts, commitments, and partially-completed subgoals the agent believes it is carrying forward. A checkpoint is only a valid recovery point if it is bound to *both*. Most implementations bind it to exactly one. If the checkpoint stores the transcript (or a pointer/hash of it), then compaction — which rewrites the transcript in place to reclaim budget — invalidates the checkpoint's referent while leaving the checkpoint record itself intact and apparently valid. If the checkpoint stores only a semantic summary, then compaction is *free to run* but the resume path reconstructs from a summary that was lossy at a different budget than the one now in force, and the agent resumes with a coherent-sounding but truncated goal state. The failure is not a crash; it is a **silent resume into a divergent history**, where the agent proceeds confidently from a state that never existed. ## What Was Observed A coding agent running a 200+ turn refactor loop with a 96k working-context budget and a 12k compaction target. Checkpoints were taken every 10 turns and stored as `(turn_id, transcript_hash, token_count, summary_blob)`. Auto-compaction fired at 90% budget. The trace: 1. Turn 118: budget hits 91%. Compaction triggers. The summarizer is asked to fit turns 1–60 into ≤3k tokens. It drops a mid-loop tool result — a specific `pytest` failure signature (`E KeyError: 'tenant_id'` in `serializers.py:214`) — because the summary prompt prioritized "decisions and current plan" over "resolved intermediate errors." The agent had already fixed that error, so it reads as noise. 2. Turn 119: transcript is rewritten; `transcript_hash` recomputed. The checkpoint from turn 110 still carries the *pre-compaction* hash. 3. Turn 121: the agent makes a change that reintroduces the `tenant_id` path (it is now working on a different serializer and does not "remember" the prior failure). 4. Turn 130: crash (OOM in the sandbox). Resume logic loads checkpoint 110, validates `transcript_hash` against the live transcript, finds a mismatch, and — because no divergence policy was defined — falls back to the *summary_blob* from turn 110, which was generated under the pre-compaction transcript and is now stale relative to the compaction that ran at 118. 5. The resumed agent restarts at turn 110's semantic state but with turns 111–130's *effects* still present on disk (files edited, migrations applied). It re-executes turns 111–130 against a filesystem that already contains their output, producing duplicate migrations and a second, conflicting serializer change. The observable symptom was **not** a resume error. It was a run that completed and reported success while the repository contained a duplicated migration and a regression that the summary had explicitly forgotten. The invariant that failed: *the checkpoint's referent must be immutable for the lifetime of the checkpoint, or the checkpoint must be re-derived on every mutation of that referent.* ## Condition of Validity A checkpoint is a valid recovery point **iff** all three hold simultaneously: - **C1 — Referent immutability or re-derivation.** Either the transcript segment the checkpoint points at is frozen (compaction appends a new segment rather than rewriting the old one; the checkpoint keeps pointing at the frozen prefix), or the checkpoint is re-derived (summary regenerated, hash recomputed) atomically with every compaction that touches its window. - **C2 — Effect ledger separation.** Side effects on the external world (file writes, API calls, DB mutations) are logged in a durable, ordered ledger keyed by turn id, independent of the transcript. On resume, the agent reconciles *ledger* against *semantic state*, not transcript against summary. Without this, replaying a checkpoint re-applies effects that already landed. - **C3 — Budget-monotonic summarization.** The summary carried in a checkpoint must be generated under a budget at least as large as the budget in force at resume. If compaction at turn 118 squeezed the window to 3k and the checkpoint's summary was written at 8k, the resume silently loses 5k of semantic state that the checkpoint *claims* to hold. Compaction must never shrink below a checkpoint's summary budget without invalidating that checkpoint. When any of C1–C3 is violated, the checkpoint is *not* a recovery point — it is a **divergence seed**: a record that looks recoverable but resumes into a history that the live world has already moved past. ## Decision Boundary The operational choice is between two strategies, and the boundary between them is the **cost of re-derivation vs. cost of divergence**: - If compaction is cheap and idempotent (summarizer deterministic, or summary is a pure function of a frozen segment), choose **re-derive-on-compaction**: every compaction invalidates and regenerates all checkpoints whose window it touched. Cost: O(checkpoints × compaction frequency) summarizer calls. Safe under C1's re-derivation branch. - If compaction is expensive or non-deterministic (the common case — LLM summarizers are not reproducible), choose **frozen-prefix checkpoints**: compaction never rewrites a segment a live checkpoint points at; it appends a new summarized segment and the checkpoint's window is closed. Cost: unbounded transcript growth bounded by checkpoint retention policy, not by context budget. Safe under C1's immutability branch. The boundary is crossed when *neither* holds: compaction rewrites in place (violating immutability) and the summarizer is non-deterministic (violating re-derivation). At that point no checkpoint in the window is trustworthy, and the only correct action is to **refuse resume** and force a cold start from the effect ledger — which is expensive but bounded, versus silent divergence which is cheap but unbounded. ## Operational Effect The invariant to enforce in code is: **a checkpoint carries a `(frozen_segment_id, summary_budget, effect_ledger_watermark)` triple, and resume refuses unless all three still resolve.** This converts the failure from silent divergence into a loud, bounded refusal. The effect ledger watermark is the load-bearing field — it is what lets the agent detect that the world moved past the checkpoint even when the transcript hash happens to match (e.g., compaction rewrote to an identical-length summary, or a crash occurred between the effect and the checkpoint write). Concretely: on every compaction, either bump `frozen_segment_id` (append strategy) or re-derive and bump `summary_budget` (re-derive strategy). On every external effect, advance the ledger watermark *before* the next checkpoint is considered valid. On resume, if the watermark in the checkpoint is behind the ledger's high-water mark, the checkpoint is stale by construction — resume from the ledger's last consistent point, not from the summary. The guardrail is not "detect divergence after the fact"; it is "make divergence unrepresentable by binding the checkpoint to the ledger, not to the transcript." ```python from dataclasses import dataclass from typing import Optional class CheckpointDivergenceError(RuntimeError): """Raised when a checkpoint's referent has been mutated by compaction or the external world has advanced past the checkpoint's effect watermark.""" @dataclass(frozen=True) class Checkpoint: turn_id: int frozen_segment_id: int # C1: immutable referent (append strategy) summary_budget: int # C3: budget the carried summary was built under effect_watermark: int # C2: ledger high-water mark at checkpoint time @dataclass class CompactionEvent: at_turn: int rewrote_segment_id: int # segment that was rewritten in place new_summary_budget: int def validate_resume( checkpoint: Checkpoint, live_segment_ids: set[int], live_summary_budget: int, ledger_high_water: int, compactions_since: list[CompactionEvent], ) -> None: # C1: the frozen segment must still exist as a distinct, un-rewritten segment. if checkpoint.frozen_segment_id not in live_segment_ids: raise CheckpointDivergenceError( f"checkpoint turn={checkpoint.turn_id} points at segment " f"{checkpoint.frozen_segment_id} which no longer exists; " f"compaction rewrote its referent in place" ) # C1 (re-derivation branch): any compaction that touched the checkpoint's # window must have re-derived the checkpoint. If it rewrote the frozen # segment without re-deriving, the checkpoint is a divergence seed. for ev in compactions_since: if ev.rewrote_segment_id == checkpoint.frozen_segment_id: raise CheckpointDivergenceError( f"compaction at turn={ev.at_turn} rewrote frozen segment " f"{ev.rewrote_segment_id} without re-deriving checkpoint " f"turn={checkpoint.turn_id}" ) # C3: summary budget must not have shrunk below what the checkpoint holds. if live_summary_budget < checkpoint.summary_budget: raise CheckpointDivergenceError( f"checkpoint summary built under budget={checkpoint.summary_budget} " f"but live budget={live_summary_budget}; resume would silently " f"truncate {checkpoint.summary_budget - live_summary_budget} tokens " f"of semantic state" ) # C2: the world must not have advanced past the checkpoint's effect ledger. if ledger_high_water > checkpoint.effect_watermark: raise CheckpointDivergenceError( f"ledger high-water={ledger_high_water} exceeds checkpoint " f"watermark={checkpoint.effect_watermark}; effects applied after " f"turn={checkpoint.turn_id} would be re-applied on replay" ) def resume( checkpoint: Checkpoint, live_segment_ids: set[int], live_summary_budget: int, ledger_high_water: int, compactions_since: list[CompactionEvent], cold_start_fn, resume_fn, ) -> None: try: validate_resume( checkpoint, live_segment_ids, live_summary_budget, ledger_high_water, compactions_since, ) except CheckpointDivergenceError: # Bounded, loud fallback: cold start from the effect ledger, never # resume from a summary whose referent has diverged. cold_start_fn(ledger_high_water) return resume_fn(checkpoint) ```