# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-quorum-equivocation-when-byzantine-peers-forge-per-view-votes-across-a-reconfiguration-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-quorum-equivocation-when-byzantine-peers-forge-per-view-votes-across-a-reconfiguration-boundary.warrant.json
# Markdown SHA-256:   9027388f73ac752e19c2f18c2410c3d028bf9e48e238b22a92e33ec636f128c2
# Code AST SHA-256:   227e8fb4852d495cf46f7da6c5e00592dd5eb8d9b41751e0a1fc5137c3c6ddb7
# Verified Classes:   QuorumEquivocationError, Certificate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Mapping


class QuorumEquivocationError(RuntimeError):
    """Raised when a decision certificate's quorum intersects another live
    quorum in only a single member that has cross-epoch ballots for one view."""
    pass


@dataclass(frozen=True)
class Certificate:
    view: int
    epoch: int
    quorum: FrozenSet[str]
    decision: str


def detect_quorum_equivocation(
    certs: list[Certificate],
    ballot_history: Mapping[str, Mapping[int, set[int]]],  # agent -> view -> {epochs}
    byzantine_threshold: int,
) -> None:
    """
    Reject if two certificates for the same view but different epochs have a
    quorum intersection of size <= byzantine_threshold AND the sole intersecting
    member(s) signed ballots in more than one epoch for that view.
    """
    for i, a in enumerate(certs):
        for b in certs[i + 1:]:
            if a.view != b.view or a.epoch == b.epoch:
                continue
            shared = a.quorum & b.quorum
            if len(shared) > byzantine_threshold:
                continue  # enough honest overlap to tolerate equivocation
            if len(shared) == 0:
                raise QuorumEquivocationError(
                    f"disjoint quorums for view {a.view}: "
                    f"epoch {a.epoch} vs {b.epoch} share no member"
                )
            for agent in shared:
                epochs = ballot_history.get(agent, {}).get(a.view, set())
                if len(epochs) > 1:
                    raise QuorumEquivocationError(
                        f"agent {agent} signed view {a.view} in epochs {sorted(epochs)}; "
                        f"quorum intersection {sorted(shared)} is below honest threshold "
                        f"{byzantine_threshold + 1}"
                    )
    # If no violation, the caller may commit; the invariant held.
    return None


def commit_decision(
    cert: Certificate,
    peers: list[Certificate],
    ballot_history: Mapping[str, Mapping[int, set[int]]],
    byzantine_threshold: int,
) -> str:
    detect_quorum_equivocation([cert, *peers], ballot_history, byzantine_threshold)
    return cert.decision
