# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-from-a-compacted-checkpoint-the-replay-divergence-invariant-in-lossy-auto-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-from-a-compacted-checkpoint-the-replay-divergence-invariant-in-lossy-auto-compaction.warrant.json
# Markdown SHA-256:   3c9ff4c442ac7786adba903f6a50128e970effe59a6ed3a875b37579e77f9d88
# Code AST SHA-256:   0e9bbf5ab5281c3504b66c7f2a3c5c2b52e7749e911923a3f5bf11344521ed7b
# Verified Classes:   DivergentResumeError, Checkpoint, TailEvent
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DivergentResumeError(RuntimeError):
    """Raised when a compacted checkpoint cannot be safely resumed."""
    pass


@dataclass
class Checkpoint:
    summary: str
    provenance: tuple[int, int]          # turn range this summary covers
    commitments: dict[int, dict]         # monotonic id -> structured side effect
    tail_start_turn: int


@dataclass
class TailEvent:
    turn: int
    kind: str                            # "revert" | "write" | "assert" | ...
    target: str
    supersedes: Optional[int] = None     # commitment id this event undoes


def assert_resumable(cp: Checkpoint, tail: list[TailEvent]) -> None:
    # Invariant 1: provenance must be strictly older than the tail.
    if cp.provenance[1] >= cp.tail_start_turn:
        raise DivergentResumeError(
            f"checkpoint provenance ends at turn {cp.provenance[1]} "
            f"but tail starts at {cp.tail_start_turn}; ranges overlap"
        )

    # Invariant 2: no tail event may contradict a live commitment.
    live = {cid: c for cid, c in cp.commitments.items() if not c.get("superseded")}
    for ev in tail:
        if ev.supersedes is not None:
            if ev.supersedes not in live:
                raise DivergentResumeError(
                    f"tail event at turn {ev.turn} supersedes commitment "
                    f"{ev.supersedes}, which is not live in checkpoint; "
                    f"checkpoint is stale relative to tail"
                )
            # Contradiction: summary asserted this commitment as current,
            # tail reverts it. Must regenerate, not reconcile by salience.
            raise DivergentResumeError(
                f"checkpoint/tail contradiction: commitment {ev.supersedes} "
                f"({live[ev.supersedes]['op']} {live[ev.supersedes]['target']}) "
                f"is reverted at turn {ev.turn}; checkpoint must be regenerated "
                f"before resume"
            )


def resume(cp: Checkpoint, tail: list[TailEvent]) -> str:
    assert_resumable(cp, tail)
    return f"resumed from turn {cp.tail_start_turn} with {len(tail)} tail events"
