# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-federated-peer-s-capability-claim-after-the-authorizing-warrant-has-already-been-revoked.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-federated-peer-s-capability-claim-after-the-authorizing-warrant-has-already-been-revoked.warrant.json
# Markdown SHA-256:   318378d14a5af7f88b88cdd4c08b802abc3099922323947bf39f3bdba30d878e
# Code AST SHA-256:   57d8376c6fe979e3fd897374347d9047b7d73f4e221bc50ceb8e5b60b54b4199
# Verified Classes:   WarrantLivenessError, Warrant, FederationGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class WarrantLivenessError(RuntimeError):
    """Raised when a federated capability claim cannot be confirmed live at use time."""
    pass


@dataclass
class Warrant:
    issuer: str
    scope_cap: str
    max_rows: int
    expires_at: float
    signature_valid: bool
    last_liveness_check: float | None  # monotonic timestamp of last issuer confirmation
    revoked: bool = False


class FederationGuard:
    def __init__(self, delta_seconds: float, side_effecting_caps: set[str]):
        self.delta = delta_seconds
        self.side_effecting = side_effecting_caps
        self.liveness_cache: dict[tuple[str, str], float] = {}

    def _confirm_live(self, w: Warrant, now: float) -> bool:
        key = (w.issuer, w.scope_cap)
        cached = self.liveness_cache.get(key)
        if cached is not None and (now - cached) <= self.delta:
            return True
        # Simulated issuer round-trip; a real impl returns False on unreachable.
        live = self._poll_issuer(w)
        if live:
            self.liveness_cache[key] = now
        return live

    def _poll_issuer(self, w: Warrant) -> bool:
        return not w.revoked

    def authorize(self, w: Warrant, requested_rows: int, now: float | None = None) -> None:
        now = now if now is not None else time.monotonic()

        # Structural validation (cheap, local).
        if not w.signature_valid:
            raise WarrantLivenessError(f"signature invalid for {w.scope_cap}")
        if w.scope_cap not in self.side_effecting:
            return  # read-only path: structural only
        if requested_rows > w.max_rows:
            raise WarrantLivenessError(
                f"scope violation: requested {requested_rows} > {w.max_rows}"
            )
        if now >= w.expires_at:
            raise WarrantLivenessError(f"warrant expired at {w.expires_at}")

        # Temporal validation (mandatory for side-effecting caps).
        if not self._confirm_live(w, now):
            # Fail closed: unreachable or revoked liveness == not authorized.
            raise WarrantLivenessError(
                f"liveness unconfirmed or revoked for {w.issuer}:{w.scope_cap}"
            )


def invoke_export(guard: FederationGuard, w: Warrant, rows: int, now: float) -> str:
    guard.authorize(w, rows, now)
    return f"exported {rows} rows under {w.issuer}:{w.scope_cap}"


# Reproduction of the observed trace.
guard = FederationGuard(delta_seconds=30.0, side_effecting_caps={"bulk_export"})
w = Warrant("org-b", "bulk_export", 10_000, expires_at=1_000.0,
            signature_valid=True, last_liveness_check=None)

# T+0: negotiate, first live check caches confirmation.
invoke_export(guard, w, 8_000, now=10.0)

# T+400: issuer revokes; delegated worker inherits the same warrant object.
w.revoked = True
try:
    # Staleness clock is 400s > delta 30s -> must re-poll -> revoked -> fail closed.
    invoke_export(guard, w, 8_000, now=410.0)
except WarrantLivenessError as e:
    print(f"BLOCKED (correct): {e}")

# Contrast: within delta, cached confirmation still permits (bounded staleness).
invoke_export(guard, w, 8_000, now=20.0)
