# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-ttl-eviction-and-namespace-scoped-memory-tools-disagree-about-the-meaning-of-now-the-monotonic-vs-wall-clock-spl.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-ttl-eviction-and-namespace-scoped-memory-tools-disagree-about-the-meaning-of-now-the-monotonic-vs-wall-clock-spl.warrant.json
# Markdown SHA-256:   530cfdfb1db6c088615baac5cf6b3875557e411e68b6e5af2d446766cd072e2a
# Code AST SHA-256:   ea4b9ac172dc1cef2a61c5a35cc5f5c92a343cf13bd8c74a78cf592a57600d20
# Verified Classes:   PhantomRecallError, MemoryRecord, VersionedMemory
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class PhantomRecallError(RuntimeError):
    """Raised when a read returns a value whose version or expiry cannot be
    reconciled with the authoritative clock, indicating a phantom-recall window."""


@dataclass(frozen=True)
class MemoryRecord:
    value: str
    version: int
    write_time_mono: float
    ttl_seconds: float
    namespace: str
    key: str

    def is_expired(self, now_mono: float) -> bool:
        # Absolute TTL against a single monotonic clock. Never compare to wall time.
        return (now_mono - self.write_time_mono) > self.ttl_seconds


class VersionedMemory:
    """Minimal memory tool with version-stamped reads and tombstone-writes.

    forget() is intentionally NOT used for coordination; invalidate() writes a
    tombstone with a version bump so invalidation propagates through replication.
    """

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

    def write(self, namespace: str, key: str, value: str, ttl: float) -> int:
        prev = self._store.get((namespace, key))
        version = (prev.version + 1) if prev else 1
        self._store[(namespace, key)] = MemoryRecord(
            value=value,
            version=version,
            write_time_mono=self._clock(),
            ttl_seconds=ttl,
            namespace=namespace,
            key=key,
        )
        return version

    def read(self, namespace: str, key: str, expected_version: Optional[int] = None) -> MemoryRecord:
        rec = self._store.get((namespace, key))
        if rec is None:
            raise PhantomRecallError(f"miss: ({namespace!r}, {key!r}) absent")
        if rec.is_expired(self._clock()):
            # Do not silently return a value the sweeper has logically expired.
            raise PhantomRecallError(
                f"expired: ({namespace!r}, {key!r}) v{rec.version} "
                f"age={self._clock() - rec.write_time_mono:.2f}s ttl={rec.ttl_seconds}s"
            )
        if expected_version is not None and rec.version != expected_version:
            # Version mismatch collapses the phantom-recall window to a hard signal.
            raise PhantomRecallError(
                f"version drift: ({namespace!r}, {key!r}) expected v{expected_version} got v{rec.version}"
            )
        return rec

    def invalidate(self, namespace: str, key: str) -> int:
        """Tombstone-write. Use instead of forget() for cross-agent coordination."""
        return self.write(namespace, key, value="__TOMBSTONE__", ttl=0.001)

    def forget(self, namespace: str, key: str) -> None:
        """Space reclamation only. NOT a coordination barrier across replicas."""
        self._store.pop((namespace, key), None)


def execute_step(mem: VersionedMemory, task_id: str, expected_plan_version: int) -> str:
    try:
        plan = mem.read("plan", f"task/{task_id}/plan", expected_version=expected_plan_version)
    except PhantomRecallError as exc:
        # Refuse to proceed on unverifiable state; re-derive instead of silently continuing.
        raise PhantomRecallError(
            f"refusing to execute step for task {task_id}: {exc}"
        ) from exc
    return plan.value
