# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-quorum-certificate-as-poisoned-when-the-signer-set-is-honest-by-count-but-equivocal-by-histor.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-quorum-certificate-as-poisoned-when-the-signer-set-is-honest-by-count-but-equivocal-by-histor.warrant.json
# Markdown SHA-256:   8be34776dde68e6eb3290e04c2529591a39a678d1e9f2367a91065f65ca9ce9e
# Code AST SHA-256:   f2cd20b77abcb581dfde57400ca58dcdcd41107c5d9204774584334c2e2b5376
# Verified Classes:   PoisonedQuorumCertificate, Vote
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class PoisonedQuorumCertificate(RuntimeError):
    """Raised when a numerically valid QC is lineage-degenerate."""


@dataclass(frozen=True)
class Vote:
    agent_id: str
    epoch: int
    lineage_root: str
    proposal_hash: str
    signature_valid: bool


def certify_quorum(
    votes: Iterable[Vote],
    proposal_hash: str,
    quorum_threshold: int,
) -> frozenset[str]:
    """
    Return the set of distinct lineage roots backing the proposal, or raise
    if the certificate's independent weight is below threshold.
    """
    roots: set[str] = set()
    seen_keys: set[tuple[str, int]] = set()

    for v in votes:
        if v.proposal_hash != proposal_hash:
            continue
        if not v.signature_valid:
            continue
        key = (v.agent_id, v.epoch)
        if key in seen_keys:
            continue
        seen_keys.add(key)
        if v.lineage_root in roots:
            # Same lineage, different key: correlated attestation, not
            # independent. Counting it would inflate the quorum.
            raise PoisonedQuorumCertificate(
                f"lineage {v.lineage_root!r} attested twice via "
                f"{v.agent_id}@{v.epoch}; quorum weight is correlated"
            )
        roots.add(v.lineage_root)

    if len(roots) < quorum_threshold:
        raise PoisonedQuorumCertificate(
            f"independent lineage weight {len(roots)} < required "
            f"{quorum_threshold}; certificate is numerically valid but "
            f"lineage-degenerate"
        )
    return frozenset(roots)
