# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-count-its-own-vote-in-a-byzantine-quorum-and-why-self-inclusion-corrupts-commitment-liveness-before-i.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-count-its-own-vote-in-a-byzantine-quorum-and-why-self-inclusion-corrupts-commitment-liveness-before-i.warrant.json
# Markdown SHA-256:   108cfa60826578c4c0e35f7185f7d9a338da3e7e5b217d2414c1e1c4a34cc62c
# Code AST SHA-256:   16c0d5739fedb5dbedf0088ddc158d51afd60207a5efc092cb14987d62cc8d99
# Verified Classes:   QuorumIndependenceViolation, Vote, QuorumCounter
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class QuorumIndependenceViolation(RuntimeError):
    """Raised when a proposing replica counts its own vote toward the commit threshold."""
    pass


@dataclass
class Vote:
    replica_id: str
    value_hash: str
    signature: bytes


@dataclass
class QuorumCounter:
    threshold: int                      # T = 2f+1
    proposer_id: str
    value_hash: str
    votes: list[Vote] = field(default_factory=list)

    def add(self, vote: Vote) -> None:
        if vote.value_hash != self.value_hash:
            raise QuorumIndependenceViolation(
                f"vote for {vote.value_hash} does not match proposal {self.value_hash}"
            )
        self.votes.append(vote)

    def independent_count(self) -> int:
        """Votes from replicas other than the proposer. Self-votes are excluded."""
        seen = set()
        for v in self.votes:
            if v.replica_id == self.proposer_id:
                continue
            seen.add(v.replica_id)
        return len(seen)

    def can_commit(self) -> bool:
        if self.independent_count() < self.threshold:
            raise QuorumIndependenceViolation(
                f"independent quorum {self.independent_count()} < threshold "
                f"{self.threshold} for proposal by {self.proposer_id}; "
                f"self-vote cannot substitute for an independent peer vote"
            )
        return True


def commit_round(counter: QuorumCounter) -> str:
    # Guardrail: commit decision excludes the proposer's own vote.
    if not counter.can_commit():
        raise QuorumIndependenceViolation("commit refused")
    return counter.value_hash
