# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-a-task-ledger-entry-under-partial-synchrony-the-late-equivocator-boundary-in-bft-multi-agent-commitment.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-a-task-ledger-entry-under-partial-synchrony-the-late-equivocator-boundary-in-bft-multi-agent-commitment.warrant.json
# Markdown SHA-256:   b0c94db6e5eb3d5d1b53e0b9f6db57370bb10d78dec5eda10a5eba56136018fa
# Code AST SHA-256:   6563b64efea49ea72e45b9c8752b632d55cd72e85a5a69e2aaa83a4ae5e33bb3
# Verified Classes:   LateEquivocationError, Lock, CommitmentReplica
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class LateEquivocationError(RuntimeError):
    """Raised when a replica would vote on a proposal whose lock is not durable
    or whose prior lock conflicts without a verified CommitQC."""
    pass


@dataclass(frozen=True)
class Lock:
    height: int
    task_id: str
    assignee: str
    durable: bool


class CommitmentReplica:
    def __init__(self, replica_id: str, store):
        self.replica_id = replica_id
        self.store = store  # must expose durable_write(key, value) -> bool

    def _lock_key(self, height: int, task_id: str) -> str:
        return f"lock:{height}:{task_id}"

    def precommit_vote(
        self,
        height: int,
        task_id: str,
        assignee: str,
        prior_lock: Optional[Lock],
        commit_qc_for_new_assignee: Optional[bytes],
    ) -> bytes:
        # Boundary check 1: conflicting prior lock requires a CommitQC.
        if prior_lock is not None and prior_lock.assignee != assignee:
            if commit_qc_for_new_assignee is None:
                raise LateEquivocationError(
                    f"conflicting lock at ({height},{task_id}): "
                    f"prior={prior_lock.assignee} new={assignee} without CommitQC"
                )

        # Boundary check 2: lock must be durable BEFORE the vote leaves.
        new_lock = Lock(height, task_id, assignee, durable=False)
        ok = self.store.durable_write(
            self._lock_key(height, task_id),
            {"assignee": assignee, "height": height},
        )
        if not ok:
            raise LateEquivocationError(
                f"lock for ({height},{task_id}) not durable; refusing PreCommitVote"
            )

        # Only now is it safe to emit the vote.
        return hashlib.sha256(
            f"{self.replica_id}:{height}:{task_id}:{assignee}".encode()
        ).digest()
