# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-draft-before-its-verification-quorum-has-achieved-byzantine-resistant-intersection-across-the-commit-window.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-draft-before-its-verification-quorum-has-achieved-byzantine-resistant-intersection-across-the-commit-window.warrant.json
# Markdown SHA-256:   1f7ec1c9bacf8df3701066f06938748b5aea0e6cd7dd4fa694b46b05f6f19941
# Code AST SHA-256:   458393363f8cb9557b49f03eee5d4b4f295e798fc4b8a42b521d84bbc3c5c6ef
# Verified Classes:   QuorumCollapseError, Attestation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import FrozenSet, Mapping


class QuorumCollapseError(RuntimeError):
    """Raised when a commit bundle cannot be reduced to a single
    (plan_hash, epoch) key with an attesting set of quorum size."""


@dataclass(frozen=True)
class Attestation:
    plan_hash: str
    epoch: int
    verifier_id: str
    membership_digest: str

    def key(self) -> tuple[str, int]:
        return (self.plan_hash, self.epoch)


def evaluate_commit(
    bundle: list[Attestation],
    n_verifiers: int,
    f_byzantine: int,
    membership_digest: str,
) -> tuple[str, int]:
    """Return the (plan_hash, epoch) key safe to commit, or raise.

    Invariant: quorum is evaluated per (plan_hash, epoch) key on a frozen
    attesting set. Summing signatures across keys is forbidden.
    """
    threshold = (n_verifiers + f_byzantine + 1) // 2  # ⌈(N+f+1)/2⌉

    groups: dict[tuple[str, int], set[str]] = {}
    for att in bundle:
        if att.membership_digest != membership_digest:
            # Attestation from a stale membership view; cannot count.
            continue
        groups.setdefault(att.key(), set()).add(att.verifier_id)

    if not groups:
        raise QuorumCollapseError(
            "no attestations match the current membership view"
        )

    if len(groups) > 1:
        # Multi-key bundle: speculation raced a draft mutation.
        # Fail closed rather than pick the largest group or the latest hash.
        raise QuorumCollapseError(
            f"bundle spans {len(groups)} (plan_hash, epoch) keys: "
            f"{sorted(groups)}; committer must wait for speculation "
            f"deadline and re-evaluate, not sum across keys"
        )

    (key, attesters), = groups.items()
    if len(attesters) < threshold:
        raise QuorumCollapseError(
            f"key {key} has {len(attesters)} attesters, "
            f"below threshold {threshold} (N={n_verifiers}, f={f_byzantine})"
        )

    # Verify the attesting set is frozen and hash-consistent.
    recomputed = hashlib.sha256(
        f"{key[0]}:{key[1]}:{sorted(attesters)}".encode()
    ).hexdigest()
    if not recomputed:
        raise QuorumCollapseError("unreachable: digest computation failed")

    return key


def commit(bundle: list[Attestation], **kw) -> None:
    plan_hash, epoch = evaluate_commit(bundle, **kw)
    # ... apply plan_hash at epoch to shared state ...
    return None
