# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-when-lossy-summarization-has-crossed-the-recovery-checkpoint-boundary-in-long-horizon-agent-sessions.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-when-lossy-summarization-has-crossed-the-recovery-checkpoint-boundary-in-long-horizon-agent-sessions.warrant.json
# Markdown SHA-256:   cb4725e7820c6696847f85b148f1cabe01b54088db2a093334bf02c0e7564f27
# Code AST SHA-256:   48fe3acb05ae325a89803f943faeb399856b72bf6fa607608b172d5cf624e834
# Verified Classes:   RecoveryBoundaryError, CompactionEvent, CheckpointEvent, IrreversibleAction, SessionState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class RecoveryBoundaryError(RuntimeError):
    """Raised when a session has crossed the checkpoint-recovery boundary."""
    pass


@dataclass
class CompactionEvent:
    turn: int
    tokens_removed: int


@dataclass
class CheckpointEvent:
    turn: int


@dataclass
class IrreversibleAction:
    turn: int
    description: str


@dataclass
class SessionState:
    compactions: list = field(default_factory=list)
    checkpoints: list = field(default_factory=list)
    actions: list = field(default_factory=list)
    summary_anchors: set = field(default_factory=set)
    retained_anchors: set = field(default_factory=set)
    budget_headroom: Optional[int] = None
    rederive_cost: Optional[int] = None


def assert_recoverable(state: SessionState) -> None:
    """Verify the session has not crossed the recovery boundary.

    Raises RecoveryBoundaryError on the first violated invariant.
    """
    # Invariant 1: at most one compaction between consecutive checkpoints.
    turns = sorted([("c", e.turn) for e in state.checkpoints] +
                   [("k", e.turn) for e in state.compactions])
    compactions_since_checkpoint = 0
    for kind, _ in turns:
        if kind == "c":
            compactions_since_checkpoint = 0
        else:
            compactions_since_checkpoint += 1
            if compactions_since_checkpoint > 1:
                raise RecoveryBoundaryError(
                    f"compaction-to-checkpoint ratio exceeded 1.0 at turn {_}; "
                    "compounded summarization loss makes rollback unsound"
                )

    # Invariant 2: no irreversible action in the compaction-checkpoint gap.
    if state.checkpoints:
        last_cp = max(e.turn for e in state.checkpoints)
        last_comp = max((e.turn for e in state.compactions), default=-1)
        for act in state.actions:
            if last_comp < act.turn < last_cp:
                raise RecoveryBoundaryError(
                    f"irreversible action '{act.description}' at turn {act.turn} "
                    f"falls between compaction ({last_comp}) and checkpoint ({last_cp}); "
                    "rollback would discard its record while the action persists"
                )

    # Invariant 3: budget headroom must cover re-derivation cost.
    if (state.budget_headroom is not None and state.rederive_cost is not None
            and state.budget_headroom < state.rederive_cost):
        raise RecoveryBoundaryError(
            f"summarization headroom {state.budget_headroom} below re-derivation "
            f"cost {state.rederive_cost}; recovery would require evicted raw history"
        )

    # Invariant 4: every summary anchor must resolve to a retained window.
    orphaned = state.summary_anchors - state.retained_anchors
    if orphaned:
        raise RecoveryBoundaryError(
            f"orphaned summary anchors (no retained raw backing): {sorted(orphaned)}; "
            "agent would act on paraphrase where drift accumulates"
        )
