# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-equivocation-before-byzantine-task-commit-consensus-can-be-trusted.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-equivocation-before-byzantine-task-commit-consensus-can-be-trusted.warrant.json
# Markdown SHA-256:   b03e0316c60177fa3e01b5760ac7de3ae2962856f6ff373d27d7026a563afdcc
# Code AST SHA-256:   075b75a3056c1ea5fdc691e747cf814fcddefdc8efb0d3288b40460b240ca100
# Verified Classes:   EquivocationDetected, Vote, CommitCoordinator
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Tuple


class EquivocationDetected(RuntimeError):
    """Raised when a vote contradicts an already-consumed nonce or value for the same epoch/task."""
    pass


@dataclass
class Vote:
    agent_id: str
    epoch: int
    task_id: str
    nonce: str
    value_hash: str


@dataclass
class CommitCoordinator:
    # key: nonce -> (agent_id, epoch, task_id, value_hash)
    seen_nonces: Dict[str, Tuple[str, int, str, str]] = field(default_factory=dict)
    # key: (agent_id, epoch, task_id) -> value_hash
    agent_epoch_value: Dict[Tuple[str, int, str], str] = field(default_factory=dict)
    quorum: int = 4
    # key: (epoch, task_id) -> value_hash -> set[agent_id]
    tally: Dict[Tuple[int, str], Dict[str, set]] = field(default_factory=dict)

    def register_promise(self, agent_id: str, epoch: int, task_id: str, nonce: str) -> None:
        """Promise phase: coordinator binds a nonce to an agent before the value is computed."""
        key = (agent_id, epoch, task_id)
        if key in self.agent_epoch_value:
            raise EquivocationDetected(
                f"agent {agent_id} already holds a promise for epoch {epoch} task {task_id}"
            )
        self.seen_nonces[nonce] = (agent_id, epoch, task_id, "")

    def accept_vote(self, vote: Vote) -> None:
        """Commit phase: enforce nonce binding and per-(agent,epoch,task) value uniqueness."""
        if vote.nonce not in self.seen_nonces:
            raise EquivocationDetected(
                f"vote nonce {vote.nonce} was never promised to {vote.agent_id}"
            )
        bound_agent, bound_epoch, bound_task, _ = self.seen_nonces[vote.nonce]
        if (bound_agent, bound_epoch, bound_task) != (vote.agent_id, vote.epoch, vote.task_id):
            raise EquivocationDetected(
                f"nonce {vote.nonce} bound to {(bound_agent, bound_epoch, bound_task)}, "
                f"vote claims {(vote.agent_id, vote.epoch, vote.task_id)}"
            )
        key = (vote.agent_id, vote.epoch, vote.task_id)
        prior = self.agent_epoch_value.get(key)
        if prior is not None and prior != vote.value_hash:
            raise EquivocationDetected(
                f"agent {vote.agent_id} equivocated on task {vote.task_id} epoch {vote.epoch}: "
                f"{prior} vs {vote.value_hash}"
            )
        self.agent_epoch_value[key] = vote.value_hash
        self.seen_nonces[vote.nonce] = (vote.agent_id, vote.epoch, vote.task_id, vote.value_hash)
        bucket = self.tally.setdefault((vote.epoch, vote.task_id), {})
        bucket.setdefault(vote.value_hash, set()).add(vote.agent_id)

    def finalize(self, epoch: int, task_id: str) -> str:
        bucket = self.tally.get((epoch, task_id), {})
        winners = [v for v, agents in bucket.items() if len(agents) >= self.quorum]
        if len(winners) > 1:
            raise EquivocationDetected(
                f"two values reached quorum for task {task_id} epoch {epoch}: {winners}"
            )
        if not winners:
            raise EquivocationDetected(f"no quorum for task {task_id} epoch {epoch}")
        return winners[0]
