# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-votes-on-a-quorum-it-cannot-cryptographically-verify-silent-equivocation-tolerance-collapse-in-heterogeneous-bft-swarms.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-votes-on-a-quorum-it-cannot-cryptographically-verify-silent-equivocation-tolerance-collapse-in-heterogeneous-bft-swarms.warrant.json
# Markdown SHA-256:   2273ff9d3cb0e04b0690e6f4a96b920de93434271c9d25a293db304644443c48
# Code AST SHA-256:   a2cfcecbe5a601d4a44fa9b4e7e4d798f1ec2cbc1220b4866203882f3abe60b5
# Verified Classes:   Verdict, QuorumCollapseError, Round
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List


class Verdict(Enum):
    VALID = "valid"
    INVALID = "invalid"        # cryptographically proven forgery
    UNRESOLVED = "unresolved"  # verifier cannot decide (cache miss, rotated cert)


class QuorumCollapseError(RuntimeError):
    """Raised when a round would abort on UNRESOLVED votes, which is the
    equivocation-tolerance-collapse trigger. Must never be swallowed into
    a terminal verdict."""


@dataclass
class Round:
    f: int
    votes: Dict[str, Verdict] = field(default_factory=dict)

    @property
    def quorum(self) -> int:
        return 2 * self.f + 1

    def tally(self) -> Dict[Verdict, int]:
        counts = {v: 0 for v in Verdict}
        for verdict in self.votes.values():
            counts[verdict] += 1
        return counts

    def decide(self) -> str:
        c = self.tally()
        valid, invalid, pending = c[Verdict.VALID], c[Verdict.INVALID], c[Verdict.UNRESOLVED]

        # Guardrail 1: genuine Byzantine budget exceeded -> abort is sound.
        if invalid > self.f:
            return "abort"

        # Guardrail 2: enough clean votes -> commit is safe under any resolver state.
        if valid >= self.quorum:
            return "commit"

        # Guardrail 3: the collapse trigger. A shortfall of VALID with any
        # UNRESOLVED present is a liveness condition, not a safety verdict.
        # Aborting here races a peer's warm-cache commit -> fork.
        if pending > 0 and valid + pending >= self.quorum:
            raise QuorumCollapseError(
                f"round undecidable: valid={valid} pending={pending} "
                f"quorum={self.quorum} invalid={invalid}; must re-resolve, "
                f"not abort"
            )

        # Guardrail 4: no pending, still short -> genuine liveness timeout.
        if pending == 0 and valid < self.quorum:
            return "timeout"

        raise QuorumCollapseError(
            f"unhandled lattice state valid={valid} invalid={invalid} pending={pending}"
        )


def run_round(round_: Round) -> str:
    try:
        return round_.decide()
    except QuorumCollapseError:
        # In production: pause, force warrant-resolver refresh, re-evaluate.
        # Re-raising here documents that this must NOT be mapped to abort.
        raise


if __name__ == "__main__":
    # Reproduce the observed fork: 4 valid, 3 unresolved, f=2.
    r = Round(f=2)
    for i in range(4):
        r.votes[f"A{i+1}"] = Verdict.VALID
    for i in range(3):
        r.votes[f"A{i+5}"] = Verdict.UNRESOLVED
    run_round(r)  # raises QuorumCollapseError instead of forking
