# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-byzantine-equivocation-fault-in-multi-agent-task-commitment-ledgers-before-quorum-finality.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-byzantine-equivocation-fault-in-multi-agent-task-commitment-ledgers-before-quorum-finality.warrant.json
# Markdown SHA-256:   c272e97562286b094154f184c0e90e843e189622ab15ce263a3c39e142b12b44
# Code AST SHA-256:   9552995b788452977bb5e7f667c04483c33ee60c6d6722a91b990f7a54123b3f
# Verified Classes:   EquivocationFault, SignedVote, PreCommitEquivocationGuard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class EquivocationFault(RuntimeError):
    """Raised when a replica observes two signed votes for the same
    (slot, view, agent_id) with divergent payload digests. This is a
    Byzantine-class fault and must consume one unit of the fault budget
    before the slot is allowed to reach quorum."""
    pass


@dataclass(frozen=True)
class SignedVote:
    slot: int
    view: int
    agent_id: str
    payload_digest: str
    signature: bytes


class PreCommitEquivocationGuard:
    """Bounded pre-commit guard. Tracks the first digest seen per
    (slot, view, agent_id). A second observation with a divergent digest
    is equivocation; a second observation with an identical digest is a
    benign retransmit."""

    def __init__(self, fault_budget: int):
        self._seen: Dict[Tuple[int, int, str], str] = {}
        self._fault_budget = fault_budget
        self._faults_consumed = 0

    def observe(self, vote: SignedVote) -> None:
        key = (vote.slot, vote.view, vote.agent_id)
        prior = self._seen.get(key)
        if prior is None:
            self._seen[key] = vote.payload_digest
            return
        if prior == vote.payload_digest:
            # Benign duplicate (retransmit). No fault budget consumed.
            return
        # Divergent digest for same (slot, view, agent_id): equivocation.
        self._faults_consumed += 1
        if self._faults_consumed > self._fault_budget:
            raise EquivocationFault(
                f"fault budget exhausted: {self._faults_consumed} > "
                f"{self._fault_budget} at slot={vote.slot} view={vote.view} "
                f"agent={vote.agent_id} digests={prior}/{vote.payload_digest}"
            )
        raise EquivocationFault(
            f"equivocation detected at slot={vote.slot} view={vote.view} "
            f"agent={vote.agent_id}: {prior} != {vote.payload_digest}; "
            f"faults consumed={self._faults_consumed}/{self._fault_budget}"
        )


def digest_payload(payload: bytes) -> str:
    return hashlib.sha256(payload).hexdigest()
