# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-quorum-collapse-in-byzantine-agent-consensus-when-equivocating-peers-pass-signature-checks.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-quorum-collapse-in-byzantine-agent-consensus-when-equivocating-peers-pass-signature-checks.warrant.json
# Markdown SHA-256:   c9f41da7fe0e422e4ec622c9f6898dfdb1b68a6c3186a7120f8def89c3456857
# Code AST SHA-256:   19739341583df8823da32a0d3cf9875a5c6651facc60e0e3c4a6c851b9ebe6f0
# Verified Classes:   QuorumEquivocationError, VoteLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class QuorumEquivocationError(RuntimeError):
    """Raised when a validly-signed vote conflicts with an existing vote
    from the same identity in the same (round, proposal_id)."""
    pass


class VoteLedger:
    def __init__(self, quorum: int):
        self.quorum = quorum
        # (round, proposal_id) -> {identity: state_hash}
        self._votes: dict[tuple[int, str], dict[str, str]] = {}
        # (round, proposal_id) -> set of equivocating identities
        self._equivocating: dict[tuple[int, str], set[str]] = {}

    def record(self, round_id: int, proposal_id: str,
               identity: str, state_hash: str, signature_valid: bool) -> None:
        key = (round_id, proposal_id)
        if not signature_valid:
            # Cryptographic failure: reject, do not flag as equivocation.
            return
        seen = self._votes.setdefault(key, {})
        flagged = self._equivocating.setdefault(key, set())

        prior = seen.get(identity)
        if prior is not None and prior != state_hash:
            # Valid signature, conflicting value, same identity, same round.
            flagged.add(identity)
            raise QuorumEquivocationError(
                f"identity={identity} round={round_id} proposal={proposal_id} "
                f"voted {prior!r} then {state_hash!r}; excluding from quorum"
            )
        seen[identity] = state_hash

    def certify(self, round_id: int, proposal_id: str,
                state_hash: str) -> bool:
        key = (round_id, proposal_id)
        seen = self._votes.get(key, {})
        flagged = self._equivocating.get(key, set())
        honest_signers = {
            ident for ident, h in seen.items()
            if h == state_hash and ident not in flagged
        }
        # Quorum must be reached by distinct, non-equivocating identities.
        return len(honest_signers) >= self.quorum


def commit_state(ledger: VoteLedger, round_id: int, proposal_id: str,
                 state_hash: str) -> str:
    if not ledger.certify(round_id, proposal_id, state_hash):
        # Refuse to commit; caller must trigger a view change.
        raise QuorumEquivocationError(
            f"cannot certify {state_hash!r} at round={round_id}: "
            f"honest quorum not reached (possible equivocation collapse)"
        )
    return state_hash
