# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-acquire-a-delegation-warrant-mid-handoff-the-re-evaluation-race-at-the-a2a-authorization-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-acquire-a-delegation-warrant-mid-handoff-the-re-evaluation-race-at-the-a2a-authorization-boundary.warrant.json
# Markdown SHA-256:   bc1004286d57b80ceea323349ce681f74fac5121f83ebddb3e76979377f610f5
# Code AST SHA-256:   6b69100e82084d21d8dc4bda7b2b6bcf695c3d6b2f4bbd298fd05ca95ba9748f
# Verified Classes:   StaleAuthorizationError, ReEvalResponse, WarrantGuard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleAuthorizationError(RuntimeError):
    """Raised when an action is attempted under a warrant whose last
    confirmed decision epoch is behind the known authoritative watermark,
    or whose confirmation has aged past the grace window."""


@dataclass(frozen=True)
class ReEvalResponse:
    authorized: bool
    decision_epoch: int
    observed_at: float  # monotonic seconds


class WarrantGuard:
    def __init__(self, grace_window_s: float = 5.0):
        self.grace_window_s = grace_window_s
        self._known_watermark: int = -1  # highest epoch known committed

    def observe_watermark(self, epoch: int) -> None:
        # Fed by push channel / quorum read / peer response.
        if epoch > self._known_watermark:
            self._known_watermark = epoch

    def check_consequential_action(
        self, resp: ReEvalResponse, now: float, action: str
    ) -> None:
        if not resp.authorized:
            raise StaleAuthorizationError(
                f"action {action!r} denied: engine returned authorized=false "
                f"at epoch {resp.decision_epoch}"
            )
        if resp.decision_epoch < self._known_watermark:
            raise StaleAuthorizationError(
                f"action {action!r} denied: stale echo at epoch "
                f"{resp.decision_epoch} < watermark {self._known_watermark} "
                f"(possible replica lag / unpropagated revocation)"
            )
        age = now - resp.observed_at
        if age > self.grace_window_s:
            raise StaleAuthorizationError(
                f"action {action!r} denied: confirmation age {age:.2f}s "
                f"exceeds grace window {self.grace_window_s:.2f}s"
            )
        # REMI satisfied: authorized, epoch >= watermark, within grace.
        return None


# --- incident replay ---
guard = WarrantGuard(grace_window_s=5.0)
t0 = time.monotonic()

# T=45s: revocation push arrives, watermark advances.
guard.observe_watermark(4411)

# T=60s: W polls a lagging replica, gets a stale authorized=true.
stale = ReEvalResponse(authorized=True, decision_epoch=4410, observed_at=t0 + 60.0)

try:
    guard.check_consequential_action(stale, now=t0 + 60.0, action="mutate:dataset")
except StaleAuthorizationError as e:
    print(f"SUSPEND + CHECKPOINT: {e}")
    # Correct behavior: checkpoint task, request fresh warrant mint,
    # do NOT commit the batch write.
