# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-gdpr-erasure-warrant-against-a-semantic-memory-that-has-already-been-distilled-into-peer-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-gdpr-erasure-warrant-against-a-semantic-memory-that-has-already-been-distilled-into-peer-agents.warrant.json
# Markdown SHA-256:   f48d2aac830bee769441de0b16e9c1330ab180ec81f9b7feca60117356624fa5
# Code AST SHA-256:   f14327d317afdb0c3298115e4ab71e1da449f16059b32e13eebe7a30888b1abb
# Verified Classes:   UnprovableErasureError, Artifact, Mesh
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class UnprovableErasureError(RuntimeError):
    """Raised when an erasure warrant cannot be walked to provenance closure."""


@dataclass
class Artifact:
    artifact_id: str
    derived_from: Set[str]  # source record IDs; empty == orphaned/unlinked
    owner_agent: str


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

    def forward_walk(self, subject_id: str) -> Set[str]:
        """Return every artifact transitively derived from subject_id."""
        reached: Set[str] = set()
        frontier = {subject_id}
        while frontier:
            current = frontier.pop()
            for aid, art in self.artifacts.items():
                if aid in reached:
                    continue
                if current in art.derived_from:
                    reached.add(aid)
                    frontier.add(aid)  # transitively reach second-order derivations
        return reached

    def erase_subject(self, subject_id: str) -> dict:
        # Detect artifacts that reference subject lineage but whose provenance
        # was pruned (empty derived_from) -> unprovable residue.
        orphans = {
            aid for aid, art in self.artifacts.items()
            if not art.derived_from and art.owner_agent != "ingest"
        }
        reachable = self.forward_walk(subject_id)

        if orphans:
            # Absence of a pointer is not absence of derivation.
            raise UnprovableErasureError(
                f"cannot prove erasure of {subject_id}: "
                f"{len(orphans)} orphaned artifacts with pruned provenance "
                f"may be derived from subject; refusing completion attestation"
            )

        for aid in reachable:
            del self.artifacts[aid]
        return {"erased_artifacts": sorted(reachable), "closure_proven": True}
