# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-commit-when-a-byzantine-agent-can-equivocate-across-the-commitment-quorum.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-commit-when-a-byzantine-agent-can-equivocate-across-the-commitment-quorum.warrant.json
# Markdown SHA-256:   be9f8472d96f93d93f53ad2c108ac30ab8700e8848229f9e6fb28f01b001de5b
# Code AST SHA-256:   53b7be4f2ea33cc1046c1056287519238aa696e5b42491e26dfb2438e0d84655
# Verified Classes:   EquivocationDetected, QuorumCertificate
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class EquivocationDetected(RuntimeError):
    """Raised when a peer's votes within one round are inconsistent or unattested."""
    pass


class QuorumCertificate:
    def __init__(self, round_id: int, value: str, signers: dict):
        # signers: peer_id -> (reason_hash, signature)
        self.round_id = round_id
        self.value = value
        self.signers = signers

    def verify_intersection(self, other: "QuorumCertificate", n: int, f: int) -> bool:
        shared = set(self.signers) & set(other.signers)
        return len(shared) >= (2 * len(self.signers) - n) and len(shared) >= f + 1


def commit_decision(observed_votes: dict, round_id: int, n: int, f: int,
                    threshold: int, certificate: QuorumCertificate | None) -> str:
    # 1. Detect direct equivocation: same peer, same round, different reason_hash.
    per_peer = {}
    for peer, (value, reason_hash, _sig) in observed_votes.items():
        if peer in per_peer and per_peer[peer][0] != reason_hash:
            raise EquivocationDetected(
                f"peer {peer} sent conflicting reason_hash {per_peer[peer][0]!r} vs {reason_hash!r} in round {round_id}"
            )
        per_peer[peer] = (reason_hash, value)

    matching = [p for p, (rh, v) in per_peer.items() if v == "commit"]

    # 2. Values alone are insufficient; require an attested certificate.
    if len(matching) >= threshold and certificate is None:
        raise EquivocationDetected(
            f"round {round_id}: {len(matching)} matching values but no quorum certificate; "
            f"equivocation unfalsifiable"
        )

    # 3. Certificate must bind to this round and value, and be intersection-safe.
    if certificate is not None:
        if certificate.round_id != round_id or certificate.value != "commit":
            raise EquivocationDetected(
                f"certificate round/value mismatch: cert=({certificate.round_id},{certificate.value}) "
                f"expected=({round_id},commit)"
            )
        if len(certificate.signers) < threshold:
            raise EquivocationDetected(
                f"certificate undersized: {len(certificate.signers)} < threshold {threshold}"
            )
        if 2 * len(certificate.signers) - n < f + 1:
            raise EquivocationDetected(
                f"certificate not intersection-safe for n={n}, f={f}: "
                f"2t-n={2*len(certificate.signers)-n} < f+1={f+1}"
            )
        return "commit"

    return "abort"
