# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revocation-that-arrived-after-it-already-acted-on-delegated-authority.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revocation-that-arrived-after-it-already-acted-on-delegated-authority.warrant.json
# Markdown SHA-256:   e1c6c47e2f988824d0d8c27e70963a04019347e797de302c6f016728b483356a
# Code AST SHA-256:   eea76d65daf746553a1002d92513c7339894d0ed47d49f578e9d28830a869fca
# Verified Classes:   StaleAuthorityError, IssuerUnreachableError, Warrant, RevocationRegistry, ToolGateway
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Dict, Optional


class StaleAuthorityError(RuntimeError):
    """Raised when an irreversible action is attempted under a warrant whose
    revocation epoch is older than the gateway's current epoch."""
    pass


class IssuerUnreachableError(RuntimeError):
    """Raised when commit-time revalidation cannot reach the issuer and the
    action is irreversible; the delegate must fail closed."""
    pass


@dataclass
class Warrant:
    warrant_id: str
    scope: str
    issuer: str
    issued_epoch: int
    revoked: bool = False


@dataclass
class RevocationRegistry:
    """Issuer-side source of truth. Epoch increments on every revocation."""
    epoch: int = 1
    revoked_ids: Dict[str, int] = field(default_factory=dict)

    def revoke(self, warrant_id: str) -> None:
        self.epoch += 1
        self.revoked_ids[warrant_id] = self.epoch


@dataclass
class ToolGateway:
    registry: RevocationRegistry
    cache_refresh_s: float = 60.0
    _cached_epoch: int = 0
    _cached_at: float = 0.0

    def _current_epoch(self, now: float) -> int:
        # Simulates a cached revocation list; the cache is the bug surface.
        if now - self._cached_at > self.cache_refresh_s:
            self._cached_epoch = self.registry.epoch
            self._cached_at = now
        return self._cached_epoch

    def commit(self, warrant: Warrant, action: str, irreversible: bool,
               now: float, issuer_reachable: bool = True) -> str:
        if irreversible:
            if not issuer_reachable:
                raise IssuerUnreachableError(
                    f"cannot revalidate {warrant.warrant_id} for irreversible "
                    f"action {action!r}; failing closed"
                )
            # Commit-time revalidation: bypass cache, read registry directly.
            live_epoch = self.registry.epoch
        else:
            live_epoch = self._current_epoch(now)

        if warrant.warrant_id in self.registry.revoked_ids:
            rev_epoch = self.registry.revoked_ids[warrant.warrant_id]
            if live_epoch >= rev_epoch:
                raise StaleAuthorityError(
                    f"warrant {warrant.warrant_id} revoked at epoch {rev_epoch}, "
                    f"gateway epoch {live_epoch}; action {action!r} blocked"
                )
        # Bind the authorizing epoch into the audit record.
        return f"committed {action!r} under {warrant.warrant_id}@epoch{live_epoch}"


def simulate_revocation_window() -> None:
    reg = RevocationRegistry()
    gw = ToolGateway(registry=reg, cache_refresh_s=60.0)
    w2 = Warrant("W2", "write:orders[sku=4471]", "A", issued_epoch=1)

    # t=12s: B validates on plan entry; gateway caches epoch 1.
    gw.commit(w2, "read:inventory", irreversible=False, now=12.0)
    # t=95s: P revokes W1 -> registry epoch becomes 2.
    reg.revoke("W1")
    # t=101s: B attempts the irreversible commit. Gateway cache still epoch 1
    # for reversible path, but irreversible path reads live epoch 2 -> blocked.
    try:
        gw.commit(w2, "write:order:4471", irreversible=True, now=101.0)
    except StaleAuthorityError as e:
        print(f"BLOCKED (correct): {e}")
        return
    raise AssertionError("irreversible action should have been blocked")


if __name__ == "__main__":
    simulate_revocation_window()
