# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-counts-a-byzantine-peer-s-silence-as-agreement-in-a-multi-agent-decision-quorum.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-counts-a-byzantine-peer-s-silence-as-agreement-in-a-multi-agent-decision-quorum.warrant.json
# Markdown SHA-256:   b34f1c04f782666f65225b72a05af042d38adb99f8e199bc99dedc8b655966ba
# Code AST SHA-256:   9614fdba25fb39cb2b8f80f646caaea4da3619aee019e4ba48f12f3028349888
# Verified Classes:   RosterIntegrityError, Outcome, QuorumCertificate
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from math import ceil


class RosterIntegrityError(RuntimeError):
    """Raised when a quorum tally would run against a roster that does not
    match the roster pinned at decision-open time, or when unresponsive
    peers exceed the tolerable cliff for the configured fault budget."""


class Outcome(Enum):
    APPROVE = "approve"
    REJECT = "reject"
    ABSTAIN = "abstain"
    UNRESPONSIVE = "unresponsive"


@dataclass(frozen=True)
class QuorumCertificate:
    decision_id: str
    roster: frozenset            # pinned at open; NEVER recomputed
    n: int                       # == len(roster), immutable
    f_tolerated: int             # Byzantine fault budget, e.g. (n-1)//3
    outcomes: dict = field(default_factory=dict)  # peer -> Outcome

    def record(self, peer: str, outcome: Outcome) -> "QuorumCertificate":
        if peer not in self.roster:
            raise RosterIntegrityError(
                f"peer {peer!r} is not in pinned roster for {self.decision_id}"
            )
        new_outcomes = dict(self.outcomes)
        new_outcomes[peer] = outcome
        return QuorumCertificate(
            self.decision_id, self.roster, self.n, self.f_tolerated, new_outcomes
        )


def tally(cert: QuorumCertificate) -> bool:
    # Invariant 1: denominator is the pinned roster, never the responsive set.
    if len(cert.roster) != cert.n:
        raise RosterIntegrityError(
            f"roster size {len(cert.roster)} != pinned n={cert.n} "
            f"for decision {cert.decision_id}"
        )

    # Invariant 2: every roster slot must resolve to exactly one outcome.
    missing = cert.roster - set(cert.outcomes)
    if missing:
        raise RosterIntegrityError(
            f"decision {cert.decision_id} has unresolved roster slots: {sorted(missing)}"
        )

    counts = {o: 0 for o in Outcome}
    for peer in cert.roster:
        counts[cert.outcomes[peer]] += 1

    # Invariant 3: the silence cliff. Unresponsive peers beyond the fault
    # budget invalidate the decision regardless of approval count.
    silence_cliff = cert.n - 3 * cert.f_tolerated  # peers we can lose and still decide
    if counts[Outcome.UNRESPONSIVE] >= silence_cliff:
        raise RosterIntegrityError(
            f"decision {cert.decision_id} crossed silence cliff: "
            f"{counts[Outcome.UNRESPONSIVE]} unresponsive >= {silence_cliff} "
            f"for n={cert.n}, f={cert.f_tolerated}; fail closed"
        )

    # Invariant 4: approval threshold against the pinned denominator.
    threshold = ceil(2 * cert.n / 3)
    return counts[Outcome.APPROVE] >= threshold


def open_decision(decision_id: str, roster: list[str]) -> QuorumCertificate:
    n = len(roster)
    f_tolerated = (n - 1) // 3
    if n < 3 * f_tolerated + 1:
        raise RosterIntegrityError(
            f"roster of {n} cannot tolerate f={f_tolerated} faults"
        )
    return QuorumCertificate(decision_id, frozenset(roster), n, f_tolerated)


# --- reproduction of the observed incident ---
cert = open_decision("mig-2025-06-12", ["A", "B", "C", "D", "E"])
for peer, out in [
    ("A", Outcome.APPROVE),
    ("B", Outcome.APPROVE),
    ("C", Outcome.APPROVE),
    ("D", Outcome.REJECT),
    ("E", Outcome.UNRESPONSIVE),   # adversarial silence, recorded honestly
]:
    cert = cert.record(peer, out)

try:
    decided = tally(cert)
    print(f"decision {cert.decision_id} -> {decided}")
except RosterIntegrityError as e:
    # n=5, f=1 -> silence_cliff = 5 - 3 = 2; one unresponsive is survivable,
    # so this run is allowed to proceed and correctly returns False.
    print(f"fail-closed: {e}")
