# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-verifier-gated-speculative-planner-is-committing-a-byzantine-favored-branch-under-correlated-verifier-fault.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-verifier-gated-speculative-planner-is-committing-a-byzantine-favored-branch-under-correlated-verifier-fault.warrant.json
# Markdown SHA-256:   dbf0da6c82715feab2a08af28c2917557bb72057af4262ef875ea79d697ab252
# Code AST SHA-256:   d3a68118b89526b8d750b516d81aaa6d40136d54f43ddfcb94b5a1645ac4d38b
# Verified Classes:   CorrelatedQuorumError, VerifierVote
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class CorrelatedQuorumError(RuntimeError):
    """Raised when a verifier quorum's agreement is not evidence-independent."""


@dataclass(frozen=True)
class VerifierVote:
    verifier_id: str
    approved: bool
    evidence_root: str          # hash of the shard/snapshot the verifier grounded on
    precondition_hash: str      # hash of the branch's asserted preconditions


def commit_branch(
    votes: list[VerifierVote],
    live_env_hash: str,
    f: int,
) -> str:
    approving = [v for v in votes if v.approved]
    n = len(votes)

    if n < 3 * f + 1:
        raise CorrelatedQuorumError(
            f"quorum size {n} below 3f+1={3*f+1} for f={f}"
        )

    roots: FrozenSet[str] = frozenset(v.evidence_root for v in approving)
    diversity = len(roots)

    # The non-obvious guard: agreement count is insufficient; roots must be independent.
    if diversity < f + 1:
        raise CorrelatedQuorumError(
            f"{len(approving)}/{n} approvals but only {diversity} distinct "
            f"evidence roots (need >= {f+1}); correlated-fault commit blocked"
        )

    if len(approving) * (3 * f + 1) < (2 * f + 1) * n:
        raise CorrelatedQuorumError(
            f"approval fraction {len(approving)}/{n} below Byzantine bound"
        )

    stale = {v.precondition_hash for v in approving} - {live_env_hash}
    if stale:
        raise CorrelatedQuorumError(
            f"branch preconditions {stale} do not match live env {live_env_hash}; "
            "escalate to resume-time revalidation"
        )

    return "commit"
