# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-quorum-certified-plan-commitment-from-surviving-a-single-hallucinating-peer-the-equivocal-precommit-split.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-quorum-certified-plan-commitment-from-surviving-a-single-hallucinating-peer-the-equivocal-precommit-split.warrant.json
# Markdown SHA-256:   04362c37d6a7d97fead444d5262a9c30af4918fb56be1b755d2e0bf14a6dde96
# Code AST SHA-256:   2ae7b5dce9def1375a8d074e21796a060525875600a098b3b1155f2602cf229f
# Verified Classes:   SerializationAgreementError, Plan
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass
from typing import Mapping


class SerializationAgreementError(RuntimeError):
    """Raised when a quorum certificate names bytes that disagree across replicas."""


@dataclass(frozen=True)
class Plan:
    steps: tuple[str, ...]

    def canonical_bytes(self) -> bytes:
        # Deterministic, sorted, no prose. This is the ONLY consensus input.
        return "\x1f".join(self.steps).encode("utf-8")

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


def accept_prepare(
    proposed_digest: str,
    local_plan: Plan,
    *,
    tolerance: float = 0.0,
) -> bool:
    """
    Acceptance predicate for PREPARE/COMMIT.

    INVARIANT: tolerance MUST be 0.0 on the consensus path. A nonzero tolerance
    converts a Byzantine safety guarantee into a probabilistic one and admits
    equivocal precommits (see Condition of Validity (a)).
    """
    if tolerance != 0.0:
        raise SerializationAgreementError(
            f"non-exact acceptance predicate (tolerance={tolerance}) on consensus "
            f"path: this voids BFT safety; use exact digest equality"
        )
    return local_plan.digest() == proposed_digest


def form_quorum_certificate(
    prepares: Mapping[str, str],
    plans_by_replica: Mapping[str, Plan],
    quorum_size: int,
) -> str:
    """
    Build a QC from PREPARE votes. Enforces that all votes name the SAME bytes,
    not merely the same digest string.
    """
    if len(prepares) < quorum_size:
        raise SerializationAgreementError(
            f"insufficient prepares: {len(prepares)} < quorum {quorum_size}"
        )
    digests = set(prepares.values())
    if len(digests) != 1:
        raise SerializationAgreementError(
            f"equivocal prepares: replicas voted on {len(digests)} distinct digests"
        )
    (digest,) = digests
    # Byte-identity check: the digest must name exactly one canonical byte string.
    byte_strings = {
        plans_by_replica[r].canonical_bytes()
        for r in prepares
        if r in plans_by_replica
    }
    if len(byte_strings) != 1:
        raise SerializationAgreementError(
            f"serialization disagreement under digest {digest[:12]}: "
            f"{len(byte_strings)} distinct byte strings across quorum"
        )
    return digest


def commit_plan(
    prepares: Mapping[str, str],
    plans_by_replica: Mapping[str, Plan],
    quorum_size: int,
    *,
    tolerance: float = 0.0,
) -> Plan:
    """
    Full commit path. Any tolerance, any equivocation, any byte divergence aborts
    BEFORE irreversible side effects (post-commit readback barrier).
    """
    if tolerance != 0.0:
        raise SerializationAgreementError("tolerance must be 0.0 to claim BFT safety")
    digest = form_quorum_certificate(prepares, plans_by_replica, quorum_size)
    # Post-commit readback: confirm the committed bytes are what will execute.
    committed = next(iter(plans_by_replica.values()))
    if committed.digest() != digest:
        raise SerializationAgreementError(
            f"readback mismatch: committed bytes hash to {committed.digest()[:12]}, "
            f"QC names {digest[:12]}"
        )
    return committed
