# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-heterogeneous-quorum-s-agreement-as-a-divergence-signal-rather-than-a-commit-signal.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-heterogeneous-quorum-s-agreement-as-a-divergence-signal-rather-than-a-commit-signal.warrant.json
# Markdown SHA-256:   570df132f166926921fe442aa7f49a954fab3557fd6c3c13752be2861a266916
# Code AST SHA-256:   ee265b0772e10d495f1b69a3e6adeb2f910f6b53ba74d8344ded8042e63a92f9
# Verified Classes:   QuorumEvidenceCollapse, Vote, SpanProvenance
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Sequence


class QuorumEvidenceCollapse(RuntimeError):
    """Raised when a quorum reaches threshold but its supporting evidence is
    not independent (shared contaminated span), so agreement cannot be
    treated as a commit signal."""
    pass


@dataclass(frozen=True)
class Vote:
    member_id: str
    verdict: str
    cited_spans: frozenset[str]


@dataclass(frozen=True)
class SpanProvenance:
    span_id: str
    source: str          # "retrieval_cache", "memory_store", "tool_output", "clean_doc"
    sanitized: bool


def effective_quorum_size(votes: Sequence[Vote],
                          provenance: dict[str, SpanProvenance]) -> int:
    """Count independent agreeing votes. Two votes that cite the same
    unsanitized span collapse into one, because their agreement is explained
    by shared contamination rather than independent reasoning."""
    if not votes:
        return 0

    verdict = votes[0].verdict
    if any(v.verdict != verdict for v in votes):
        return 0  # no agreement at all

    seen_contaminated: set[str] = set()
    independent = 0
    for v in votes:
        contaminated = {
            s for s in v.cited_spans
            if s in provenance and not provenance[s].sanitized
        }
        if contaminated & seen_contaminated:
            # This vote's agreement is explained by a span another vote already
            # used. Collapse: do not increment.
            continue
        seen_contaminated |= contaminated
        independent += 1
    return independent


def commit_or_escalate(votes: Sequence[Vote],
                       provenance: dict[str, SpanProvenance],
                       f: int) -> str:
    """Commit only if the *independent* agreeing set reaches f+1.
    Otherwise raise, forcing escalation to a cache-bypassing re-query."""
    independent = effective_quorum_size(votes, provenance)
    required = f + 1
    if independent < required:
        collapsed = len(votes) - independent
        raise QuorumEvidenceCollapse(
            f"Quorum reached threshold on raw votes ({len(votes)}) but only "
            f"{independent} independent agreeing vote(s) after collapsing "
            f"{collapsed} vote(s) onto shared contaminated evidence; "
            f"required {required}. Escalating to isolated re-query."
        )
    return votes[0].verdict
