# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-honor-a-forget-call-tombstone-resurrection-via-provenance-sharded-re-derivation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-honor-a-forget-call-tombstone-resurrection-via-provenance-sharded-re-derivation.warrant.json
# Markdown SHA-256:   0526849d49b6f42b1b99c7dd7d2f8e7e4671e37192002244ef38670bfb72e490
# Code AST SHA-256:   b48b064b7090ec9db01ad8e7f9fa34eac52a5aaf792813c41f029d7a822bb56d
# Verified Classes:   ProvenanceClosureError, MemRecord, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class ProvenanceClosureError(RuntimeError):
    """Raised when forget_memory cannot prove the forgotten set is unreachable."""
    pass

@dataclass
class MemRecord:
    id: str
    subjects: list[str] = field(default_factory=list)
    parents: list[str] = field(default_factory=list)
    tombstoned: bool = False

class MemoryStore:
    def __init__(self, records: dict[str, MemRecord], dag_consistent: bool):
        self.records = records
        self.dag_consistent = dag_consistent  # snapshot fence with subject index

    def _resolve(self, rid: str) -> Optional[MemRecord]:
        return self.records.get(rid)

    def forget(self, subject: str) -> dict:
        if not self.dag_consistent:
            raise ProvenanceClosureError(
                f"subject index and provenance DAG not fenced; "
                f"refusing to report deletion for {subject!r}"
            )
        roots = [r.id for r in self.records.values() if subject in r.subjects]
        frontier, seen = list(roots), set()
        while frontier:
            rid = frontier.pop()
            if rid in seen:
                continue
            seen.add(rid)
            rec = self._resolve(rid)
            if rec is None:
                raise ProvenanceClosureError(
                    f"dangling parent edge at {rid!r}; closure unprovable for {subject!r}"
                )
            rec.tombstoned = True
            # forward closure: every child that names this node as parent
            for child in self.records.values():
                if rid in child.parents:
                    frontier.append(child.id)
        return {"deleted": len(seen), "status": "OK"}

    def read(self, query: str) -> list[MemRecord]:
        out = []
        for rec in self.records.values():
            if rec.tombstoned:
                continue
            if any(self.records.get(p) and self.records[p].tombstoned
                   for p in rec.parents):
                continue  # parent-liveness guard: suppress resurrection
            out.append(rec)
        return out
