# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resurrect-a-forgotten-memory-through-a-stale-derived-index-after-a-scoped-retention-deletion.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-a-forgotten-memory-through-a-stale-derived-index-after-a-scoped-retention-deletion.warrant.json
# Markdown SHA-256:   e690567c7352c8d071dd9c2f0066e51ea674535d6e36b8d92fc8ac1762031faf
# Code AST SHA-256:   1a589639201c35cad498d2378bdc6fad19a9c557d0687c21bf326c34272eb52a
# Verified Classes:   ResurrectionViolation, MemoryChunk, ScopedMemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ResurrectionViolation(RuntimeError):
    """Raised when a retrieved memory traces to a forgotten or expired scope."""


@dataclass
class MemoryChunk:
    chunk_id: str
    scope: str
    text: str
    derived_from: set[str] = field(default_factory=set)
    expired: bool = False


class ScopedMemoryStore:
    def __init__(self) -> None:
        self._chunks: dict[str, MemoryChunk] = {}
        self._tombstoned_scopes: set[str] = set()
        self._quarantine: set[str] = set()

    def write(self, chunk: MemoryChunk) -> None:
        self._chunks[chunk.chunk_id] = chunk

    def forget(self, scope: str) -> None:
        # Tombstone the scope and quarantine it permanently.
        self._tombstoned_scopes.add(scope)
        self._quarantine.add(scope)

    def _provenance_is_live(self, chunk: MemoryChunk, seen: set[str]) -> bool:
        if chunk.chunk_id in seen:
            return True  # cycle guard: already validated
        seen.add(chunk.chunk_id)
        if chunk.scope in self._quarantine:
            return False
        for ancestor_id in chunk.derived_from:
            ancestor = self._chunks.get(ancestor_id)
            if ancestor is None:
                # dangling pointer to a deleted primary: treat as dead ancestry
                return False
            if not self._provenance_is_live(ancestor, seen):
                return False
        return True

    def read(self, scope: str, include_expired: bool = False) -> list[MemoryChunk]:
        if scope == "*" and not include_expired:
            # broad reads must not silently lower the retention floor
            raise ResurrectionViolation(
                "wildcard read requires include_expired=True; "
                "lowering the floor un-forgets decayed memory"
            )
        results: list[MemoryChunk] = []
        for chunk in self._chunks.values():
            if scope != "*" and chunk.scope != scope:
                continue
            if chunk.expired and not include_expired:
                continue
            if not self._provenance_is_live(chunk, set()):
                raise ResurrectionViolation(
                    f"chunk {chunk.chunk_id} in scope {chunk.scope} "
                    f"traces to a quarantined or tombstoned ancestor"
                )
            results.append(chunk)
        return results


def safe_forget_and_verify(store: ScopedMemoryStore, scope: str) -> None:
    store.forget(scope)
    # Post-condition: no live chunk may trace back into the forgotten scope.
    for chunk in list(store._chunks.values()):
        if chunk.scope == scope:
            continue
        if not store._provenance_is_live(chunk, set()):
            raise ResurrectionViolation(
                f"forget({scope!r}) left retrievable descendant {chunk.chunk_id}"
            )
