# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-a-heterogeneous-llm-agent-bft-quorum-when-the-equivocating-node-is-also-its-own-most-confident-witness.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-a-heterogeneous-llm-agent-bft-quorum-when-the-equivocating-node-is-also-its-own-most-confident-witness.warrant.json
# Markdown SHA-256:   3e4005ad8ab604ffa44095b2551cf10c3ec3388840404c830fbcf51d9656d93f
# Code AST SHA-256:   1d1352970ffb759ecc9ca15e44adabab6b5b7433593220c7d138ed390707640b
# Verified Classes:   EquivocationClass, EquivocationBudgetError, SignedProposal
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class EquivocationClass(Enum):
    MALICIOUS = "malicious"
    STOCHASTIC = "stochastic"
    UNDETERMINED = "undetermined"


class EquivocationBudgetError(RuntimeError):
    """Raised when quarantine of a stochastic replica would push the
    effective Byzantine budget past the quorum's safety threshold."""


@dataclass(frozen=True)
class SignedProposal:
    replica_id: str
    view: int
    seq: int
    payload: bytes
    digest: str
    decoding_seed: int | None
    temperature: float

    def envelope_key(self) -> tuple[str, int, int]:
        return (self.replica_id, self.view, self.seq)


def classify_equivocation(
    a: SignedProposal,
    b: SignedProposal,
    invariant_violated: bool,
) -> EquivocationClass:
    if a.envelope_key() != b.envelope_key():
        raise ValueError("proposals are not an equivocation pair")
    if invariant_violated:
        return EquivocationClass.MALICIOUS
    same_config = (
        a.decoding_seed == b.decoding_seed
        and a.temperature == b.temperature
    )
    if same_config and a.digest != b.digest:
        # Deterministic decoding diverged: external cause, treat as Byzantine.
        return EquivocationClass.MALICIOUS
    if a.temperature > 0.0 and a.digest != b.digest:
        return EquivocationClass.STOCHASTIC
    return EquivocationClass.UNDETERMINED


def recompute_effective_budget(
    n: int,
    f_nominal: int,
    stochastic_quarantined: int,
) -> int:
    """Effective Byzantine budget for value safety after quarantine.

    A stochastic replica contributes to the value-safety budget because it
    can produce two signature-valid values that both attract corroborators.
    """
    effective = f_nominal + stochastic_quarantined
    if effective > (n - 1) // 3:
        raise EquivocationBudgetError(
            f"effective Byzantine budget {effective} exceeds quorum tolerance "
            f"{(n - 1) // 3} for n={n}; safety proof void, must resize quorum "
            f"or force deterministic decoding"
        )
    return effective


def handle_detected_equivocation(
    a: SignedProposal,
    b: SignedProposal,
    invariant_violated: bool,
    n: int,
    f_nominal: int,
    prior_stochastic_quarantined: int,
) -> tuple[EquivocationClass, int]:
    cls = classify_equivocation(a, b, invariant_violated)
    if cls is EquivocationClass.MALICIOUS:
        # Expel from both value and view quorums.
        return cls, f_nominal
    if cls is EquivocationClass.STOCHASTIC:
        # Quarantine for value, retain for view; recompute budget.
        new_effective = recompute_effective_budget(
            n=n,
            f_nominal=f_nominal,
            stochastic_quarantined=prior_stochastic_quarantined + 1,
        )
        return cls, new_effective
    # UNDETERMINED: refuse to act silently; surface for operator escalation.
    raise EquivocationBudgetError(
        f"equivocation between {a.replica_id} view={a.view} seq={a.seq} "
        f"is undetermined (seeds={a.decoding_seed},{b.decoding_seed}, "
        f"temps={a.temperature},{b.temperature}); cannot classify as "
        f"malicious or stochastic without input provenance"
    )
