# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-ttl-expired-memory-handle-after-retrieval-augmented-forgetting-has-already-reclaimed-the-underlying-slot.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-ttl-expired-memory-handle-after-retrieval-augmented-forgetting-has-already-reclaimed-the-underlying-slot.warrant.json
# Markdown SHA-256:   07c8857bf60b46dc26a9113e08a7636955733a78edb5f87556eaeb022c169f32
# Code AST SHA-256:   9c0c089a6927bd76874319c624e72d11e4574f4696412f293d8e07783bedc4f8
# Verified Classes:   StaleHandleError, TTLExpiredError, Record, Handle, MemoryStore
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass, field
from typing import Any, Optional


class StaleHandleError(RuntimeError):
    """Raised when a memory handle's generation no longer matches the slot.

    This is the *safe* failure: the slot was reclaimed and reused, and the
    read is rejected rather than returning another writer's record.
    """


class TTLExpiredError(RuntimeError):
    """Raised when a record's own TTL has elapsed."""


@dataclass
class Record:
    key: str
    value: Any
    writer_id: str
    generation: int
    created_at: float
    ttl: float

    def expired(self, now: float) -> bool:
        return now >= self.created_at + self.ttl


@dataclass
class Handle:
    key: str
    generation: int
    issued_at: float
    declared_ttl: float


@dataclass
class MemoryStore:
    """Toy store with RAF-style out-of-order reclamation and slot reuse.

    `_slots` maps key -> current Record. RAF may reclaim a slot before its
    TTL by overwriting it; the generation counter is what makes reuse
    observable to handle-holders.
    """

    _slots: dict[str, Record] = field(default_factory=dict)
    _gen: dict[str, int] = field(default_factory=dict)

    def write(self, key: str, value: Any, writer_id: str, ttl: float) -> Handle:
        gen = self._gen.get(key, 0) + 1
        self._gen[key] = gen
        now = time.time()
        self._slots[key] = Record(
            key=key, value=value, writer_id=writer_id,
            generation=gen, created_at=now, ttl=ttl,
        )
        return Handle(key=key, generation=gen, issued_at=now, declared_ttl=ttl)

    def read(self, handle: Handle) -> Any:
        rec = self._slots.get(handle.key)
        if rec is None:
            raise TTLExpiredError(f"slot {handle.key!r} reclaimed and not reused")
        if rec.generation != handle.generation:
            # The slot was reclaimed (possibly before declared TTL by RAF)
            # and reused by another writer. Refuse to return the impostor.
            raise StaleHandleError(
                f"handle {handle.key!r}:g{handle.generation} is stale; "
                f"slot now holds g{rec.generation} written by {rec.writer_id!r}"
            )
        if rec.expired(time.time()):
            raise TTLExpiredError(f"record {handle.key!r} expired at ttl={rec.ttl}s")
        return rec.value

    def read_by_key(self, key: str, expected_writer: Optional[str] = None) -> Any:
        """Resume-safe read: re-resolves through the index, never trusts a handle."""
        rec = self._slots.get(key)
        if rec is None or rec.expired(time.time()):
            raise TTLExpiredError(f"key {key!r} absent or expired")
        if expected_writer is not None and rec.writer_id != expected_writer:
            raise StaleHandleError(
                f"key {key!r} now owned by {rec.writer_id!r}, expected {expected_writer!r}"
            )
        return rec.value

    def raf_reclaim(self, key: str, new_value: Any, new_writer: str, new_ttl: float) -> None:
        """Simulate retrieval-augmented forgetting: reclaim before declared TTL."""
        self.write(key, new_value, writer_id=new_writer, ttl=new_ttl)


def resume_and_verify(store: MemoryStore, restored: Handle, original_writer: str) -> Any:
    """Called on checkpoint resume. Must not trust `restored` blindly."""
    try:
        return store.read(restored)
    except StaleHandleError:
        # Slot was recycled during suspension. Re-resolve by key under
        # writer-identity constraint; if the original writer's record is
        # gone, surface it rather than accepting the impostor.
        try:
            return store.read_by_key(restored.key, expected_writer=original_writer)
        except (StaleHandleError, TTLExpiredError) as exc:
            raise StaleHandleError(
                f"on resume, {restored.key!r} no longer holds {original_writer!r}'s "
                f"record; original assumption is unrecoverable: {exc}"
            ) from exc


# --- demonstration of the failure and the guardrail ---
if __name__ == "__main__":
    store = MemoryStore()
    h = store.write("plan/step3/assumption", "vendor X SLA = 4h",
                    writer_id="planner-P", ttl=72 * 3600)

    # Suspension window: another agent's RAF pass reclaims the slot early
    # and reuses it. (In production this is a separate process; simulated here.)
    store.raf_reclaim("plan/step3/assumption", "vendor X SLA = 12h (revised)",
                      new_writer="summarizer-Q", new_ttl=24 * 3600)

    # Unguarded handle read would silently return Q's record. Guarded read:
    try:
        store.read(h)
    except StaleHandleError as exc:
        print(f"guarded read rejected impostor: {exc}")

    # Resume path: re-resolve by key under writer constraint.
    try:
        resume_and_verify(store, h, original_writer="planner-P")
    except StaleHandleError as exc:
        print(f"resume correctly refused to adopt Q's value: {exc}")
