# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scoped-eviction-memory-tools-from-resurrecting-forgotten-facts-through-provenance-tracked-recall.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scoped-eviction-memory-tools-from-resurrecting-forgotten-facts-through-provenance-tracked-recall.warrant.json
# Markdown SHA-256:   d16a159d48298b9b82a035a0e2f2820d6b8b90acefb072fac8883db7966d560f
# Code AST SHA-256:   47af4f689152d3f4f43d97b17bbe6af0770234abb1b2ddb488817537d4a97e9d
# Verified Classes:   EvictionInvariantViolation, MemoryRecord, ScopedMemory
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class EvictionInvariantViolation(RuntimeError):
    """Raised when a recall would surface a fact whose provenance
    transitively derives from an evicted record."""
    pass


@dataclass
class MemoryRecord:
    scope: str
    key: str
    content: str
    derived_from: list[str] = field(default_factory=list)


class ScopedMemory:
    def __init__(self) -> None:
        self._records: dict[str, MemoryRecord] = {}
        # Eviction ledger must outlive every derivative that references a key.
        self._evicted: set[str] = set()

    def _rid(self, scope: str, key: str) -> str:
        return f"{scope}/{key}"

    def write(self, rec: MemoryRecord) -> None:
        self._records[self._rid(rec.scope, rec.key)] = rec

    def forget(self, scope: str, key: str) -> dict:
        rid = self._rid(scope, key)
        # Taint-and-redact: do NOT cascade-delete cross-scope derivatives.
        self._evicted.add(rid)
        self._records.pop(rid, None)
        return {"evicted": 1, "scope": scope, "ledger_size": len(self._evicted)}

    def _ancestors_revoked(self, rec: MemoryRecord, seen: Optional[set[str]] = None) -> bool:
        seen = seen or set()
        for anc in rec.derived_from:
            if anc in self._evicted:
                return True
            if anc in seen:
                continue
            seen.add(anc)
            parent = self._records.get(anc)
            if parent is not None and self._ancestors_revoked(parent, seen):
                return True
        return False

    def recall(self, query_scope: str, predicate) -> list[dict]:
        hits: list[dict] = []
        for rid, rec in self._records.items():
            if not predicate(rec):
                continue
            if self._ancestors_revoked(rec):
                # Poisoned recall: withhold fact-bearing fields entirely.
                hits.append({
                    "id": rid,
                    "revoked": True,
                    "reason": f"ancestor evicted: {sorted(set(rec.derived_from) & self._evicted)}",
                })
                continue
            hits.append({"id": rid, "revoked": False, "content": rec.content,
                         "provenance": rec.derived_from})
        return hits

    def assert_recall_clean(self, query_scope: str, predicate) -> None:
        for hit in self.recall(query_scope, predicate):
            if hit.get("revoked"):
                raise EvictionInvariantViolation(
                    f"recall in scope {query_scope!r} would surface a fact "
                    f"derived from evicted record(s) {hit['reason']}. "
                    f"Agent must drop this hit, not reason around it."
                )
