# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocating-peers-when-bft-quorum-certificates-are-valid-but-state-divergence-is-silent.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocating-peers-when-bft-quorum-certificates-are-valid-but-state-divergence-is-silent.warrant.json
# Markdown SHA-256:   4a9a442ee1e2538e61876ac7fc4b50506290c3375f99ea1f6188e21543b7413d
# Code AST SHA-256:   0dd8bbccf035530e68c38a9fabd2e065f245344fa1c617b80bab22153bbbb2ad
# Verified Classes:   EquivocationSuspected, FieldSpec, StateRoot
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import statistics
from dataclasses import dataclass
from typing import Literal, Sequence

Determinism = Literal["DETERMINISTIC", "NONDETERMINISTIC"]


class EquivocationSuspected(RuntimeError):
    """Raised when QC-valid states diverge beyond the declared determinism partition."""


@dataclass(frozen=True)
class FieldSpec:
    name: str
    determinism: Determinism
    # For NONDETERMINISTIC fields: declared distribution family and params.
    distribution: str | None = None


@dataclass(frozen=True)
class StateRoot:
    instance_id: str
    transaction_digest: str
    fields: dict[str, str]
    signature_valid: bool


def canonical_projection(
    root: StateRoot, specs: Sequence[FieldSpec]
) -> tuple[str, dict[str, str]]:
    """Split state into (deterministic_hash, nondeterministic_fields)."""
    det = {s.name: root.fields.get(s.name, "") for s in specs if s.determinism == "DETERMINISTIC"}
    nondet = {s.name: root.fields.get(s.name, "") for s in specs if s.determinism == "NONDETERMINISTIC"}
    blob = "|".join(f"{k}={v}" for k, v in sorted(det.items()))
    return hashlib.sha256(blob.encode()).hexdigest(), nondet


def check_consensus(
    roots: Sequence[StateRoot],
    specs: Sequence[FieldSpec],
    threshold: int,
    alpha: float = 0.01,
) -> None:
    """
    Enforce the execution-determinism partition invariant.
    Raises EquivocationSuspected on any of:
      1. QC-invalid root claiming to be certified.
      2. Deterministic-projection disagreement across QC-valid roots.
      3. Nondeterministic field whose empirical distribution is a point-mass
         where a uniform distribution was declared (the equivocation tell).
    """
    certified = [r for r in roots if r.signature_valid]
    if len(certified) < threshold:
        raise EquivocationSuspected(
            f"insufficient certified roots: {len(certified)} < {threshold}"
        )

    det_hashes = {canonical_projection(r, specs)[0] for r in certified}
    if len(det_hashes) > 1:
        raise EquivocationSuspected(
            f"deterministic projection forked across {len(det_hashes)} roots: "
            f"{sorted(det_hashes)}"
        )

    nondet_specs = [s for s in specs if s.determinism == "NONDETERMINISTIC"]
    for spec in nondet_specs:
        values = [canonical_projection(r, specs)[1].get(spec.name, "") for r in certified]
        distinct = set(values)
        if spec.distribution == "uniform" and len(distinct) == 1 and len(values) >= threshold:
            # Point-mass where uniform was declared: adversary substitution tell.
            raise EquivocationSuspected(
                f"field '{spec.name}' collapsed to point-mass {distinct!r} "
                f"across {len(values)} certified roots; uniform distribution declared"
            )
        if spec.distribution == "uniform" and len(distinct) < max(2, len(values) // 4):
            # Degenerate concentration: flag for challenge round.
            raise EquivocationSuspected(
                f"field '{spec.name}' distribution degenerate: "
                f"{len(distinct)} distinct over {len(values)} samples"
            )
