# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-a-redacted-memory-yet-still-retrieve-it-through-an-episodic-to-semantic-distillation-residue.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-a-redacted-memory-yet-still-retrieve-it-through-an-episodic-to-semantic-distillation-residue.warrant.json
# Markdown SHA-256:   60099c7f477be95040ad854e2612ceaee287596e98fd325663e73f53d052d544
# Code AST SHA-256:   e53a2b2164f0b555b81eaa752c1ea9896f7ebf40ebc2178cf838411fc4709439
# Verified Classes:   ErasureClosureError, SemanticFact, MemoryTier
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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

class ErasureClosureError(RuntimeError):
    """Raised when erasure of an episodic root leaves a live derivation residue."""
    pass

@dataclass
class SemanticFact:
    fact_id: str
    text: str
    root_ids: Set[str] = field(default_factory=set)   # full episodic derivation set

class MemoryTier:
    def __init__(self) -> None:
        self.episodic: Dict[str, str] = {}
        self.semantic: Dict[str, SemanticFact] = {}
        self.tombstones: Set[str] = set()  # consulted by the vector index at query time

    def distill(self, parents: List[str], fact_id: str, text: str) -> SemanticFact:
        # Correct distillation: UNION parent roots, never overwrite with last-writer.
        roots: Set[str] = set()
        for p in parents:
            if p in self.semantic:
                roots |= self.semantic[p].root_ids
            else:
                roots.add(p)  # p is an episodic root
        fact = SemanticFact(fact_id, text, roots)
        self.semantic[fact_id] = fact
        return fact

    def erase(self, root_id: str) -> None:
        # Phase 1: compute derivation closure downward from the root.
        reachable = [fid for fid, f in self.semantic.items() if root_id in f.root_ids]
        # Phase 2: delete artifacts and tombstone them for the vector index.
        self.episodic.pop(root_id, None)
        for fid in reachable:
            self.semantic.pop(fid, None)
            self.tombstones.add(fid)
        # Phase 3: closure check — no surviving fact may still reference the root.
        residue = [fid for fid, f in self.semantic.items() if root_id in f.root_ids]
        if residue:
            raise ErasureClosureError(
                f"erasure of {root_id!r} incomplete; residue in {residue}"
            )

    def retrieve(self, query_fact_id: str) -> SemanticFact:
        if query_fact_id in self.tombstones:
            raise ErasureClosureError(
                f"retrieval of tombstoned artifact {query_fact_id!r} blocked"
            )
        return self.semantic[query_fact_id]

def erase_or_fail(tier: MemoryTier, root_id: str) -> None:
    try:
        tier.erase(root_id)
    except ErasureClosureError:
        raise
    # Post-condition: probe must confirm the root is unreachable via any derivation.
    for fid, fact in tier.semantic.items():
        if root_id in fact.root_ids:
            raise ErasureClosureError(
                f"post-erasure probe found {root_id!r} still reachable via {fid!r}"
            )
