# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-rotated-aaif-credential-as-unverified-despite-a-valid-signature.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-rotated-aaif-credential-as-unverified-despite-a-valid-signature.warrant.json
# Markdown SHA-256:   4d4e6f531fc9287a916d5168cc2bf20f0f6bed7017f74132ced105111a17a7c4
# Code AST SHA-256:   e4e3e969c340c4467fdb41c0f84e5c2fc504df2d21f4aac67e3ffb68dbcad603
# Verified Classes:   StaleRevocationView, CredentialRollback, Credential, VerifierState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class StaleRevocationView(RuntimeError):
    """Raised when a credential cannot be verified because the verifier's
    revocation view is older than the propagation bound. The credential may
    be valid; the verifier cannot prove it is not revoked."""


class CredentialRollback(RuntimeError):
    """Raised when a presented credential's epoch is below the verifier's
    durable high-water mark for that subject. Signature validity is
    irrelevant; this is a replay/rollback and must never be accepted."""


@dataclass
class Credential:
    subject: str
    epoch: int
    not_after: float
    signature_valid: bool


@dataclass
class VerifierState:
    propagation_bound: float          # seconds; p99 revocation gossip latency
    max_provisional_age: float        # hard cap on provisional trust
    last_synced: float                # wall-clock of last revocation sync
    max_epoch_seen: dict = field(default_factory=dict)
    provisional_since: float | None = None

    def verify(self, cred: Credential, now: float | None = None) -> str:
        now = time.time() if now is None else now

        if not cred.signature_valid or now >= cred.not_after:
            raise StaleRevocationView(
                f"credential for {cred.subject} fails signature/window check"
            )

        seen = self.max_epoch_seen.get(cred.subject, -1)
        if cred.epoch < seen:
            raise CredentialRollback(
                f"epoch {cred.epoch} < high-water {seen} for {cred.subject}; "
                f"rollback rejected regardless of signature"
            )

        view_age = now - self.last_synced
        if view_age >= self.propagation_bound:
            if self.provisional_since is None:
                self.provisional_since = now
            if now - self.provisional_since >= self.max_provisional_age:
                raise StaleRevocationView(
                    f"revocation view for {cred.subject} stale for "
                    f"{view_age:.1f}s and provisional budget exhausted; "
                    f"failing closed"
                )
            # Provisional: may proceed, must NOT sign attestations.
            return "provisional"

        # Fresh view and monotonic epoch: verified.
        self.provisional_since = None
        self.max_epoch_seen[cred.subject] = cred.epoch
        return "verified"


def sign_attestation(state: VerifierState, cred: Credential, now: float) -> dict:
    status = state.verify(cred, now)
    if status != "verified":
        raise StaleRevocationView(
            f"refusing to sign attestation over {cred.subject}: "
            f"credential is {status}, not verified; a stale attestation "
            f"would launder revoked authority to downstream agents"
        )
    return {
        "subject": cred.subject,
        "epoch": cred.epoch,
        "last_synced": state.last_synced,
        "max_epoch_seen": dict(state.max_epoch_seen),
    }
