# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-forgets-a-memory-its-own-derived-summaries-still-cite.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-forgets-a-memory-its-own-derived-summaries-still-cite.warrant.json
# Markdown SHA-256:   2dd58c30e9825db13b3215af363801af202f7703fb08262920fdf87ff0da08bb
# Code AST SHA-256:   266269b28fdd5da79244b83fa264dbfa996577d4fbc458c0639adf3f597de800
# Verified Classes:   ProvenanceClosureError, MemoryRecord, ProvenanceTrackedStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceClosureError(RuntimeError):
    """Raised when forget() cannot prove the provenance closure is empty."""
    pass


@dataclass
class MemoryRecord:
    id: str
    content: str
    sources: list[str] = field(default_factory=list)      # outbound provenance
    derived_from: list[str] = field(default_factory=list) # outbound provenance


class ProvenanceTrackedStore:
    def __init__(self) -> None:
        self.records: dict[str, MemoryRecord] = {}
        # reverse index: source_id -> set of artifact ids that cite it
        self.cited_by: dict[str, set[str]] = {}

    def write(self, rec: MemoryRecord) -> None:
        self.records[rec.id] = rec
        for src in set(rec.sources) | set(rec.derived_from):
            self.cited_by.setdefault(src, set()).add(rec.id)

    def _closure(self, target_id: str) -> set[str]:
        """Transitive set of artifacts whose provenance cites target_id."""
        seen: set[str] = set()
        frontier = list(self.cited_by.get(target_id, set()))
        while frontier:
            node = frontier.pop()
            if node in seen or node == target_id:
                continue
            seen.add(node)
            frontier.extend(self.cited_by.get(node, set()))
        return seen

    def forget(self, target_id: str, *, allow_partial: bool = False) -> set[str]:
        if target_id not in self.records:
            raise ProvenanceClosureError(
                f"forget target {target_id!r} not present; cannot compute closure"
            )

        closure = self._closure(target_id)
        # An artifact that cannot prove its erased-source contribution is
        # unrecoverable must be invalidated in full, not repaired.
        invalidated = {target_id} | closure

        # Guardrail: if any surviving artifact still cites something in the
        # invalidated set (i.e. closure was not actually closed), refuse.
        dangling = {
            art
            for art in self.records
            if art not in invalidated
            and (set(self.records[art].sources) | set(self.records[art].derived_from))
            & invalidated
        }
        if dangling and not allow_partial:
            raise ProvenanceClosureError(
                f"forget({target_id!r}) would leave dangling provenance edges "
                f"from {sorted(dangling)}; closure incomplete — refusing to "
                f"report success on partial erasure"
            )

        for rid in invalidated:
            rec = self.records.pop(rid, None)
            if rec is None:
                continue
            for src in set(rec.sources) | set(rec.derived_from):
                self.cited_by.get(src, set()).discard(rid)
        return invalidated
