# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-negotiated-capability-grant-as-void-because-the-brokering-trust-anchor-rotated-mid-exchange.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-negotiated-capability-grant-as-void-because-the-brokering-trust-anchor-rotated-mid-exchange.warrant.json
# Markdown SHA-256:   1e96270fa62021e6d7aba207a06d1e92dbba2cb1a26457f15387e2126e2eb1e0
# Code AST SHA-256:   0377919a475f186467fa4841657c67863e8a2861d25c617e33acce2d5fd9d7fc
# Verified Classes:   GrantVoidError, AnchorResolution, Grant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class GrantVoidError(RuntimeError):
    """Raised when a grant is unexpired and unforged but signed under an
    anchor epoch the verifier cannot honor. Must NOT be retried; must
    route to renegotiation."""


class AnchorResolution(Enum):
    CURRENT = "current"
    RETIRED_HONORED = "retired_honored"
    UNKNOWN = "unknown"


@dataclass(frozen=True)
class Grant:
    grant_id: str
    anchor_epoch: str | None
    validity_seconds: int
    policy_hash: str


def resolve_anchor(epoch: str | None, known_current: str,
                   known_retired_honored: frozenset[str]) -> AnchorResolution:
    if epoch is None:
        # Legacy grant: no provenance across a rotation boundary.
        return AnchorResolution.UNKNOWN
    if epoch == known_current:
        return AnchorResolution.CURRENT
    if epoch in known_retired_honored:
        return AnchorResolution.RETIRED_HONORED
    return AnchorResolution.UNKNOWN


def verify_grant(grant: Grant, known_current: str,
                 known_retired_honored: frozenset[str],
                 now_elapsed: int) -> AnchorResolution:
    if now_elapsed > grant.validity_seconds:
        raise GrantVoidError(
            f"grant {grant.grant_id} past validity window; renegotiate"
        )
    resolution = resolve_anchor(
        grant.anchor_epoch, known_current, known_retired_honored
    )
    if resolution is AnchorResolution.UNKNOWN:
        # Void, not forged, not expired. Do not enter retry middleware.
        raise GrantVoidError(
            f"grant {grant.grant_id} signed under unhonorable anchor epoch "
            f"{grant.anchor_epoch!r}; policy_hash={grant.policy_hash}; "
            f"route to renegotiation, not retry"
        )
    return resolution
