# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-byzantine-agreement-on-task-outcome-as-unsound-when-the-auditor-quorum-is-drawn-from-a-shared-non-indepen.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-byzantine-agreement-on-task-outcome-as-unsound-when-the-auditor-quorum-is-drawn-from-a-shared-non-indepen.warrant.json
# Markdown SHA-256:   927c8ba732970a8eb96354647421b66eb7c1bc787fa3ff64b7eeb26be1312f75
# Code AST SHA-256:   d8d9cf7b7809a78a57b26376f217fa379c41e222e64b34c1d4d7132268801adb
# Verified Classes:   CorrelatedQuorumError, AuditorVote
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class CorrelatedQuorumError(RuntimeError):
    """Raised when a quorum's apparent agreement is not backed by independent voters."""


@dataclass
class AuditorVote:
    auditor_id: str
    verdict: str            # "PASS" / "FAIL"
    model_id: str
    prompt_hash: str
    retrieval_index_id: str
    reasoning_trace: str


def _signature(v: AuditorVote) -> str:
    return hashlib.sha256(
        f"{v.model_id}|{v.prompt_hash}|{v.retrieval_index_id}".encode()
    ).hexdigest()


def _trace_overlap(a: str, b: str) -> float:
    # Cheap proxy for reasoning-trace convergence; production uses embedding cosine.
    sa, sb = set(a.split()), set(b.split())
    if not sa or not sb:
        return 0.0
    return len(sa & sb) / len(sa | sb)


def effective_independent_voters(votes: list[AuditorVote], overlap_threshold: float = 0.85) -> int:
    """Count distinct failure modes, not distinct instances.

    Two auditors sharing a substrate signature AND converging in reasoning
    are counted as ONE voter: they share a common-mode failure path.
    """
    distinct = {}
    for v in votes:
        sig = _signature(v)
        if sig not in distinct:
            distinct[sig] = v
        else:
            if _trace_overlap(distinct[sig].reasoning_trace, v.reasoning_trace) >= overlap_threshold:
                continue  # clone of an existing voter; no added entropy
            distinct[sig + v.auditor_id] = v
    return len(distinct)


def commit_outcome(votes: list[AuditorVote], f: int) -> str:
    """Commit a task outcome only if effective independent quorum is met."""
    if not votes:
        raise CorrelatedQuorumError("no votes to adjudicate")

    verdicts = {v.verdict for v in votes}
    if len(verdicts) != 1:
        # Genuine disagreement: fall through to normal BFT handling elsewhere.
        return "CONTESTED"

    agreed = verdicts.pop()
    agreeing = [v for v in votes if v.verdict == agreed]
    eff_n = effective_independent_voters(agreeing)
    required = 2 * f + 1

    if eff_n < required:
        raise CorrelatedQuorumError(
            f"Apparent quorum of {len(agreeing)} agreeing auditors collapses to "
            f"effective_n={eff_n} independent voters (required {required}, f={f}). "
            f"Agreement is correlated, not Byzantine-safe: outcome '{agreed}' "
            f"must be reported as unverified-correlated, not committed."
        )

    return f"VERIFIED:{agreed}:eff_n={eff_n}"


# --- observed failure replay ---
votes = [
    AuditorVote("A1", "PASS", "model-x", "rubric-v3", "idx-shared",
                "loop bound fixed using range len inclusive check ok"),
    AuditorVote("A2", "PASS", "model-x", "rubric-v3", "idx-shared",
                "loop bound fixed using range len inclusive check ok"),
    AuditorVote("A3", "PASS", "model-x", "rubric-v3", "idx-shared",
                "loop bound fixed using range len inclusive check ok"),
]
try:
    commit_outcome(votes, f=1)  # 3-0 vote, but a single shared substrate
except CorrelatedQuorumError as e:
    print("BLOCKED:", e)
