# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-agent-s-memory-poisoning-detector-has-inverted-its-provenance-direction-on-forget-operations.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-agent-s-memory-poisoning-detector-has-inverted-its-provenance-direction-on-forget-operations.warrant.json
# Markdown SHA-256:   25d21dc8a8aa3a5645b69aa430b5ad1bc919323211e072b68b5af2f978e1da7d
# Code AST SHA-256:   f5bdce38bb97cba0f22845a7aad0b47a2980942ff9d2d35a8f932b855e9b1f9a
# Verified Classes:   InvertedProvenanceError, MemoryNode, ProvenanceGraph
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class InvertedProvenanceError(RuntimeError):
    """Raised when a forget retraction's descendant walk returns fewer
    nodes than the node's recorded write-time fan-in, indicating the
    traversal direction was inverted (ancestors walked instead of
    descendants)."""


@dataclass
class MemoryNode:
    node_id: str
    parents: list[str] = field(default_factory=list)   # derivation ancestors
    children: list[str] = field(default_factory=list)  # derivation descendants
    tombstoned: bool = False


class ProvenanceGraph:
    def __init__(self) -> None:
        self.nodes: dict[str, MemoryNode] = {}

    def add(self, node: MemoryNode) -> None:
        self.nodes[node.node_id] = node

    def descendants(self, node_id: str) -> set[str]:
        seen: set[str] = set()
        stack = list(self.nodes[node_id].children)
        while stack:
            cur = stack.pop()
            if cur in seen:
                continue
            seen.add(cur)
            stack.extend(self.nodes[cur].children)
        return seen


def forget_with_direction_assert(graph: ProvenanceGraph, node_id: str) -> set[str]:
    """Retract a fact and all downstream derivations, asserting the
    traversal is reverse (descendant) closure, not ancestor closure."""
    node = graph.nodes[node_id]
    write_fan_in = len(node.children)

    # Direction-tagged reverse walk.
    invalidated = graph.descendants(node_id)

    # Structural invariant: a node with recorded children cannot have
    # zero descendants. Zero here means the walk ran the wrong direction.
    if write_fan_in > 0 and len(invalidated) < write_fan_in:
        raise InvertedProvenanceError(
            f"forget({node_id}) reported {len(invalidated)} descendants "
            f"but write-time fan-in is {write_fan_in}; traversal likely "
            f"walked ancestors instead of descendants"
        )

    # Residue check: no live edge may point into a tombstone after commit.
    for child_id in invalidated:
        child = graph.nodes[child_id]
        for parent_id in child.parents:
            if parent_id == node_id and not child.tombstoned:
                raise InvertedProvenanceError(
                    f"dangling derivation edge {child_id} -> {parent_id} "
                    f"survived retraction"
                )

    node.tombstoned = True
    for child_id in invalidated:
        graph.nodes[child_id].tombstoned = True
    return invalidated
