# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-the-erasure-tombstone-but-keep-the-embedding-a-boundary-invariant-for-gdpr-style-deletion-across-vector-stores-and-episodi.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-the-erasure-tombstone-but-keep-the-embedding-a-boundary-invariant-for-gdpr-style-deletion-across-vector-stores-and-episodi.warrant.json
# Markdown SHA-256:   7903ecd12c27a96dbc4eb27f68c27afac3c80b10c1a0ecfe39e05f42a2a201ef
# Code AST SHA-256:   f872ac09471f9e89fb9957da96805d046280904193c65ec579f9e1a97a114323
# Verified Classes:   ErasureResurrectionError, Tombstone
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ErasureResurrectionError(RuntimeError):
    """Raised when a post-erasure distillation replay produces a memory
    that references a token span belonging to an erased subject."""


@dataclass
class Tombstone:
    subject: str
    span_hashes: set[str] = field(default_factory=set)  # hashes, never raw spans
    erased_event_ids: set[str] = field(default_factory=set)


def hash_span(token: str) -> str:
    return hashlib.sha256(token.encode("utf-8")).hexdigest()


def verify_erasure_fixed_point(
    tombstone: Tombstone,
    redistilled_memories: list[dict],
    live_store_metadata: list[dict],
) -> None:
    """
    Enforce the invariant: erasure is a fixed point of distillation.

    redistilled_memories: output of D(redacted_log) run in sandbox.
    live_store_metadata: metadata of vectors currently served.

    Raises if any redistilled memory carries an erased span hash, or if the
    live store contains a vector that the post-erasure distillation would not
    reproduce (a resurrection candidate).
    """
    live_ids = {m.get("memory_id") for m in live_store_metadata}

    for mem in redistilled_memories:
        mem_span_hashes = set(mem.get("span_hashes", ()))
        leaked = mem_span_hashes & tombstone.span_hashes
        if leaked:
            raise ErasureResurrectionError(
                f"subject {tombstone.subject!r} resurrected in memory "
                f"{mem.get('memory_id')!r}: {len(leaked)} erased span hash(es) "
                f"present in redistilled output; erasure is not a fixed point"
            )
        if mem.get("memory_id") not in live_ids:
            raise ErasureResurrectionError(
                f"memory {mem.get('memory_id')!r} exists in post-erasure "
                f"distillation but not in live store; distiller and store have "
                f"diverged and the live store may hold stale copies"
            )

    # Tombstone must never be embedded as free text into the retrieval surface.
    for meta in live_store_metadata:
        if meta.get("source") == "compliance_table" and tombstone.subject in str(meta):
            raise ErasureResurrectionError(
                f"tombstone for {tombstone.subject!r} was ingested into the "
                f"vector store as memory {meta.get('memory_id')!r}; the erased "
                f"identifier is now retrievable by semantic similarity"
            )


def complete_erasure(
    tombstone: Tombstone,
    distiller_locked: bool,
    redistilled_memories: list[dict],
    live_store_metadata: list[dict],
) -> str:
    if not distiller_locked:
        # Cannot prove the fixed point while a scheduled distiller may run.
        return "pending_revalidation"
    verify_erasure_fixed_point(tombstone, redistilled_memories, live_store_metadata)
    return "complete"
