# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-erasure-scope-leakage-when-a-derived-memory-summary-survives-a-gdpr-forget-on-its-source-records.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-erasure-scope-leakage-when-a-derived-memory-summary-survives-a-gdpr-forget-on-its-source-records.warrant.json
# Markdown SHA-256:   b5093f7a06b4cd25655264b257e94d5cd24729ddae84654b3ccc7ba7bc68282c
# Code AST SHA-256:   79325cd9d95fbc63a0106f72e1658e967a1cd385710a72f9414663f509d365c4
# Verified Classes:   ErasureClosureViolation, Artifact, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ErasureClosureViolation(RuntimeError):
    """Raised when a forget() call cannot prove derivation-closure erasure."""


@dataclass
class Artifact:
    artifact_id: str
    kind: str                      # "episode" | "summary" | "embedding"
    derived_from: frozenset[str]   # provenance record ids; empty == unverifiable
    subjects: frozenset[str]
    ttl_days: int


@dataclass
class MemoryStore:
    artifacts: dict[str, Artifact] = field(default_factory=dict)

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

    def closure_of(self, subject_id: str) -> set[str]:
        """Transitive closure of artifacts derived from any record of a subject."""
        seed = {a.artifact_id for a in self.artifacts.values()
                if subject_id in a.subjects}
        changed = True
        while changed:
            changed = False
            for a in self.artifacts.values():
                if a.artifact_id in seed:
                    continue
                if a.derived_from & seed:
                    seed.add(a.artifact_id)
                    changed = True
        return seed

    def forget(self, subject_id: str) -> dict:
        target = self.closure_of(subject_id)
        if not target:
            # deleted == 0 is ambiguous: no records, or decay already ate the sources
            return {"deleted": 0, "status": "ambiguous", "subject": subject_id}

        unverifiable = [self.artifacts[i].artifact_id for i in target
                        if not self.artifacts[i].derived_from]
        if unverifiable:
            raise ErasureClosureViolation(
                f"forget({subject_id}) hit artifacts with no provenance: {unverifiable}; "
                "cannot assert closure erasure"
            )

        for aid in target:
            del self.artifacts[aid]
        return {"deleted": len(target), "status": "complete", "subject": subject_id}

    def verify_erasure(self, subject_id: str) -> bool:
        return not self.closure_of(subject_id)


def erasure_workflow(store: MemoryStore, subject_id: str) -> str:
    result = store.forget(subject_id)
    if result["status"] == "ambiguous":
        # decay-orphan path: sources expired before derivatives
        raise ErasureClosureViolation(
            f"forget({subject_id}) returned deleted=0; possible decay orphan — "
            "run closure probe before asserting erasure"
        )
    if not store.verify_erasure(subject_id):
        raise ErasureClosureViolation(
            f"post-erasure closure non-empty for {subject_id}; derived artifact survived"
        )
    return "verified-complete"
