# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-quorum-signature-bound-equivocation-and-the-2f-1-illusion-under-hallucinating-peers.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-quorum-signature-bound-equivocation-and-the-2f-1-illusion-under-hallucinating-peers.warrant.json
# Markdown SHA-256:   206f9353095584796ef3e595c412801232fed94d9b9e1e69bea8f57627158dd8
# Code AST SHA-256:   c70eebfa94f96a6da1a86bb7720443474d9997efe4a4b003c706fbcff50d1502
# Verified Classes:   CorrelatedQuorumError, Vote, Quorum
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class CorrelatedQuorumError(RuntimeError):
    """Raised when a quorum threshold is met only by provenance-correlated votes."""


@dataclass
class Vote:
    agent_id: str
    decision: str            # "PASS" / "FAIL"
    provenance: str          # hash of retrieval index + model family + prompt template
    stable: bool             # survived perturbation replay
    verification_strength: int  # 0 = heuristic, 1 = schema validator, 2 = replayable trace


@dataclass
class Quorum:
    votes: list = field(default_factory=list)
    f: int = 1

    @property
    def threshold(self) -> int:
        return 2 * self.f + 1

    def _provenance_classes(self, decision: str) -> set:
        # Only stable votes count as witnesses; correlated provenances collapse.
        return {
            v.provenance
            for v in self.votes
            if v.decision == decision and v.stable
        }

    def certify(self, decision: str) -> int:
        classes = self._provenance_classes(decision)
        return len(classes)

    def commit(self) -> str:
        for decision in ("PASS", "FAIL"):
            raw_count = sum(1 for v in self.votes if v.decision == decision)
            if raw_count < self.threshold:
                continue
            certified = self.certify(decision)
            if certified < self.threshold:
                minority = [v for v in self.votes if v.decision != decision]
                minority_strength = max(
                    (v.verification_strength for v in minority), default=0
                )
                majority_strength = max(
                    (v.verification_strength for v in self.votes
                     if v.decision == decision), default=0
                )
                raise CorrelatedQuorumError(
                    f"decision={decision} raw_count={raw_count} "
                    f"threshold={self.threshold} but certified_witnesses={certified} "
                    f"(provenance classes collapsed). "
                    f"majority_strength={majority_strength} "
                    f"minority_strength={minority_strength}. "
                    f"Escalate to trace-replay; do not commit on headcount."
                )
            return decision
        raise CorrelatedQuorumError(
            f"no decision reached threshold={self.threshold}; "
            f"quorum is in challengeable state."
        )


def adjudicate(votes: list, f: int = 1) -> str:
    q = Quorum(votes=votes, f=f)
    return q.commit()


if __name__ == "__main__":
    # The observed failure: three correlated PASS votes, two independent FAIL votes.
    correlated_prov = hashlib.sha256(b"model-A|index-shared|prompt-v3").hexdigest()
    independent_prov = hashlib.sha256(b"model-B|index-independent|prompt-v3").hexdigest()

    votes = [
        Vote("a1", "PASS", correlated_prov, stable=True, verification_strength=0),
        Vote("a2", "PASS", correlated_prov, stable=True, verification_strength=0),
        Vote("a3", "PASS", correlated_prov, stable=True, verification_strength=0),
        Vote("b1", "FAIL", independent_prov, stable=True, verification_strength=1),
        Vote("b2", "FAIL", independent_prov, stable=True, verification_strength=1),
    ]

    try:
        result = adjudicate(votes, f=1)
        print("committed:", result)
    except CorrelatedQuorumError as e:
        print("BLOCKED:", e)
