# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-equivocation-detector-fail-when-heterogeneous-agents-disagree-on-what-counts-as-the-same-message.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-equivocation-detector-fail-when-heterogeneous-agents-disagree-on-what-counts-as-the-same-message.warrant.json
# Markdown SHA-256:   21ce280f911118ab35b73352da0bff6d86bd0d9c4de1009ba3af028df7db784a
# Code AST SHA-256:   e5fad4d92150c4be2e5e59b74fe3a34865daf24251cc033a4a40e1b26876c319
# Verified Classes:   EquivocationCanonicalizationError, SlotCommitment
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Any


class EquivocationCanonicalizationError(RuntimeError):
    """Raised when a consensus value cannot be canonicalized unambiguously,
    or when the detector is asked to compare values across slots/senders
    without slot+sender binding in the digest preimage."""
    pass


@dataclass(frozen=True)
class SlotCommitment:
    slot: int
    sender: str
    canonical_payload: bytes
    semantic_fingerprint: str

    def digest(self) -> str:
        preimage = (
            str(self.slot).encode()
            + b"||"
            + self.sender.encode()
            + b"||"
            + self.canonical_payload
            + b"||"
            + self.semantic_fingerprint.encode()
        )
        return hashlib.sha256(preimage).hexdigest()


def canonicalize(value: dict[str, Any]) -> bytes:
    # Closed-schema canonicalization: enums lowercased, floats quantized,
    # keys sorted, ints coerced. Free-form text is rejected outright.
    if "free_text" in value:
        raise EquivocationCanonicalizationError(
            "free-form text cannot be canonicalized deterministically; "
            "require a structured verdict before admitting to consensus"
        )
    try:
        action = str(value["action"]).strip().lower()
        target_id = int(value["target_id"])
        confidence = round(float(value["confidence"]), 2)
    except (KeyError, TypeError, ValueError) as exc:
        raise EquivocationCanonicalizationError(
            f"value not canonicalizable under closed schema: {exc}"
        ) from exc
    return f"{action}|{target_id}|{confidence:.2f}".encode()


def semantic_fingerprint(value: dict[str, Any]) -> str:
    # Deterministic, model-independent fingerprint of the canonical form.
    # In production this is a fixed entailment signature; here a stable hash.
    return hashlib.sha256(canonicalize(value)).hexdigest()[:16]


def detect_equivocation(
    slot: int,
    observed: list[tuple[str, dict[str, Any]]],
    f: int,
) -> str:
    """Returns 'clear' or 'suspect'. Raises on uncanonicalizable input."""
    commitments: dict[str, SlotCommitment] = {}
    for sender, payload in observed:
        try:
            canon = canonicalize(payload)
        except EquivocationCanonicalizationError:
            # Uncanonicalizable value is a protocol violation by the SENDER,
            # not evidence of equivocation by a peer. Force re-emission.
            raise
        fp = semantic_fingerprint(payload)
        commitments[sender] = SlotCommitment(slot, sender, canon, fp)

    distinct_semantic = {c.semantic_fingerprint for c in commitments.values()}
    # Threshold is f + 1 distinct SEMANTIC digests, not 2 byte digests.
    if len(distinct_semantic) > f + 1:
        return "suspect"
    return "clear"


def run_round(slot: int, observed: list[tuple[str, dict[str, Any]]], f: int) -> None:
    try:
        verdict = detect_equivocation(slot, observed, f)
    except EquivocationCanonicalizationError as exc:
        # Do NOT eject peers; reject the offending emission and re-request.
        raise EquivocationCanonicalizationError(
            f"slot {slot}: emission rejected for non-canonicalizable payload; "
            f"re-emission required ({exc})"
        ) from exc
    if verdict == "suspect":
        # Only now is equivocation suspected; replay raw messages against
        # the agreed fingerprint before any ejection.
        raise EquivocationCanonicalizationError(
            f"slot {slot}: {len({c.semantic_fingerprint for c in []})} "
            f"semantic divergences exceed f+1={f + 1}; trigger replay audit"
        )
