# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-withhold-its-vote-when-a-byzantine-quorum-intersects-its-own-epistemic-uncertainty.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-withhold-its-vote-when-a-byzantine-quorum-intersects-its-own-epistemic-uncertainty.warrant.json
# Markdown SHA-256:   21bde5e18850dfbdb1384544380a1002e45fd5de864b5cf167653c9d8e6ab8be
# Code AST SHA-256:   28db5d8a8ff6b1f0ba49b97d276882a62479ea96f258c1f9efbbaad4dad87831
# Verified Classes:   QuorumIndependenceError, Vote
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class QuorumIndependenceError(RuntimeError):
    """Raised when a quorum's counted votes fail the independence invariant."""
    pass


@dataclass(frozen=True)
class Vote:
    instance_id: str
    decision: str            # "SUPPORT" | "REFUTE" | "ABSTAIN"
    margin: float            # top-token prob minus runner-up
    evidence_spans: tuple    # hashes of contested spans actually attended to
    truncated: bool = False


def span_hash(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]


def certify_vote(vote: Vote, contested_spans: set, margin_floor: float) -> Vote:
    """Downgrade an uncertain or uncertifiable vote to ABSTAIN."""
    if vote.margin < margin_floor:
        return Vote(vote.instance_id, "ABSTAIN", vote.margin, vote.evidence_spans, vote.truncated)
    if vote.truncated and (contested_spans - set(vote.evidence_spans)):
        # The voter cannot certify spans it never saw.
        return Vote(vote.instance_id, "ABSTAIN", vote.margin, vote.evidence_spans, vote.truncated)
    return vote


def commit_quorum(votes: list, contested_spans: set, f: int, margin_floor: float) -> str:
    certified = [certify_vote(v, contested_spans, margin_floor) for v in votes]
    counted = [v for v in certified if v.decision != "ABSTAIN"]

    # Effective N shrinks with abstentions; threshold is recomputed, never lowered.
    effective_n = len(counted)
    threshold = (2 * effective_n) // 3 + 1

    for decision in ("SUPPORT", "REFUTE"):
        faction = [v for v in counted if v.decision == decision]
        if len(faction) < threshold:
            continue
        # Independence invariant: need f+1 pairwise-disjoint evidence sets.
        distinct = {tuple(sorted(v.evidence_spans)) for v in faction}
        if len(distinct) < f + 1:
            raise QuorumIndependenceError(
                f"quorum for {decision} reached {len(faction)}/{effective_n} but only "
                f"{len(distinct)} distinct evidence sets (need {f + 1}); votes are "
                f"correlated, not independent — refusing to commit."
            )
        return decision

    raise QuorumIndependenceError(
        f"no faction reached threshold {threshold} over effective N={effective_n}; "
        f"re-sample with decorrelated evidence rather than lowering the threshold."
    )
