# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-verify-weight-manifest-attestation-when-the-runtime-re-quantizes-on-load.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-verify-weight-manifest-attestation-when-the-runtime-re-quantizes-on-load.warrant.json
# Markdown SHA-256:   0a26f7715a9cbfa4cbb633b3b5c3891970162847fc75af43300a8600f61242ef
# Code AST SHA-256:   c9c43cb29ca4b3c9b0123b543d26fe6b925dd4afd2de591a90ac95c3101af846
# Verified Classes:   AttestationClosureError, Manifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AttestationClosureError(RuntimeError):
    """Raised when a manifest under-specifies the artifact->execution map."""
    pass


@dataclass
class Manifest:
    artifact_digest: str
    runtime_version: str
    quant_scheme: str | None
    calibration_digest: str | None   # digest of calibration set, if any
    rng_seed: int | None
    kernel_lib_version: str | None
    runtime_weight_digest: str | None  # post-load digest, instance-signed
    signature_valid: bool


REQUIRED_TRANSFORM_FIELDS = ("calibration_digest", "rng_seed", "kernel_lib_version")


def verify_execution_binding(manifest: Manifest, observed_weight_digest: str) -> bool:
    if not manifest.signature_valid:
        raise AttestationClosureError("manifest signature invalid; cannot proceed")

    # If the runtime transformed weights, the transform must be fully closed.
    if manifest.quant_scheme is not None:
        missing = [
            f for f in REQUIRED_TRANSFORM_FIELDS
            if getattr(manifest, f) is None
        ]
        if missing:
            raise AttestationClosureError(
                f"quant_scheme={manifest.quant_scheme!r} declared but transform "
                f"closure incomplete; missing {missing}. Artifact attestation "
                f"does not bind executing weights."
            )

    # The instance must report a post-load digest and it must match what
    # the verifier independently observed from the loaded tensors.
    if manifest.runtime_weight_digest is None:
        raise AttestationClosureError(
            "no runtime_weight_digest: cannot confirm executing weights match "
            "the attested function"
        )
    if manifest.runtime_weight_digest != observed_weight_digest:
        raise AttestationClosureError(
            "runtime_weight_digest mismatch: executing weights diverge from "
            "attested weights"
        )

    return True


def admit_peer(manifest: Manifest, observed_weight_digest: str) -> str:
    try:
        verify_execution_binding(manifest, observed_weight_digest)
    except AttestationClosureError as e:
        # Quarantine, not silent admit. Excluded from consensus-critical roles.
        return f"QUARANTINED: {e}"
    return "ADMITTED"
