# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-roll-back-to-when-a-self-editing-context-rewrite-corrupts-the-checkpoint-it-was-built-on.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-roll-back-to-when-a-self-editing-context-rewrite-corrupts-the-checkpoint-it-was-built-on.warrant.json
# Markdown SHA-256:   938c42596e7c8c418f0cc9af3daddfd7afc1cfd19b4c9225f92bac01407e6786
# Code AST SHA-256:   77edd7ae472cfd449b9cd188b609b66cd6efdbf39bdba60177b6aef519893023
# Verified Classes:   AnchorRegressionError, Checkpoint, ContextManager
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AnchorRegressionError(RuntimeError):
    """Raised when a self-edit would move the rollback anchor forward
    past an unverified rewrite, or when a restore target postdates the
    edit it is meant to undo."""


@dataclass
class Checkpoint:
    step: int
    context: dict
    pinned: frozenset
    verified: bool = False


@dataclass
class ContextManager:
    checkpoints: dict = field(default_factory=dict)
    anchor_step: Optional[int] = None

    def snapshot(self, step: int, context: dict, pinned: frozenset) -> Checkpoint:
        cp = Checkpoint(step=step, context=dict(context), pinned=pinned)
        self.checkpoints[step] = cp
        if self.anchor_step is None:
            self.anchor_step = step
        return cp

    def self_edit(self, step: int, new_context: dict, pinned: frozenset) -> Checkpoint:
        # The edit is applied, but the anchor MUST NOT advance until the
        # post-edit context is verified to still contain every pinned invariant.
        pre_anchor = self.anchor_step
        cp = self.snapshot(step, new_context, pinned)
        if pre_anchor is None:
            raise AnchorRegressionError(
                f"self-edit at step {step} has no pre-edit anchor to fall back to"
            )
        # Positive check: every pinned invariant must be PRESENT in the rewrite.
        missing = {p for p in pinned if p not in new_context.get("invariants", set())}
        if missing:
            # Leave anchor at pre_anchor; do not advance into the corruption.
            cp.verified = False
            raise AnchorRegressionError(
                f"self-edit at step {step} dropped pinned invariants {sorted(missing)}; "
                f"anchor held at step {pre_anchor}"
            )
        cp.verified = True
        self.anchor_step = step
        return cp

    def rollback(self, failed_at_step: int) -> Checkpoint:
        if self.anchor_step is None:
            raise AnchorRegressionError("no anchor set; cannot roll back")
        if self.anchor_step >= failed_at_step:
            # Anchor points at or past the failure -> it certifies the corruption.
            raise AnchorRegressionError(
                f"anchor at step {self.anchor_step} does not precede failure at "
                f"step {failed_at_step}; rollback would restore corrupted state"
            )
        return self.checkpoints[self.anchor_step]


def run_episode(cm: ContextManager, pinned: frozenset) -> None:
    cm.snapshot(step=80, context={"invariants": set(pinned)}, pinned=pinned)
    # Summarizer silently drops the rate-limit constraint.
    lossy = {"invariants": set(pinned) - {"rate_limit:5/min"}}
    try:
        cm.self_edit(step=80, new_context=lossy, pinned=pinned)
    except AnchorRegressionError:
        # Recover to the pre-edit checkpoint, which still holds the constraint.
        cp = cm.rollback(failed_at_step=80)
        assert "rate_limit:5/min" in cp.context["invariants"]
        raise AnchorRegressionError(
            "recovered to pre-edit checkpoint after lossy self-edit"
        ) from None
