# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-byzantine-speculative-branch-divergence-before-commit-in-multi-agent-speculative-decoding.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-byzantine-speculative-branch-divergence-before-commit-in-multi-agent-speculative-decoding.warrant.json
# Markdown SHA-256:   5b4a80adb046d288356249409677ec1e50124d59b05651a5d7f4406b8f7f0948
# Code AST SHA-256:   0d946d31b4310af4b24a12e1dbf5cb1cdd8ba0d073b372fe71f93b570eb0e364
# Verified Classes:   ByzantineDivergence, Branch, Accept
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ByzantineDivergence(RuntimeError):
    """Raised when a speculative branch's committed prefix does not match the
    prefix the verifier scored. This is a Byzantine fault, not an ordinary
    rejection: the drafter reported a hash it did not condition on."""


@dataclass(frozen=True)
class Branch:
    branch_id: str
    tokens: tuple
    reported_prefix_hash: str
    drafter_id: str


@dataclass(frozen=True)
class Accept:
    branch_id: str
    verifier_id: str
    scored_token_count: int
    accepted: bool


def _hash_prefix(prefix_tokens: tuple) -> str:
    h = hashlib.sha256()
    for t in prefix_tokens:
        h.update(t.encode("utf-8"))
        h.update(b"\x00")
    return h.hexdigest()


def commit_branch(
    branch: Branch,
    accepts: list,
    pruner_reconstructed_prefix: tuple,
    quorum: int = 2,
) -> dict:
    """Commit a branch only if the pruner's own reconstruction hashes to the
    reported prefix AND a quorum accepted. The hash is recomputed locally;
    the reported value is never trusted as a commit precondition on its own.
    """
    if not pruner_reconstructed_prefix:
        raise ByzantineDivergence(
            f"branch {branch.branch_id}: empty pruner prefix; "
            f"drafter {branch.drafter_id} reported {branch.reported_prefix_hash!r} "
            f"but pruner has no context to verify against"
        )

    local_hash = _hash_prefix(pruner_reconstructed_prefix)
    if local_hash != branch.reported_prefix_hash:
        raise ByzantineDivergence(
            f"branch {branch.branch_id}: prefix divergence. "
            f"drafter {branch.drafter_id} reported {branch.reported_prefix_hash!r}, "
            f"pruner reconstructed {local_hash!r} over "
            f"{len(pruner_reconstructed_prefix)} tokens. "
            f"Quorum does not override this check."
        )

    accepted = [a for a in accepts if a.branch_id == branch.branch_id and a.accepted]
    if len(accepted) < quorum:
        raise ByzantineDivergence(
            f"branch {branch.branch_id}: quorum not reached "
            f"({len(accepted)}/{quorum})"
        )

    for a in accepted:
        if a.scored_token_count != len(pruner_reconstructed_prefix):
            raise ByzantineDivergence(
                f"branch {branch.branch_id}: verifier {a.verifier_id} scored "
                f"{a.scored_token_count} tokens but pruner commits "
                f"{len(pruner_reconstructed_prefix)}; hash match is suspect"
            )

    return {
        "branch_id": branch.branch_id,
        "committed_prefix_hash": local_hash,
        "tokens": branch.tokens,
        "accepts": [a.verifier_id for a in accepted],
    }
