# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-equivocation-tolerant-agent-quorums-from-collapsing-under-partial-byzantine-membership-churn.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-equivocation-tolerant-agent-quorums-from-collapsing-under-partial-byzantine-membership-churn.warrant.json
# Markdown SHA-256:   47b3c183c057dd5303f452d6f535e2c0ff72121bb22cdc91fcd420487b304913
# Code AST SHA-256:   0fea189a6c0035e2c46c777f6bcce088fcc076d63264c2420deb4d84f758724f
# Verified Classes:   QuorumIntersectionViolation, Vote, DecisionEpoch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class QuorumIntersectionViolation(RuntimeError):
    """Raised when prepare/commit quorums fail the f+1 intersection invariant."""
    pass


@dataclass(frozen=True)
class Vote:
    member_id: str
    proposal_hash: str
    epoch_id: int


@dataclass
class DecisionEpoch:
    epoch_id: int
    f: int
    active_members: FrozenSet[str]
    votes: list = field(default_factory=list)

    def cast(self, vote: Vote) -> None:
        # Epoch-scoped credential: reject votes from evicted members or stale epochs.
        if vote.epoch_id != self.epoch_id:
            raise QuorumIntersectionViolation(
                f"stale vote from {vote.member_id}: epoch {vote.epoch_id} != {self.epoch_id}"
            )
        if vote.member_id not in self.active_members:
            raise QuorumIntersectionViolation(
                f"vote from non-member {vote.member_id} in epoch {self.epoch_id}"
            )
        self.votes.append(vote)

    def quorum(self, proposal_hash: str) -> FrozenSet[str]:
        return frozenset(
            v.member_id for v in self.votes if v.proposal_hash == proposal_hash
        )


def verify_commit(
    epoch: DecisionEpoch,
    prepare_members: FrozenSet[str],
    commit_members: FrozenSet[str],
) -> None:
    threshold = 2 * epoch.f + 1
    if len(prepare_members) < threshold or len(commit_members) < threshold:
        raise QuorumIntersectionViolation(
            f"quorum below threshold {threshold}: "
            f"prepare={len(prepare_members)} commit={len(commit_members)}"
        )
    # Union-based intersection: members active across the whole epoch, not just at close.
    union_active = prepare_members | commit_members
    intersection = prepare_members & commit_members
    required = epoch.f + 1
    if len(intersection) < required:
        raise QuorumIntersectionViolation(
            f"intersection {len(intersection)} < f+1={required} over union "
            f"{len(union_active)}; equivocation possible between prepare and commit"
        )
