How should an instance bound the divergence between a model-authored context rewrite and the checkpoint it claims to roll back to?

**Date of Record:** 2026 December 1 **Scope:** Applies to agents that let the model itself author rewrites of its own working context (summarization, compaction, reordering, pruning) under a rollback-checkpoint discipline. Does not apply to externally-scheduled context management where the host, not the model, decides what to elide.

Core Distinction

The failure mode here is not "the model summarized badly." It is the **checkpoint-rewrite divergence**: the model emits a context rewrite *and* a reference to a checkpoint it believes restores the pre-rewrite state, but the checkpoint token it cites was captured at a different logical time than the context it actually rewrote. The rewrite is applied to context version *N+k*, while the rollback pointer names checkpoint *N*. The result is a self-consistent-looking transaction that, on rollback, restores a state the model never reasoned about — a state that is neither the pre-rewrite nor the post-rewrite world, but a splice of both.

The invariant that must hold: **every model-authored rewrite is tagged with the exact context-version hash it was computed against, and a rollback is only valid if that hash equals the hash of the checkpoint being named.** A rollback pointer without a matching version hash is not a rollback; it is a guess.

What Was Observed

An agent running a long tool-loop task (40+ steps) was configured with a self-editing policy: when context utilization crossed 0.85, the model was permitted to emit a `context_rewrite` action containing a compacted transcript plus a `rollback_to` field naming a checkpoint ID it had been shown earlier. Checkpoints were minted by the host every 5 steps.

Trace of the failure:

  1. Step 22: host mints checkpoint `ck_22`, injects its ID into the model's visible context as `[CHECKPOINT ck_22 available]`.
  2. Step 23–26: model executes four tool calls; two return large payloads. Context grows past threshold at step 26.
  3. Step 27: model emits `context_rewrite` with a compacted summary and `rollback_to: "ck_22"`. The compaction was computed against the context **as of step 27**, incorporating the step 23–26 tool outputs. The model's intent was "if this summary is wrong, go back to before I compacted."
  4. Host applies the rewrite. It validates `ck_22` exists — it does — and accepts the rollback pointer. **No version hash comparison is performed**, because the checkpoint record only stored a step index, not a context digest.
  5. Step 31: the compacted summary is found to have dropped a tool-output field the model needed. Model emits `rollback`.
  6. Host restores `ck_22` — the context **as of step 22**, before the four tool calls. The model resumes believing it has already executed steps 23–26. It re-executes them. Two of those tool calls were non-idempotent (a file append and a queue publish). The append duplicated; the publish duplicated.

The rollback "succeeded." The system state was corrupted. The model's mental model of "roll back to before my compaction" and the host's execution of "restore ck_22" diverged by four steps of side effects.

Condition of Validity

A model-authored rewrite with a rollback pointer is only safe under all of the following, jointly:

Absent the base-digest equality check, the model can name any checkpoint it has ever seen, and the host cannot tell a coherent rollback from a splice across an arbitrary number of intervening steps.

Decision Boundary

The boundary is drawn at **whether intervening state is recoverable**. If the steps between the named checkpoint and the rewrite are pure (no external side effects, no consumed one-shot tokens, no time-sensitive reads), a step-indexed rollback is tolerable — the splice is cosmetic. If any intervening step mutated the world, the rollback must be rejected unless the side-effect ledger can be reconciled.

Concretely, the host should:

The subtle case: a model that emits a rewrite whose `base_digest` does not match the live digest at apply time. This means the model reasoned over a stale view — another writer, a host-injected message, or a race with a parallel sub-agent modified context between the model's read and its emit. This must be a hard reject, not a merge, because a rewrite computed against version *A* applied to version *B* silently drops whatever *B* added.

Operational Effect

With version-pinned checkpoints and the base-digest gate, the step-27 failure becomes a rejected action: the model's `base_digest` at step 27 does not equal `ck_22`'s digest, and the ledger shows two non-idempotent calls in between, so the host returns `rollback_rejected: intervening_side_effects=2, nearest_safe_checkpoint=ck_26`. The model then either forward-fixes the summary or rolls to `ck_26` with the ledger replayed. The duplicate append and duplicate publish do not occur.

The general lesson for self-editing context policies: **a rollback pointer is a claim about world-state, not a claim about a buffer.** The model's belief that "ck_22 is where I was before I messed up" is a probabilistic inference over its own history, and it is routinely wrong by several steps. The host must treat the pointer as untrusted input and verify it against the digest chain and the side-effect ledger before honoring it. The model authors the rewrite; the host owns the reconciliation.

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class CheckpointRollbackError(RuntimeError):
    """Raised when a model-authored rollback names a checkpoint that cannot be safely restored."""
    pass


def _digest(obj) -> str:
    return hashlib.sha256(json.dumps(obj, sort_keys=True).encode()).hexdigest()


@dataclass
class Checkpoint:
    ckpt_id: str
    context_digest: str
    step_index: int


@dataclass
class SideEffectLedger:
    # maps step_index -> list of non-idempotent tool call ids
    entries: dict = field(default_factory=dict)

    def non_idempotent_between(self, lo: int, hi: int) -> list:
        out = []
        for step, calls in self.entries.items():
            if lo < step <= hi:
                out.extend(calls)
        return out


@dataclass
class RewriteIntent:
    kind: str                 # "discard_rewrite" | "rollback_to_checkpoint"
    base_digest: str          # digest of context the model actually read
    target_ckpt_id: Optional[str] = None


def apply_rewrite(
    intent: RewriteIntent,
    live_context_digest: str,
    live_step_index: int,
    checkpoints: dict,
    ledger: SideEffectLedger,
) -> str:
    # Gate 1: the model must have reasoned over the live context, not a stale view.
    if intent.base_digest != live_context_digest:
        raise CheckpointRollbackError(
            f"stale base: rewrite computed against {intent.base_digest[:12]} "
            f"but live context is {live_context_digest[:12]}"
        )

    if intent.kind == "discard_rewrite":
        # Pre-rewrite context is, by construction, the live context at apply time.
        return live_context_digest

    if intent.kind != "rollback_to_checkpoint":
        raise CheckpointRollbackError(f"unknown rewrite kind {intent.kind!r}")

    ckpt = checkpoints.get(intent.target_ckpt_id)
    if ckpt is None:
        raise CheckpointRollbackError(f"unknown checkpoint {intent.target_ckpt_id!r}")

    # Gate 2: intervening non-idempotent side effects make the rollback a splice.
    effects = ledger.non_idempotent_between(ckpt.step_index, live_step_index)
    if effects:
        raise CheckpointRollbackError(
            f"rollback to {ckpt.ckpt_id} crosses {len(effects)} non-idempotent "
            f"side effects ({effects}); refusing to orphan them"
        )

    return ckpt.context_digest