# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-forget-tombstone-has-been-silently-resurrected-by-semantic-distillation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-forget-tombstone-has-been-silently-resurrected-by-semantic-distillation.warrant.json
# Markdown SHA-256:   2c0abe452b30a883b9faca0ed6c380bd7b566fbaef636ec8deb3ea6ac179615f
# Code AST SHA-256:   5a3b2a00fca54434f39ad71279396e634fdffbed13e11f6bf2033d7a04c96c9c
# Verified Classes:   ErasureInvariantViolation, ForgetResult, MemoryBackend
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class ErasureInvariantViolation(RuntimeError):
    """Raised when a forget call's claimed erasure cannot be verified at the read layer."""


@dataclass
class ForgetResult:
    deleted: bool
    distillation_watermark: float | None
    derived_artifacts_quarantined: int
    record_id: str


@dataclass
class MemoryBackend:
    # Episodic records and derived semantic nodes, with lineage edges.
    episodic: dict[str, dict] = field(default_factory=dict)
    semantic: dict[str, dict] = field(default_factory=dict)
    tombstones: dict[str, float] = field(default_factory=dict)

    def forget(self, record_id: str) -> ForgetResult:
        if record_id not in self.episodic:
            return ForgetResult(True, None, 0, record_id)
        tau = time.monotonic()
        self.tombstones[record_id] = tau
        del self.episodic[record_id]
        # Quarantine derived nodes whose lineage touches the erased record.
        quarantined = 0
        for node_id, node in list(self.semantic.items()):
            lineage = node.get("lineage") or []
            if record_id in lineage:
                del self.semantic[node_id]
                quarantined += 1
            elif node.get("lineage") is None:
                # Null provenance: cannot prove it did not ingest the record.
                pass
        return ForgetResult(True, tau, quarantined, record_id)

    def read(self, query: str, k: int = 5) -> list[dict]:
        # Read-side filter: drop any node whose lineage intersects a tombstone.
        out = []
        for node in self.semantic.values():
            lineage = node.get("lineage") or []
            if any(rid in self.tombstones for rid in lineage):
                continue
            if query.lower() in node.get("text", "").lower():
                out.append(node)
        return out[:k]


def verified_forget(backend: MemoryBackend, record_id: str, probe_query: str) -> ForgetResult:
    """Apply forget and assert the erasure holds at the read layer."""
    result = backend.forget(record_id)

    if result.distillation_watermark is None:
        raise ErasureInvariantViolation(
            f"forget({record_id}) returned no distillation watermark; "
            "semantic residue cannot be bounded. Refusing to assert erasure."
        )

    residual = backend.read(probe_query, k=5)
    if residual:
        raise ErasureInvariantViolation(
            f"forget({record_id}) claimed deletion but read probe '{probe_query}' "
            f"returned {len(residual)} derived node(s) — tombstone resurrected by distillation."
        )

    return result
