# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-keep-executing-revoked-tool-calls-after-a-federated-aaif-revocation-sweep.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-keep-executing-revoked-tool-calls-after-a-federated-aaif-revocation-sweep.warrant.json
# Markdown SHA-256:   bb3b79b32a9cb1e6543fda9dae8d7952782650d7136df7b1383116a2f21cccc6
# Code AST SHA-256:   5751f0c859eeeae5885858acd935334f936ce636991da1a6ee09ef89ade5ec87
# Verified Classes:   StaleEpochLeaseError, Warrant, EpochLease, PolicyEnforcementPoint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleEpochLeaseError(RuntimeError):
    """Raised when a PEP attempts to enforce a warrant without a current epoch lease."""
    pass


@dataclass
class Warrant:
    agent_id: str
    tool: str
    args_hash: str
    policy_epoch: int
    expiry: float


@dataclass
class EpochLease:
    epoch: int
    valid_until: float


class PolicyEnforcementPoint:
    def __init__(self, pep_id: str, lease: EpochLease):
        self.pep_id = pep_id
        self.lease = lease

    def _assert_lease_current(self, now: float) -> None:
        # Guardrail invariant: no execution past lease expiry, regardless of warrant.
        if now > self.lease.valid_until:
            raise StaleEpochLeaseError(
                f"PEP {self.pep_id}: epoch lease expired at {self.lease.valid_until} "
                f"(now={now}); refusing all tool execution until renewed. "
                f"Cannot prove currency for epoch {self.lease.epoch}."
            )

    def renew_lease(self, new_lease: EpochLease) -> None:
        # Monotonic adoption: never regress the epoch.
        if new_lease.epoch < self.lease.epoch:
            raise StaleEpochLeaseError(
                f"PEP {self.pep_id}: refusing epoch regression "
                f"{self.lease.epoch} -> {new_lease.epoch}"
            )
        self.lease = new_lease

    def authorize(self, warrant: Warrant, args_hash: str, now: float) -> bool:
        self._assert_lease_current(now)

        if warrant.policy_epoch != self.lease.epoch:
            # Covers both stale (older) and future (unparseable) epochs.
            return False
        if warrant.policy_epoch > self.lease.epoch:
            raise StaleEpochLeaseError(
                f"PEP {self.pep_id}: warrant epoch {warrant.policy_epoch} "
                f"ahead of local {self.lease.epoch}"
            )
        if now >= warrant.expiry:
            return False
        if warrant.args_hash != args_hash:
            return False
        return True


def execute_tool(pep: PolicyEnforcementPoint, warrant: Warrant,
                 args_hash: str, now: float) -> str:
    if not pep.authorize(warrant, args_hash, now):
        return "DENIED"
    return f"EXECUTED {warrant.tool} for {warrant.agent_id}"


if __name__ == "__main__":
    # Scenario reproduction: PEP missed the 4411 -> 4412 revocation bump.
    pep = PolicyEnforcementPoint("pep-stale", EpochLease(epoch=4411, valid_until=1000.0))
    w = Warrant("agent-17", "deploy", "abc123", policy_epoch=4411, expiry=1026.0)

    # Within lease: old-epoch warrant still passes (the bug's window).
    print(execute_tool(pep, w, "abc123", now=1005.0))  # EXECUTED

    # Past lease: PEP self-fails-closed even though warrant is unexpired.
    try:
        execute_tool(pep, w, "abc123", now=1001.0 + 1.0)  # lease.valid_until=1000 -> expired
    except StaleEpochLeaseError as e:
        print(f"BLOCKED: {e}")
