# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-decision-under-a-byzantine-quorum-that-only-appears-to-reach-bft-threshold.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-decision-under-a-byzantine-quorum-that-only-appears-to-reach-bft-threshold.warrant.json
# Markdown SHA-256:   8337f5d240f902f4ca40826af8d4ea543350b213e2bfd2b7b2cc959e76ed0a21
# Code AST SHA-256:   10da28b9afbefe89c795b9d8a46b1d3673fc45b5c584b1306db2dabff5ebd3a5
# Verified Classes:   ByzantineCommitViolation, Vote, QuorumRound
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Dict, List, Optional


class ByzantineCommitViolation(RuntimeError):
    """Raised when a quorum commit would violate BFT provenance or safety."""
    pass


@dataclass(frozen=True)
class Vote:
    voter_id: str
    proposal_digest: str
    payload_digest: str
    rationale_digest: str
    signature: str
    is_abstain: bool = False

    def binding_digest(self) -> str:
        return hashlib.sha256(
            f"{self.voter_id}|{self.proposal_digest}|{self.payload_digest}|"
            f"{self.rationale_digest}|{self.is_abstain}".encode()
        ).hexdigest()


@dataclass
class QuorumRound:
    round_number: int
    n: int
    f: int
    expected_payload_digests: Dict[str, str]  # proposal_digest -> payload_digest
    votes: List[Vote] = field(default_factory=list)

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

    def admit(self, vote: Vote) -> None:
        if vote.is_abstain:
            self.votes.append(vote)
            return
        expected = self.expected_payload_digests.get(vote.proposal_digest)
        if expected is None:
            raise ByzantineCommitViolation(
                f"vote for unknown proposal digest {vote.proposal_digest}"
            )
        if vote.payload_digest != expected:
            raise ByzantineCommitViolation(
                f"payload digest mismatch for {vote.proposal_digest}: "
                f"voter saw {vote.payload_digest}, expected {expected} "
                f"(truncated payload?)"
            )
        self.votes.append(vote)

    def commit(self) -> Optional[str]:
        counts: Dict[str, int] = {}
        seen_bindings = set()
        for v in self.votes:
            if v.is_abstain:
                continue
            b = v.binding_digest()
            if b in seen_bindings:
                raise ByzantineCommitViolation(
                    f"duplicate vote binding {b} from {v.voter_id}"
                )
            seen_bindings.add(b)
            counts[v.proposal_digest] = counts.get(v.proposal_digest, 0) + 1

        winners = [d for d, c in counts.items() if c >= self.threshold]
        if len(winners) > 1:
            raise ByzantineCommitViolation(
                f"FORK_DETECTED at round {self.round_number}: "
                f"multiple digests reached threshold {self.threshold}: {winners}"
            )
        if len(winners) == 1:
            return winners[0]
        return None  # liveness stall; caller must re-propose, not relax threshold


def run_round(round_number: int, n: int, f: int,
              proposals: Dict[str, str], votes: List[Vote]) -> Optional[str]:
    r = QuorumRound(round_number=round_number, n=n, f=f,
                    expected_payload_digests=proposals)
    for v in votes:
        r.admit(v)
    return r.commit()


# Reproduction of the observed failure: truncated payloads produce
# votes whose payload_digest does not match the coordinator's proposal.
if __name__ == "__main__":
    proposals = {
        "D_r": hashlib.sha256(b"rollback-full-payload").hexdigest(),
        "D_f": hashlib.sha256(b"forward-full-payload").hexdigest(),
    }
    truncated_r = hashlib.sha256(b"rollback-full-payl").hexdigest()
    truncated_f = hashlib.sha256(b"forward-full-payl").hexdigest()
    bad_votes = [
        Vote("A6", "D_r", truncated_r, "rat", "sig6"),
        Vote("A7", "D_f", truncated_f, "rat", "sig7"),
    ]
    try:
        run_round(1, n=7, f=2, proposals=proposals, votes=bad_votes)
    except ByzantineCommitViolation as e:
        print(f"rejected as required: {e}")
