# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-a-forgetting-cascade-when-provenance-tracked-deletion-outruns-the-semantic-layer-it-depends-on.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-a-forgetting-cascade-when-provenance-tracked-deletion-outruns-the-semantic-layer-it-depends-on.warrant.json
# Markdown SHA-256:   32197a2ad2b1af63408ab2e035167d3ed24baeb359cba1e5312058801191b55f
# Code AST SHA-256:   c26c5c614a8e6bdec1b9131b2801aa1fbae0cea41a6541136d7cedbc4b3311bc
# Verified Classes:   UnresolvedForgettingCascade, MemoryRecord, ProvenanceStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class UnresolvedForgettingCascade(RuntimeError):
    """Raised when a forget cascade leaves semantic records with partial or dangling support."""
    pass


@dataclass
class MemoryRecord:
    record_id: str
    kind: str                      # "episodic" | "semantic"
    support: list[str] = field(default_factory=list)
    tombstoned: bool = False


class ProvenanceStore:
    def __init__(self, records: dict[str, MemoryRecord]):
        self.records = records

    def _forward_edges(self, node_id: str) -> list[str]:
        return [r.record_id for r in self.records.values()
                if node_id in r.support and not r.tombstoned]

    def forget(self, source_id: str) -> set[str]:
        """Transitive forget with fixed-point re-walk and partial-support halt."""
        if source_id not in self.records:
            raise UnresolvedForgettingCascade(f"unknown source {source_id}")

        deleted: set[str] = set()
        frontier = [source_id]
        self.records[source_id].tombstoned = True
        deleted.add(source_id)

        # Fixed point: follow edges from every newly tombstoned node,
        # not just the original target.
        while frontier:
            node = frontier.pop()
            for child in self._forward_edges(node):
                if child in deleted:
                    continue
                self.records[child].tombstoned = True
                deleted.add(child)
                frontier.append(child)

        # Re-derive support closure of all survivors.
        unresolved: list[str] = []
        for rec in self.records.values():
            if rec.tombstoned or rec.kind != "semantic":
                continue
            live = [s for s in rec.support
                    if s in self.records and not self.records[s].tombstoned]
            dead = [s for s in rec.support if s not in live]
            if dead and live:
                # Partial support: graph cannot decide over- vs under-forget.
                unresolved.append(rec.record_id)
            elif dead and not live:
                # Fully unsupported: must be tombstoned, cascade was incomplete.
                rec.tombstoned = True
                deleted.add(rec.record_id)

        if unresolved:
            raise UnresolvedForgettingCascade(
                f"forget({source_id}) halted: partially-supported survivors "
                f"require re-distillation or explicit policy decision: {unresolved}"
            )
        return deleted
