# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-gdpr-style-erasure-request-has-been-silently-defeated-by-kv-cache-and-vector-index-resurrection.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-gdpr-style-erasure-request-has-been-silently-defeated-by-kv-cache-and-vector-index-resurrection.warrant.json
# Markdown SHA-256:   7f6a13503e24862bd5feec079afc2c0d7da50b29fc4c34c22aa345e3b411f43e
# Code AST SHA-256:   87315feecd496de0d3aae46e886ab0241332c79a533e51b4bd95ad74c8ef6116
# Verified Classes:   ErasureResurrectionError, MemoryRow, KVCheckpoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass, field
from typing import Optional


class ErasureResurrectionError(RuntimeError):
    """Raised when an erasure request is defeated by a surviving derivative
    or a pre-erasure KV checkpoint, despite delete counters reporting success."""
    pass


@dataclass
class MemoryRow:
    row_id: str
    subject_id: Optional[str]
    embedding: list[float]
    erasure_epoch: int
    derived_from: set[str] = field(default_factory=set)


@dataclass
class KVCheckpoint:
    session_id: str
    erasure_epoch: int


def cosine(a: list[float], b: list[float]) -> float:
    dot = sum(x * y for x, y in zip(a, b))
    na = math.sqrt(sum(x * x for x in a))
    nb = math.sqrt(sum(y * y for y in b))
    if na == 0 or nb == 0:
        return 0.0
    return dot / (na * nb)


def verify_erasure(
    subject_id: str,
    erased_embedding: list[float],
    current_epoch: int,
    surviving_rows: list[MemoryRow],
    checkpoints: list[KVCheckpoint],
    tau_erase: float = 0.80,
    tau_retrieve: float = 0.75,
) -> str:
    """Read-side proof that a subject is unreachable. Returns 'ERASED',
    'QUARANTINED_PENDING_REVIEW', or 'ERASURE_UNVERIFIED'."""

    # Invariant 2: no checkpoint older than the erasure epoch may be loadable.
    stale = [c for c in checkpoints if c.erasure_epoch < current_epoch]
    if stale:
        raise ErasureResurrectionError(
            f"pre-erasure checkpoint(s) {[c.session_id for c in stale]} "
            f"survive at epoch < {current_epoch}; resume would resurrect KV pages"
        )

    candidates = []
    for row in surviving_rows:
        # Invariant 1: key-based survivors are a hard failure.
        if row.subject_id == subject_id:
            raise ErasureResurrectionError(
                f"row {row.row_id} still keyed to {subject_id} after delete"
            )
        # Invariant 3/4: probe by latent similarity, not by key.
        sim = cosine(row.embedding, erased_embedding)
        if sim >= tau_erase:
            candidates.append((row.row_id, sim))

    if not candidates:
        return "ERASED"

    # Invariant 4: any survivor in [tau_erase, tau_retrieve) is conditionally
    # defeated; quarantine before allowing completion.
    if any(sim >= tau_retrieve for _, sim in candidates):
        return "QUARANTINED_PENDING_REVIEW"

    # Survivors below retrieval threshold but above erase bound: we cannot
    # prove unreachability without a complete derivative reverse-index.
    return "ERASURE_UNVERIFIED"
