# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-speculative-execution-fork-silently-diverge-from-quorum-commit-when-a-byzantine-peer-replays-a-side-effecting-action-under-a-di.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-speculative-execution-fork-silently-diverge-from-quorum-commit-when-a-byzantine-peer-replays-a-side-effecting-action-under-a-di.warrant.json
# Markdown SHA-256:   2c7cace8a773d46a390c2574518f6011648c05689ffb17722e4b101f076dcbb8
# Code AST SHA-256:   befa76516ff4cc8c62f28230e813f1b88a05382b31acb03dcbe0972cd9e2cdbe
# Verified Classes:   SpeculativeEffectDivergence
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import hmac


class SpeculativeEffectDivergence(RuntimeError):
    """Raised when quorum-committed payloads do not bind to a single effector application."""


def _h(payload: dict) -> str:
    return hashlib.sha256(repr(sorted(payload.items())).encode()).hexdigest()


def verify_effect_bound_commit(
    votes: list[dict],
    effector_applied_count: int,
    quorum: int,
) -> str:
    """
    votes: list of {"payload": dict, "idempotency_key": str, "receipt_id": str}
    effector_applied_count: number of times the effector actually applied h(P) this round.
    Returns the committed idempotency key on success.
    """
    if not votes:
        raise SpeculativeEffectDivergence("no votes to commit")

    payload_hash = _h(votes[0]["payload"])
    matching = [v for v in votes if _h(v["payload"]) == payload_hash]

    # Invariant 1: payload quorum.
    if len(matching) < quorum:
        raise SpeculativeEffectDivergence(
            f"payload quorum not met: {len(matching)} < {quorum}"
        )

    # Invariant 2: idempotency key must be bound inside the voted payload.
    keys = {v["idempotency_key"] for v in matching}
    if len(keys) != 1:
        raise SpeculativeEffectDivergence(
            f"idempotency key not bound to payload; divergent keys {keys} "
            f"for payload_hash {payload_hash[:12]} — Byzantine replay suspected"
        )
    bound_key = keys.pop()

    # Invariant 3: effector must have applied exactly once for this payload+key.
    if effector_applied_count != 1:
        raise SpeculativeEffectDivergence(
            f"effector applied {effector_applied_count} times for key {bound_key[:12]}; "
            f"expected exactly 1 — speculative effects diverged from quorum commit"
        )

    return bound_key
