# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-forget-a-memory-write-it-has-already-acknowledged-the-acknowledgment-without-provenance-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-forget-a-memory-write-it-has-already-acknowledged-the-acknowledgment-without-provenance-boundary.warrant.json
# Markdown SHA-256:   103698233361398b9bfcef0af7fe714b60136145a7869468f6c4a867d335498d
# Code AST SHA-256:   5b055f6286f75befe3e927a77128227cd4746a30bde81410f5e9174e84d43c6b
# Verified Classes:   ProvenanceState, UncommittedProvenanceError, MemoryHandle, MemoryClient
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass
from enum import Enum


class ProvenanceState(Enum):
    PENDING = "pending"
    COMMITTED = "committed"
    REJECTED = "rejected"


class UncommittedProvenanceError(RuntimeError):
    """Raised when an agent attempts to use an acknowledged-but-uncommitted
    memory handle as evidence (e.g., to justify a read or a dedup decision)."""


@dataclass(frozen=True)
class MemoryHandle:
    id: str
    state: ProvenanceState


class MemoryClient:
    """Minimal protocol surface: write returns a handle whose provenance
    state the caller MUST inspect before using the id as evidence."""

    def __init__(self) -> None:
        self._committed: dict[str, str] = {}
        self._pending: dict[str, str] = {}

    def write(self, key: str, content: str) -> MemoryHandle:
        mid = f"m_{len(self._pending) + len(self._committed):04d}"
        self._pending[mid] = content
        return MemoryHandle(id=mid, state=ProvenanceState.PENDING)

    def flush(self, handle: MemoryHandle) -> MemoryHandle:
        if handle.id not in self._pending:
            return MemoryHandle(id=handle.id, state=ProvenanceState.REJECTED)
        self._committed[handle.id] = self._pending.pop(handle.id)
        return MemoryHandle(id=handle.id, state=ProvenanceState.COMMITTED)

    def read(self, handle: MemoryHandle) -> str:
        if handle.state is not ProvenanceState.COMMITTED:
            raise UncommittedProvenanceError(
                f"handle {handle.id} has provenance={handle.state.value}; "
                f"a read-through here would return null and invite an overwrite"
            )
        return self._committed[handle.id]


def remember_and_confirm(client: MemoryClient, key: str, content: str) -> MemoryHandle:
    """Write, then force provenance to COMMITTED before returning a handle
    the caller is permitted to treat as evidence."""
    handle = client.write(key, content)
    if handle.state is ProvenanceState.PENDING:
        handle = client.flush(handle)
    if handle.state is not ProvenanceState.COMMITTED:
        raise UncommittedProvenanceError(
            f"write to {key!r} acknowledged as {handle.id} but provenance "
            f"resolved to {handle.state.value}; refusing to return a handle "
            f"that reads would treat as durable"
        )
    return handle


def safe_read_back(client: MemoryClient, handle: MemoryHandle) -> str:
    # Guarded read: the boundary is enforced here, not at the call site.
    if handle.state is ProvenanceState.PENDING:
        raise UncommittedProvenanceError(
            f"attempted read-back on pending handle {handle.id}; "
            f"flush before reading or the read is not evidence"
        )
    return client.read(handle)
