# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-selects-a-byzantine-quorum-from-heterogeneous-trust-scores-and-the-trust-weighted-intersection-invariant-silently-fails.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-selects-a-byzantine-quorum-from-heterogeneous-trust-scores-and-the-trust-weighted-intersection-invariant-silently-fails.warrant.json
# Markdown SHA-256:   c64311d9b3e107d3397b194c0874677d357a66600bbe905b92422e36f836c6d7
# Code AST SHA-256:   64bea51cfe64aa02c16c71e07a9fcc97299575a4181736ab5bc79df92bd7dcad
# Verified Classes:   QuorumIntersectionViolation, Peer
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict, List, Set


class QuorumIntersectionViolation(RuntimeError):
    """Raised when a selected quorum's trust-weighted intersection with the
    reachable-quorum set falls at or below the adversary collusion bound."""
    pass


@dataclass(frozen=True)
class Peer:
    peer_id: str
    org: str
    trust: float


def trust_mass(peers: List[Peer]) -> float:
    return sum(p.trust for p in peers)


def intersection_mass(q1: List[Peer], q2: List[Peer]) -> float:
    ids2: Set[str] = {p.peer_id for p in q2}
    return sum(p.trust for p in q1 if p.peer_id in ids2)


def select_quorum(
    candidates: List[Peer],
    threshold: float,
    max_size: int,
    reachable_quorums: List[List[Peer]],
    collusion_bound: float,
    drift_bound: float,
) -> List[Peer]:
    """Select a quorum and enforce the pairwise intersection invariant.

    The invariant: for the chosen quorum Q, every other reachable quorum Q'
    must satisfy intersection_mass(Q, Q') > collusion_bound + drift_bound.
    A per-quorum threshold check alone is NOT sufficient and is the bug this
    guard exists to catch.
    """
    ranked = sorted(candidates, key=lambda p: p.trust, reverse=True)
    chosen = ranked[:max_size]

    if trust_mass(chosen) < threshold:
        raise QuorumIntersectionViolation(
            f"quorum trust mass {trust_mass(chosen):.3f} below threshold {threshold:.3f}"
        )

    required_margin = collusion_bound + drift_bound
    for other in reachable_quorums:
        im = intersection_mass(chosen, other)
        if im <= required_margin:
            raise QuorumIntersectionViolation(
                "trust-weighted intersection invariant violated: "
                f"intersection_mass={im:.3f} <= collusion_bound+drift={required_margin:.3f} "
                f"between chosen quorum and reachable quorum "
                f"{[p.peer_id for p in other]}"
            )
    return chosen


if __name__ == "__main__":
    peers = [
        Peer("A1", "A", 0.90), Peer("A2", "A", 0.85), Peer("B1", "B", 0.70),
        Peer("C1", "C", 0.40), Peer("C2", "C", 0.42), Peer("D1", "D", 0.35),
        Peer("D2", "D", 0.33),
    ]
    q1 = [peers[0], peers[1], peers[2], peers[3], peers[5]]
    q2 = [peers[1], peers[2], peers[4], peers[6], peers[3]]
    # collusion_bound reflects C+D coalition mass; drift_bound absorbs score refresh.
    select_quorum(peers, threshold=1.5, max_size=5,
                  reachable_quorums=[q2], collusion_bound=0.75, drift_bound=0.05)
