# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-equivocates-across-a-byzantine-quorum-the-commitment-finality-split-in-multi-agent-bft-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-equivocates-across-a-byzantine-quorum-the-commitment-finality-split-in-multi-agent-bft-consensus.warrant.json
# Markdown SHA-256:   396994b827bfe99aced73c43c33b4eb21e1c73fe174fd1bb7e2279b7e2de9c16
# Code AST SHA-256:   9e9a8fe80210bd7c3dd76374bc12bcbcd43d3886c1c81cab571253258f007dd4
# Verified Classes:   EquivocationError, Prepare, SignOnceCache
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EquivocationError(RuntimeError):
    """Raised when a replica attempts to sign a conflicting prepare for the same round."""


@dataclass(frozen=True)
class Prepare:
    task_id: str
    round: int
    version: int
    context_digest: str


def context_digest(prompt_template: str, retrieved_snapshot: str) -> str:
    h = hashlib.sha256()
    h.update(prompt_template.encode())
    h.update(b"\x00")
    h.update(retrieved_snapshot.encode())
    return h.hexdigest()


class SignOnceCache:
    """Binds a replica to one signature per (task_id, round). Enforces the BFT invariant."""

    def __init__(self) -> None:
        self._signed: dict[tuple[str, int], tuple[str, bytes]] = {}

    def sign(self, prepare: Prepare, signature_fn) -> bytes:
        key = (prepare.task_id, prepare.round)
        prior = self._signed.get(key)
        if prior is not None:
            prior_digest, prior_sig = prior
            if prior_digest != prepare.context_digest:
                raise EquivocationError(
                    f"replica already signed {key} with context_digest={prior_digest[:12]}, "
                    f"refusing to sign conflicting digest={prepare.context_digest[:12]} "
                    f"(version {prepare.version}); force a round advance instead"
                )
            return prior_sig
        sig = signature_fn(prepare)
        self._signed[key] = (prepare.context_digest, sig)
        return sig


def handle_prepare(cache: SignOnceCache, prepare: Prepare, signature_fn) -> bytes:
    # Transport may redeliver; the cache makes redelivery idempotent and safe.
    return cache.sign(prepare, signature_fn)
