# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-honor-a-forget-call-when-provenance-tracked-deletion-would-orphan-a-derived-semantic-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-honor-a-forget-call-when-provenance-tracked-deletion-would-orphan-a-derived-semantic-memory.warrant.json
# Markdown SHA-256:   72c8b0de141a94e2e3d6219c67397af1bfd79eb635141d90485003ca002106e5
# Code AST SHA-256:   2d4cba13b48c84d7d66b0b2e7c8249b552dcbbff2bf8a8091db9ff7fa27c18da
# Verified Classes:   ProvenanceOrphanError, Record, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field

class ProvenanceOrphanError(RuntimeError):
    """Raised when forget() would leave a live record derived from a tombstone."""
    def __init__(self, target, quarantined, taint_source):
        self.target = target
        self.quarantined = quarantined
        self.taint_source = taint_source
        super().__init__(
            f"forget({target!r}) refused: {len(quarantined)} descendant(s) "
            f"{quarantined} have fan-in > 1 and no re-derivation path; "
            f"they must be quarantined against taint_source={taint_source!r}"
        )

@dataclass
class Record:
    handle: str
    derived_from: list = field(default_factory=list)  # parent handles
    tombstoned: bool = False
    quarantined: bool = False
    taint_source: str | None = None

class MemoryStore:
    def __init__(self):
        self.records: dict[str, Record] = {}

    def _children(self, handle):
        return [r for r in self.records.values() if handle in r.derived_from]

    def _closure(self, handle):
        """Transitive descendants of handle via derivation edges."""
        seen, stack = set(), [handle]
        while stack:
            cur = stack.pop()
            for child in self._children(cur):
                if child.handle not in seen:
                    seen.add(child.handle)
                    stack.append(child.handle)
        return seen

    def forget(self, handle, strategy=None):
        if handle not in self.records:
            raise KeyError(handle)
        closure = self._closure(handle)
        # fan-in > 1 means the child also depends on a surviving parent
        orphans = [
            self.records[d] for d in closure
            if len(self.records[d].derived_from) > 1
        ]
        if orphans and strategy != "cascade":
            # No re-derivation path assumed: distillations are lossy.
            quarantined = sorted(o.handle for o in orphans)
            for o in orphans:
                o.quarantined = True
                o.taint_source = handle
            self.records[handle].tombstoned = True
            raise ProvenanceOrphanError(handle, quarantined, handle)
        # Safe: pure chain or explicit cascade authorization.
        for d in closure:
            self.records[d].tombstoned = True
        self.records[handle].tombstoned = True
        return {"deleted": sorted(closure | {handle})}

    def read(self, handle):
        r = self.records[handle]
        if r.tombstoned or r.quarantined:
            return None  # retrieval filter enforces the invariant
        return r
