# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-mid-task-when-a-memory-tool-s-retention-policy-silently-evicts-the-write-it-just-acknowledged.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-mid-task-when-a-memory-tool-s-retention-policy-silently-evicts-the-write-it-just-acknowledged.warrant.json
# Markdown SHA-256:   d76d6f1526b0c43239702f6004f8f9939468b801b7bc4e4a9dc6ffd0f7927c2b
# Code AST SHA-256:   6a4f652c6f1302dedb20277e1313d04ccd1e51c505abb943d43119b08762dae1
# Verified Classes:   RetentionHorizonViolation, EvictedKeyMisread, RetentionClass, MemoryTool
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RetentionHorizonViolation(RuntimeError):
    """Raised when a write's retention TTL cannot outlive the agent's remaining task lease."""


class EvictedKeyMisread(RuntimeError):
    """Raised when a read treats an evicted-but-acknowledged key as never-written."""


@dataclass
class RetentionClass:
    name: str
    ttl_s: int


EPHEMERAL = RetentionClass("ephemeral", 600)
SESSION = RetentionClass("session", 3600)
DURABLE = RetentionClass("durable", 86400)


class MemoryTool:
    def __init__(self):
        self._store = {}  # key -> (value, expires_at, class_name)

    def write(self, key, value, retention: RetentionClass, now=None):
        now = now if now is not None else time.time()
        # Ack is issued immediately; durability is a lease, not a commit.
        self._store[key] = (value, now + retention.ttl_s, retention.name)
        return {"status": "stored", "id": f"m_{key}", "ttl_s": retention.ttl_s,
                "retention_class": retention.name}

    def read(self, key, now=None):
        now = now if now is not None else time.time()
        rec = self._store.get(key)
        if rec is None:
            return {"status": "not_found"}
        value, expires_at, class_name = rec
        if now >= expires_at:
            # Tombstone: distinguishes evicted from never-existed.
            return {"status": "evicted", "evicted_at": expires_at,
                    "retention_class": class_name}
        return {"status": "found", "value": value}


def guarded_write(memory: MemoryTool, key: str, value, retention: RetentionClass,
                  remaining_task_lease_s: int, rederive_fallback_registered: bool):
    """Invariant: a write may only be trusted for the retention class it inspected.

    If the retention TTL cannot outlive the remaining task lease, the write is
    rejected unless the caller has registered an explicit re-derivation fallback
    for this key. This moves the failure from silent mid-task eviction to the
    causal decision point.
    """
    if retention.ttl_s < remaining_task_lease_s and not rederive_fallback_registered:
        raise RetentionHorizonViolation(
            f"write({key!r}) retention={retention.name} ttl={retention.ttl_s}s "
            f"< remaining_task_lease={remaining_task_lease_s}s and no re-derivation "
            f"fallback registered; escalate retention class or register fallback"
        )
    ack = memory.write(key, value, retention)
    # Propagate retention metadata into the agent's working set, not just the id.
    return ack


def guarded_read(memory: MemoryTool, key: str, expect_written: bool):
    """Invariant: an evicted key must not be treated as never-written."""
    resp = memory.read(key)
    if resp["status"] == "not_found" and expect_written:
        raise EvictedKeyMisread(
            f"read({key!r}) returned not_found but the agent recorded a prior ack; "
            f"store lacks tombstone or the write was never committed"
        )
    if resp["status"] == "evicted":
        raise EvictedKeyMisread(
            f"read({key!r}) hit evicted record from class "
            f"{resp['retention_class']!r} at {resp['evicted_at']}; "
            f"re-derive from source rather than assume-absent"
        )
    return resp


if __name__ == "__main__":
    mem = MemoryTool()
    t0 = 1_000_000.0
    # Agent writes at t0 with a 40-step task whose lease is 1200s.
    guarded_write(mem, "depgraph", {"nodes": 42}, EPHEMERAL,
                  remaining_task_lease_s=1200, rederive_fallback_registered=False)
    # ^ raises RetentionHorizonViolation before the lying ack is ever issued.
