# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-memory-erasure-proof-certifies-the-wrong-context-window.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-memory-erasure-proof-certifies-the-wrong-context-window.warrant.json
# Markdown SHA-256:   651e0653fc4da34391b8c51f5350ce159c643da7a6d3f3d013dee6243208c08b
# Code AST SHA-256:   0f9cf73e9b309a5ed9fdc858b7633dd90aaed017676e58cc40a4c34afd06e632
# Verified Classes:   ErasureProofInvalid, Span, ErasureProof
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Iterable, Sequence


class ErasureProofInvalid(RuntimeError):
    """Raised when an erasure proof is cryptographically valid but semantically unsound."""


@dataclass(frozen=True)
class Span:
    span_id: str
    tenant_id: str
    payload: bytes


@dataclass(frozen=True)
class ErasureProof:
    erased_ids: Sequence[str]
    commit_erased: str          # digest over the erased leaves
    root_after: str             # digest over survivors
    signature: str
    recall_estimate: float
    index_built_at: float
    read_filter_key: str


def _digest(items: Iterable[bytes]) -> str:
    h = hashlib.sha256()
    for item in sorted(items):
        h.update(item)
    return h.hexdigest()


def verify_erasure_proof(
    proof: ErasureProof,
    store_before: Sequence[Span],
    store_after: Sequence[Span],
    target_tenant: str,
    policy_field: str,
    min_recall: float = 0.95,
    index_stable_since: float = 0.0,
) -> None:
    # 1. Cryptographic half: recompute survivors root.
    survivors = [s.payload for s in store_after]
    if _digest(survivors) != proof.root_after:
        raise ErasureProofInvalid("root_after does not match surviving store")

    # 2. Completeness half: the erased set must equal the policy selection.
    expected = {s.span_id for s in store_before if getattr(s, policy_field) == target_tenant}
    erased = set(proof.erased_ids)
    if expected - erased:
        raise ErasureProofInvalid(
            f"under-selection: {len(expected - erased)} policy spans never erased "
            f"(recall={proof.recall_estimate}, index_built_at={proof.index_built_at})"
        )
    if erased - expected:
        raise ErasureProofInvalid(
            f"over-selection: {len(erased - expected)} non-policy spans erased"
        )

    # 3. Commitment must cover exactly the erased leaves.
    erased_payloads = [s.payload for s in store_before if s.span_id in erased]
    if _digest(erased_payloads) != proof.commit_erased:
        raise ErasureProofInvalid("commit_erased does not bind the erased leaves")

    # 4. Read-path congruence: filter key must equal the policy field.
    if proof.read_filter_key != policy_field:
        raise ErasureProofInvalid(
            f"read path filters on {proof.read_filter_key!r}, policy on {policy_field!r}; "
            "survivors remain retrievable through a different key"
        )

    # 5. Recall currency: approximate selection inadmissible if index rebuilt in window.
    if proof.recall_estimate < min_recall:
        raise ErasureProofInvalid(f"recall {proof.recall_estimate} below {min_recall}")
    if proof.index_built_at > index_stable_since:
        raise ErasureProofInvalid("index rebuilt within retention window; recall stale")
