# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-retention-semantics-violation-when-an-agent-s-memory-tool-api-reports-success-but-the-write-is-silently-shadowed.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-retention-semantics-violation-when-an-agent-s-memory-tool-api-reports-success-but-the-write-is-silently-shadowed.warrant.json
# Markdown SHA-256:   d874cf2c26ffc375234a7c4ccf652fd86db91e2fdf630243f3514594af87fdbb
# Code AST SHA-256:   01eba83440f6b9751ea437fe7fb8528d36f04165255e345119b087c7d025b4ad
# Verified Classes:   RetentionShadowError, WriteReceipt, ReadResult, MemoryClient
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class RetentionShadowError(RuntimeError):
    """Raised when a memory write is acknowledged but a different record is authoritative on read."""


@dataclass(frozen=True)
class WriteReceipt:
    key: str
    record_id: str
    retention_class: str  # e.g. "ttl=300", "pinned", "scope=session"


@dataclass(frozen=True)
class ReadResult:
    key: str
    record_id: str
    value: object


class MemoryClient:
    """Thin wrapper over a read/write/forget memory tool API with retention semantics."""

    def __init__(self, transport, multi_record_per_key: bool):
        self._t = transport
        self._multi = multi_record_per_key
        self._receipts: dict[str, WriteReceipt] = {}

    def write(self, key: str, value: object, retention_class: str) -> WriteReceipt:
        resp = self._t.call("write", key=key, value=value, retention=retention_class)
        if resp.get("status") != "ok":
            raise RetentionShadowError(f"write rejected for {key}: {resp}")
        receipt = WriteReceipt(key=key, record_id=resp["record_id"], retention_class=retention_class)
        self._receipts[key] = receipt
        return receipt

    def read_verified(self, key: str) -> ReadResult:
        """Read a key and assert the served record is the one we last wrote.

        Only enforces identity when the store permits multiple live records per key;
        single-record stores resolve by recency and need no identity check.
        """
        res = self._t.call("read", key=key)
        result = ReadResult(key=key, record_id=res["record_id"], value=res["value"])
        if not self._multi:
            return result

        receipt = self._receipts.get(key)
        if receipt is None:
            return result  # never wrote this key; nothing to shadow

        if result.record_id != receipt.record_id:
            # Deterministic, reproducible: reads are stable but wrong. Not a race.
            raise RetentionShadowError(
                f"key {key!r} shadowed: wrote record {receipt.record_id} "
                f"(retention={receipt.retention_class}) but read serves {result.record_id}. "
                f"Write-ack is acceptance, not authority. Halt plan; do not retry."
            )
        return result

    def forget_and_confirm(self, key: str) -> None:
        """Forget is a record operation, not a key operation. Confirm the key is empty."""
        resp = self._t.call("forget", key=key)
        if resp.get("deleted", 0) > 0:
            # A positive count does not mean the authoritative record is gone.
            probe = self._t.call("read", key=key)
            if probe.get("record_id") is not None:
                raise RetentionShadowError(
                    f"forget({key!r}) reported deleted={resp['deleted']} "
                    f"but read still serves {probe['record_id']}. "
                    f"Tombstone or pinned record outranks the deletion."
                )
        self._receipts.pop(key, None)
