# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-plan-under-byzantine-quorum-without-binding-the-plan-hash-to-the-signed-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-plan-under-byzantine-quorum-without-binding-the-plan-hash-to-the-signed-warrant.warrant.json
# Markdown SHA-256:   e62d6b5fa06fa6f95658734cfbe0945653cf2e29a1bb8378d8276b20b9070b07
# Code AST SHA-256:   15917e5b460fc16241ac88295f9e955af2f3b4eaaf7b9f807a796c07ab84b2dc
# Verified Classes:   PlanCommitmentError, Vote
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class PlanCommitmentError(RuntimeError):
    """Raised when a quorum-endorsed plan cannot be bound to an executable plan."""


@dataclass(frozen=True)
class Vote:
    voter_id: str
    round_id: str
    plan_digest: str
    endorsing: bool  # True iff the voter's canonical digest matched the proposer's


def canonical_digest(plan: dict) -> str:
    # Single canonicalization spec shared by proposer, voters, and executor.
    return hashlib.sha256(
        json.dumps(plan, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
    ).hexdigest()


def tally_endorsements(votes: list[Vote], proposer_digest: str, threshold: int) -> str:
    # Endorsing votes ONLY. Abstentions and rejections never count toward quorum.
    endorsing = [v for v in votes if v.endorsing and v.plan_digest == proposer_digest]
    if len(endorsing) < threshold:
        raise PlanCommitmentError(
            f"quorum not met on endorsements: {len(endorsing)}/{threshold} "
            f"(received {len(votes)} votes, {len(votes) - len(endorsing)} non-endorsing)"
        )
    return proposer_digest


def execute_plan(plan: dict, quorum_endorsed_digest: str, first_step_is_irreversible: bool) -> None:
    # Re-verify at the execution boundary. The vote layer is not trusted to
    # have bound the plan the executor is about to interpret.
    actual = canonical_digest(plan)
    if actual != quorum_endorsed_digest:
        raise PlanCommitmentError(
            f"executor plan digest {actual[:12]} does not match quorum-endorsed "
            f"digest {quorum_endorsed_digest[:12]}; refusing to begin irreversible step"
        )
    if first_step_is_irreversible:
        # Safe to proceed: the plan about to run is byte-identical to the
        # plan a supermajority endorsed.
        pass
