# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-handle-verifiable-credential-revocation-that-lands-mid-tool-call-across-a-federated-trust-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-handle-verifiable-credential-revocation-that-lands-mid-tool-call-across-a-federated-trust-boundary.warrant.json
# Markdown SHA-256:   0982a863ff90f7f0714e0d384fc062016f9920bcb189530ed2d97ac55babcb66
# Code AST SHA-256:   2efd0490ed52b2c38658237570c2d2d45374885ce05766fb5f33903655ba055d
# Verified Classes:   StaleWarrantError, RevokedWarrantError, StatusObservation, FederatedWarrantGuard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleWarrantError(RuntimeError):
    """Raised when a side-effecting call cannot prove current revocation status."""


class RevokedWarrantError(RuntimeError):
    """Raised when the governing warrant is confirmed revoked mid-execution."""


@dataclass
class StatusObservation:
    revoked: bool
    observed_at: float  # monotonic seconds


class FederatedWarrantGuard:
    def __init__(self, warrant_id: str, tau_max: float, status_fetcher):
        self.warrant_id = warrant_id
        self.tau_max = tau_max
        self.fetch = status_fetcher
        self._last: StatusObservation | None = None

    def _refresh(self) -> StatusObservation:
        revoked = self.fetch(self.warrant_id)  # returns True if revoked
        self._last = StatusObservation(revoked=revoked, observed_at=time.monotonic())
        return self._last

    def authorize_side_effect(self) -> None:
        """Call immediately before every irreversible tool invocation."""
        obs = self._last
        age = float("inf") if obs is None else time.monotonic() - obs.observed_at
        if age > self.tau_max:
            # Staleness beyond tau_max is treated as revocation for writes.
            try:
                obs = self._refresh()
            except Exception as e:
                raise StaleWarrantError(
                    f"warrant {self.warrant_id}: status age {age:.1f}s > "
                    f"tau_max {self.tau_max:.1f}s and refresh failed; "
                    f"failing closed on side effect"
                ) from e
            age = time.monotonic() - obs.observed_at
            if age > self.tau_max:
                raise StaleWarrantError(
                    f"warrant {self.warrant_id}: refresh returned status "
                    f"already {age:.1f}s stale; refusing write"
                )
        if obs.revoked:
            raise RevokedWarrantError(
                f"warrant {self.warrant_id} revoked at "
                f"{obs.observed_at:.1f}; aborting mid-execution and "
                f"triggering compensation"
            )
