# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-garbage-collection-pass-is-about-to-sever-a-provenance-chain-it-still-depends-on.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-garbage-collection-pass-is-about-to-sever-a-provenance-chain-it-still-depends-on.warrant.json
# Markdown SHA-256:   17160948bd8cfbc2891b54bb15e9b5e291068d3b6e966085a3fd12a4b733f58d
# Code AST SHA-256:   ff475119cb948f2b1ae44b396e675b27cb1f7a43b9acc9774268f926882f09cf
# Verified Classes:   ProvenanceSeveranceError, Node
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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

class ProvenanceSeveranceError(RuntimeError):
    """Raised when a GC pass would collect a node still cited by a survivor."""
    pass

@dataclass
class Node:
    node_id: str
    salience: float
    derived_from: Set[str] = field(default_factory=set)
    provenance_status: str = "backed"  # "backed" | "orphaned" | "root"

def plan_gc(nodes: Dict[str, Node], threshold: float, pin_factor: float = 1.0) -> Set[str]:
    # Phase 1: mark by salience, but raise retention floor by dependent salience.
    evict = {nid for nid, n in nodes.items() if n.salience < threshold}
    for nid, n in nodes.items():
        if nid in evict:
            continue
        for support in n.derived_from:
            if support in evict:
                support_node = nodes[support]
                # Pin: dependent salience protects its evidence.
                support_node.salience = max(
                    support_node.salience, n.salience * pin_factor
                )
                if support_node.salience >= threshold:
                    evict.discard(support)
    return evict

def sweep(nodes: Dict[str, Node], evict: Set[str]) -> List[str]:
    survivors = set(nodes) - evict
    # Phase 2: reachability re-check at sweep time (edges may have changed).
    for d in survivors:
        severed = nodes[d].derived_from & evict
        if severed:
            raise ProvenanceSeveranceError(
                f"node {d} (salience={nodes[d].salience}) still cites "
                f"evicted evidence {sorted(severed)}; refusing to orphan "
                f"a retained belief. Pin or demote {d} before sweeping."
            )
    removed = []
    for nid in evict:
        del nodes[nid]
        removed.append(nid)
    return removed

def run_gc(nodes: Dict[str, Node], threshold: float) -> List[str]:
    evict = plan_gc(nodes, threshold)
    return sweep(nodes, evict)
