# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-delegated-agent-keep-executing-with-authority-its-principal-already-revoked.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-delegated-agent-keep-executing-with-authority-its-principal-already-revoked.warrant.json
# Markdown SHA-256:   470aab0fa9001b4ff1657cac04faf962e712d25ef19d308ca002a8e5d7201ffa
# Code AST SHA-256:   9d676a33e37e51a38140be9486ec1d47e3cae86fe85f6c4d1c21011d8c18ee67
# Verified Classes:   StaleWarrantError, ChainIdentityMismatchError, Warrant, RootEpoch, DelegatedExecutor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class StaleWarrantError(RuntimeError):
    """Raised when a leaf warrant's issuance epoch is behind the root's current epoch,
    meaning an ancestor in the delegation chain may have been revoked."""
    pass


class ChainIdentityMismatchError(RuntimeError):
    """Raised when a parent attests validity for a warrant whose parent_id does not
    match the leaf's recorded parent — the chain has forked or been re-issued."""
    pass


@dataclass
class Warrant:
    id: str
    parent_id: Optional[str]
    chain_root: str
    scope: frozenset
    issuance_epoch: int
    expiry: float


@dataclass
class RootEpoch:
    root_id: str
    epoch: int
    signed_at: float


class DelegatedExecutor:
    def __init__(self, warrant: Warrant, root_epoch_fetch, staleness_bound: float = 5.0):
        self.warrant = warrant
        self._fetch_root_epoch = root_epoch_fetch
        self._staleness_bound = staleness_bound
        self._cached_epoch: Optional[RootEpoch] = None
        self._cached_at: float = 0.0

    def _current_root_epoch(self) -> RootEpoch:
        now = time.time()
        if self._cached_epoch is None or (now - self._cached_at) > self._staleness_bound:
            self._cached_epoch = self._fetch_root_epoch(self.warrant.chain_root)
            self._cached_at = now
        return self._cached_epoch

    def _assert_chain_live(self) -> None:
        root = self._current_root_epoch()
        # Invariant: a warrant issued at epoch E is dead the moment the root
        # advances past E, because the advance records a revocation somewhere
        # in the chain rooted at chain_root. The leaf cannot know *which* hop
        # was revoked without a full walk, so it must fail closed.
        if self.warrant.issuance_epoch < root.epoch:
            raise StaleWarrantError(
                f"warrant {self.warrant.id} issued at epoch "
                f"{self.warrant.issuance_epoch} but root {root.root_id} "
                f"is at epoch {root.epoch}; ancestor may be revoked"
            )
        if time.time() > self.warrant.expiry:
            raise StaleWarrantError(f"warrant {self.warrant.id} expired")

    def _assert_parent_identity(self, parent_attestation: dict) -> None:
        if parent_attestation.get("warrant_id") != self.warrant.parent_id:
            raise ChainIdentityMismatchError(
                f"parent attested for {parent_attestation.get('warrant_id')} "
                f"but leaf expects {self.warrant.parent_id}; chain forked"
            )

    def execute_side_effect(self, action: str, parent_attestation: dict) -> str:
        # Order matters: identity before liveness, because a forked chain can
        # present a live-but-unrelated parent that would otherwise pass liveness.
        self._assert_parent_identity(parent_attestation)
        self._assert_chain_live()
        # Only now is the action authorized under a live, identity-bound chain.
        return f"executed:{action}"


def fetch_root_epoch(root_id: str) -> RootEpoch:
    # Stub: real implementation queries the root's signed epoch endpoint.
    return RootEpoch(root_id=root_id, epoch=7, signed_at=time.time())


if __name__ == "__main__":
    leaf = Warrant(
        id="W_t", parent_id="W_e", chain_root="O",
        scope=frozenset({"write:repo/branch/feature-42"}),
        issuance_epoch=5, expiry=time.time() + 3600,
    )
    ex = DelegatedExecutor(leaf, fetch_root_epoch)
    # Root advanced from epoch 5 to 7 — an ancestor was revoked mid-flight.
    ex.execute_side_effect("write:src/auth/session.py", {"warrant_id": "W_e"})
