# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-quorum-is-byzantine-unsafe-before-a-decision-commits.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-quorum-is-byzantine-unsafe-before-a-decision-commits.warrant.json
# Markdown SHA-256:   32b715a7b97e09fb260761724222a97641454c2eae06f58edd40b24328dd84d1
# Code AST SHA-256:   d5006d6461757353e4103574d40d3a5e5079d577f205bb60445da032ab39e1c7
# Verified Classes:   QuorumIntersectionError, Vote
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class QuorumIntersectionError(RuntimeError):
    """Raised when a quorum is cardinality-safe but intersection-unsafe."""


@dataclass(frozen=True)
class Vote:
    agent_id: str
    fault_domain: str
    epoch: int


def verify_quorum_safety(
    prepare: FrozenSet[Vote],
    commit: FrozenSet[Vote],
    f: int,
    current_epoch: int,
) -> None:
    # Epoch fencing: stale votes must never count toward threshold.
    for v in prepare | commit:
        if v.epoch != current_epoch:
            raise QuorumIntersectionError(
                f"stale vote from {v.agent_id} at epoch {v.epoch}, "
                f"current epoch {current_epoch}"
            )

    # Cardinality check (necessary, not sufficient).
    if len(prepare) < 2 * f + 1 or len(commit) < 2 * f + 1:
        raise QuorumIntersectionError(
            f"cardinality below 2f+1: prepare={len(prepare)}, commit={len(commit)}"
        )

    # Intersection safety: must share at least f+1 independent honest agents.
    inter = prepare & commit
    if len(inter) < f + 1:
        raise QuorumIntersectionError(
            f"quorum intersection {len(inter)} < f+1={f + 1}; "
            "cardinality held but intersection safety failed"
        )

    # Independence check: distinct fault domains, not just distinct IDs.
    domains = {v.fault_domain for v in inter}
    if len(domains) < f + 1:
        raise QuorumIntersectionError(
            f"only {len(domains)} independent fault domains in intersection, "
            f"need {f + 1}; correlated faults exceed configured f"
        )


def commit_decision(prepare, commit, f, current_epoch) -> bool:
    verify_quorum_safety(prepare, commit, f, current_epoch)
    return True
