# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-forget-tool-deletions-from-resurrecting-through-stale-derived-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-forget-tool-deletions-from-resurrecting-through-stale-derived-memory.warrant.json
# Markdown SHA-256:   7dc7d796578fefe9316029d2d8272338710c918960fbcf9281bcdc4640b9c549
# Code AST SHA-256:   b91301644a5490fb4b07fbfd3d0da120e3dcadf7a57c3f07a948d6ea2d92835e
# Verified Classes:   TombstonedLineageError, ForgetClosureError, State, Artifact, MemoryStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Set, List


class TombstonedLineageError(RuntimeError):
    """Raised when retrieval touches an artifact whose lineage reaches a tombstone."""
    pass


class ForgetClosureError(RuntimeError):
    """Raised when forget cannot prove cascade closure over all derived artifacts."""
    pass


class State(Enum):
    LIVE = "live"
    DELETED = "deleted"
    ORPHANED = "orphaned"


@dataclass
class Artifact:
    id: str
    derived_from: List[str]
    state: State = State.LIVE
    generation: int = 0


class MemoryStore:
    def __init__(self) -> None:
        self.artifacts: Dict[str, Artifact] = {}
        self.reverse: Dict[str, Set[str]] = {}   # primary id -> derived ids
        self.tombstones: Dict[str, float] = {}   # id -> deletion timestamp
        self.cache_generation: Dict[str, int] = {}

    def write(self, art: Artifact) -> None:
        # Lineage must be recorded BEFORE the artifact is retrievable.
        for src in art.derived_from:
            self.reverse.setdefault(src, set()).add(art.id)
        self.artifacts[art.id] = art

    def lookup_state(self, aid: str) -> State:
        # Tombstone is a definite state, never None.
        if aid in self.tombstones:
            return State.DELETED
        art = self.artifacts.get(aid)
        return art.state if art else State.ORPHANED

    def forget(self, aid: str) -> str:
        if aid not in self.artifacts and aid not in self.tombstones:
            raise ForgetClosureError(f"cannot forget unknown id {aid}")
        self.tombstones[aid] = time.time()
        self.artifacts.pop(aid, None)

        # Fail closed if the reverse index cannot enumerate dependents.
        if aid not in self.reverse:
            raise ForgetClosureError(
                f"reverse index missing for {aid}; cascade closure unprovable"
            )

        unclosed: List[str] = []
        for dep in self.reverse[aid]:
            art = self.artifacts.get(dep)
            if art is None:
                continue
            if any(self.lookup_state(s) == State.DELETED for s in art.derived_from):
                art.state = State.ORPHANED
                unclosed.append(dep)

        # Invalidate dependent caches by generation, not TTL.
        for key in list(self.cache_generation):
            self.cache_generation[key] += 1

        if unclosed:
            return f"PARTIAL: {len(unclosed)} artifacts lineage-blocked"
        return "CLOSED"

    def retrieve(self, aid: str) -> Artifact:
        art = self.artifacts.get(aid)
        if art is None:
            raise TombstonedLineageError(f"{aid} absent or tombstoned")
        for src in art.derived_from:
            if self.lookup_state(src) == State.DELETED:
                # Never downgrade to "unverified"; fail closed.
                raise TombstonedLineageError(
                    f"{aid} derives from tombstoned {src}"
                )
        return art
