# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-honor-a-scoped-forget-when-the-target-memory-record-is-still-referenced-by-a-live-in-flight-derivation-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-honor-a-scoped-forget-when-the-target-memory-record-is-still-referenced-by-a-live-in-flight-derivation-chain.warrant.json
# Markdown SHA-256:   d6f26af70a50c7004db37cad4e52bf2808894bcb459582885dde0d3085e14c7e
# Code AST SHA-256:   ef2b9bfd1940caf36f393e919f01b83403ca77d5cf9e498cdaea7d813876941a
# Verified Classes:   UnretractableMemoryError, MemoryRecord, ProvenanceMemoryStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field


class UnretractableMemoryError(RuntimeError):
    """Raised when forget() is asked to retract a record that still has live
    derivation descendants and the caller did not authorize a cascade."""


@dataclass
class MemoryRecord:
    id: str
    scope: str
    content: str
    derived_from: list[str] = field(default_factory=list)
    forgotten: bool = False


SCOPE_RANK = {"session": 0, "tenant": 1, "global": 2}


class ProvenanceMemoryStore:
    def __init__(self) -> None:
        self._records: dict[str, MemoryRecord] = {}

    def write(self, rec: MemoryRecord) -> None:
        # Scope monotonicity: a derivation may not widen scope beyond its
        # narrowest source.
        for parent_id in rec.derived_from:
            parent = self._records.get(parent_id)
            if parent is None:
                raise UnretractableMemoryError(
                    f"derivation cites unknown source {parent_id!r}; "
                    "unprovenanced writes are not admissible"
                )
            if SCOPE_RANK[rec.scope] > SCOPE_RANK[parent.scope]:
                raise UnretractableMemoryError(
                    f"{rec.id!r} widens scope {parent.scope}->{rec.scope}; "
                    "requires re-attestation"
                )
        self._records[rec.id] = rec

    def _live_descendants(self, root_id: str) -> list[str]:
        # Transitive closure over derivation edges, excluding forgotten nodes.
        out, frontier = [], [root_id]
        while frontier:
            cur = frontier.pop()
            for rid, rec in self._records.items():
                if cur in rec.derived_from and not rec.forgotten:
                    out.append(rid)
                    frontier.append(rid)
        return out

    def forget(self, record_id: str, *, cascade: bool = False) -> None:
        rec = self._records.get(record_id)
        if rec is None or rec.forgotten:
            return
        descendants = self._live_descendants(record_id)
        if descendants and not cascade:
            # Fail closed: verification over the row would lie about the DAG.
            raise UnretractableMemoryError(
                f"cannot retract {record_id!r}: live derivations "
                f"{descendants} still depend on it; pass cascade=True to "
                "tombstone the closure atomically"
            )
        for rid in descendants:
            self._records[rid].forgotten = True
        rec.forgotten = True

    def verify_retracted(self, record_id: str) -> bool:
        # The real invariant: no live derivation reachable from the record.
        return not self._live_descendants(record_id) and self._records[record_id].forgotten


def sanitize_after_poisoning(store: ProvenanceMemoryStore, flagged_id: str) -> None:
    try:
        store.forget(flagged_id, cascade=False)
    except UnretractableMemoryError:
        # Escalate: cascade retraction + re-derivation from clean slate.
        store.forget(flagged_id, cascade=True)
    if not store.verify_retracted(flagged_id):
        raise UnretractableMemoryError(
            f"post-retraction verification failed for {flagged_id!r}"
        )
