# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-count-a-byzantine-quorum-vote-from-a-heterogeneous-llm-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-count-a-byzantine-quorum-vote-from-a-heterogeneous-llm-agent.warrant.json
# Markdown SHA-256:   cf71d888f4aeef21f1caed90c3341505a3f676c6492bc5d15047e616dbeaa6b3
# Code AST SHA-256:   89080f08c05fe9e1c46167ae087ec9200d1069e1d0b4530dec4d88e5a7f4be55
# Verified Classes:   ProvenanceInvalidVote, Vote
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence


class ProvenanceInvalidVote(RuntimeError):
    """Raised when a vote is authentic but must not count toward quorum."""
    pass


@dataclass(frozen=True)
class Vote:
    agent_id: str
    model_family: str
    prompt_hash: str
    decoding_config: str
    block_hash: str
    height: int
    justification_embedding: tuple[float, ...]
    local_view_hashes: frozenset[str]


def _cosine(a: tuple[float, ...], b: tuple[float, ...]) -> float:
    dot = sum(x * y for x, y in zip(a, b))
    na = sum(x * x for x in a) ** 0.5
    nb = sum(y * y for y in b) ** 0.5
    if na == 0 or nb == 0:
        return 0.0
    return dot / (na * nb)


def admit_vote(
    vote: Vote,
    already_counted: Sequence[Vote],
    duplicate_threshold: float = 0.92,
) -> bool:
    if vote.block_hash not in vote.local_view_hashes:
        raise ProvenanceInvalidVote(
            f"agent {vote.agent_id} voted for {vote.block_hash} "
            f"not present in its own local view"
        )

    for prior in already_counted:
        if (
            prior.model_family == vote.model_family
            and prior.prompt_hash == vote.prompt_hash
            and prior.decoding_config == vote.decoding_config
        ):
            raise ProvenanceInvalidVote(
                f"agent {vote.agent_id} shares full provenance tuple with "
                f"{prior.agent_id}; not an independent voter"
            )
        if _cosine(prior.justification_embedding, vote.justification_embedding) >= duplicate_threshold:
            raise ProvenanceInvalidVote(
                f"agent {vote.agent_id} justification is near-duplicate of "
                f"{prior.agent_id} at threshold {duplicate_threshold}; "
                f"suspected correlated fault"
            )

    return True
