# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-forget-a-provenance-tagged-memory-whose-write-quorum-was-never-acknowledged.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-forget-a-provenance-tagged-memory-whose-write-quorum-was-never-acknowledged.warrant.json
# Markdown SHA-256:   4593a995b8873cbc0e3e4d09c6c207c40e9612a4a972499d79bcf62f704d1823
# Code AST SHA-256:   c85b091da065f81c0e7885553f79ba6b3aac5b688705a680428ddd39c43f4092
# Verified Classes:   UncommittedForgetError, WriteHandle, MemoryStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UncommittedForgetError(RuntimeError):
    """Raised when forget_memory targets a provenance tag with no durable commit token."""
    pass


@dataclass
class WriteHandle:
    provenance: str
    commit_token: Optional[str]  # None => episodic append not yet ordered


class MemoryStore:
    def __init__(self) -> None:
        self._committed: dict[str, str] = {}   # provenance -> commit_token
        self._pending: dict[str, WriteHandle] = {}

    def write_memory(self, provenance: str, durable: bool) -> WriteHandle:
        handle = WriteHandle(provenance, commit_token=f"tok:{provenance}" if durable else None)
        if durable:
            self._committed[provenance] = handle.commit_token  # type: ignore[assignment]
        else:
            self._pending[provenance] = handle
        return handle

    def forget_memory(self, provenance: str, commit_token: Optional[str]) -> str:
        # Invariant: a forget must name a token that the store has durably committed.
        if commit_token is None or self._committed.get(provenance) != commit_token:
            raise UncommittedForgetError(
                f"refusing to forget {provenance!r}: no durable commit token; "
                f"issue retract(handle) instead and let the write pipeline apply it on flush"
            )
        del self._committed[provenance]
        return "forgotten"

    def retract(self, handle: WriteHandle) -> str:
        # Cancel a pending write before it flushes; ordered after the write by construction.
        if handle.provenance in self._pending:
            del self._pending[handle.provenance]
            return "retracted_pending"
        return self.forget_memory(handle.provenance, handle.commit_token)


# Trigger: optimistic write, then immediate forget in the same reasoning loop.
store = MemoryStore()
h = store.write_memory("span_42", durable=False)
try:
    store.forget_memory("span_42", commit_token=None)
except UncommittedForgetError as e:
    print("blocked:", e)
    print("safe path:", store.retract(h))
