# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-a-fact-but-still-recall-its-embedding-neighbors-erasure-propagation-failures-across-agent-memory-graphs.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-a-fact-but-still-recall-its-embedding-neighbors-erasure-propagation-failures-across-agent-memory-graphs.warrant.json
# Markdown SHA-256:   76c4f2db01b97a3429f71fca81cf000077969d287c68cb796a5bef24192223b8
# Code AST SHA-256:   339fcbcdefaf4ddfdb8bb9847c63af74cda93121c2421c8a6bfd581311475729
# Verified Classes:   ErasureClosureViolation, MemoryNode, ErasureRequest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ErasureClosureViolation(RuntimeError):
    """Raised when an erasure request cannot be proven to cover its reachability closure."""
    pass


@dataclass
class MemoryNode:
    node_id: str
    kind: str                      # "episodic" | "summary"
    subject_ids: set[str]
    source_pointers: set[str] = field(default_factory=set)
    provenance_subjects: set[str] = field(default_factory=set)  # transitive, incl. co-occurrence merges


@dataclass
class ErasureRequest:
    subject_id: str
    require_synchronous_compaction: bool = True


def compute_closure(nodes: dict[str, MemoryNode], subject_id: str) -> set[str]:
    """Transitive closure over provenance, not just source pointers."""
    closure: set[str] = set()
    frontier = [n for n in nodes.values() if subject_id in n.provenance_subjects
                or subject_id in n.subject_ids]
    while frontier:
        node = frontier.pop()
        if node.node_id in closure:
            continue
        closure.add(node.node_id)
        # any summary whose provenance absorbed this node's subjects is contaminated
        for other in nodes.values():
            if other.node_id in closure:
                continue
            if other.source_pointers & {node.node_id} or (
                other.provenance_subjects & node.provenance_subjects
                and other.kind == "summary"
            ):
                frontier.append(other)
    return closure


def execute_erasure(nodes: dict[str, MemoryNode], req: ErasureRequest,
                    index_tombstoned: set[str], probe_hits: Iterable[str]) -> set[str]:
    closure = compute_closure(nodes, req.subject_id)
    if not closure:
        return set()

    # Invariant 1: provenance closure must be fully enumerated before deletion.
    unprovenanced = [nid for nid in closure if not nodes[nid].provenance_subjects]
    if unprovenanced:
        raise ErasureClosureViolation(
            f"nodes {unprovenanced} in closure lack provenance; cannot prove erasure completeness"
        )

    # Invariant 2: tombstone barrier must be visible to all read paths before ack.
    if req.require_synchronous_compaction and not closure <= index_tombstoned:
        raise ErasureClosureViolation(
            f"index tombstone barrier incomplete: {closure - index_tombstoned} still live in ANN"
        )

    # Invariant 3: post-erasure reconstruction probe must return no hits.
    hits = set(probe_hits)
    if hits & closure:
        raise ErasureClosureViolation(
            f"reconstruction probe re-derived erased content via {hits & closure}"
        )

    for nid in closure:
        nodes.pop(nid, None)
    return closure
