# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-in-a-delegated-capability-chain-keep-executing-after-its-warrant-was-revoked-the-revocation-visibility-gap-across-a2a-hops.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-in-a-delegated-capability-chain-keep-executing-after-its-warrant-was-revoked-the-revocation-visibility-gap-across-a2a-hops.warrant.json
# Markdown SHA-256:   c3e7d02cbf60992d2d043adac406422f5ceb4c1accacf5562c0424dd0f0cd1c4
# Code AST SHA-256:   4d70dfe958e37248da03ce57fa8490fad646c0e7dd6d9d7f9ace443d9746332a
# Verified Classes:   StaleWarrantExecution, RootIssuer, Warrant, Executor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class StaleWarrantExecution(RuntimeError):
    """Raised when an executor attempts a consequential action under a warrant
    whose root issuer has advanced its revocation epoch past the warrant's."""
    pass


@dataclass
class RootIssuer:
    issuer_id: str
    revocation_epoch: int = 0
    revoked_warrants: set = field(default_factory=set)

    def revoke(self, warrant_id: str) -> None:
        self.revoked_warrants.add(warrant_id)
        self.revocation_epoch += 1


@dataclass
class Warrant:
    warrant_id: str
    root_issuer_id: str
    epoch_at_mint: int
    scope: str
    expires_at: float
    parent_id: str | None = None

    def attenuate(self, child_id: str, narrower_scope: str, ttl: float) -> "Warrant":
        # Attenuation narrows scope but MUST preserve root epoch reference.
        return Warrant(
            warrant_id=child_id,
            root_issuer_id=self.root_issuer_id,
            epoch_at_mint=self.epoch_at_mint,
            scope=narrower_scope,
            expires_at=time.time() + ttl,
            parent_id=self.warrant_id,
        )


class Executor:
    def __init__(self, issuer_registry: dict[str, RootIssuer]):
        self._issuers = issuer_registry

    def check_preconditions(self, warrant: Warrant) -> None:
        # Precondition 1: not expired locally.
        if time.time() >= warrant.expires_at:
            raise StaleWarrantExecution(
                f"warrant {warrant.warrant_id} expired at {warrant.expires_at}"
            )
        # Precondition 2: root issuer has not advanced epoch past mint.
        issuer = self._issuers.get(warrant.root_issuer_id)
        if issuer is None:
            raise StaleWarrantExecution(
                f"root issuer {warrant.root_issuer_id} unreachable; "
                f"cannot confirm liveness of {warrant.warrant_id}"
            )
        if issuer.revocation_epoch > warrant.epoch_at_mint:
            raise StaleWarrantExecution(
                f"warrant {warrant.warrant_id} stale: root epoch "
                f"{issuer.revocation_epoch} > mint epoch {warrant.epoch_at_mint}"
            )
        if warrant.warrant_id in issuer.revoked_warrants:
            raise StaleWarrantExecution(
                f"warrant {warrant.warrant_id} explicitly revoked at root"
            )

    def consequential_action(self, warrant: Warrant, path: str) -> str:
        # Re-read root state on EVERY consequential action, not at handoff.
        self.check_preconditions(warrant)
        return f"read {path} under scope {warrant.scope}"


# Demonstration of the gap and its closure:
issuer = RootIssuer("orchestrator-O")
w0 = Warrant("W0", "orchestrator-O", issuer.revocation_epoch, "fs:read:/tenant-7", time.time() + 3600)
w1 = w0.attenuate("W1", "fs:read:/tenant-7/reports", ttl=600)
ex = Executor({"orchestrator-O": issuer})

ex.consequential_action(w1, "/tenant-7/reports/q3.md")  # ok
issuer.revoke("W0")                                      # tenant offboarded
try:
    ex.consequential_action(w1, "/tenant-7/reports/q4.md")  # must now fail
except StaleWarrantExecution as e:
    # Correct behavior: execution refused at the boundary, not after.
    print(f"blocked: {e}")
