# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-provenance-inversion-when-a-forget-operation-silently-orphans-a-derived-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-provenance-inversion-when-a-forget-operation-silently-orphans-a-derived-memory.warrant.json
# Markdown SHA-256:   a266625f392b61c3e2b8f5456f39372846172ec02e355e795397a83464fdcba8
# Code AST SHA-256:   61c6abaa7aa01c874742da92e3089001d1b54204fb0bf4531fa8f8b82b8a94d9
# Verified Classes:   ProvenanceOrphanedError, Fact, MemoryStore
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceOrphanedError(RuntimeError):
    """Raised when a derived fact's provenance chain terminates at a forgotten node."""
    pass


@dataclass
class Fact:
    id: str
    content: str
    derived_from: tuple[str, ...] = ()
    orphaned: bool = False


class MemoryStore:
    """Minimal read/write/forget store with non-cascading forget (the failure mode)."""

    def __init__(self) -> None:
        self._facts: dict[str, Fact] = {}

    def write(self, fact: Fact) -> None:
        self._facts[fact.id] = fact

    def read(self, fact_id: str) -> Optional[Fact]:
        return self._facts.get(fact_id)

    def forget(self, fact_id: str) -> dict:
        # Non-cascading: removes node, leaves descendants with dangling edges.
        removed = self._facts.pop(fact_id, None)
        return {"status": "ok" if removed else "not_found", "removed": 1 if removed else 0}


def resolve_grounding(store: MemoryStore, fact_id: str, max_depth: int = 8) -> Fact:
    """Walk derived_from to a grounded terminal. Raise if any hop is missing or orphaned."""
    seen: set[str] = set()
    current_id = fact_id
    for _ in range(max_depth):
        if current_id in seen:
            raise ProvenanceOrphanedError(f"cycle detected at {current_id}")
        seen.add(current_id)
        fact = store.read(current_id)
        if fact is None:
            raise ProvenanceOrphanedError(
                f"provenance chain from {fact_id} terminates at forgotten node {current_id}"
            )
        if fact.orphaned:
            raise ProvenanceOrphanedError(f"fact {current_id} is marked orphaned")
        if not fact.derived_from:
            return fact  # grounded terminal
        current_id = fact.derived_from[0]
    raise ProvenanceOrphanedError(f"provenance chain from {fact_id} exceeds max_depth={max_depth}")


def act_on_derived_fact(store: MemoryStore, fact_id: str) -> str:
    try:
        grounded = resolve_grounding(store, fact_id)
    except ProvenanceOrphanedError as exc:
        # Demote to provisional; refuse the gated action.
        raise ProvenanceOrphanedError(
            f"refusing action on {fact_id}: {exc}. Re-derive from a live source."
        ) from exc
    return grounded.content


# Reproduction of the observed trace.
store = MemoryStore()
store.write(Fact("F1", "staging DB at 10.0.4.12"))
store.write(Fact("F2", "staging accepts writes from runner", derived_from=("F1",)))
store.write(Fact("F3", "safe to run migration against staging", derived_from=("F2",)))

store.forget("F1")  # returns {"status": "ok", "removed": 1} — no cascade, no orphan flag

# Lazy reader (the bug): trusts immediate parent.
assert store.read("F3").derived_from == ("F2",)  # looks grounded

# Eager reader (the guardrail): walks to terminal, detects the orphan.
try:
    act_on_derived_fact(store, "F3")
except ProvenanceOrphanedError as exc:
    print(f"detected: {exc}")
