# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-observe-phantom-memory-after-a-scoped-namespace-delete-tombstone-ordering-and-the-ttl-resurrection-window-in-agent-memory-tool-ap.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-observe-phantom-memory-after-a-scoped-namespace-delete-tombstone-ordering-and-the-ttl-resurrection-window-in-agent-memory-tool-ap.warrant.json
# Markdown SHA-256:   37248836e93cdf233ccfcf7d0bb1cb10750bad47bd5a5189377a90be800d8f4f
# Code AST SHA-256:   99714d06e3afb066036898c5096e95488c265e0f8d68fd45f1ad37d535bf0f82
# Verified Classes:   StaleEpochWrite, PropagationPending, ForgetState, NamespaceEpoch, MemoryStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Optional


class StaleEpochWrite(RuntimeError):
    """Raised when a write targets a namespace whose tombstone is still propagating
    and the write does not carry the post-forget epoch."""
    pass


class PropagationPending(RuntimeError):
    """Raised when a read or cold-start resolution is attempted against a namespace
    whose forget has not yet been confirmed complete at all replicas."""
    pass


class ForgetState(Enum):
    LIVE = "live"
    PENDING = "pending"
    COMPLETE = "complete"


@dataclass
class NamespaceEpoch:
    epoch: int = 0
    forget_state: ForgetState = ForgetState.LIVE


@dataclass
class MemoryStore:
    # namespace -> {key: (value, expires_at, epoch_at_write)}
    data: Dict[str, Dict[str, tuple]] = field(default_factory=dict)
    epochs: Dict[str, NamespaceEpoch] = field(default_factory=dict)

    def _epoch(self, ns: str) -> NamespaceEpoch:
        return self.epochs.setdefault(ns, NamespaceEpoch())

    def forget(self, ns: str) -> int:
        """Issue a tombstone. Returns the new epoch. Propagation is async."""
        e = self._epoch(ns)
        e.epoch += 1
        e.forget_state = ForgetState.PENDING
        # Tombstone predicate: delete entries written at epoch < new epoch.
        self.data[ns] = {
            k: v for k, v in self.data.get(ns, {}).items() if v[2] >= e.epoch
        }
        return e.epoch

    def confirm_propagation(self, ns: str) -> None:
        self._epoch(ns).forget_state = ForgetState.COMPLETE

    def write(self, ns: str, key: str, value: str, ttl: int, epoch: int) -> None:
        e = self._epoch(ns)
        if e.forget_state is ForgetState.PENDING and epoch < e.epoch:
            # Fail closed: a write that races a pending tombstone is rejected
            # unless it carries the post-forget epoch.
            raise StaleEpochWrite(
                f"write to {ns}/{key} carries epoch {epoch} but namespace "
                f"is at epoch {e.epoch} with tombstone pending"
            )
        self.data.setdefault(ns, {})[key] = (value, ttl, epoch)

    def read(self, ns: str) -> Dict[str, str]:
        e = self._epoch(ns)
        if e.forget_state is ForgetState.PENDING:
            raise PropagationPending(
                f"read of {ns} refused: forget epoch {e.epoch} not yet propagated"
            )
        return {k: v[0] for k, v in self.data.get(ns, {}).items()}


def resume_task(store: MemoryStore, ns: str, prior_epoch: int) -> Dict[str, str]:
    """Cold-start resume. Refuses to infer 'empty namespace' while a forget is
    in flight, and refuses to write with a pre-forget epoch."""
    e = store._epoch(ns)
    if e.forget_state is ForgetState.PENDING:
        raise PropagationPending(
            f"cannot resume {ns}: prior_epoch={prior_epoch} but tombstone at "
            f"epoch {e.epoch} is still propagating; wait for confirmation"
        )
    if prior_epoch < e.epoch:
        raise StaleEpochWrite(
            f"resume of {ns} with epoch {prior_epoch} < current {e.epoch}: "
            f"namespace was forgotten since this instance last wrote"
        )
    return store.read(ns)
