# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-stale-capability-warrants-from-surviving-a-mid-swarm-revocation-the-monotonic-epoch-fence-and-its-handoff-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-stale-capability-warrants-from-surviving-a-mid-swarm-revocation-the-monotonic-epoch-fence-and-its-handoff-gap.warrant.json
# Markdown SHA-256:   635bb7c1491a1709269087e2a6a08f4889d04456a043f97b74a70f7039afa3fe
# Code AST SHA-256:   9c7a5bff71d64e21a9e2fe8aafc5ad23c127ca254940f5ee8d044b664fb556e2
# Verified Classes:   StaleWarrantError, Warrant, PeerAuthority
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class StaleWarrantError(RuntimeError):
    """Raised when a warrant's epoch cannot be proven to postdate the last observed revocation."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    epoch: int          # logical counter from root authority, not wall-clock
    ttl_seconds: int


class PeerAuthority:
    def __init__(self, root_check, delta_allow: int):
        self._root_check = root_check      # callable(warrant_id) -> bool
        self._delta_allow = delta_allow
        self._watermark = 0                # max revocation epoch observed; never regresses

    def observe_revocation(self, epoch: int) -> None:
        # Idempotent, monotonic: out-of-order revokes converge to max, never regress.
        if epoch > self._watermark:
            self._watermark = epoch

    def authorize(self, w: Warrant, now_epoch: int) -> None:
        # Fail-closed on uncertainty: if the warrant is too far ahead of our
        # watermark, we cannot prove it postdates the last revocation we know of.
        if w.epoch - self._watermark > self._delta_allow:
            if not self._root_check(w.warrant_id):
                raise StaleWarrantError(
                    f"warrant {w.warrant_id} (epoch={w.epoch}) failed synchronous "
                    f"root check against watermark={self._watermark}"
                )
            # Root confirmed; adopt the confirmed epoch as a floor.
            self.observe_revocation(w.epoch)
            return

        # Strict comparison: a warrant at or below the watermark is stale by
        # definition (it may be the very warrant that was revoked).
        if w.epoch <= self._watermark:
            raise StaleWarrantError(
                f"warrant {w.warrant_id} (epoch={w.epoch}) is not strictly greater "
                f"than revocation watermark={self._watermark}"
            )

    def execute_handoff(self, w: Warrant, now_epoch: int, action) -> None:
        # Re-validate at execution time, not receipt time: queued handoffs go stale.
        self.authorize(w, now_epoch)
        return action()
