# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-its-own-equivocation-before-a-heterogeneous-bft-round-can-terminate.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-its-own-equivocation-before-a-heterogeneous-bft-round-can-terminate.warrant.json
# Markdown SHA-256:   7ba41224fc0707b0ffae47ddb5883a70415680a26dce1e8066eaa30f7b644335
# Code AST SHA-256:   46a83df63c5082c65d0c01a09d191f3b7be3332ed8638a3d60d0415b4c588bb1
# Verified Classes:   EquivocationBoundaryError, VoteLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class EquivocationBoundaryError(RuntimeError):
    """Raised when a replica would emit a second conflicting signed vote for one key."""


@dataclass
class VoteLedger:
    # key -> canonical signed payload bytes; durable in production (WAL / fsync)
    _entries: dict = field(default_factory=dict)

    @staticmethod
    def key(round_id: int, proposal_id: str, vote_type: str, solicitation_id: str | None):
        # solicitation_id is part of the signed domain ONLY when resampling is intended.
        return (round_id, proposal_id, vote_type, solicitation_id)

    def lookup(self, k):
        return self._entries.get(k)

    def commit(self, k, payload: bytes):
        self._entries[k] = payload


def deterministic_digest(proposal_bytes: bytes) -> str:
    return hashlib.sha256(proposal_bytes).hexdigest()


def cast_vote(
    ledger: VoteLedger,
    round_id: int,
    proposal_bytes: bytes,
    vote_type: str,
    solicitation_id: str | None,
    model_infer,          # callable(prompt) -> str, stochastic
    sign,                 # callable(bytes) -> bytes
) -> bytes:
    k = VoteLedger.key(round_id, proposal_bytes and deterministic_digest(proposal_bytes),
                       vote_type, solicitation_id)

    cached = ledger.lookup(k)
    if cached is not None:
        # Re-solicitation under the same signed domain: return original, never re-derive.
        return cached

    # Digest computed by deterministic code, NOT by the model, so the key is stable.
    digest = deterministic_digest(proposal_bytes)
    raw = model_infer(
        json.dumps({"proposal_digest": digest, "vote": vote_type})
    )

    payload = sign(raw.encode())

    # Re-check: a concurrent path may have committed while inference ran.
    existing = ledger.lookup(k)
    if existing is not None and existing != payload:
        raise EquivocationBoundaryError(
            f"conflicting signed vote for key {k}: "
            f"existing={existing[:8].hex()} new={payload[:8].hex()} "
            f"— re-derivation under a fixed signed domain is a protocol violation"
        )

    ledger.commit(k, payload)  # write-before-transmit; must be durable before returning
    return payload
