# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-equivocation-collapse-when-byzantine-agent-quorums-reconcile-divergent-task-commitments.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-equivocation-collapse-when-byzantine-agent-quorums-reconcile-divergent-task-commitments.warrant.json
# Markdown SHA-256:   50fd67838220be57c2e9559c7b3b499131973874a1825b05af73976a82069e23
# Code AST SHA-256:   4a16c13cdf4ce103fe22bf58e84196a67511f48b7ca4c21f89716335f05519b5
# Verified Classes:   EquivocationCollapse, Commit, SlotLockedReconciler
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict, Tuple


class EquivocationCollapse(RuntimeError):
    """Raised when an agent emits conflicting commits for the same slot."""
    pass


@dataclass(frozen=True)
class Commit:
    agent_id: str
    epoch: int
    slot: Tuple[str, int]        # (task_id, step_index)
    value_hash: str
    signature: str


class SlotLockedReconciler:
    """Enforces single-shot voting per (agent_id, epoch, slot)."""

    def __init__(self) -> None:
        # (agent_id, epoch, slot) -> value_hash
        self._ledger: Dict[Tuple[str, int, Tuple[str, int]], str] = {}

    def accept(self, commit: Commit) -> None:
        key = (commit.agent_id, commit.epoch, commit.slot)
        prior = self._ledger.get(key)
        if prior is None:
            self._ledger[key] = commit.value_hash
            return
        if prior != commit.value_hash:
            # Non-malicious equivocation: same agent, same epoch, same slot,
            # two validly-signed but divergent values. This is NOT a hash
            # mismatch to be outvoted -- it is a fault event.
            raise EquivocationCollapse(
                f"agent={commit.agent_id} epoch={commit.epoch} "
                f"slot={commit.slot} emitted {prior!r} then {commit.value_hash!r}; "
                f"quarantine both quorums and roll to a fresh epoch"
            )
        # Idempotent re-delivery: safe to ignore.
        return

    def reconcile(self, commits) -> str:
        """Return canonical value only if no equivocation was observed."""
        for c in commits:
            self.accept(c)
        values = {self._ledger[k] for k in self._ledger if k[1] == commits[0].epoch}
        if len(values) != 1:
            raise EquivocationCollapse(
                f"epoch {commits[0].epoch} holds {len(values)} distinct values; "
                f"refusing to pick the larger quorum"
            )
        return values.pop()
