# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tombstoned-memory-from-resurfacing-through-summary-derived-retrieval-in-agent-read-write-forget-interfaces.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tombstoned-memory-from-resurfacing-through-summary-derived-retrieval-in-agent-read-write-forget-interfaces.warrant.json
# Markdown SHA-256:   529bf3add58c598ed70fa6ba2c5f8c9fe49bde9fd81e0ff9be2baac269245875
# Code AST SHA-256:   52ec6f0598fb49cb73b1f21273f51271d2258672f3ea90dc56a667f79108b413
# Verified Classes:   ResurrectionByDerivationError, Artifact, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ResurrectionByDerivationError(RuntimeError):
    """Raised when a read or write would surface material from a tombstoned entity
    via a derived artifact (summary, digest, index entry) whose derivation closure
    reaches the tombstone."""


@dataclass
class Artifact:
    id: str
    kind: str  # "primary" | "summary" | "digest" | "index"
    derived_from: list[str] = field(default_factory=list)
    text: str = ""


class MemoryStore:
    def __init__(self) -> None:
        self.artifacts: dict[str, Artifact] = {}
        self.tombstones: set[str] = set()

    def write(self, art: Artifact) -> None:
        self.artifacts[art.id] = art

    def forget(self, entity_id: str) -> dict:
        # Shallow forget: delete primary, record tombstone. Does NOT touch derivations.
        self.artifacts.pop(entity_id, None)
        self.tombstones.add(entity_id)
        return {"deleted": True, "contract": "shallow"}

    def _closure(self, art: Artifact, seen: Optional[set[str]] = None) -> set[str]:
        seen = seen or set()
        if art.id in seen:
            return seen
        seen.add(art.id)
        for parent in art.derived_from:
            if parent in self.artifacts:
                self._closure(self.artifacts[parent], seen)
        return seen

    def read(self, art_id: str) -> Artifact:
        art = self.artifacts.get(art_id)
        if art is None:
            raise ResurrectionByDerivationError(f"artifact {art_id} not present")
        closure = self._closure(art)
        tainted = closure & self.tombstones
        if tainted:
            # Read-time invariant: R ∩ closure(t) must be empty. Violation => refuse.
            raise ResurrectionByDerivationError(
                f"artifact {art_id} derives from tombstoned {sorted(tainted)}; "
                f"refusing to inject into context"
            )
        return art

    def write_from_source(self, new: Artifact) -> None:
        # Guard: never launder a derived artifact into a new primary record
        # if its closure touches a tombstone.
        closure = self._closure(new)
        tainted = closure & self.tombstones
        if tainted:
            raise ResurrectionByDerivationError(
                f"new record {new.id} would launder tombstoned {sorted(tainted)}"
            )
        self.artifacts[new.id] = new


# Reproduction of the observed failure and the guard that bounds it.
store = MemoryStore()
store.write(Artifact("note_4412", "primary", text="staging rotation deferred to vendor"))
store.write(Artifact("summary_17", "summary", derived_from=["note_4412"], text="rotation deferred"))
store.forget("note_4412")
try:
    store.read("summary_17")  # would have resurfaced the forgotten fact
except ResurrectionByDerivationError as e:
    print("bounded:", e)
try:
    store.write_from_source(Artifact("note_5120", "primary", derived_from=["summary_17"]))
except ResurrectionByDerivationError as e:
    print("laundering blocked:", e)
