# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-tombstoned-memory-erasure-against-a-retention-scoped-read-cache-before-serving-a-resumed-task.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-tombstoned-memory-erasure-against-a-retention-scoped-read-cache-before-serving-a-resumed-task.warrant.json
# Markdown SHA-256:   5a962703702f69645da64b3d5961b046048d6fd13e09af8515637aabeff7f461
# Code AST SHA-256:   89f2796c2a8b841d24d6d9513bc888a40aa8b8252190658dbf8d88e1d11dffcc
# Verified Classes:   ErasureBoundaryViolation, Tombstone, ScopeState, ScopedMemory
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ErasureBoundaryViolation(RuntimeError):
    """Raised when a read would serve a record whose scope has advanced past
    the instance's checkpoint epoch, or whose key is tombstoned."""
    pass


@dataclass
class Tombstone:
    key: str
    erased_at: float
    reason: str


@dataclass
class ScopeState:
    epoch: int = 0
    tombstones: dict = field(default_factory=dict)  # key -> Tombstone

    def bump(self, key: str, reason: str) -> None:
        self.epoch += 1
        self.tombstones[key] = Tombstone(key=key, erased_at=time.time(), reason=reason)


class ScopedMemory:
    """Backend with per-scope monotonic erasure epochs and a read cache that
    MUST consult the epoch before serving a hit."""

    def __init__(self) -> None:
        self._store: dict = {}          # (scope, key) -> value
        self._scopes: dict = {}         # scope -> ScopeState
        self._cache: dict = {}          # (scope, key) -> value

    def _scope(self, scope: str) -> ScopeState:
        return self._scopes.setdefault(scope, ScopeState())

    def write(self, scope: str, key: str, value, sources: Optional[list] = None) -> None:
        self._store[(scope, key)] = {"value": value, "sources": sources or []}
        self._cache[(scope, key)] = value

    def forget(self, scope: str, key: str, reason: str = "rtbf") -> None:
        self._scope(scope).bump(key, reason)
        self._store.pop((scope, key), None)
        self._cache.pop((scope, key), None)
        # transitively erase derived writes that cite this key
        for (s, k), rec in list(self._store.items()):
            if any(src[1] == key and src[0] == scope for src in rec["sources"]):
                self.forget(s, k, reason=f"derived-from:{scope}/{key}")

    def read(self, scope: str, key: str, checkpoint_epoch: int) -> object:
        state = self._scope(scope)
        # INVARIANT 1: fail closed on any epoch advance past checkpoint
        if state.epoch > checkpoint_epoch:
            self._cache.pop((scope, key), None)
            raise ErasureBoundaryViolation(
                f"scope {scope!r} advanced epoch {checkpoint_epoch}->{state.epoch}; "
                f"cache untrusted, rebuild required before serving {key!r}"
            )
        # INVARIANT 2: tombstone on the read path, not just write path
        if key in state.tombstones:
            raise ErasureBoundaryViolation(
                f"key {key!r} in scope {scope!r} tombstoned: "
                f"{state.tombstones[key].reason}"
            )
        if (scope, key) in self._cache:
            return self._cache[(scope, key)]
        rec = self._store.get((scope, key))
        if rec is None:
            raise ErasureBoundaryViolation(f"absent record {scope}/{key}")
        self._cache[(scope, key)] = rec["value"]
        return rec["value"]


def resume_task(mem: ScopedMemory, scope: str, key: str, checkpoint_epoch: int):
    """Called on task resume; must not swallow ErasureBoundaryViolation."""
    try:
        return mem.read(scope, key, checkpoint_epoch)
    except ErasureBoundaryViolation:
        # correct behavior: rebuild from backend at current epoch, do not serve cache
        raise
