# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-serve-a-memory-read-when-provenance-tombstones-and-ttl-expiry-race-against-an-in-flight-erasure-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-serve-a-memory-read-when-provenance-tombstones-and-ttl-expiry-race-against-an-in-flight-erasure-warrant.warrant.json
# Markdown SHA-256:   9430697459a13c31650f41f97fbb1e8a03d97ff04e0b305cd22530889b01ebfe
# Code AST SHA-256:   2d7560b45514051212e638a57080953ca960b59899ba9fe5a48ea702f5586ede
# Verified Classes:   WarrantViolation, ProvenanceClosureUnverified, Ledger, PositiveCacheEntry, MemoryTool
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field

class WarrantViolation(RuntimeError):
    """Raised when a read would serve a record covered by a committed erasure warrant."""
    pass

class ProvenanceClosureUnverified(RuntimeError):
    """Raised when a read cannot prove the record is outside any warrant's closure."""
    pass

@dataclass
class Ledger:
    version: int = 0
    warrants: dict = field(default_factory=dict)  # key -> warrant_id

    def commit_warrant(self, key: str, warrant_id: str) -> None:
        self.warrants[key] = warrant_id
        self.version += 1  # global monotonic bump; invalidates all positive caches

@dataclass
class PositiveCacheEntry:
    ledger_version: int
    expiry: float

class MemoryTool:
    def __init__(self, ledger: Ledger):
        self.ledger = ledger
        self.store: dict = {}
        self.provenance: dict = {}  # key -> set of ancestor keys
        self.cache: dict = {}       # key -> PositiveCacheEntry

    def write(self, key: str, value: str, ttl: float, derived_from=()) -> None:
        # Provenance is mandatory: an unrooted record cannot be proven out of closure.
        self.store[key] = (value, time.monotonic() + ttl)
        self.provenance[key] = set(derived_from)
        self.cache[key] = PositiveCacheEntry(self.ledger.version, time.monotonic() + ttl)

    def _in_warrant_closure(self, key: str) -> bool:
        # Fail-closed: walk ancestors; an unresolvable edge means in-closure.
        stack, seen = [key], set()
        while stack:
            k = stack.pop()
            if k in seen:
                continue
            seen.add(k)
            if k in self.ledger.warrants:
                return True
            if k not in self.provenance:
                raise ProvenanceClosureUnverified(f"no provenance for {k!r}")
            stack.extend(self.provenance[k])
        return False

    def read(self, key: str) -> str:
        entry = self.cache.get(key)
        # Positive cache is only trusted if the ledger has not advanced.
        if entry is not None and entry.ledger_version == self.ledger.version:
            if self._in_warrant_closure(key):
                # Cache predates a warrant commit: must not serve.
                raise WarrantViolation(f"stale positive cache for {key!r} under warrant")
            if time.monotonic() < entry.expiry and key in self.store:
                return self.store[key][0]
        # Fall through: consult authoritative ledger.
        if self._in_warrant_closure(key):
            self.cache.pop(key, None)
            return "FORGOTTEN"
        if key not in self.store or time.monotonic() >= self.store[key][1]:
            return "FORGOTTEN"
        self.cache[key] = PositiveCacheEntry(self.ledger.version, self.store[key][1])
        return self.store[key][0]

    def forget(self, key: str, warrant_id: str) -> None:
        self.ledger.commit_warrant(key, warrant_id)
        # Version bump invalidates every positive cache entry at once.
        self.cache.clear()
