# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scoped-forget-memory-tools-from-leaving-resurrectable-residue-across-agent-cold-starts.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scoped-forget-memory-tools-from-leaving-resurrectable-residue-across-agent-cold-starts.warrant.json
# Markdown SHA-256:   ccfa0f75e936715446a1ee44e71449f12afc1d4487fc9e1588d0d6d0ecce3187
# Code AST SHA-256:   3a814f275dcf43883743c0f445443438c0800527edf1feeb896d0535e2ea4afe
# Verified Classes:   ResurrectionViolation, DerivedRecord, MemoryTier
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from typing import Dict, Set, Optional


class ResurrectionViolation(RuntimeError):
    """Raised when a forget-acknowledged scope yields retrievable residue
    via a derived tier (distillation, replica, or cache)."""
    pass


@dataclass
class DerivedRecord:
    record_id: str
    scope: str
    content: str
    provenance: Set[str]          # raw record ids this was derived from
    commit_seq: int               # sequence at which it became visible


@dataclass
class MemoryTier:
    raw: Dict[str, str] = field(default_factory=dict)          # record_id -> content
    tombstones: Dict[str, int] = field(default_factory=dict)  # scope -> forget seq
    derived: Dict[str, DerivedRecord] = field(default_factory=dict)
    cache: Dict[str, str] = field(default_factory=dict)       # (scope,query) -> content
    scope_generation: Dict[str, int] = field(default_factory=dict)
    applied_watermark: Dict[str, int] = field(default_factory=dict)  # replica watermark per scope
    seq: int = 0

    def next_seq(self) -> int:
        self.seq += 1
        return self.seq

    def write_raw(self, record_id: str, scope: str, content: str) -> None:
        self.raw[record_id] = content
        self._scope_of[record_id] = scope

    _scope_of: Dict[str, str] = field(default_factory=dict)

    def forget(self, scope: str, keys: list[str]) -> None:
        seq = self.next_seq()
        self.tombstones[scope] = seq
        self.scope_generation[scope] = self.scope_generation.get(scope, 0) + 1
        # propagate: invalidate derived records whose provenance touches the scope
        for rid, rec in list(self.derived.items()):
            if rec.scope == scope or any(
                self._scope_of.get(src) == scope for src in rec.provenance
            ):
                del self.derived[rid]
        # invalidate cache by scope generation (key includes gen)
        for k in [k for k in self.cache if k.startswith(f"{scope}:")]:
            del self.cache[k]

    def read(self, scope: str, query: str, replica_watermark: Optional[int] = None) -> Optional[str]:
        tomb = self.tombstones.get(scope, -1)
        wm = replica_watermark if replica_watermark is not None else self.applied_watermark.get(scope, self.seq)
        if wm < tomb:
            raise ResurrectionViolation(
                f"stale read refused: replica watermark {wm} < tombstone {tomb} for scope {scope}"
            )
        gen = self.scope_generation.get(scope, 0)
        key = f"{scope}:{gen}:{query}"
        if key in self.cache:
            return self.cache[key]
        # semantic tier lookup: any derived record in scope
        for rec in self.derived.values():
            if rec.scope == scope and rec.commit_seq >= tomb and query in rec.content:
                self.cache[key] = rec.content
                return rec.content
        return None

    def distill(self, scope: str, summary: str, sources: list[str]) -> None:
        tomb = self.tombstones.get(scope, -1)
        # barrier: distillation must not snapshot-then-commit across a forget
        for src in sources:
            if self._scope_of.get(src) == scope and self.tombstones.get(scope, -1) > -1:
                # source is tombstoned; refuse to derive from it
                raise ResurrectionViolation(
                    f"distillation source {src} is tombstoned in scope {scope}"
                )
        seq = self.next_seq()
        rec = DerivedRecord(
            record_id=f"sem-{seq}", scope=scope, content=summary,
            provenance=set(sources), commit_seq=seq,
        )
        self.derived[rec.record_id] = rec


def verify_non_resurrection(tier: MemoryTier, scope: str, forbidden: str) -> None:
    """Post-forget verification must query the retrieval path the agent will use."""
    hit = tier.read(scope, forbidden)
    if hit is not None and forbidden in hit:
        raise ResurrectionViolation(
            f"forgotten content '{forbidden}' resurrected in scope {scope}"
        )
