# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-verify-cryptographic-erasure-proofs-when-forgetting-a-memory-shard-whose-key-was-rotated-mid-audit.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-verify-cryptographic-erasure-proofs-when-forgetting-a-memory-shard-whose-key-was-rotated-mid-audit.warrant.json
# Markdown SHA-256:   76a6feb3054a7b34e2c08db5cdf83086d544f1d3f4df187cca705b2f74c06594
# Code AST SHA-256:   ad719c22fe94796acbb4ab8a6272fb24d3598dcc4d9e04407225c0a602f78e3f
# Verified Classes:   ErasureProofInvalid, SealRecord, ErasureAttestation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ErasureProofInvalid(RuntimeError):
    """Raised when a cryptographic erasure attestation does not cover the full wrap-set."""
    pass


@dataclass(frozen=True)
class SealRecord:
    shard_id: str
    key_versions: FrozenSet[str]  # every version that ever wrapped this shard
    keyring_hash_at_seal: str


@dataclass(frozen=True)
class ErasureAttestation:
    shard_id: str
    destroyed_versions: FrozenSet[str]
    keyring_hash_at_destruction: str
    signature_valid: bool


def verify_erasure(seal: SealRecord, attestation: ErasureAttestation) -> str:
    if not attestation.signature_valid:
        raise ErasureProofInvalid(f"{seal.shard_id}: attestation signature invalid")

    if attestation.shard_id != seal.shard_id:
        raise ErasureProofInvalid(
            f"shard mismatch: seal={seal.shard_id} attestation={attestation.shard_id}"
        )

    missing = seal.key_versions - attestation.destroyed_versions
    if missing:
        # The observed failure: subset destruction passes a naive check but
        # leaves a decryptable replica behind. Refuse to claim PROVEN.
        raise ErasureProofInvalid(
            f"{seal.shard_id}: destroyed_set is a strict subset of wrap-set; "
            f"undestroyed key versions: {sorted(missing)}. "
            f"Status must be ERASURE_INCOMPLETE, not PROVEN."
        )

    if attestation.keyring_hash_at_destruction != seal.keyring_hash_at_seal:
        raise ErasureProofInvalid(
            f"{seal.shard_id}: keyring rotated between seal and destruction "
            f"({seal.keyring_hash_at_seal} -> {attestation.keyring_hash_at_destruction}); "
            f"proof is INDETERMINATE."
        )

    return "PROVEN"


# Reproduction of the incident: shard wrapped under K7 and K8, only K8 destroyed.
seal = SealRecord("S", frozenset({"K7", "K8"}), "hash-a")
bad = ErasureAttestation("S", frozenset({"K8"}), "hash-a", signature_valid=True)
try:
    verify_erasure(seal, bad)
except ErasureProofInvalid as e:
    print("REJECTED:", e)
