# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-revokes-a-provenance-ancestor-mid-replay-ttl-scoped-memory-stores-and-the-dangling-derivation-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-revokes-a-provenance-ancestor-mid-replay-ttl-scoped-memory-stores-and-the-dangling-derivation-invariant.warrant.json
# Markdown SHA-256:   1205f7a585414f63f483fb290553b53693920f26e836d83401b67f9faa4e1344
# Code AST SHA-256:   206329d4880683df5eebbe7685cf5ca9e47d80c19e1266269c52679699552dc7
# Verified Classes:   DanglingDerivationError, Record, ProvenanceStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DanglingDerivationError(RuntimeError):
    """Raised when a write would create a record whose ancestry includes a revoked node."""


@dataclass
class Record:
    id: str
    derived_from: list[str] = field(default_factory=list)
    revoked: bool = False
    ttl: Optional[int] = None


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

    def write(self, rec: Record) -> None:
        # Invariant: full transitive ancestry must be live and unrevoked.
        for parent_id in self._transitive_ancestors(rec.derived_from):
            parent = self._records.get(parent_id)
            if parent is None:
                raise DanglingDerivationError(
                    f"write {rec.id!r}: ancestor {parent_id!r} is missing "
                    f"(revoked or expired; cannot distinguish without audit log)"
                )
            if parent.revoked:
                raise DanglingDerivationError(
                    f"write {rec.id!r}: ancestor {parent_id!r} is revoked; "
                    f"derivation would launder taint"
                )
        self._records[rec.id] = rec

    def forget(self, rec_id: str, *, cascade: bool) -> list[str]:
        target = self._records.get(rec_id)
        if target is None:
            return []
        live_descendants = self._live_descendants(rec_id)
        if live_descendants and not cascade:
            # Referential-integrity gate: refuse node-only revocation.
            raise DanglingDerivationError(
                f"forget {rec_id!r}: live descendants {live_descendants!r} block "
                f"non-cascading revocation; pass cascade=True or expire via TTL"
            )
        target.revoked = True
        for d in live_descendants:
            self._records[d].revoked = True
        return [rec_id, *live_descendants]

    def read(self, rec_id: str) -> Record:
        rec = self._records.get(rec_id)
        if rec is None or rec.revoked:
            raise DanglingDerivationError(f"read {rec_id!r}: revoked or absent")
        for anc in self._transitive_ancestors(rec.derived_from):
            if self._records.get(anc, Record(anc, revoked=True)).revoked:
                raise DanglingDerivationError(
                    f"read {rec_id!r}: tainted by revoked ancestor {anc!r}"
                )
        return rec

    def _transitive_ancestors(self, roots: list[str]) -> set[str]:
        seen: set[str] = set()
        stack = list(roots)
        while stack:
            cur = stack.pop()
            if cur in seen:
                continue
            seen.add(cur)
            parent = self._records.get(cur)
            if parent is not None:
                stack.extend(parent.derived_from)
        return seen

    def _live_descendants(self, rec_id: str) -> list[str]:
        out = []
        for rid, rec in self._records.items():
            if rid == rec_id or rec.revoked:
                continue
            if rec_id in self._transitive_ancestors(rec.derived_from):
                out.append(rid)
        return out
