# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-equivocation-in-byzantine-llm-consensus-the-signed-transcript-fork-witness-and-why-semantic-agreement-cannot-substitu.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-equivocation-in-byzantine-llm-consensus-the-signed-transcript-fork-witness-and-why-semantic-agreement-cannot-substitu.warrant.json
# Markdown SHA-256:   d4f4ec8f27ee9192bcf92c290c8902ed7994e9badac028c07a363e78b9dae137
# Code AST SHA-256:   2122b64536f2ae24715f0a3a1f07bfa75770cb065c0d69b1b1c257e984868e12
# Verified Classes:   EquivocationBoundaryError, SignedPayload
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class EquivocationBoundaryError(RuntimeError):
    """Raised when a hash-divergence cannot be classified as fork vs. benign drift."""
    pass


@dataclass(frozen=True)
class SignedPayload:
    agent_id: str
    slot: int
    view: int
    committed: dict          # canonical, machine-comparable fields only
    signature: bytes         # signature over (slot, view, H(canon(committed)))


def canon(payload: dict) -> bytes:
    return json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()


def payload_hash(p: SignedPayload) -> str:
    return hashlib.sha256(canon(p.committed)).hexdigest()


def is_superset(a: dict, b: dict) -> bool:
    return all(k in a for k in b) and a != b


def committed_keys_conflict(a: dict, b: dict) -> bool:
    shared = set(a) & set(b)
    return any(a[k] != b[k] for k in shared)


def classify_divergence(p1: SignedPayload, p2: SignedPayload) -> str:
    """Return 'fork', 'benign_drift', or raise if the boundary is undecidable."""
    if (p1.agent_id, p1.slot, p1.view) != (p2.agent_id, p2.slot, p2.view):
        raise EquivocationBoundaryError(
            "payloads not bound to same (agent, slot, view); witness unsound"
        )

    hash_distinct = payload_hash(p1) != payload_hash(p2)
    superset = is_superset(p1.committed, p2.committed) or is_superset(p2.committed, p1.committed)
    value_conflict = committed_keys_conflict(p1.committed, p2.committed)

    # Re-canonicalization: if committed field sets collapse under canonical
    # reduction, the fork was serialization-induced, not Byzantine.
    recanon_collapses = canon(p1.committed) == canon(p2.committed)

    if not hash_distinct:
        return "benign_drift"
    if superset or recanon_collapses or not value_conflict:
        return "benign_drift"
    return "fork"


def decide_eviction(p1: SignedPayload, p2: SignedPayload) -> bool:
    verdict = classify_divergence(p1, p2)
    if verdict == "fork":
        return True
    if verdict == "benign_drift":
        return False
    raise EquivocationBoundaryError(f"unclassifiable divergence: {verdict}")


# Trace replay of the observed incident:
#   C signed a merge of P1 and P2 -> committed keys agree in value,
#   reason field diverged. Correct verdict: benign_drift, do NOT evict.
p1 = SignedPayload("C", slot=7, view=3,
                   committed={"action": "rollback", "target": "db-primary", "reason": "latency"},
                   signature=b"\x00")
p2 = SignedPayload("C", slot=7, view=3,
                   committed={"action": "rollback", "target": "db-primary",
                              "reason": "p99 latency spike"},
                   signature=b"\x01")

assert decide_eviction(p1, p2) is False  # boundary correctly refuses eviction
