# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-a-right-to-be-forgotten-deletion-is-provenance-incomplete-across-a-derived-memory-lattice.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-a-right-to-be-forgotten-deletion-is-provenance-incomplete-across-a-derived-memory-lattice.warrant.json
# Markdown SHA-256:   f7a5d969c9fd195878794c882cb6f7df4734fd3f39fba7af8dab700022ba569f
# Code AST SHA-256:   5ed3aaef8e1e2d6588144db7ae1767365245c7d20ca89f9805bf59e8362dcc06
# Verified Classes:   ProvenanceGapError, MemoryNode
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProvenanceGapError(RuntimeError):
    """Raised when an erasure warrant would be emitted over an unclosed provenance DAG."""
    pass


class MemoryNode:
    def __init__(self, node_id, kind, subject_ids, provenance):
        self.node_id = node_id
        self.kind = kind                      # "episodic" | "semantic" | "summary"
        self.subject_ids = set(subject_ids)
        self.provenance = set(provenance)     # direct parent node_ids
        self.tombstoned = False
        self.quarantined = False


def assert_erasure_closed(graph, subject_id, depth_limit=64):
    """
    Verify that no live node is reachable from a node bearing subject_id.
    Traverses the FULL descendant closure, not one hop.
    Raises ProvenanceGapError if any live descendant survives.
    """
    roots = {n.node_id for n in graph.values() if subject_id in n.subject_ids}
    if not roots:
        return  # nothing to erase; caller decides whether to attest

    # Build child index (reverse edges).
    children = {nid: set() for nid in graph}
    for nid, node in graph.items():
        for parent in node.provenance:
            if parent in children:
                children[parent].add(nid)

    # BFS the full descendant closure from every root.
    live_descendants = set()
    frontier = list(roots)
    seen = set(roots)
    depth = 0
    while frontier:
        if depth > depth_limit:
            raise ProvenanceGapError(
                f"provenance closure exceeded depth {depth_limit}; "
                f"cycle or unbounded derivation suspected at subject {subject_id}"
            )
        next_frontier = []
        for nid in frontier:
            for child in children.get(nid, ()):
                if child in seen:
                    continue
                seen.add(child)
                node = graph[child]
                if not node.tombstoned:
                    live_descendants.add(child)
                next_frontier.append(child)
        frontier = next_frontier
        depth += 1

    if live_descendants:
        # Distinguish re-derivable from quarantine-required.
        for nid in live_descendants:
            node = graph[nid]
            retained = node.provenance - roots
            if not retained:
                # All provenance is deleted; cannot re-derive. Quarantine.
                node.quarantined = True
        raise ProvenanceGapError(
            f"erasure for subject {subject_id} is provenance-incomplete: "
            f"{len(live_descendants)} live descendant(s) reachable "
            f"({sorted(live_descendants)}); re-derivation or quarantine required "
            f"before warrant may be issued"
        )


def emit_erasure_warrant(graph, subject_id):
    """Only emits after closure is proven. Never attests over a gap."""
    assert_erasure_closed(graph, subject_id)  # raises if incomplete
    for node in graph.values():
        if subject_id in node.subject_ids:
            node.tombstoned = True
    return {"subject": subject_id, "status": "erased", "attested": True}
