# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-when-llm-agents-sign-conflicting-votes-under-temperature-induced-paraphrase-drift.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-when-llm-agents-sign-conflicting-votes-under-temperature-induced-paraphrase-drift.warrant.json
# Markdown SHA-256:   05c844af80e9c6a403346e24f5646fe62e13b944ea6e0aedf7aa6a7e296ef210
# Code AST SHA-256:   faa91e983017d34b27475cc11c0e2155a46683c999ebbc24ba4579709bfe6ced
# Verified Classes:   EquivocationBoundaryError, SignedVote
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Optional


class EquivocationBoundaryError(RuntimeError):
    """Raised when the decision layer of a signed vote cannot be canonically
    reconstructed, or when a detector attempts to compare attestation-layer
    bytes as if they were decision-layer bytes."""
    pass


@dataclass(frozen=True)
class SignedVote:
    height: int
    round: int
    phase: str
    signer_id: str
    decision_core: bytes          # canonical, no sampled tokens
    attestation: bytes            # rationale, model_id, prompt_hash; sampled
    context_digest: bytes         # hash of exact context window used
    sampling_params_hash: bytes   # binds temperature/top_p/etc.
    signature: bytes


def canonical_decision_core(
    height: int,
    round: int,
    phase: str,
    decision: str,
    context_digest: bytes,
    sampling_params_hash: bytes,
) -> bytes:
    """Fixed-width, deterministic encoding. No free text, no sampled tokens.
    Any field derived from an LLM sample is forbidden here."""
    if decision not in ("ACCEPT", "REJECT", "NIL"):
        raise EquivocationBoundaryError(
            f"decision must be one of ACCEPT/REJECT/NIL, got {decision!r}"
        )
    payload = {
        "h": height,
        "r": round,
        "phase": phase,
        "d": decision,
        "ctx": context_digest.hex(),
        "sp": sampling_params_hash.hex(),
    }
    # sort_keys + separators => byte-stable across model families and locales
    return json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()


def detect_equivocation(a: SignedVote, b: SignedVote) -> Optional[str]:
    """Return 'EQUIVOCATION', 'PARAPHRASE_DRIFT', or None.

    The safety decision consults decision_core ONLY. The attestation layer is
    never compared for equality; divergence there is expected under T>0.
    """
    if (a.height, a.round, a.phase, a.signer_id) != (
        b.height, b.round, b.phase, b.signer_id
    ):
        raise EquivocationBoundaryError(
            "votes are not for the same (height, round, phase, signer) tuple; "
            "cannot evaluate equivocation"
        )

    # Guard: decision_core must be canonical and must not embed attestation.
    for v in (a, b):
        if v.attestation and v.attestation[:16] in v.decision_core:
            raise EquivocationBoundaryError(
                "decision_core appears to embed attestation bytes; "
                "sampled tokens leaked into the safety layer"
            )

    same_core = a.decision_core == b.decision_core
    same_attest = a.attestation == b.attestation

    if same_core and same_attest:
        return None
    if same_core and not same_attest:
        # benign paraphrase drift: same decision, different sampled rationale
        return "PARAPHRASE_DRIFT"
    # decision_core differs under identical (h, r, signer) => equivocation,
    # regardless of whether attestation matches (adversary controls attestation)
    return "EQUIVOCATION"


def process_incoming_vote(
    incoming: SignedVote,
    prior_votes: dict[tuple[int, int, str, str], SignedVote],
    slash_threshold: int = 1,
) -> str:
    key = (incoming.height, incoming.round, incoming.phase, incoming.signer_id)
    prior = prior_votes.get(key)
    if prior is None:
        prior_votes[key] = incoming
        return "ACCEPTED"

    verdict = detect_equivocation(prior, incoming)
    if verdict == "EQUIVOCATION":
        # emit CONFLICT_PROOF with both signed payloads; do not consult rationale
        raise EquivocationBoundaryError(
            f"equivocation detected: signer={incoming.signer_id} "
            f"h={incoming.height} r={incoming.round} phase={incoming.phase}; "
            f"decision_core mismatch under identical signer tuple. "
            f"Slashing; rationale content is not admissible evidence."
        )
    if verdict == "PARAPHRASE_DRIFT":
        # telemetry only; do not bump view, do not slash
        return "DRIFT_LOGGED"
    return "DUPLICATE"
