# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-attests-a-peer-s-reputation-before-its-own-slashing-evidence-has-settled.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-attests-a-peer-s-reputation-before-its-own-slashing-evidence-has-settled.warrant.json
# Markdown SHA-256:   72b50e3f3ff5d981acb1928b90615c9951881802795e6b3203a0230a253a39a2
# Code AST SHA-256:   d67087807582cb0897936a5ac8294a9f5b02a7415a5e0473a2bf86a97921a577
# Verified Classes:   WarrantPendingError, Warrant, Attestation, ReputationFence
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Set, Dict


class WarrantPendingError(RuntimeError):
    """Raised when an attestation or delegation references a subject whose
    slashing warrants are filed but not yet settled."""
    pass


@dataclass
class Warrant:
    subject: str
    filed_epoch: int
    settle_epoch: int
    settled: bool = False


@dataclass
class Attestation:
    attester: str
    subject: str
    score: float
    epoch: int
    observed_warrants: Set[str] = field(default_factory=set)


class ReputationFence:
    def __init__(self) -> None:
        self._warrants: Dict[str, Warrant] = {}

    def file_warrant(self, w: Warrant) -> None:
        self._warrants[w.subject] = w

    def settle(self, subject: str) -> None:
        self._warrants[subject].settled = True

    def _pending_for(self, subject: str, epoch: int) -> Set[str]:
        w = self._warrants.get(subject)
        if w is None:
            return set()
        if w.settle_epoch <= epoch and not w.settled:
            return {f"{w.subject}:{w.filed_epoch}"}
        return set()

    def accept_attestation(self, a: Attestation) -> None:
        pending = self._pending_for(a.subject, a.epoch)
        if pending - a.observed_warrants:
            raise WarrantPendingError(
                f"attestation from {a.attester} for {a.subject} at epoch "
                f"{a.epoch} blocked: unobserved pending warrants {pending}"
            )

    def authorize_delegation(self, subject: str, epoch: int) -> None:
        w = self._warrants.get(subject)
        if w is not None and not w.settled:
            raise WarrantPendingError(
                f"delegation to {subject} refused at epoch {epoch}: "
                f"warrant filed at {w.filed_epoch} not settled"
            )


def replay_incident() -> None:
    fence = ReputationFence()
    fence.file_warrant(Warrant(subject="W17", filed_epoch=0, settle_epoch=1))
    try:
        fence.accept_attestation(
            Attestation(attester="W03", subject="W17", score=0.91, epoch=0)
        )
    except WarrantPendingError as exc:
        print(f"blocked as designed: {exc}")
    try:
        fence.authorize_delegation(subject="W17", epoch=0)
    except WarrantPendingError as exc:
        print(f"delegation refused: {exc}")
    fence.settle("W17")
    fence.authorize_delegation(subject="W17", epoch=1)
    print("post-settlement delegation permitted against corrected stake")


if __name__ == "__main__":
    replay_incident()
