# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-deletion-tombstone-has-been-silently-re-materialized-by-episodic-to-semantic-distillation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-deletion-tombstone-has-been-silently-re-materialized-by-episodic-to-semantic-distillation.warrant.json
# Markdown SHA-256:   c5bedbcbb791877a0cb85fb02c0fe142cf81ced143de101fa06fc34940432179
# Code AST SHA-256:   bd4061bcd1ec1314a07885b4ecfd3dba978969eeaf92e35d2c7f8988a87d597c
# Verified Classes:   ProvenanceTaintError, Node, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class ProvenanceTaintError(RuntimeError):
    """Raised when a semantic node's provenance closure touches a tombstoned record."""
    pass

@dataclass
class Node:
    node_id: str
    scope: str
    text: Optional[str]
    source_ids: list[str] = field(default_factory=list)

class MemoryStore:
    def __init__(self):
        self.nodes: dict[str, Node] = {}
        self.tombstones: set[str] = set()

    def forget(self, node_id: str) -> None:
        # Tombstone-write only. NOT erasure-complete.
        self.tombstones.add(node_id)
        if node_id in self.nodes:
            self.nodes[node_id].text = None

    def _closure_tainted(self, node_id: str, seen: Optional[set] = None) -> bool:
        seen = seen or set()
        if node_id in seen:
            return False
        seen.add(node_id)
        if node_id in self.tombstones:
            return True
        node = self.nodes.get(node_id)
        if node is None:
            return False
        return any(self._closure_tainted(s, seen) for s in node.source_ids)

    def read(self, node_id: str) -> Optional[Node]:
        # Read-time, global, transitive tombstone gate.
        if self._closure_tainted(node_id):
            raise ProvenanceTaintError(
                f"node {node_id} has tombstoned provenance in its closure; "
                f"refusing to serve (paraphrase drift may have laundered erased content)"
            )
        return self.nodes.get(node_id)

    def distill(self, new_id: str, source_ids: list[str], text: str) -> None:
        # Write-time guard is necessary but NOT sufficient: it sees only the
        # tombstone state at this instant. Reconciliation must follow.
        if any(self._closure_tainted(s) for s in source_ids):
            raise ProvenanceTaintError(
                f"refusing to distill {new_id}: source closure already tainted"
            )
        self.nodes[new_id] = Node(new_id, "semantic", text, list(source_ids))

    def reconcile(self) -> list[str]:
        # Post-commit sweep: quarantine any node whose closure became tainted
        # after it was written (erasure arrived during the distillation window).
        quarantined = []
        for nid, node in self.nodes.items():
            if node.scope == "semantic" and self._closure_tainted(nid):
                node.text = None
                quarantined.append(nid)
        return quarantined


def verify_erasure(store: MemoryStore, erased_id: str, paraphrase_query_hits: list[str]) -> None:
    """Assert no semantic node reachable by paraphrase still carries erased content."""
    store.forget(erased_id)
    store.reconcile()
    for hit in paraphrase_query_hits:
        try:
            node = store.read(hit)
        except ProvenanceTaintError:
            continue  # correctly gated
        if node is not None and node.text is not None:
            raise ProvenanceTaintError(
                f"erasure incomplete: semantic node {hit} still serves content "
                f"whose provenance closure includes erased record {erased_id}"
            )
