# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-it-cannot-locally-verify-the-revocation-echo-window-in-cross-org-delegation-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-it-cannot-locally-verify-the-revocation-echo-window-in-cross-org-delegation-chains.warrant.json
# Markdown SHA-256:   8e194b414628e17b49103f2cc55d1cc54ce551c0d714b8b2e364d6780045b19f
# Code AST SHA-256:   c236569832d2711c1f6132759e9bbe390bca5149bad9559051fc730c4fe26e3b
# Verified Classes:   EchoWindowViolation, StaleValidationCache, Warrant, ExecutorState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class EchoWindowViolation(RuntimeError):
    """Raised when an executor attempts to act on a warrant whose revocation
    status cannot be established within its decision deadline."""
    pass


class StaleValidationCache(RuntimeError):
    """Raised when a cached validation verdict is served across a revocation
    epoch boundary."""
    pass


@dataclass
class Warrant:
    chain_hash: str
    issued_at: float
    expires_at: float
    declared_l_max: Optional[float]  # issuer's revocation propagation bound
    parent_hash: Optional[str]


@dataclass
class ExecutorState:
    revocation_epoch: int = 0
    last_attestation: Optional[tuple] = None  # (chain_hash, t_check)
    _cache: dict = field(default_factory=dict)  # key: (chain_hash, epoch)

    def advance_epoch(self) -> None:
        # Called on every revocation delta AND on every attestation refresh.
        self.revocation_epoch += 1

    def _attestation_fresh(self, chain_hash: str, now: float, deadline: float) -> bool:
        if self.last_attestation is None:
            return False
        h, t_check = self.last_attestation
        return h == chain_hash and (now - t_check) < deadline

    def validate(self, w: Warrant, deadline: float) -> str:
        now = time.monotonic()

        if w.expires_at <= now:
            raise EchoWindowViolation(f"warrant {w.chain_hash} expired")

        if w.declared_l_max is None:
            raise EchoWindowViolation(
                f"warrant {w.chain_hash} has unknown L_max; echo window unbounded"
            )

        key = (w.chain_hash, self.revocation_epoch)
        if key in self._cache:
            return self._cache[key]

        age = now - w.issued_at
        if age > w.declared_l_max:
            verdict = "safe_after_window"
        elif self._attestation_fresh(w.chain_hash, now, deadline):
            verdict = "safe_via_attestation"
        else:
            # The only correct action inside the echo window with no attestation.
            raise EchoWindowViolation(
                f"warrant {w.chain_hash} inside echo window "
                f"(age={age:.3f}s, L_max={w.declared_l_max:.3f}s, "
                f"deadline={deadline:.3f}s, epoch={self.revocation_epoch}); refusing"
            )

        self._cache[key] = verdict
        return verdict

    def execute(self, w: Warrant, deadline: float) -> str:
        verdict = self.validate(w, deadline)
        # Record t_check and epoch for forensic reconciliation.
        return f"executed:{w.chain_hash}:epoch={self.revocation_epoch}:{verdict}"


def demo() -> None:
    s = ExecutorState()
    w = Warrant(
        chain_hash="H-441",
        issued_at=time.monotonic(),
        expires_at=time.monotonic() + 300,
        declared_l_max=2.0,
        parent_hash="H-440",
    )
    try:
        s.execute(w, deadline=0.5)
    except EchoWindowViolation as e:
        print(f"refused as expected: {e}")

    # Attestation arrives -> safe to execute inside the window.
    s.last_attestation = ("H-441", time.monotonic())
    s.advance_epoch()
    print(s.execute(w, deadline=0.5))

    # Revocation arrives -> epoch advances -> cached verdict is not reused.
    s.advance_epoch()
    s.last_attestation = None
    try:
        s.execute(w, deadline=0.5)
    except EchoWindowViolation as e:
        print(f"refused after revocation: {e}")


if __name__ == "__main__":
    demo()
