# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-quorum-commit-under-equivocating-agents-in-partially-synchronous-swarms.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-quorum-commit-under-equivocating-agents-in-partially-synchronous-swarms.warrant.json
# Markdown SHA-256:   e2c2a9b691aede4b813f6dd289ead6ced4aab282c3547505ebc31021d7115d15
# Code AST SHA-256:   3d98afa521f16c39fb2baf121bf40b4c7e5727a97cbdfd28292d4e0c79b8a273
# Verified Classes:   SpeculativeCommitViolation, Vote, Quorum, SpeculativeConsensusGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Dict, Optional


class SpeculativeCommitViolation(RuntimeError):
    """Raised when a speculative commit is externalized before its
    equivocation set is monotone-closed, violating the closure invariant."""
    pass


@dataclass(frozen=True)
class Vote:
    agent_id: str
    round_no: int
    payload_hash: str
    signature: str


@dataclass
class Quorum:
    round_no: int
    payload_hash: str
    members: FrozenSet[str]
    equivocation_closed: bool = False
    speculation_depth: int = 0
    externalized: bool = False


class SpeculativeConsensusGate:
    def __init__(self, quorum_size: int, auditor_intersection_guaranteed: bool):
        self.quorum_size = quorum_size
        self.auditor_intersection_guaranteed = auditor_intersection_guaranteed
        self._votes: Dict[int, Dict[str, list[Vote]]] = {}
        self._audit_reports: Dict[int, list[FrozenSet[str]]] = {}

    def record_vote(self, v: Vote) -> None:
        self._votes.setdefault(v.round_no, {}).setdefault(v.agent_id, []).append(v)

    def record_audit(self, round_no: int, equivocators: FrozenSet[str]) -> None:
        self._audit_reports.setdefault(round_no, []).append(equivocators)

    def equivocation_closed(self, round_no: int, members: FrozenSet[str]) -> bool:
        # Closure requires the union of auditor views to cover every member
        # AND the auditor family to be quorum-intersecting. Without intersection
        # guarantee, closure is unprovable even if reports look complete.
        if not self.auditor_intersection_guaranteed:
            return False
        reports = self._audit_reports.get(round_no, [])
        if not reports:
            return False
        covered = frozenset().union(*reports)
        # every member must have been audited by at least one report whose
        # view intersected another auditor's view
        return members.issubset(covered) and len(reports) >= 2

    def try_externalize(self, q: Quorum, gst_confirmed: bool) -> None:
        if q.speculation_depth > 1:
            raise SpeculativeCommitViolation(
                f"round {q.round_no}: speculation depth {q.speculation_depth} "
                f"exceeds depth-1 invariant; cannot externalize chained "
                f"speculative commits"
            )
        closed = self.equivocation_closed(q.round_no, q.members)
        if not closed and not gst_confirmed:
            raise SpeculativeCommitViolation(
                f"round {q.round_no}: quorum satisfied but equivocation set "
                f"not monotone-closed and GST not confirmed; externalization "
                f"would permit forked state under partition"
            )
        if closed and self._has_equivocator(q.round_no, q.members):
            raise SpeculativeCommitViolation(
                f"round {q.round_no}: equivocation detected in quorum "
                f"membership after closure; commit must retract, not externalize"
            )
        q.equivocation_closed = closed
        q.externalized = True

    def _has_equivocator(self, round_no: int, members: FrozenSet[str]) -> bool:
        for agent_id in members:
            votes = self._votes.get(round_no, {}).get(agent_id, [])
            hashes = {v.payload_hash for v in votes}
            if len(hashes) > 1:
                return True
        return False
