# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-by-a-peer-that-signs-distinct-commitment-roots-for-the-same-task-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-by-a-peer-that-signs-distinct-commitment-roots-for-the-same-task-epoch.warrant.json
# Markdown SHA-256:   a4b2c5af65f24a7168d56507b9472389df1dd56c0a1c18941e0d06685710419b
# Code AST SHA-256:   89ef41dd05954e95dba2ecab9205286abbc896f67e0df0c22bee183a8f1dc0ba
# Verified Classes:   EquivocationDetected, SignedRoot, EquivocationLog
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class EquivocationDetected(RuntimeError):
    """Raised when a replica observes two distinct signed commitment roots
    from the same leader for the same (task, epoch)."""
    pass


@dataclass(frozen=True)
class SignedRoot:
    leader_id: str
    task_id: str
    epoch: int
    root_digest: str
    signature: bytes
    membership: Tuple[str, ...]  # authorized quorum set for this epoch


@dataclass
class EquivocationLog:
    # (task_id, epoch) -> list of distinct SignedRoots seen from the same leader
    seen: Dict[Tuple[str, int], List[SignedRoot]] = field(default_factory=dict)
    evidence: Dict[Tuple[str, int], Tuple[str, SignedRoot, SignedRoot]] = field(default_factory=dict)

    def record(self, sr: SignedRoot) -> None:
        key = (sr.task_id, sr.epoch)
        bucket = self.seen.setdefault(key, [])
        for prior in bucket:
            if prior.leader_id == sr.leader_id and prior.root_digest != sr.root_digest:
                # Same leader, same epoch, different signed root => equivocation.
                self.evidence[key] = (sr.leader_id, prior, sr)
                raise EquivocationDetected(
                    f"leader {sr.leader_id} signed distinct roots for "
                    f"task={sr.task_id} epoch={sr.epoch}: "
                    f"{prior.root_digest} vs {sr.root_digest}"
                )
        bucket.append(sr)


def commit_certificate(
    cert_epoch: int,
    cert_task: str,
    cert_signatures: List[Tuple[str, bytes]],
    log: EquivocationLog,
) -> bool:
    """Placement B: refuse to commit any certificate whose epoch has live
    equivocation evidence, even if every signature verifies."""
    key = (cert_task, cert_epoch)
    if key in log.evidence:
        leader, a, b = log.evidence[key]
        raise EquivocationDetected(
            f"refusing to commit task={cert_task} epoch={cert_epoch}: "
            f"leader {leader} equivocated ({a.root_digest} vs {b.root_digest})"
        )
    # Cryptographic verification of cert_signatures against membership
    # is assumed to have already passed at this point.
    return True
