# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-when-a-forget-request-races-a-read-write-memory-tool-s-retention-reaper.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-when-a-forget-request-races-a-read-write-memory-tool-s-retention-reaper.warrant.json
# Markdown SHA-256:   3203b9d3a14531368732e97d8c065f6192ce634689528827828572fe9354d7b3
# Code AST SHA-256:   f14585c597d266e0579767708cbe030a460c22ca94bdfcd238db1956d394bf5e
# Verified Classes:   ProvenanceLaunderingError, Record, MemoryTool
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a write or read would violate the forget invariant."""


@dataclass
class Record:
    id: str
    content: str
    provenance: frozenset[str]
    commit_ts: float
    ttl: float


class MemoryTool:
    def __init__(self, reaper_interval: float = 10.0):
        self.records: dict[str, Record] = {}
        self.backward: dict[str, set[str]] = {}   # provenance_id -> derived ids
        self.pending_forget: set[str] = set()
        self.reaped: set[str] = set()
        self.reaper_interval = reaper_interval
        self._next = 0
        self._clock = time.monotonic

    def _new_id(self) -> str:
        self._next += 1
        return f"r{self._next}"

    def write(self, content: str, provenance: list[str], ttl: float) -> str:
        # Fence: reject any provenance intersecting pending-forget or reaped.
        tainted = set(provenance) & (self.pending_forget | self.reaped)
        if tainted:
            raise ProvenanceLaunderingError(
                f"write rejected: provenance {sorted(tainted)} is forgotten or pending forget"
            )
        rid = self._new_id()
        rec = Record(rid, content, frozenset(provenance), self._clock(), ttl)
        self.records[rid] = rec
        for p in provenance:
            self.backward.setdefault(p, set()).add(rid)
        return rid

    def read(self, query: str, provenance_of: Optional[str] = None) -> list[Record]:
        # Read-time predicate: fail closed on any record whose provenance
        # intersects the forget sets, even if its own TTL is valid.
        out = []
        for rec in self.records.values():
            if provenance_of is not None:
                if provenance_of not in rec.provenance:
                    continue
            if query not in rec.content:
                continue
            if rec.provenance & (self.pending_forget | self.reaped):
                raise ProvenanceLaunderingError(
                    f"read of {rec.id} would return laundered content: "
                    f"provenance {sorted(rec.provenance & (self.pending_forget | self.reaped))} forgotten"
                )
            if self._clock() - rec.commit_ts > rec.ttl:
                continue
            out.append(rec)
        return out

    def forget(self, source_id: str) -> None:
        self.pending_forget.add(source_id)
        # Eager transitive retraction of derivatives.
        for derived in list(self.backward.get(source_id, ())):
            self.records.pop(derived, None)
        self.backward.pop(source_id, None)

    def reap(self) -> None:
        now = self._clock()
        for rid, rec in list(self.records.items()):
            expired = now - rec.commit_ts > rec.ttl
            forgotten = bool(rec.provenance & self.pending_forget)
            if expired or forgotten:
                self.records.pop(rid, None)
        self.reaped |= self.pending_forget
        self.pending_forget.clear()


def audited_forget_cycle(tool: MemoryTool, source_id: str) -> None:
    """Forget a source and verify no derivative survives it."""
    tool.forget(source_id)
    tool.reap()
    # Backward closure check: no live record may reference the source.
    survivors = [
        rid for rid, rec in tool.records.items() if source_id in rec.provenance
    ]
    if survivors:
        raise ProvenanceLaunderingError(
            f"forget({source_id}) left {len(survivors)} laundered derivatives: {survivors}"
        )
    # Forward resolution check: every live provenance id must still resolve.
    for rid, rec in tool.records.items():
        dangling = rec.provenance & tool.reaped
        if dangling:
            raise ProvenanceLaunderingError(
                f"record {rid} carries orphaned provenance {sorted(dangling)}"
            )
