# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-gdpr-style-erasure-request-as-unsatisfiable-until-every-derived-semantic-memory-artifact-not-just-the-raw-e.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-gdpr-style-erasure-request-as-unsatisfiable-until-every-derived-semantic-memory-artifact-not-just-the-raw-e.warrant.json
# Markdown SHA-256:   df7bcfbc963cb84042ab32214ed0864cd1629c69d7257ceb36097c82cf9c440c
# Code AST SHA-256:   78b07bc4aa2bdcd8597ef6f187854c6ec50a473258f9011c5fadd728b8261519
# Verified Classes:   ErasureUnsatisfiableError, DerivedArtifact, MemoryGraph
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ErasureUnsatisfiableError(RuntimeError):
    """Raised when erasure cannot be proven complete because derived artifacts
    or caches cannot be unlinked from the erased subject."""


@dataclass
class DerivedArtifact:
    artifact_id: str
    kind: str  # "episodic" | "semantic" | "consolidated" | "cache_entry"
    provenance: frozenset[str] | None  # None == unknown/untracked


@dataclass
class MemoryGraph:
    artifacts: dict[str, DerivedArtifact] = field(default_factory=dict)
    tombstones: set[str] = field(default_factory=set)

    def register(self, art: DerivedArtifact) -> None:
        self.artifacts[art.artifact_id] = art

    def intersecting(self, subject: str) -> Iterable[DerivedArtifact]:
        for art in self.artifacts.values():
            if art.provenance is None:
                # Unknown provenance is conservatively treated as intersecting.
                yield art
            elif subject in art.provenance:
                yield art


def execute_erasure(graph: MemoryGraph, subject: str) -> None:
    # Phase 1: tombstone first so no retrieval/consolidation path can resurrect.
    graph.tombstones.add(subject)

    # Phase 2: identify every derived artifact that encodes the subject.
    targets = list(graph.intersecting(subject))

    untracked = [a for a in targets if a.provenance is None]
    if untracked:
        raise ErasureUnsatisfiableError(
            f"subject={subject!r} has {len(untracked)} derived artifact(s) with "
            f"unknown provenance (ids={[a.artifact_id for a in untracked]}); "
            f"cannot prove unlink. Erasure remains PENDING."
        )

    # Phase 3: unlink all tracked artifacts.
    for art in targets:
        del graph.artifacts[art.artifact_id]

    # Phase 4: verify no path still intersects.
    residual = list(graph.intersecting(subject))
    if residual:
        raise ErasureUnsatisfiableError(
            f"post-unlink verification failed for subject={subject!r}: "
            f"{[a.artifact_id for a in residual]} still intersect."
        )

    graph.tombstones.discard(subject)  # erasure complete
