# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-byzantine-llm-peer-s-semantically-plausible-vote-as-a-distinct-attack-class-from-a-crashed-peer-s-silence.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-byzantine-llm-peer-s-semantically-plausible-vote-as-a-distinct-attack-class-from-a-crashed-peer-s-silence.warrant.json
# Markdown SHA-256:   6e6e03fc1f3b07e7d535113fd620becc1e955934448945d8f69d86132d2786ed
# Code AST SHA-256:   854053d0aca5ba94199e9ded03565d184652af3fa1ba5a92989b45c535514ebb
# Verified Classes:   CorrelatedByzantineQuorumError, Vote, QuorumResult
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Iterable


class CorrelatedByzantineQuorumError(RuntimeError):
    """Raised when a quorum is reached but rests on too few independent evidence roots."""
    pass


@dataclass(frozen=True)
class Vote:
    peer_id: str
    verdict: str                      # "VERIFIED" | "REFUTED"
    evidence_roots: frozenset[str]    # provenance hashes of every artifact relied upon
    rationale: str = ""               # NOT used for weighting; fluency is attacker-controlled


@dataclass
class QuorumResult:
    verdict: str
    vote_count: int
    effective_roots: int
    requires_grounding: bool


def effective_quorum(
    votes: Iterable[Vote],
    n: int,
    require_independent_roots: int,
) -> QuorumResult:
    """
    Compute quorum over evidence roots rather than raw votes.

    A quorum of VERIFIED votes that all trace to the same evidence root has
    effective independence 1, regardless of how many peers voted. Such a
    result must NOT be emitted; it must be escalated to out-of-band grounding.
    """
    votes = list(votes)
    verified = [v for v in votes if v.verdict == "VERIFIED"]

    # Classical liveness check: do we even have a majority of voters?
    if len(verified) * 2 <= n:
        return QuorumResult("NO_QUORUM", len(verified), 0, requires_grounding=False)

    # Count distinct evidence roots backing the VERIFIED verdict.
    roots: set[str] = set()
    for v in verified:
        roots.update(v.evidence_roots)

    effective = len(roots)

    # Correlated-Byzantine guard: quorum reached, but independence too low.
    if effective < require_independent_roots:
        # Every verified vote shares a poisoned ancestor -> refuse to emit.
        raise CorrelatedByzantineQuorumError(
            f"Quorum of {len(verified)} VERIFIED votes rests on only "
            f"{effective} independent evidence root(s); required "
            f"{require_independent_roots}. Treating as correlated Byzantine, "
            f"not ordinary fault. Escalating to out-of-band grounding."
        )

    return QuorumResult(
        verdict="VERIFIED",
        vote_count=len(verified),
        effective_roots=effective,
        requires_grounding=False,
    )


def attest_root(artifact_text: str, source_id: str) -> str:
    """Provenance hash for a retrieved artifact; dedup key for evidence roots."""
    h = hashlib.sha256()
    h.update(source_id.encode())
    h.update(b"\x00")
    h.update(artifact_text.encode())
    return h.hexdigest()


if __name__ == "__main__":
    poisoned = attest_root("The claim is verified per [fabricated-cite].", "attacker-doc")
    trusted = attest_root("Independent API confirms claim.", "trusted-api")

    # Three peers all read the same poisoned document: correlated votes.
    correlated = [
        Vote("A", "VERIFIED", frozenset({poisoned})),
        Vote("B", "VERIFIED", frozenset({poisoned})),
        Vote("D", "VERIFIED", frozenset({poisoned})),
        Vote("C", "REFUTED", frozenset({trusted})),
        Vote("E", "REFUTED", frozenset({trusted})),
    ]
    try:
        effective_quorum(correlated, n=5, require_independent_roots=2)
    except CorrelatedByzantineQuorumError as exc:
        print(f"HALT: {exc}")

    # Same voters, but one verified vote grounded out-of-band: independence restored.
    grounded = [
        Vote("A", "VERIFIED", frozenset({poisoned})),
        Vote("B", "VERIFIED", frozenset({poisoned})),
        Vote("D", "VERIFIED", frozenset({poisoned, trusted})),  # independent corroboration
        Vote("C", "REFUTED", frozenset({trusted})),
        Vote("E", "REFUTED", frozenset({trusted})),
    ]
    print(effective_quorum(grounded, n=5, require_independent_roots=2))
