# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-torn-erasure-when-a-memory-store-acknowledges-a-right-to-erasure-request-but-its-vector-index-still-retains-the-embeddin.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-torn-erasure-when-a-memory-store-acknowledges-a-right-to-erasure-request-but-its-vector-index-still-retains-the-embeddin.warrant.json
# Markdown SHA-256:   8690ca35a57428b37f2bbc6a054fbc4485584d409d1fab2b4823aa39975b5dfd
# Code AST SHA-256:   de3a389131bffe90ba5c8c6f1a8d1bc242fb1d5e1f78b5144713c26f4047bc87
# Verified Classes:   TornErasureError, ResurrectionError, Tombstone, VectorEntry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class TornErasureError(RuntimeError):
    """Raised when an erasure receipt is issued but physical erasure is unproven."""
    pass


class ResurrectionError(RuntimeError):
    """Raised when a tombstoned subject re-enters the store via consolidation."""
    pass


@dataclass(frozen=True)
class Tombstone:
    memory_id: str
    subject_key: str
    content_hash: str
    erasure_seq: int


@dataclass(frozen=True)
class VectorEntry:
    memory_id: str
    subject_key: str
    content_hash: str
    embedding_model: str


def audit_erasure(
    tombstones: Iterable[Tombstone],
    live_vectors: Iterable[VectorEntry],
    erasure_watermark: int,
    index_supports_enumeration: bool,
) -> None:
    """Gate the erasure watermark on a ghost audit.

    Must be called before advancing the tenant erasure watermark and before
    issuing any receipt that claims physical erasure.
    """
    if not index_supports_enumeration:
        raise TornErasureError(
            "vector index cannot enumerate live IDs; physical erasure is "
            "unprovable and no receipt may be issued"
        )

    live_by_id = {v.memory_id: v for v in live_vectors}
    live_by_hash = {v.content_hash: v for v in live_vectors}

    for ts in tombstones:
        if ts.erasure_seq > erasure_watermark:
            continue
        if ts.memory_id in live_by_id:
            raise TornErasureError(
                f"tombstoned memory {ts.memory_id} still has a live vector "
                f"at erasure_seq {ts.erasure_seq}; compaction has not dropped it"
            )
        if ts.content_hash in live_by_hash:
            raise TornErasureError(
                f"tombstoned content hash {ts.content_hash} reappeared under "
                f"memory {live_by_hash[ts.content_hash].memory_id}; "
                f"resurrection via re-embedding is not erasure"
            )


def check_consolidation_ingest(
    candidate: VectorEntry,
    tombstones_by_subject: dict,
) -> None:
    """Run on the consolidation ingest path before writing any new vector."""
    ts: Optional[Tombstone] = tombstones_by_subject.get(candidate.subject_key)
    if ts is not None:
        raise ResurrectionError(
            f"consolidation attempted to reinsert subject {candidate.subject_key} "
            f"as memory {candidate.memory_id} after erasure_seq {ts.erasure_seq}; "
            f"tombstone lineage must block the write"
        )


def probe_for_leak(
    probe_neighbors: list,
    erased_memory_ids: set,
    erased_content_hashes: set,
) -> None:
    """Probe-based detector: the tombstone filter hides leaks from ordinary reads."""
    for neighbor in probe_neighbors:
        if neighbor.memory_id in erased_memory_ids:
            raise TornErasureError(
                f"probe retrieved erased memory {neighbor.memory_id}; "
                f"tombstone filter is applied at render time, not retrieval time"
            )
        if neighbor.content_hash in erased_content_hashes:
            raise TornErasureError(
                f"probe retrieved content hash {neighbor.content_hash} of an "
                f"erased subject under memory {neighbor.memory_id}"
            )
