# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-revoked-agent-warrant-has-failed-to-propagate-across-an-a2a-federation-mesh.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-revoked-agent-warrant-has-failed-to-propagate-across-an-a2a-federation-mesh.warrant.json
# Markdown SHA-256:   4e199aff633a3660efd3b36ac56d804ea7d7a31a1937369b42414970b1c3f7cb
# Code AST SHA-256:   fc3407e28147e857890ee6eae784ef32a642bdca34f27d5a2d14c5aac7cc3bdf
# Verified Classes:   RevocationPropagationError, Warrant, VerifierState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class RevocationPropagationError(RuntimeError):
    """Raised when a verifier cannot establish that a warrant and its
    full delegation ancestry are free of revocation, yet is asked to
    accept the warrant. Indicates a revocation-propagation failure,
    not a malformed warrant."""


@dataclass
class Warrant:
    warrant_id: str
    issuer: str
    rev_epoch: int          # issuer's revocation epoch at issuance
    parent_id: Optional[str] = None
    not_after: float = 0.0


@dataclass
class VerifierState:
    # Monotonic per-issuer epoch. NEVER reset on cache eviction;
    # eviction sets present=False, which forces UNVERIFIED.
    issuer_epoch: dict = field(default_factory=dict)
    epoch_present: dict = field(default_factory=dict)
    revoked_ids: set = field(default_factory=set)


def accept_warrant(chain: list[Warrant], state: VerifierState, now: float) -> str:
    if not chain:
        raise RevocationPropagationError("empty delegation chain")

    # Walk every link, not just the leaf. A revoked ancestor taints
    # all descendants even though their signatures are intact.
    for w in chain:
        if w.warrant_id in state.revoked_ids:
            return "REVOKED"
        if w.parent_id and w.parent_id in state.revoked_ids:
            return "REVOKED"

        if not state.epoch_present.get(w.issuer, False):
            # Cache miss is lack of evidence, never evidence of absence.
            raise RevocationPropagationError(
                f"issuer {w.issuer} epoch unverified for warrant {w.warrant_id}; "
                "refusing to treat UNVERIFIED as VALID"
            )

        local_epoch = state.issuer_epoch[w.issuer]
        if w.rev_epoch > local_epoch:
            # Warrant was issued in an epoch this verifier has never seen.
            # Its revocation status is unknowable here.
            raise RevocationPropagationError(
                f"warrant {w.warrant_id} rev_epoch={w.rev_epoch} exceeds "
                f"verifier epoch {local_epoch} for issuer {w.issuer}; "
                "revocation state is stale"
            )

        if now > w.not_after:
            return "EXPIRED"

    return "VALID"


def sync_epoch(state: VerifierState, issuer: str, epoch: int) -> None:
    # Monotonic advance only. A stale sync must not roll back the epoch.
    current = state.issuer_epoch.get(issuer, -1)
    if epoch < current:
        raise RevocationPropagationError(
            f"epoch rollback for {issuer}: {epoch} < {current}"
        )
    state.issuer_epoch[issuer] = epoch
    state.epoch_present[issuer] = True


def evict_cache(state: VerifierState, issuer: str) -> None:
    # Eviction clears presence but preserves the monotonic epoch value,
    # so a subsequent warrant with a higher rev_epoch is still caught.
    state.epoch_present[issuer] = False
