# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-votes-on-a-commitment-it-cannot-verify-quorum-poisoning-via-unverifiable-attestations-in-bft-agent-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-votes-on-a-commitment-it-cannot-verify-quorum-poisoning-via-unverifiable-attestations-in-bft-agent-consensus.warrant.json
# Markdown SHA-256:   9b89a618a4051d615934fd2347dea1155efe073ae3ab29a40676bce5bd858c67
# Code AST SHA-256:   b76a2908f6fcea71a37346ca29f3e4dcb0ebe39b98f0e2c89e971b6345b83d3e
# Verified Classes:   QuorumUnsoundError, Vote
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class QuorumUnsoundError(RuntimeError):
    """Raised when a numeric quorum lacks f+1 independent-evidence votes."""
    pass


@dataclass(frozen=True)
class Vote:
    agent_id: str
    commitment_id: str
    decision: str                      # "commit" | "abstain"
    evidence: FrozenSet[str] = field(default_factory=frozenset)  # tokens actually inspected


def count_independent(votes: list[Vote]) -> int:
    """Largest set of commit votes with pairwise-disjoint, non-empty evidence."""
    commit_votes = [v for v in votes if v.decision == "commit" and v.evidence]
    chosen: list[Vote] = []
    used: set[str] = set()
    for v in sorted(commit_votes, key=lambda x: len(x.evidence)):
        if not (v.evidence & used):
            chosen.append(v)
            used |= v.evidence
    return len(chosen)


def try_commit(commitment_id: str, votes: list[Vote], n: int, f: int) -> str:
    quorum = 2 * f + 1
    total_commits = sum(1 for v in votes if v.decision == "commit")
    if total_commits < quorum:
        return "no-quorum"
    independent = count_independent(votes)
    if independent < f + 1:
        # e.g. trace above: total_commits=3 (>=quorum) but independent=1 (<f+1=2)
        raise QuorumUnsoundError(
            f"{commitment_id}: numeric quorum {total_commits}/{quorum} met, "
            f"but only {independent} independent-evidence votes (need {f + 1}); "
            f"refusing commit to avoid stale-premise execution"
        )
    return "committed"


# Reproduce the observed failure and show the guardrail firing.
trace = [
    Vote("A", "K_17", "commit", frozenset({"hash_output"})),  # proposer re-derived
    Vote("B", "K_17", "commit", frozenset({"hash_output"})),
    Vote("C", "K_17", "commit", frozenset({"hash_output"})),  # same evidence source as B
    Vote("D", "K_17", "commit", frozenset()),                 # echo: no evidence
]

try:
    try_commit("K_17", trace, n=5, f=1)
except QuorumUnsoundError as e:
    print("BLOCKED:", e)
