# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-forgotten-memory-still-survives-in-a-derived-artifact-after-a-gdpr-erasure-request.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-forgotten-memory-still-survives-in-a-derived-artifact-after-a-gdpr-erasure-request.warrant.json
# Markdown SHA-256:   5be2e3b46bd3318591268a233925c3c3056846bef9620093b67c1299972fd319
# Code AST SHA-256:   76ea1ae58205bb652bd55d10843b2660ef8315c3d26e110f09307c0716c269cf
# Verified Classes:   ErasureClosureViolation, Artifact, AgentMemoryStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Set, Dict, List


class ErasureClosureViolation(RuntimeError):
    """Raised when an erasure request cannot be satisfied because live
    derived artifacts survive the transitive provenance closure of the
    target record. Callers MUST NOT treat this as a transient error;
    the record must be quarantined and the artifacts re-derived or
    invalidated before erasure can be acknowledged."""
    pass


@dataclass
class Artifact:
    artifact_id: str
    kind: str                      # "episode" | "semantic" | "centroid" | "kv_cache"
    derived_from: Set[str] = field(default_factory=set)
    tainted: bool = False
    live: bool = True


class AgentMemoryStore:
    def __init__(self) -> None:
        self._artifacts: Dict[str, Artifact] = {}

    def add(self, art: Artifact) -> None:
        self._artifacts[art.artifact_id] = art

    def _provenance_closure(self, record_id: str) -> List[Artifact]:
        """Walk forward from a record to every live artifact that was
        derived from it, transitively. Requires derived_from edges to
        have been written at derivation time."""
        frontier = {record_id}
        seen: Set[str] = set()
        closure: List[Artifact] = []
        while frontier:
            current = frontier.pop()
            if current in seen:
                continue
            seen.add(current)
            for art in self._artifacts.values():
                if current in art.derived_from and art.live and not art.tainted:
                    closure.append(art)
                    frontier.add(art.artifact_id)
        return closure

    def erase(self, record_id: str, reconstruction_threshold_tau: float = 0.7) -> None:
        closure = self._provenance_closure(record_id)
        # Centroids, adapters, and KV caches cannot be surgically edited;
        # they must be tainted and rebuilt. If any survive, refuse.
        unresolvable = [
            a for a in closure
            if a.kind in ("centroid", "kv_cache") and not a.tainted
        ]
        if unresolvable:
            ids = ", ".join(a.artifact_id for a in unresolvable)
            raise ErasureClosureViolation(
                f"erasure of {record_id} blocked: {len(unresolvable)} live "
                f"derived artifact(s) cannot be invalidated in-transaction "
                f"({ids}). Quarantine {record_id} and schedule re-derivation."
            )
        # Semantic nodes and episodes can be deleted directly.
        for art in closure:
            art.live = False
        self._artifacts[record_id].live = False
        # Success is only reachable when the closure was fully resolved.


# --- observed failure trace ---
store = AgentMemoryStore()
store.add(Artifact("ep_001", "episode"))
store.add(Artifact("sem_017", "semantic", derived_from={"ep_001", "ep_002"}))
store.add(Artifact("cent_ivfpq_4", "centroid", derived_from={"ep_001", "ep_003"}))

try:
    store.erase("ep_001")
except ErasureClosureViolation as e:
    # Correct behavior: do NOT return 204. Quarantine and re-derive.
    print(f"REFUSED: {e}")
