# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-commit-to-a-plan-when-a-byzantine-quorum-appears-satisfied.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-commit-to-a-plan-when-a-byzantine-quorum-appears-satisfied.warrant.json
# Markdown SHA-256:   2338360427bca19d83dc612b4d4c7856818470a546a0ebe9e2b25a89a0f68e0c
# Code AST SHA-256:   50432c3827da1fc5511ca87a201e9be566ee1803d09893bcbf730ddc21a95a79
# Verified Classes:   QuorumValidityError, Vote
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Mapping


class QuorumValidityError(RuntimeError):
    """Raised when quorum satisfaction is observed but quorum validity cannot be established."""


@dataclass(frozen=True)
class Vote:
    signer: str
    digest: str
    epoch: int
    signature_ok: bool


def canonical_digest(plan: Mapping) -> str:
    # Deterministic canonical form: sorted keys, explicit step count.
    canonical = json.dumps(plan, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def commit_plan(
    local_plan: Mapping,
    votes: list[Vote],
    threshold: int,
    epoch: int,
    membership: set[str],
) -> str:
    local_digest = canonical_digest(local_plan)

    # Reject votes outside the current epoch or membership, and unverified signatures.
    valid = [
        v for v in votes
        if v.epoch == epoch and v.signer in membership and v.signature_ok
    ]

    # Equivocation check: any signer with two distinct digests in this epoch is Byzantine.
    by_signer: dict[str, set[str]] = {}
    for v in valid:
        by_signer.setdefault(v.signer, set()).add(v.digest)
    equivocators = {s for s, digests in by_signer.items() if len(digests) > 1}
    if equivocators:
        raise QuorumValidityError(
            f"equivocation detected in epoch {epoch}: signers {sorted(equivocators)}"
        )

    # Digest-bound quorum: count only votes whose digest equals the locally re-derived digest.
    bound = [v for v in valid if v.digest == local_digest]
    if len(bound) < threshold:
        # Distinguish the coordinator-bug case for diagnostics.
        union_signers = {v.signer for v in valid}
        if len(union_signers) >= threshold:
            raise QuorumValidityError(
                "identity-bound quorum reached but no single digest reached threshold; "
                f"local_digest={local_digest} union_signers={sorted(union_signers)}"
            )
        raise QuorumValidityError(
            f"digest-bound quorum not reached: {len(bound)}/{threshold} for {local_digest}"
        )

    return local_digest
