# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-tombstone-has-been-resurrected-decay-weighted-retrieval-re-materializing-right-to-be-forgotten-records-through-epis.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-tombstone-has-been-resurrected-decay-weighted-retrieval-re-materializing-right-to-be-forgotten-records-through-epis.warrant.json
# Markdown SHA-256:   8110a092fb3efee1ff7f4478e72499a0145639db4e82711fe51df70187a3d0ed
# Code AST SHA-256:   0a58a7580e7164f8832c5caf9c6cc9719076a2f674823f94ac5117f1ca61772d
# Verified Classes:   ResurrectionInvariantViolation, MemoryNode, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ResurrectionInvariantViolation(RuntimeError):
    """Raised when a forget() call would leave reconstructable lineage behind."""
    pass


@dataclass
class MemoryNode:
    node_id: str
    kind: str                      # "episodic" | "semantic"
    source_ids: tuple[str, ...] = ()
    tombstoned: bool = False


@dataclass
class MemoryStore:
    nodes: dict[str, MemoryNode] = field(default_factory=dict)
    deletion_epoch: int = 0

    def lineage_closure(self, root_id: str) -> set[str]:
        seen: set[str] = set()
        stack = [root_id]
        while stack:
            nid = stack.pop()
            if nid in seen or nid not in self.nodes:
                continue
            seen.add(nid)
            stack.extend(self.nodes[nid].source_ids)
        return seen

    def forget(self, root_id: str) -> None:
        closure = self.lineage_closure(root_id)
        survivors = [
            nid for nid in closure
            if not self.nodes[nid].tombstoned and nid != root_id
        ]
        if survivors:
            raise ResurrectionInvariantViolation(
                f"forget({root_id}) would leave {len(survivors)} derived "
                f"artifact(s) reconstructable: {sorted(survivors)}. "
                f"Lineage-closing forget requires tombstoning the full "
                f"provenance closure and bumping the deletion epoch so the "
                f"distillation pass cannot re-derive from surviving neighbors."
            )
        for nid in closure:
            self.nodes[nid].tombstoned = True
        self.deletion_epoch += 1

    def distill(self, source_id: str, new_id: str) -> None:
        if self.nodes[source_id].tombstoned:
            raise ResurrectionInvariantViolation(
                f"distill({source_id}) attempted after deletion epoch "
                f"{self.deletion_epoch}; source is tombstoned and may not be "
                f"re-summarized into {new_id}."
            )
        self.nodes[new_id] = MemoryNode(
            node_id=new_id, kind="semantic", source_ids=(source_id,)
        )
