# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-consensus-commit-the-quorum-poisoning-boundary-in-speculative-multi-agent-orchestration.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-consensus-commit-the-quorum-poisoning-boundary-in-speculative-multi-agent-orchestration.warrant.json
# Markdown SHA-256:   cc79ced3edd4964cdbefcac7c0ec334019c47ac1f9842ab2e30faafa58926c0c
# Code AST SHA-256:   a35c30fc8290c1d1e1a96f5fb9a3366f578f61d5598d7c3c937f06635fc107d5
# Verified Classes:   QuorumPoisoningError, Vote, ConsensusGate
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class QuorumPoisoningError(RuntimeError):
    """Raised when a consensus commit is backed by a single shared premise."""


@dataclass
class Vote:
    agent_id: str
    conclusion: str
    premise_fingerprint: str
    has_falsifying_evidence: bool = False


@dataclass
class ConsensusGate:
    threshold: int
    min_distinct_premises: int = 2

    def commit(self, votes: List[Vote]) -> str:
        if not votes:
            raise QuorumPoisoningError("no votes to gate on")

        tally: Dict[str, List[Vote]] = {}
        for v in votes:
            tally.setdefault(v.conclusion, []).append(v)

        winner, agreeing = max(tally.items(), key=lambda kv: len(kv[1]))
        if len(agreeing) < self.threshold:
            raise QuorumPoisoningError(
                f"quorum not reached: {len(agreeing)} < {self.threshold}"
            )

        fingerprints = {v.premise_fingerprint for v in agreeing}
        if len(fingerprints) < self.min_distinct_premises:
            # Agreement is correlated: all supporters share one premise.
            if not any(v.has_falsifying_evidence for v in agreeing):
                raise QuorumPoisoningError(
                    "consensus agrees on a single shared premise with no "
                    "falsifying evidence; vote is information-free"
                )
            raise QuorumPoisoningError(
                "consensus agrees on a single premise fingerprint; "
                "re-fan-out with diversified contexts before commit"
            )

        return winner


def speculative_commit(votes: List[Vote], threshold: int = 3) -> str:
    gate = ConsensusGate(threshold=threshold)
    try:
        return gate.commit(votes)
    except QuorumPoisoningError:
        # Abort, do not lower threshold; caller must re-fan-out or escalate.
        raise
