# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-forget-request-as-unsatisfiable-rather-than-partially-satisfied-the-derived-summary-resurrection-boundary-in-agent-memor.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-forget-request-as-unsatisfiable-rather-than-partially-satisfied-the-derived-summary-resurrection-boundary-in-agent-memor.warrant.json
# Markdown SHA-256:   6697ec92628bcf62fc298c1b8882f14e04c9ba670c62067d4fe9b5dda74be542
# Code AST SHA-256:   8e753681323bf8a481618b13e26281bc5fa11ac9739544e68f9459bd498623e7
# Verified Classes:   ErasureUnsatisfiableError, DerivedNode, ErasureRequest, ErasureHandler
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ErasureUnsatisfiableError(RuntimeError):
    """Raised when erasure cannot be certified because the derivation
    closure of the target fact is incomplete or unenumerable."""


@dataclass
class DerivedNode:
    node_id: str
    source_ids: frozenset  # empty/None means provenance was aggregated away
    index: str             # which retrieval index holds this node


@dataclass
class ErasureRequest:
    fact_id: str
    reconstruction_threshold: int = 0  # max allowed hits on adversarial probe


class ErasureHandler:
    def __init__(self, derivation_graph: dict, indexes: dict):
        self.graph = derivation_graph      # node_id -> DerivedNode
        self.indexes = indexes             # index name -> probe callable

    def closure(self, fact_id: str) -> frozenset:
        """Transitive set of derived nodes reachable from the source fact."""
        reachable, frontier = set(), [fact_id]
        while frontier:
            cur = frontier.pop()
            for nid, node in self.graph.items():
                if cur in node.source_ids and nid not in reachable:
                    reachable.add(nid)
                    frontier.append(nid)
        return frozenset(reachable)

    def _provenance_complete(self, fact_id: str) -> bool:
        # Any node whose source set was aggregated away is an unknown edge.
        for node in self.graph.values():
            if not node.source_ids:
                return False
        return True

    def erase(self, req: ErasureRequest) -> str:
        if not self._provenance_complete(req.fact_id):
            # Cannot enumerate the closure -> must fail closed, not delete-and-hope.
            raise ErasureUnsatisfiableError(
                f"provenance closure for {req.fact_id!r} is unenumerable; "
                f"quarantine affected index regions and refuse retrieval"
            )

        nodes = self.closure(req.fact_id)
        for nid in nodes:
            node = self.graph[nid]
            probe = self.indexes.get(node.index)
            if probe is None:
                raise ErasureUnsatisfiableError(
                    f"derived node {nid!r} lives in index {node.index!r} "
                    f"with no probe registered; cannot certify erasure"
                )
            # Re-derive from surviving sources, then adversarially re-probe.
            hits = probe(req.fact_id)
            if hits > req.reconstruction_threshold:
                raise ErasureUnsatisfiableError(
                    f"derived node {nid!r} still reconstructs {req.fact_id!r} "
                    f"({hits} hits > threshold {req.reconstruction_threshold})"
                )
        return "ERASED"


def handle_erasure(graph, indexes, fact_id):
    handler = ErasureHandler(graph, indexes)
    try:
        return handler.erase(ErasureRequest(fact_id=fact_id))
    except ErasureUnsatisfiableError as e:
        # Surface to operator; do NOT downgrade to "satisfied".
        return f"ERASURE_UNSATISFIABLE: {e}"
