# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-task-commit-it-cannot-verify-quorum-intersection-blindness-in-byzantine-agent-consensus-under-partial-observability.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-task-commit-it-cannot-verify-quorum-intersection-blindness-in-byzantine-agent-consensus-under-partial-observability.warrant.json
# Markdown SHA-256:   e0691089bf00cff166c00e389f3cb4cb1dae68c54350e03c95bddce545f378da
# Code AST SHA-256:   68d9741c744920bfebdc190b3e03c1f2d156b71d761fc79b1bf9f7a6477258e2
# Verified Classes:   SplitEvidenceQuorumError, PinnedVote
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Iterable


class SplitEvidenceQuorumError(RuntimeError):
    """Raised when a would-be quorum of COMMIT votes is not pinned to a common referent.

    This is the operational enforcement of the Evidence-Locality Invariant (ELI):
    a quorum of signatures is only a quorum of evidence if every COMMIT vote in it
    shares the same (epoch, snapshot_id) referent. Without the pin, 2f+1 honest
    agents can commit a task no single agent could verify, and the audit replay
    will surface the commit as contradicted.
    """


@dataclass(frozen=True)
class PinnedVote:
    agent_id: str
    decision: str          # "COMMIT" | "ABORT"
    epoch: int
    snapshot_id: str
    predicate: str         # e.g. "schema_version==42"
    evidence_digest: str   # hash of the tool output the agent actually saw


def commit_round(
    votes: Iterable[PinnedVote],
    *,
    total_agents: int,
    byzantine_budget: int,
    pinned_epoch: int,
    pinned_snapshot_id: str,
) -> str:
    """Return the round outcome, or raise if the quorum is evidentially hollow.

    Safety rule: a COMMIT quorum is valid only if it has size >= 2f+1 AND every
    COMMIT vote in it is pinned to (pinned_epoch, pinned_snapshot_id). Votes
    pinned to a different referent are *not* counted toward the quorum — they
    are evidence of an observation partition, and the round must abort.
    """
    votes = list(votes)
    if len(votes) != total_agents:
        raise SplitEvidenceQuorumError(
            f"expected {total_agents} votes, got {len(votes)}; round incomplete"
        )

    quorum_threshold = 2 * byzantine_budget + 1

    commits = [v for v in votes if v.decision == "COMMIT"]
    pinned_commits = [
        v for v in commits
        if v.epoch == pinned_epoch and v.snapshot_id == pinned_snapshot_id
    ]
    unpinned_commits = [v for v in commits if v not in pinned_commits]

    if len(commits) >= quorum_threshold and unpinned_commits:
        # The dangerous case from the record: enough signatures, but the
        # signatures are over incompatible world-states.
        referents = sorted({(v.epoch, v.snapshot_id) for v in commits})
        raise SplitEvidenceQuorumError(
            "split-evidence quorum: "
            f"{len(commits)} COMMIT votes span referents {referents}; "
            f"pinned referent was ({pinned_epoch}, {pinned_snapshot_id!r}). "
            "Abort round and re-issue reads pinned to a single epoch."
        )

    if len(pinned_commits) >= quorum_threshold:
        return "COMMIT"

    # An honest ABORT vote whose evidence contradicts the pinned referent is
    # itself a signal: the pinned snapshot may be stale. Surface it rather
    # than silently discarding it.
    contradicting_aborts = [
        v for v in votes
        if v.decision == "ABORT"
        and (v.epoch, v.snapshot_id) != (pinned_epoch, pinned_snapshot_id)
    ]
    if contradicting_aborts:
        raise SplitEvidenceQuorumError(
            f"pinned referent ({pinned_epoch}, {pinned_snapshot_id!r}) is "
            f"contradicted by {len(contradicting_aborts)} ABORT vote(s) on "
            "other referents; snapshot may be stale, re-pin before voting"
        )

    return "ABORT"
