# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-task-under-a-quorum-view-that-is-not-a-valid-quorum-intersection.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-task-under-a-quorum-view-that-is-not-a-valid-quorum-intersection.warrant.json
# Markdown SHA-256:   94eb2f2c57d95feea2c34af90fdc700a45b5c07a5c826e5c816303a1d1fb0d7c
# Code AST SHA-256:   6c43bbb81b111453f73fe339837aaece75fbe9d0efaf7d049629b94f355d48d6
# Verified Classes:   QuorumIntersectionError, Vote
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict, Tuple


class QuorumIntersectionError(RuntimeError):
    """Raised when a vote set satisfies cardinality but not intersection validity."""
    pass


@dataclass(frozen=True)
class Vote:
    view: int
    epoch: int
    signer: str
    task_hash: str


def commit_task(
    votes: list[Vote],
    current_view: int,
    current_epoch: int,
    n: int,
    task_hash: str,
) -> str:
    """
    Commit a task record only if the vote set is a valid quorum:
    - cardinality >= 2f + 1 distinct signers
    - all votes share current_view and current_epoch
    - all votes agree on task_hash
    """
    if n < 4 or n % 3 != 1:
        raise QuorumIntersectionError(
            f"invalid membership size n={n}; expected n = 3f + 1 with f >= 1"
        )
    f = (n - 1) // 3
    threshold = 2 * f + 1

    # Key by (view, epoch, signer) so duplicates and cross-view votes
    # cannot inflate the count.
    keyed: Dict[Tuple[int, int, str], Vote] = {}
    for v in votes:
        if v.task_hash != task_hash:
            continue
        keyed[(v.view, v.epoch, v.signer)] = v

    distinct_signers = {k[2] for k in keyed}
    if len(distinct_signers) < threshold:
        raise QuorumIntersectionError(
            f"insufficient distinct signers: {len(distinct_signers)} < {threshold}"
        )

    for (view, epoch, signer) in keyed:
        if view != current_view:
            raise QuorumIntersectionError(
                f"vote from stale view {view} != {current_view} for signer {signer}"
            )
        if epoch != current_epoch:
            raise QuorumIntersectionError(
                f"vote from stale epoch {epoch} != {current_epoch} for signer {signer}"
            )

    # Cardinality and binding both hold; commit is safe.
    return task_hash
