# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-memory-write-acknowledgment-as-a-retention-guarantee-and-when-must-it-re-verify-before-acting.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-memory-write-acknowledgment-as-a-retention-guarantee-and-when-must-it-re-verify-before-acting.warrant.json
# Markdown SHA-256:   5ffc1220db1b1436ff31268aad6887ea623bc749501258b6dca1554147585dc3
# Code AST SHA-256:   e7957c3ce08bd5f014a156de88f09158f97099ac6a8d373436d024ca3deffac8
# Verified Classes:   MemoryContractViolation, Visibility, MemoryRecord, MemoryClient
# 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 Optional


class MemoryContractViolation(RuntimeError):
    """Raised when an agent treats an acknowledgment as a retention guarantee
    that the memory tool's contract does not actually provide."""


class Visibility(Enum):
    VISIBLE = "visible"
    PENDING = "pending"      # write accepted, not yet readable
    ABSENT = "absent"        # genuinely not stored


@dataclass
class MemoryRecord:
    key: str
    value: str
    retention: str           # "session" | "persistent" | "ttl:<seconds>"
    visible: Visibility = Visibility.PENDING
    tombstoned_paths: set[str] = field(default_factory=set)
    live_paths: set[str] = field(default_factory=lambda: {"exact", "semantic", "summary"})


class MemoryClient:
    """Toy model of a memory tool with batched writes and path-scoped forget."""

    def __init__(self) -> None:
        self._store: dict[str, MemoryRecord] = {}
        self._flush_pending: dict[str, MemoryRecord] = {}

    def write(self, key: str, value: str, retention: str) -> str:
        rec = MemoryRecord(key=key, value=value, retention=retention)
        # Acknowledged immediately, but only visible after flush.
        self._flush_pending[key] = rec
        return rec.key

    def flush(self) -> None:
        for key, rec in self._flush_pending.items():
            rec.visible = Visibility.VISIBLE
            self._store[key] = rec
        self._flush_pending.clear()

    def read(self, key: str) -> tuple[Visibility, Optional[str]]:
        if key in self._flush_pending:
            return Visibility.PENDING, None
        rec = self._store.get(key)
        if rec is None:
            return Visibility.ABSENT, None
        return rec.visible, rec.value

    def forget(self, key: str, paths: list[str]) -> None:
        rec = self._store.get(key)
        if rec is None:
            return
        unknown = set(paths) - rec.live_paths
        if unknown:
            raise MemoryContractViolation(
                f"forget named paths the store does not track: {sorted(unknown)}"
            )
        rec.tombstoned_paths.update(paths)
        # BUG (by design, to model the failure): exact path cleared, but
        # semantic/summary paths remain live if not named.

    def distill(self, key: str, source_path: str) -> str:
        rec = self._store.get(key)
        if rec is None:
            return ""
        if source_path not in rec.tombstoned_paths:
            # Re-enters distillation even though the agent "forgot" the key
            # via a different path.
            return rec.value
        return ""


def write_then_read_safely(
    client: MemoryClient, key: str, value: str, retention: str
) -> str:
    """Correct pattern: a pending read is NOT evidence the write was lost.
    Never issue a corrective overwrite on PENDING."""
    client.write(key, value, retention)
    vis, stored = client.read(key)
    if vis is Visibility.PENDING:
        # Hold the value in working context; do not re-write.
        return value
    if vis is Visibility.ABSENT:
        # Only here is a corrective write justified.
        client.write(key, value, retention)
        return value
    if stored != value:
        raise MemoryContractViolation(
            f"read-after-write returned divergent value for {key!r}: "
            f"expected {value!r}, got {stored!r}"
        )
    return stored


def forget_and_distill_safely(
    client: MemoryClient, key: str, distill_paths: list[str]
) -> str:
    """A forget is a retention guarantee ONLY across the paths it enumerates.
    Refuse to distill from any path the forget did not cover."""
    client.forget(key, paths=distill_paths)
    rec = client._store.get(key)
    if rec is not None:
        uncovered = rec.live_paths - rec.tombstoned_paths
        if uncovered & set(distill_paths):
            raise MemoryContractViolation(
                f"forget did not cover paths {sorted(uncovered)} but distillation "
                f"reads from {distill_paths}; refusing to distill"
            )
    return client.distill(key, source_path=distill_paths[0])


def run() -> None:
    client = MemoryClient()
    # Correct: pending read does not trigger overwrite.
    assert write_then_read_safely(client, "db_region", "eu-west-1", "session") == "eu-west-1"

    # Incorrect forget scope: names only 'exact', but distillation reads 'semantic'.
    client.flush()
    client.write("user_pii", "alice@example.com", "persistent")
    client.flush()
    try:
        forget_and_distill_safely(client, "user_pii", distill_paths=["semantic"])
    except MemoryContractViolation as exc:
        print(f"blocked: {exc}")


if __name__ == "__main__":
    run()
