# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-sign-a-plan-quorum-certificate-under-equivocating-byzantine-peers.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-sign-a-plan-quorum-certificate-under-equivocating-byzantine-peers.warrant.json
# Markdown SHA-256:   dd97660d407cba4b51576b216717dc8cb3a6a0110abbf08fdf2c5186ef74989e
# Code AST SHA-256:   3399980ef451fc3f88736f99c5e463c9095f3fff1267199487b9da2a2816e362
# Verified Classes:   EquivocationRiskError, PlanBody
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass
from typing import Mapping, FrozenSet


class EquivocationRiskError(RuntimeError):
    """Raised when an agent cannot bound the equivocation surface of a plan
    and therefore must refuse to sign the quorum certificate."""


@dataclass(frozen=True)
class PlanBody:
    epoch: int
    params: Mapping[str, object]
    canonicalizer_version: str


def assert_field_complete(
    body: PlanBody,
    canonicalizer_fields: FrozenSet[str],
    executor_behavioral_fields: FrozenSet[str],
    peer_canonicalizer_version: str,
) -> None:
    # (1) Every behaviorally-relevant field the executor reads must be inside
    #     the digest preimage, or two distinct bodies can collide to one hash.
    missing = executor_behavioral_fields - canonicalizer_fields
    if missing:
        raise EquivocationRiskError(
            f"lossy preimage: behavioral fields {sorted(missing)} absent from "
            f"canonicalizer; distinct plan bodies could share a plan_hash"
        )

    # (2) A peer on a different canonicalizer version may drop fields this
    #     signer cannot see. Cross-version quorums are unsafe.
    if body.canonicalizer_version != peer_canonicalizer_version:
        raise EquivocationRiskError(
            f"canonicalizer version skew: local={body.canonicalizer_version!r} "
            f"peer={peer_canonicalizer_version!r}; refuse cross-version quorum"
        )

    # (3) Params carrying behavioral fields must be present, not defaulted away.
    for field in executor_behavioral_fields:
        if field not in body.params:
            raise EquivocationRiskError(
                f"behavioral field {field!r} missing from plan body params; "
                f"cannot certify execution equivalence"
            )


def sign_quorum_certificate(
    body: PlanBody,
    received_hash: str,
    recomputed_hash: str,
    canonicalizer_fields: FrozenSet[str],
    executor_behavioral_fields: FrozenSet[str],
    peer_canonicalizer_version: str,
    prior_qc_hash: str | None,
) -> str:
    if recomputed_hash != received_hash:
        raise EquivocationRiskError(
            f"hash mismatch: received={received_hash} recomputed={recomputed_hash}"
        )
    if prior_qc_hash is not None and prior_qc_hash != received_hash:
        raise EquivocationRiskError(
            f"conflicting QC for epoch {body.epoch}: "
            f"prior={prior_qc_hash} new={received_hash}"
        )
    assert_field_complete(
        body, canonicalizer_fields, executor_behavioral_fields,
        peer_canonicalizer_version,
    )
    return received_hash
