# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-peer-warrant-during-in-flight-a2a-delegation-when-the-revocation-event-and-the-delegation-token-race-across-orga.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-peer-warrant-during-in-flight-a2a-delegation-when-the-revocation-event-and-the-delegation-token-race-across-orga.warrant.json
# Markdown SHA-256:   c0f485521b5fa94db99ebeb2d78250297e53dfdfd6ae17c4c69a6570ade08e0f
# Code AST SHA-256:   643a835bbb36999923ed610e7737ec83acf3f0f301181a05c0ee5d3e58ddd0b4
# Verified Classes:   AuthorityState, WarrantAuthorityError, Warrant, PeerError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from enum import Enum


class AuthorityState(Enum):
    VALID = "valid"
    UNKNOWN = "unknown"          # cannot observe peer's revocation status
    LOST = "lost"                # peer explicitly reported revocation
    SCOPE_MISMATCH = "scope_mismatch"


class WarrantAuthorityError(RuntimeError):
    """Raised when a warrant's authority horizon is exceeded or unobservable."""


@dataclass(frozen=True)
class Warrant:
    issuer_domain: str
    subject: str
    issued_at: float
    exp: float
    revocation_latency_bound: float | None  # None => issuer did not declare it


@dataclass(frozen=True)
class PeerError:
    reason: str  # "revoked" | "scope_insufficient" | "unknown_warrant" | "transient"


def authority_horizon(w: Warrant, now: float) -> float:
    if w.revocation_latency_bound is None:
        # No declared bound => unbounded staleness => refuse to delegate.
        raise WarrantAuthorityError(
            f"issuer {w.issuer_domain} declares no revocation_latency_bound; "
            f"warrant authority is unobservable"
        )
    return min(w.exp, now + w.revocation_latency_bound)


def check_warrant_usable(w: Warrant, now: float, required_runtime: float) -> None:
    horizon = authority_horizon(w, now)
    if now >= horizon:
        raise WarrantAuthorityError(
            f"warrant for {w.subject} at {w.issuer_domain} is past authority "
            f"horizon {horizon:.0f} (now={now:.0f})"
        )
    if now + required_runtime > horizon:
        raise WarrantAuthorityError(
            f"required runtime {required_runtime:.0f}s exceeds remaining "
            f"authority horizon {horizon - now:.0f}s; decompose into re-authorized "
            f"segments"
        )


def classify_peer_response(err: PeerError) -> AuthorityState:
    if err.reason == "revoked":
        return AuthorityState.LOST
    if err.reason == "scope_insufficient":
        return AuthorityState.SCOPE_MISMATCH
    if err.reason == "unknown_warrant":
        # Peer does not recognize our warrant: treat as authority unknown, not transient.
        return AuthorityState.UNKNOWN
    return AuthorityState.UNKNOWN  # transient errors do not prove authority


def on_peer_error(w: Warrant, err: PeerError, now: float) -> None:
    state = classify_peer_response(err)
    if state is AuthorityState.LOST:
        raise WarrantAuthorityError(
            f"peer {w.subject} in {w.issuer_domain} reported revocation; "
            f"halting delegation, no cache fallback permitted"
        )
    if state is AuthorityState.UNKNOWN:
        # Cannot distinguish outage from refusal: fail closed.
        raise WarrantAuthorityError(
            f"peer authority status unobservable for {w.subject}; "
            f"refusing to continue under warrant expiring {w.exp:.0f}"
        )
    if state is AuthorityState.SCOPE_MISMATCH:
        raise WarrantAuthorityError(
            f"warrant scope insufficient for {w.subject}; re-mint required"
        )


def run_segment(w: Warrant, now: float, segment_runtime: float) -> None:
    check_warrant_usable(w, now, segment_runtime)
    # ... execute segment, then on any peer error:
    # on_peer_error(w, PeerError("revoked"), now + segment_runtime)


if __name__ == "__main__":
    now = time.time()
    # Issuer declares 90s bound; warrant exp is 1h. Usable horizon is now+90s.
    w = Warrant("domain-b", "worker-7", now, now + 3600, revocation_latency_bound=90.0)
    try:
        run_segment(w, now, segment_runtime=2400)  # 40-min subtask in one shot
    except WarrantAuthorityError as e:
        print(f"refused: {e}")
        # Correct response: decompose into 90s segments with re-mint at each boundary.
    # Issuer that declares no bound is undelegatable:
    w2 = Warrant("domain-c", "worker-9", now, now + 3600, revocation_latency_bound=None)
    try:
        check_warrant_usable(w2, now, 10)
    except WarrantAuthorityError as e:
        print(f"refused: {e}")
