# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-tagged-memory-deletion-from-silently-resurrecting-forgotten-facts-during-episodic-to-semantic-distillation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-tagged-memory-deletion-from-silently-resurrecting-forgotten-facts-during-episodic-to-semantic-distillation.warrant.json
# Markdown SHA-256:   0f472c8987c51bb8f9a77193e2f3aa2aa1c63cd0c72e6a3dc1e8d67b40a205f2
# Code AST SHA-256:   403e8e403ec9d8132dea59da2ec3e702436600b321dc728536b8a0c34896a6a3
# Verified Classes:   ResurrectionRiskError, Record, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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

class ResurrectionRiskError(RuntimeError):
    """Raised when a forget() would leave a partially-justified derived record live."""
    pass

@dataclass
class Record:
    rid: str
    content: str
    # derivation history: every input ever consulted
    provenance: Set[str] = field(default_factory=set)
    # minimal propositions required to justify the assertion
    content_deps: Set[str] = field(default_factory=set)
    stale: bool = False

class MemoryStore:
    def __init__(self) -> None:
        self._records: Dict[str, Record] = {}

    def write(self, rec: Record) -> None:
        # Guardrail: a derived record must declare content deps that are
        # covered by its provenance at write time.
        if not rec.content_deps.issubset(rec.provenance):
            raise ResurrectionRiskError(
                f"{rec.rid}: content_deps {rec.content_deps} not covered by "
                f"provenance {rec.provenance}; refusing to store unjustified record"
            )
        self._records[rec.rid] = rec

    def forget(self, target: str, strict: bool = True) -> List[str]:
        if target not in self._records:
            return []
        invalidated: List[str] = []
        for rid, rec in self._records.items():
            if rid == target:
                continue
            if target in rec.provenance:
                surviving = rec.provenance - {target}
                covered = rec.content_deps.issubset(surviving)
                if not covered and rec.content_deps:
                    # partial coverage: the dangerous zone
                    if strict:
                        raise ResurrectionRiskError(
                            f"forget({target}) would leave {rid} partially "
                            f"justified: deps {rec.content_deps} not covered by "
                            f"surviving provenance {surviving}"
                        )
                    rec.stale = True
                    invalidated.append(rid)
                elif not covered and not rec.content_deps:
                    # pure pointer with empty deps -> safe delete
                    invalidated.append(rid)
        del self._records[target]
        for rid in invalidated:
            if rid in self._records and not self._records[rid].content_deps:
                del self._records[rid]
        return invalidated

    def read(self, rid: str) -> Record:
        rec = self._records[rid]
        if rec.stale:
            raise ResurrectionRiskError(
                f"read({rid}) blocked: record is stale after upstream forget; "
                f"re-derive from live sources before use"
            )
        return rec
