# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-task-after-its-warrant-has-been-revoked-the-revocation-vs-cache-race-in-federated-a2a-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-task-after-its-warrant-has-been-revoked-the-revocation-vs-cache-race-in-federated-a2a-handoffs.warrant.json
# Markdown SHA-256:   478d446f9e4b34776497111a47758c863204d36b909950e133ff158e5ea2c342
# Code AST SHA-256:   1f9ee198adcd14d5c5c3650e6414294f723621380be9b1387f5ba73b1144da1d
# Verified Classes:   StaleWarrantEpochError, Warrant, CapabilityCache
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class StaleWarrantEpochError(RuntimeError):
    """Raised when a capability decision would be used at commit time against an
    epoch read older than the warrant's revocation propagation SLA, or when a
    derived warrant copies a parent's epoch instead of re-reading the issuer."""


@dataclass
class Warrant:
    warrant_id: str
    subject: str
    scope: str
    not_after: float
    revocation_epoch: int          # as CLAIMED by the presenter
    parent: Optional["Warrant"] = None
    issuer_epoch_endpoint: Optional[str] = None
    max_epoch_age: float = 10.0    # seconds; must be < propagation SLA


@dataclass
class CapabilityCache:
    positive_ttl: float = 60.0
    _entries: dict = field(default_factory=dict)

    def _key(self, w: Warrant, issuer_epoch: int) -> tuple:
        # Keyed on the ISSUER'S current epoch, never the warrant's claimed epoch.
        return (w.warrant_id, issuer_epoch)

    def check(self, w: Warrant, issuer_epoch: int, now: float) -> bool:
        entry = self._entries.get(self._key(w, issuer_epoch))
        if entry is None:
            return False
        minted, ttl = entry
        return now - minted < ttl

    def record_positive(self, w: Warrant, issuer_epoch: int, now: float) -> None:
        self._entries[self._key(w, issuer_epoch)] = (now, self.positive_ttl)

    def invalidate_lineage(self, w: Warrant) -> None:
        cur = w
        while cur is not None:
            for k in [k for k in self._entries if k[0] == cur.warrant_id]:
                del self._entries[k]
            cur = cur.parent


def read_issuer_epoch(w: Warrant, issuer_state: dict, now: float) -> tuple:
    """Returns (epoch, read_at). In production this is a network call to
    w.issuer_epoch_endpoint with a hard timeout; here it reads a dict."""
    if w.issuer_epoch_endpoint is None:
        raise StaleWarrantEpochError(
            f"warrant {w.warrant_id} has no issuer epoch endpoint; "
            f"cannot establish freshness for cross-domain action"
        )
    epoch = issuer_state.get(w.warrant_id, w.revocation_epoch)
    return epoch, now


def authorize_cross_domain_action(
    w: Warrant,
    cache: CapabilityCache,
    issuer_state: dict,
    now: float,
) -> None:
    """Gate for any action crossing an administrative boundary: sub-delegation,
    shared-store write, payment, third-party message. Fails closed on staleness."""
    if now >= w.not_after:
        raise StaleWarrantEpochError(
            f"warrant {w.warrant_id} expired at {w.not_after}, now {now}"
        )

    # Walk the lineage; every ancestor's epoch must be re-read and fresh.
    cur = w
    while cur is not None:
        epoch, read_at = read_issuer_epoch(cur, issuer_state, now)
        age = now - read_at
        if age > cur.max_epoch_age:
            raise StaleWarrantEpochError(
                f"epoch read for {cur.warrant_id} is {age:.1f}s old, "
                f"exceeds max_epoch_age {cur.max_epoch_age}s; refusing cross-domain action"
            )
        if epoch > cur.revocation_epoch:
            # Issuer has advanced past the presented epoch: revoked or superseded.
            cache.invalidate_lineage(cur)
            raise StaleWarrantEpochError(
                f"warrant {cur.warrant_id} presented at epoch {cur.revocation_epoch}, "
                f"issuer is at epoch {epoch}; lineage invalidated"
            )
        cur = cur.parent

    # Only now may a cached positive decision be consulted, keyed on issuer epoch.
    epoch, _ = read_issuer_epoch(w, issuer_state, now)
    if not cache.check(w, epoch, now):
        cache.record_positive(w, epoch, now)


def derive_subwarrant(
    parent: Warrant,
    child_id: str,
    scope: str,
    issuer_state: dict,
    now: float,
) -> Warrant:
    """Derive a child warrant. The child MUST carry the issuer's CURRENT epoch,
    not the parent's claimed epoch, or the stale-epoch bug propagates."""
    epoch, read_at = read_issuer_epoch(parent, issuer_state, now)
    if now - read_at > parent.max_epoch_age:
        raise StaleWarrantEpochError(
            f"cannot derive from {parent.warrant_id}: epoch read stale by "
            f"{now - read_at:.1f}s"
        )
    if epoch > parent.revocation_epoch:
        raise StaleWarrantEpochError(
            f"cannot derive from revoked {parent.warrant_id}: "
            f"claimed epoch {parent.revocation_epoch}, issuer epoch {epoch}"
        )
    return Warrant(
        warrant_id=child_id,
        subject=parent.subject,
        scope=scope,
        not_after=parent.not_after,
        revocation_epoch=epoch,          # re-read, not copied
        parent=parent,
        issuer_epoch_endpoint=parent.issuer_epoch_endpoint,
        max_epoch_age=parent.max_epoch_age,
    )
