# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-byzantine-quorum-collapse-when-agent-auditors-equivocate-across-overlapping-quorum-slices.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-byzantine-quorum-collapse-when-agent-auditors-equivocate-across-overlapping-quorum-slices.warrant.json
# Markdown SHA-256:   a0e2a6f1b1fa272b62602c84f37408b0aacbf2f33fa79a706a32c266d148c962
# Code AST SHA-256:   05938a5e33de56940df964026ae54ef970d1ab30c9547c7f66ed8d08787f7374
# Verified Classes:   QuorumIntersectionError, Slice
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Mapping


class QuorumIntersectionError(RuntimeError):
    """Raised when a quorum slice cannot prove honest intersection with peers."""
    pass


@dataclass(frozen=True)
class Slice:
    owner: str
    members: FrozenSet[str]


def min_honest_intersection(
    slices: Mapping[str, Slice],
    byzantine: FrozenSet[str],
    f: int,
) -> int:
    """
    Compute the minimum number of honest auditors shared by any pair of slices.
    Safety requires this to be >= 1, which is guaranteed iff every pairwise
    intersection has size >= f + 1 (pigeonhole over the fault budget).
    """
    owners = list(slices)
    worst = None
    for i in range(len(owners)):
        for j in range(i + 1, len(owners)):
            a = slices[owners[i]]
            b = slices[owners[j]]
            shared = a.members & b.members
            honest_shared = shared - byzantine
            if worst is None or len(honest_shared) < worst:
                worst = len(honest_shared)
    return worst if worst is not None else 0


def certify_decision(
    decision_id: str,
    quorum: Slice,
    slices: Mapping[str, Slice],
    byzantine: FrozenSet[str],
    f: int,
    signatures: int,
) -> None:
    """
    Refuse to certify unless the quorum meets intra-slice size AND the global
    slice graph provably intersects in at least one honest auditor.
    """
    required = (2 * len(quorum.members)) // 3 + 1
    if signatures < required:
        raise QuorumIntersectionError(
            f"decision {decision_id}: quorum size {signatures} < required {required}"
        )

    deficit = min_honest_intersection(slices, byzantine, f)
    if deficit <= 0:
        raise QuorumIntersectionError(
            f"decision {decision_id}: honest intersection deficit ({deficit}); "
            f"equivocation would be unwitnessed — refusing to certify"
        )

    for owner, peer in slices.items():
        if len(peer.members & quorum.members) < f + 1:
            raise QuorumIntersectionError(
                f"decision {decision_id}: quorum fails f+1 intersection with slice {owner}"
            )
