# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-a-memory-it-never-proved-it-deleted-tombstone-divergence-between-vector-index-erasure-and-attestation-ledgers-in-gdpr-boun.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-a-memory-it-never-proved-it-deleted-tombstone-divergence-between-vector-index-erasure-and-attestation-ledgers-in-gdpr-boun.warrant.json
# Markdown SHA-256:   6b8630943e6deb40f9dcbe3f371d241ef164319b1f9d6bc2645459050e2fd6f4
# Code AST SHA-256:   9e5cbc7820a867afc3591d33d42955fb801f42f3afd8c190fa2dd591101c189e
# Verified Classes:   TombstoneDivergenceError, Memory, Attestation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class TombstoneDivergenceError(RuntimeError):
    """Raised when an erasure attestation certifies a seed set that is
    strictly smaller than the derivation closure actually reachable by
    semantic retrieval."""
    pass


@dataclass
class Memory:
    mem_id: str
    content: str
    provenance: frozenset[str] = field(default_factory=frozenset)  # source record ids


@dataclass
class Attestation:
    subject_id: str
    seed_ids: frozenset[str]
    closure_ids: frozenset[str]
    digest: str


def compute_derivation_closure(subject_id: str,
                               memories: list[Memory],
                               seed_ids: frozenset[str]) -> frozenset[str]:
    """Transitive closure of memories whose provenance intersects the seed.
    Returns the set of mem_ids that must be invalidated."""
    closure: set[str] = set()
    frontier = [m for m in memories if m.provenance & seed_ids]
    while frontier:
        m = frontier.pop()
        if m.mem_id in closure:
            continue
        closure.add(m.mem_id)
        # any memory derived from an already-invalidated memory joins the closure
        frontier.extend(
            other for other in memories
            if m.mem_id in other.provenance and other.mem_id not in closure
        )
    return frozenset(closure)


def emit_attestation(subject_id: str,
                     memories: list[Memory],
                     seed_ids: frozenset[str],
                     provenance_complete: bool) -> Attestation:
    if not provenance_complete:
        # Sound fallback: refuse to certify information-scoped erasure.
        raise TombstoneDivergenceError(
            f"cannot attest erasure of {subject_id!r}: provenance is lossy, "
            f"derivation closure unknown; record-scoped attestation only"
        )

    closure = compute_derivation_closure(subject_id, memories, seed_ids)

    # The certificate must cover the closure, not the seed. A digest over
    # seed_ids alone is a false certificate: it names a set strictly smaller
    # than the information actually removed from reachable state.
    uncovered = [m for m in memories
                 if m.mem_id in closure and m.provenance & seed_ids]
    if not uncovered and closure:
        raise TombstoneDivergenceError(
            f"attestation for {subject_id!r} covers seed {sorted(seed_ids)} "
            f"but derivation closure {sorted(closure)} is non-empty; "
            f"semantic probes would still surface erased content"
        )

    digest = hashlib.sha256(
        "|".join(sorted(seed_ids | closure)).encode()
    ).hexdigest()
    return Attestation(subject_id, seed_ids, closure, digest)


def verify_semantic_probe(att: Attestation,
                          probe_hits: list[Memory]) -> None:
    """Replay a semantic query; any hit whose provenance intersects the
    attested closure means the attestation is a lie."""
    leaked = [m for m in probe_hits if m.provenance & att.closure_ids]
    if leaked:
        raise TombstoneDivergenceError(
            f"attestation {att.digest[:12]} for {att.subject_id!r} is "
            f"divergent: semantic probe returned {[m.mem_id for m in leaked]} "
            f"derived from erased closure"
        )
