# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-byzantine-agreement-stop-trusting-llm-agent-testimony-before-it-commits-shared-state.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-byzantine-agreement-stop-trusting-llm-agent-testimony-before-it-commits-shared-state.warrant.json
# Markdown SHA-256:   6df9c4376e8d4de5c39f6300fc23d1a3fb3b57d77ac2e4bd132b93417a80b0c1
# Code AST SHA-256:   23e39cf0f2934cf7a2c514a04182529fbf5157ba2867c35004eba6b0aa8d158f
# Verified Classes:   CorrelatedQuorumError, NonReproducibleTransitionError, Vote
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Sequence


class CorrelatedQuorumError(RuntimeError):
    """Raised when a quorum's votes collapse to too few independent evidence sources."""
    pass


class NonReproducibleTransitionError(RuntimeError):
    """Raised when an independent verifier cannot re-execute the proposed transition."""
    pass


@dataclass(frozen=True)
class Vote:
    agent_id: str
    value_hash: str
    evidence_hash: str
    signature: bytes


def evidence_hash(document: bytes) -> str:
    return hashlib.sha256(document).hexdigest()


def commit_shared_state(
    votes: Sequence[Vote],
    f: int,
    independent_reexecution_succeeds: bool,
) -> str:
    quorum = 2 * f + 1
    if len(votes) < quorum:
        raise CorrelatedQuorumError(
            f"insufficient votes: {len(votes)} < quorum {quorum}"
        )

    distinct_values = {v.value_hash for v in votes}
    if len(distinct_values) != 1:
        raise CorrelatedQuorumError(
            f"quorum reached on conflicting values: {distinct_values}"
        )

    # The non-obvious check: count independent evidence sources, not votes.
    distinct_evidence = {v.evidence_hash for v in votes}
    if len(distinct_evidence) < f + 1:
        raise CorrelatedQuorumError(
            f"correlated quorum: {len(votes)} votes but only "
            f"{len(distinct_evidence)} independent evidence sources "
            f"(need >= {f + 1}). Refusing to commit despite quorum."
        )

    if not independent_reexecution_succeeds:
        raise NonReproducibleTransitionError(
            "independent verifier could not reproduce transition from its own snapshot"
        )

    return next(iter(distinct_values))
