# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resurrect-forgotten-memory-when-a-scoped-retention-write-races-a-ttl-expiry-sweep.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-forgotten-memory-when-a-scoped-retention-write-races-a-ttl-expiry-sweep.warrant.json
# Markdown SHA-256:   c1cf275a1ebb062fba9e825fc3733b4468222188fde0ea1efda277f710905dab
# Code AST SHA-256:   a0b192b7d4bb30948071fee75f9196685fab8b249c1ef2596adf24570aab01f8
# Verified Classes:   RetentionClosureViolation, MemoryRecord, ScopedMemoryStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class RetentionClosureViolation(RuntimeError):
    """Raised when a derived memory write would resurrect out-of-retention content."""


@dataclass
class MemoryRecord:
    id: str
    scope: str
    ttl_seconds: int
    derived_from: list[str] = field(default_factory=list)
    forgotten_at: Optional[float] = None


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

    def put(self, rec: MemoryRecord) -> None:
        self._records[rec.id] = rec

    def _closure(self, root_ids: list[str]) -> set[str]:
        seen: set[str] = set()
        stack = list(root_ids)
        while stack:
            rid = stack.pop()
            if rid in seen:
                continue
            seen.add(rid)
            rec = self._records.get(rid)
            if rec is not None:
                stack.extend(rec.derived_from)
        return seen

    def write_derived(
        self,
        new_id: str,
        scope: str,
        declared_ttl: int,
        derived_from: list[str],
    ) -> MemoryRecord:
        ancestors = self._closure(derived_from)
        dirty = [
            aid
            for aid in ancestors
            if (a := self._records.get(aid)) is not None
            and (a.forgotten_at is not None or a.scope != scope)
        ]
        if dirty:
            raise RetentionClosureViolation(
                f"write {new_id} in scope {scope} would resurrect out-of-retention "
                f"ancestors: {sorted(dirty)}"
            )
        bounded_ttl = min(
            [declared_ttl] + [self._records[a].ttl_seconds for a in ancestors if a in self._records]
        )
        rec = MemoryRecord(
            id=new_id,
            scope=scope,
            ttl_seconds=bounded_ttl,
            derived_from=list(derived_from),
        )
        self._records[new_id] = rec
        return rec


def demo() -> None:
    store = ScopedMemoryStore()
    store.put(MemoryRecord(id="ep_7731", scope="user:8841", ttl_seconds=3600))
    store.put(
        MemoryRecord(
            id="sem_5502",
            scope="user:8841",
            ttl_seconds=2_592_000,
            derived_from=["ep_7731"],
        )
    )
    store._records["ep_7731"].forgotten_at = 1_700_000_000.0
    try:
        store.write_derived(
            new_id="sem_6119",
            scope="user:8841",
            declared_ttl=2_592_000,
            derived_from=["sem_5502"],
        )
    except RetentionClosureViolation as exc:
        print(f"blocked: {exc}")


if __name__ == "__main__":
    demo()
