# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-a-consolidated-fact-the-moment-its-episodic-source-is-evicted.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-a-consolidated-fact-the-moment-its-episodic-source-is-evicted.warrant.json
# Markdown SHA-256:   bae1982836ee4a50b32157c6697e3f6f0e9fd3bb3daffff173cad62be2e81fdb
# Code AST SHA-256:   a89772ea2313791e4700a200b9ba3275b380722916f2bae854ad54dc12ed70f9
# Verified Classes:   OrphanedAbstractionError, EpisodicEntry, SemanticNode
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class OrphanedAbstractionError(RuntimeError):
    """Raised when a semantic node would lose all provenance to eviction."""
    pass


@dataclass
class EpisodicEntry:
    id: str
    timestamp: int
    content: str


@dataclass
class SemanticNode:
    id: str
    summary: str
    confidence: float
    derived_at: int
    support_epoch: int
    decay_rate: float
    provenance: list[str] = field(default_factory=list)
    provenance_tombstones: list[str] = field(default_factory=list)


def is_orphaned(node: SemanticNode, live_episodic_ids: set[str], now: int,
                ttl: int) -> bool:
    live_sources = [p for p in node.provenance if p in live_episodic_ids]
    stale = (now - node.support_epoch) > ttl
    return stale and not live_sources


def safe_evict(entry_id: str, live_episodic_ids: set[str],
               semantic_index: dict[str, list[str]],
               nodes: dict[str, SemanticNode], now: int,
               ttl: int, consolidation_interval: int) -> None:
    """Evict an episodic entry only if no live semantic node depends solely on it."""
    dependents = semantic_index.get(entry_id, [])
    for node_id in dependents:
        node = nodes[node_id]
        other_live = [p for p in node.provenance
                      if p != entry_id and p in live_episodic_ids]
        if not other_live:
            # Sole source: force consolidation before eviction.
            if (now - node.derived_at) >= consolidation_interval:
                raise OrphanedAbstractionError(
                    f"Cannot evict {entry_id}: sole provenance for {node_id} "
                    f"(derived_at={node.derived_at}, support_epoch="
                    f"{node.support_epoch}). Consolidate first."
                )
            # If consolidation is due but not yet run, block eviction.
            raise OrphanedAbstractionError(
                f"Eviction of {entry_id} would orphan {node_id} before next "
                f"consolidation window; defer eviction."
            )
        # Add tombstone so the node still records that a source existed.
        node.provenance_tombstones.append(entry_id)
        node.provenance.remove(entry_id)


def effective_confidence(node: SemanticNode, now: int) -> float:
    """Confidence must decay on the semantic tier, independent of episodic tier."""
    age = now - node.support_epoch
    return max(0.0, node.confidence * (1.0 - node.decay_rate * age))
