# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-equivocation-drift-when-heterogeneous-byzantine-llm-voters-converge-on-a-shared-state-without-agreeing-on-the-evidence.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-equivocation-drift-when-heterogeneous-byzantine-llm-voters-converge-on-a-shared-state-without-agreeing-on-the-evidence.warrant.json
# Markdown SHA-256:   250eb47d396ed6cc1cde4ab7c7f04c7123ad4e408ffc9cb25d4e2845efd9c758
# Code AST SHA-256:   111cc1ecc1ff1a76e9aea950298d4fa93e34ec0ff1fcc0d58be06239f8012bf4
# Verified Classes:   EquivocationDriftError, EvidenceRef, Ballot
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class EquivocationDriftError(RuntimeError):
    """Raised when a vote quorum passes but the independence set does not."""


@dataclass(frozen=True)
class EvidenceRef:
    source_id: str
    content_hash: str
    fetched_at: float
    derived: bool = False  # True if this ref points at another agent's message


@dataclass
class Ballot:
    agent_id: str
    vote: str  # "commit" | "reject"
    evidence: list[EvidenceRef] = field(default_factory=list)


def independence_set(
    ballots: Iterable[Ballot],
    source_ttl: dict[str, float],
    now: float,
) -> set[tuple[str, str]]:
    seen: set[tuple[str, str]] = set()
    for b in ballots:
        if b.vote != "commit":
            continue
        for ref in b.evidence:
            if ref.derived:
                continue  # peer rationale: not independent
            if now - ref.fetched_at > source_ttl.get(ref.source_id, 0.0):
                continue  # stale
            seen.add((ref.source_id, ref.content_hash))
    return seen


def verify_commit(
    ballots: list[Ballot],
    n: int,
    source_ttl: dict[str, float],
    now: float,
) -> None:
    quorum = (2 * n) // 3 + 1
    commits = [b for b in ballots if b.vote == "commit"]
    if len(commits) < quorum:
        raise EquivocationDriftError(
            f"vote quorum failed: {len(commits)}/{n} < {quorum}"
        )
    indep = independence_set(commits, source_ttl, now)
    if len(indep) < quorum:
        raise EquivocationDriftError(
            f"equivocation drift: vote quorum={len(commits)} passed "
            f"but independence set={len(indep)} < {quorum}; "
            f"rationales are mutually exclusive or derived"
        )
    # invariant holds: quorum backed by quorum-sized independent evidence
