# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-a-speculative-branch-under-quorum-verification-the-divergent-witness-equivocation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-a-speculative-branch-under-quorum-verification-the-divergent-witness-equivocation-boundary.warrant.json
# Markdown SHA-256:   9d39fc154063a157c14df21cc8833b8087acd4a1644a01614b5c011c89338f92
# Code AST SHA-256:   d4c0d88515a299d654534e4e51cc27af4592a5cd7df580fbb852e76d361907a9
# Verified Classes:   QuorumCommitBoundaryError, Witness, BranchEnvelope
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class QuorumCommitBoundaryError(RuntimeError):
    """Raised when a speculative branch cannot be soundly committed or rejected."""
    pass


@dataclass
class Witness:
    replica_id: str
    branch_id: str
    canonicalizer_version: str
    environment_epoch: str          # e.g. config mtime hash, cache epoch
    commit_relevant: dict           # fields downstream will actually read
    trace_summary: dict             # non-commit-relevant path info
    declared_commit_fields: frozenset
    declared_reads: frozenset       # what downstream consumer will read


@dataclass
class BranchEnvelope:
    branch_id: str
    accepted_canonicalizer_versions: frozenset
    required_commit_fields: frozenset
    quorum_threshold: int
    fault_budget: int


def witness_hash(w: Witness) -> str:
    payload = json.dumps(
        {"branch_id": w.branch_id,
         "canon": w.canonicalizer_version,
         "epoch": w.environment_epoch,
         "commit": w.commit_relevant},
        sort_keys=True, separators=(",", ":"),
    )
    return hashlib.sha256(payload.encode()).hexdigest()


def evaluate_quorum(env: BranchEnvelope, witnesses: list[Witness]) -> str:
    # Static completeness gate: witness must cover downstream reads.
    for w in witnesses:
        missing = env.required_commit_fields - w.declared_commit_fields
        if missing:
            raise QuorumCommitBoundaryError(
                f"replica {w.replica_id} witness omits commit-relevant fields {sorted(missing)}; "
                f"hash agreement would be vacuous"
            )
        uncovered = w.declared_reads - w.declared_commit_fields
        if uncovered:
            raise QuorumCommitBoundaryError(
                f"replica {w.replica_id} downstream reads {sorted(uncovered)} "
                f"not covered by witness; branch would commit on lossy projection"
            )

    # Canonicalizer version gate: incomparable witnesses must not be compared.
    versions = {w.canonicalizer_version for w in witnesses}
    if not versions <= env.accepted_canonicalizer_versions:
        bad = sorted(versions - env.accepted_canonicalizer_versions)
        raise QuorumCommitBoundaryError(
            f"witnesses span unaccepted canonicalizer versions {bad}; escalate to schema reconciliation"
        )
    if len(versions) > 1:
        raise QuorumCommitBoundaryError(
            f"witnesses span multiple canonicalizer versions {sorted(versions)}; "
            f"hash comparison is undefined across versions"
        )

    # Group by (hash, epoch). Agreement across epochs is not agreement.
    buckets: dict[tuple[str, str], list[Witness]] = {}
    for w in witnesses:
        buckets.setdefault((witness_hash(w), w.environment_epoch), []).append(w)

    qualifying = [(k, v) for k, v in buckets.items() if len(v) >= env.quorum_threshold]
    if len(qualifying) == 1:
        return "COMMIT"

    if len(qualifying) > 1:
        raise QuorumCommitBoundaryError(
            f"multiple distinct quorum-valid buckets for branch {env.branch_id}: "
            f"{[k for k, _ in qualifying]}; equivocation suspected"
        )

    # No quorum: distinguish fault from legitimate path divergence.
    distinct_reasons = {
        (witness_hash(w), w.environment_epoch) for w in witnesses
    }
    if len(distinct_reasons) > env.fault_budget + 1:
        raise QuorumCommitBoundaryError(
            f"no quorum and {len(distinct_reasons)} distinct outcome classes exceed "
            f"fault budget {env.fault_budget}; widen equivalence class and re-collect, do not retry"
        )
    raise QuorumCommitBoundaryError(
        f"no quorum for branch {env.branch_id}; {len(distinct_reasons)} outcome class(es), "
        f"within fault budget — escalate to coordinator"
    )
