# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-equivocation-drift-when-byzantine-llm-validators-disagree-through-paraphrase-rather-than-contradiction.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-equivocation-drift-when-byzantine-llm-validators-disagree-through-paraphrase-rather-than-contradiction.warrant.json
# Markdown SHA-256:   639bd737b0e67ff76b3081c4000868e8369327400001e52e94365a883366f278
# Code AST SHA-256:   6ef694811bac2bab4e5ddb11a333aad7c079530335dab00448f4cccf49090f21
# Verified Classes:   SemanticEquivocationError, SupportClass, Attestation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Sequence


class SemanticEquivocationError(RuntimeError):
    """Raised when a quorum's attestations agree on label but not on evidentiary support,
    or when a signed rationale does not parse to its signed verdict."""


class SupportClass(Enum):
    VERIFIED = "verified"
    DEFAULTED = "defaulted"
    UNVERIFIABLE = "unverifiable"


@dataclass(frozen=True)
class Attestation:
    proposal_hash: str
    verdict: str          # "ACCEPT" | "REJECT"
    support: SupportClass
    rationale: str
    parser_version: str
    model_id: str


def parse_verdict(rationale: str, parser_version: str) -> str:
    # Fixed, versioned parser. Must be total and deterministic for the invariant to hold.
    if parser_version != "v3":
        raise SemanticEquivocationError(
            f"unknown parser_version {parser_version!r}; cannot re-derive verdict"
        )
    # Toy extractor: real implementations must be pinned and audited.
    lowered = rationale.lower()
    if "not the case that" in lowered and "fail" in lowered:
        return "ACCEPT"
    return "REJECT" if "reject" in lowered else "ACCEPT"


def require_consistent_quorum(atts: Sequence[Attestation], f: int) -> str:
    if len(atts) < 2 * f + 1:
        raise SemanticEquivocationError(
            f"quorum too small: {len(atts)} < {2 * f + 1}"
        )

    # Invariant 2: rationale-verdict consistency under the signed parser version.
    for a in atts:
        derived = parse_verdict(a.rationale, a.parser_version)
        if derived != a.verdict:
            raise SemanticEquivocationError(
                f"validator {a.model_id} on {a.proposal_hash}: signed verdict "
                f"{a.verdict!r} but rationale parses to {derived!r} under "
                f"{a.parser_version}; treat as Byzantine for this round"
            )

    # Invariant 3: agreement requires matching support class, not just label.
    labels = {a.verdict for a in atts}
    if len(labels) != 1:
        raise SemanticEquivocationError(
            f"split verdicts on {atts[0].proposal_hash}: {labels}"
        )
    supports = {a.support for a in atts}
    if len(supports) != 1:
        raise SemanticEquivocationError(
            f"evidentially split quorum on {atts[0].proposal_hash}: "
            f"labels agree ({labels.pop()}) but support classes {supports} "
            f"differ; withhold commit and re-derive with body pinned"
        )
    return atts[0].verdict


def commit(atts: Sequence[Attestation], f: int) -> str:
    try:
        return require_consistent_quorum(atts, f)
    except SemanticEquivocationError as exc:
        # Escalate: re-prompt all validators with the full proposal body pinned.
        raise SemanticEquivocationError(
            f"commit withheld, re-derivation required: {exc}"
        ) from exc
