# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-byzantine-quorum-speculative-plan-commit-when-the-proposer-s-witness-set-diverges-from-the-auditor-s-repla.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-byzantine-quorum-speculative-plan-commit-when-the-proposer-s-witness-set-diverges-from-the-auditor-s-repla.warrant.json
# Markdown SHA-256:   50f364a8103fa11d68d5b71cc992c805f3cb84562ce976b7570f8e415ec21f6d
# Code AST SHA-256:   c70b81c5cecb80659e3563fb477a8eadd8294d9c1afa7bb1e41777e5b9d4704e
# Verified Classes:   SpeculativeCommitEvidenceError, Witness, PrepareVote, PlanCommit
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class SpeculativeCommitEvidenceError(RuntimeError):
    """Raised when a BFT commit ratifies intent but not evidence."""


@dataclass(frozen=True)
class Witness:
    post_condition_id: str
    canonical_bytes: bytes

    def digest(self) -> str:
        return hashlib.sha256(self.canonical_bytes).hexdigest()


@dataclass(frozen=True)
class PrepareVote:
    replica_id: str
    plan_digest: str
    witness_set: tuple[Witness, ...]
    verdict: str  # "prepare" | "prepare-with-fallback" | "abort"


@dataclass
class PlanCommit:
    plan_digest: str
    committed_witness_root: Optional[str]
    votes: list[PrepareVote] = field(default_factory=list)
    quorum_width: int = 3  # 3f+1 with f=1


def _witness_root(witnesses: tuple[Witness, ...]) -> str:
    leaves = sorted(w.digest() for w in witnesses)
    return hashlib.sha256("".join(leaves).encode()).hexdigest()


def validate_commit_evidence(
    commit: PlanCommit,
    executed_branch_post_conditions: tuple[str, ...],
) -> None:
    prepare_votes = [v for v in commit.votes if v.verdict.startswith("prepare")]

    if commit.committed_witness_root is None:
        raise SpeculativeCommitEvidenceError(
            f"plan {commit.plan_digest[:12]} committed without witness root; "
            "quorum ratifies intent, not evidence"
        )

    if len(prepare_votes) < commit.quorum_width:
        raise SpeculativeCommitEvidenceError(
            f"insufficient prepare votes: {len(prepare_votes)} < {commit.quorum_width}"
        )

    # Majority-equivalence check on every post-condition the executed branch reads.
    for pc_id in executed_branch_post_conditions:
        by_digest: dict[str, int] = {}
        for vote in prepare_votes:
            for w in vote.witness_set:
                if w.post_condition_id == pc_id:
                    by_digest[w.digest()] = by_digest.get(w.digest(), 0) + 1
        if not by_digest:
            raise SpeculativeCommitEvidenceError(
                f"post-condition {pc_id} read by executed branch has no witness in quorum"
            )
        top_digest, top_count = max(by_digest.items(), key=lambda kv: kv[1])
        majority = (len(prepare_votes) // 2) + 1
        if top_count < majority:
            raise SpeculativeCommitEvidenceError(
                f"post-condition {pc_id} witness divergence: top set {top_count}/"
                f"{len(prepare_votes)} below majority {majority}; no branch validated"
            )
        # Executor must pin to the majority witness, not the proposer's claim.
        committed = commit.committed_witness_root
        if committed is not None and top_digest not in committed:
            raise SpeculativeCommitEvidenceError(
                f"majority witness {top_digest[:12]} for {pc_id} absent from "
                f"committed root {committed[:12]}"
            )


def execute_speculative_plan(commit: PlanCommit, branch_post_conditions: tuple[str, ...]) -> None:
    validate_commit_evidence(commit, branch_post_conditions)
    # Only reached if evidence-equivalent quorum exists on every read post-condition.
    return None
