# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-a-poisoned-memory-but-retain-its-descendants-provenance-edge-orphaning-in-dependency-tracked-forget-operations.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-a-poisoned-memory-but-retain-its-descendants-provenance-edge-orphaning-in-dependency-tracked-forget-operations.warrant.json
# Markdown SHA-256:   9e758ee4b2482947cf8c0567a5ba979239018fe4ef815a485b0bcb0ae37778f1
# Code AST SHA-256:   3db0b113d642d238cf88a82a3dcf4ef8ae5d8b27e3c5d38bb646d8c438bef7b2
# Verified Classes:   ProvenanceClosureError, Memory
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set, List


class ProvenanceClosureError(RuntimeError):
    """Raised when a forget operation would leave a retrievable node with a tainted justification chain."""
    pass


@dataclass
class Memory:
    id: str
    parents: List[str] = field(default_factory=list)
    contribution_spans: Dict[str, tuple] = field(default_factory=dict)  # parent_id -> byte range
    tainted_by: Set[str] = field(default_factory=set)
    quarantined: bool = False


def forget(store: Dict[str, Memory], target: str, cascade: bool = True) -> Set[str]:
    """
    Forget `target`. Returns the set of node ids whose justification chain touched
    the target and were therefore quarantined or deleted.

    Invariant enforced: after return, no retrievable node has `target` in its
    provenance closure unless it was explicitly re-derived (not handled here).
    """
    if target not in store:
        raise ProvenanceClosureError(f"forget target {target!r} not present in store")

    # Reverse reachability over derived_from edges.
    closure: Set[str] = set()
    frontier = [target]
    while frontier:
        cur = frontier.pop()
        for mid, mem in store.items():
            if cur in mem.parents and mid not in closure:
                closure.add(mid)
                frontier.append(mid)

    affected: Set[str] = set()
    for mid in closure:
        mem = store[mid]
        # Multi-parent node: retainable ONLY if the forgotten parent's
        # contribution is attributable and excisable.
        if len(mem.parents) > 1:
            if target not in mem.contribution_spans:
                # No span data -> cannot excise poison -> quarantine.
                mem.quarantined = True
                mem.tainted_by.add(target)
                affected.add(mid)
            else:
                # Span known: caller must rewrite content; mark tainted until then.
                mem.tainted_by.add(target)
                affected.add(mid)
        else:
            # Single-parent descendant: delete outright under cascade.
            if not cascade:
                raise ProvenanceClosureError(
                    f"single-parent descendant {mid!r} of {target!r} requires cascade=True"
                )
            affected.add(mid)

    # Drop the target and any single-parent descendants we chose to delete.
    to_delete = {target} | {
        mid for mid in affected
        if len(store[mid].parents) == 1
    }
    for mid in to_delete:
        store.pop(mid, None)

    # Post-condition: no live node may carry the forgotten id in tainted_by
    # without being quarantined.
    for mid, mem in store.items():
        if target in mem.tainted_by and not mem.quarantined:
            raise ProvenanceClosureError(
                f"post-forget violation: {mid!r} tainted by {target!r} but still retrievable"
            )

    return affected
