# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-byzantine-quorum-failure-as-a-divergence-in-reasoning-rather-than-a-divergence-in-output.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-byzantine-quorum-failure-as-a-divergence-in-reasoning-rather-than-a-divergence-in-output.warrant.json
# Markdown SHA-256:   196fffe79e81d5df664825e0f8a58c6cf06a1ab7118c72b2b4e02fb8a71ff4b8
# Code AST SHA-256:   5d94e804cae1199454be21a173b5e17a1ec6421e73f21e68fe7d73aef8c08fcc
# Verified Classes:   UnsoundQuorumCommit, Vote, Quorum
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Iterable


class UnsoundQuorumCommit(RuntimeError):
    """Raised when a quorum reaches decision threshold but not evidence threshold."""


@dataclass(frozen=True)
class Vote:
    instance_id: str
    decision: str
    evidence_spans: tuple[str, ...]
    tool_call_hash: str | None = None

    def evidence_cluster(self) -> str:
        if not self.evidence_spans:
            return "empty"
        joined = "|".join(sorted(self.evidence_spans))
        return hashlib.sha256(joined.encode()).hexdigest()[:16]


@dataclass
class Quorum:
    n: int
    f: int
    votes: list[Vote] = field(default_factory=list)

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

    @property
    def evidence_threshold(self) -> int:
        return self.f + 1

    def tally(self, decision: str) -> list[Vote]:
        return [v for v in self.votes if v.decision == decision]

    def evidence_clusters(self, votes: Iterable[Vote]) -> set[str]:
        return {v.evidence_cluster() for v in votes}

    def commit(self) -> str:
        for decision in {v.decision for v in self.votes}:
            backers = self.tally(decision)
            if len(backers) < self.decision_threshold:
                continue
            clusters = self.evidence_clusters(backers)
            if len(clusters) < self.evidence_threshold:
                raise UnsoundQuorumCommit(
                    f"decision={decision!r} reached {len(backers)}/{self.n} votes "
                    f"but only {len(clusters)} evidence cluster(s); "
                    f"threshold requires {self.evidence_threshold}. "
                    f"Classify as reasoning divergence and cross-examine, "
                    f"do not commit."
                )
            return decision
        raise UnsoundQuorumCommit(
            f"no decision reached {self.decision_threshold}/{self.n} votes"
        )


# Replay of the recorded episode: 3 reject votes, 2 distinct evidence clusters.
quorum = Quorum(n=5, f=1)
quorum.votes = [
    Vote("A1", "support", ("abstract:s3",)),
    Vote("A2", "support", ("abstract:s3",)),
    Vote("B1", "reject", ("footnote:f7",), tool_call_hash="r1"),
    Vote("B2", "reject", ("footnote:f7",), tool_call_hash="r1"),
    Vote("C1", "reject", ("truncated:snippet",), tool_call_hash="r9"),
]
# Under a pure counting rule this commits "reject". Under the evidence invariant it must halt.
quorum.commit()  # raises UnsoundQuorumCommit
