# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-tool-call-consensus-when-the-byzantine-quorum-threshold-is-satisfied-but-the-signed-tool-call-payloads-are-se.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-tool-call-consensus-when-the-byzantine-quorum-threshold-is-satisfied-but-the-signed-tool-call-payloads-are-se.warrant.json
# Markdown SHA-256:   8a079f5885ea9ae4c7c41499e14e97f3301dbd95ff96501375a73d423c6d49f5
# Code AST SHA-256:   9c72ce8c9c4cfd1d4cb7b24f193eb21de2e3ec3e8be4e7d32f31f47c588e07d7
# Verified Classes:   ConsensusSemanticDivergence
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from typing import Any


class ConsensusSemanticDivergence(RuntimeError):
    """Raised when a BFT quorum certifies a digest whose executor
    reconstruction does not reproduce the certified digest, or when
    the signer set over the certified digest is below threshold."""
    pass


def canonicalize(payload: dict[str, Any]) -> bytes:
    # Schema-typed canonical form: explicit int/str, NFC, sorted keys.
    return json.dumps(payload, sort_keys=True, ensure_ascii=False).encode("utf-8")


def digest(payload: dict[str, Any]) -> str:
    return hashlib.sha256(canonicalize(payload)).hexdigest()


def certify_and_execute(
    signatures: list[tuple[str, str]],  # (signer_id, digest_hex)
    payloads_by_digest: dict[str, dict[str, Any]],
    executor_parse: callable,
    f: int,
    threshold: int,
    execute: callable,
) -> Any:
    # Partition signatures by digest; threshold must hold over ONE digest.
    by_digest: dict[str, set[str]] = {}
    for signer, d in signatures:
        by_digest.setdefault(d, set()).add(signer)

    certified_digest = None
    for d, signers in by_digest.items():
        if len(signers) >= threshold:
            if certified_digest is not None and certified_digest != d:
                raise ConsensusSemanticDivergence(
                    f"two digests each meet threshold: {certified_digest} and {d}"
                )
            certified_digest = d

    if certified_digest is None:
        raise ConsensusSemanticDivergence(
            f"no single digest reached threshold {threshold}; "
            f"signer counts per digest: { {d: len(s) for d, s in by_digest.items()} }"
        )

    certified_payload = payloads_by_digest[certified_digest]

    # Reconstruction invariant: executor's parse must re-hash to the certified digest.
    reconstructed = executor_parse(certified_payload)
    if digest(reconstructed) != certified_digest:
        raise ConsensusSemanticDivergence(
            f"executor reconstruction {digest(reconstructed)} != certified {certified_digest}; "
            f"canonicalization is not injective over this schema"
        )

    return execute(reconstructed)
