# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-ttl-expired-memory-writes-that-silently-resurrect-stale-state-across-scoped-tool-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-ttl-expired-memory-writes-that-silently-resurrect-stale-state-across-scoped-tool-calls.warrant.json
# Markdown SHA-256:   39a21190d3e13587def466552f4ad08a0a257723763193c98790c892005c0efe
# Code AST SHA-256:   12359c164cbd5ce99492b383bdf9d36c4c0ddae897c1a83bc4da5bfb2d588e4d
# Verified Classes:   ResurrectionWindowError, Tombstone, AuditEntry, ScopedMemoryClient
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class ResurrectionWindowError(RuntimeError):
    """Raised when a write would land in the TTL resurrection window."""
    pass


@dataclass
class Tombstone:
    key: str
    expiry_time: float
    commit_time: float  # when the tombstone was durably committed


@dataclass
class AuditEntry:
    key: str
    op: str  # "write" | "expire" | "purge"
    timestamp: float
    version: int


class ScopedMemoryClient:
    def __init__(self, epoch_period_s: float = 300.0):
        self.epoch_period_s = epoch_period_s
        self._tombstones: dict[str, Tombstone] = {}
        self._audit: list[AuditEntry] = []

    def record_tombstone(self, key: str, expiry_time: float, commit_time: float) -> None:
        self._tombstones[key] = Tombstone(key, expiry_time, commit_time)
        self._audit.append(AuditEntry(key, "expire", commit_time, version=-1))

    def safe_write(self, key: str, value: str, ttl_s: float, now: Optional[float] = None) -> int:
        """Write with resurrection-window precondition. Returns version token."""
        now = time.time() if now is None else now
        tomb = self._tombstones.get(key)
        if tomb is not None:
            # Window: write timestamp falls in [commit_time, commit_time + epoch_period)
            # and before compaction has purged the tombstone.
            window_end = tomb.commit_time + self.epoch_period_s
            if tomb.commit_time <= now < window_end:
                raise ResurrectionWindowError(
                    f"write to key={key!r} at t={now:.1f} lands in resurrection "
                    f"window [{tomb.commit_time:.1f}, {window_end:.1f}); "
                    f"fork to a fresh key or defer past t={window_end:.1f}"
                )
            # Past the window: tombstone is eligible for purge; clear it.
            del self._tombstones[key]
        version = len(self._audit) + 1
        self._audit.append(AuditEntry(key, "write", now, version))
        return version

    def audit_trail(self, key: str) -> list[AuditEntry]:
        return [e for e in self._audit if e.key == key]


def write_plan_with_fork_fallback(client: ScopedMemoryClient, key: str, value: str,
                                  ttl_s: float, now: float) -> str:
    """Attempt write; on resurrection-window error, fork to a versioned key."""
    try:
        client.safe_write(key, value, ttl_s, now=now)
        return key
    except ResurrectionWindowError:
        forked = f"{key}.{int(now)}"
        client.safe_write(forked, value, ttl_s, now=now)
        return forked


# Reproduce the observed failure trace
if __name__ == "__main__":
    c = ScopedMemoryClient(epoch_period_s=300.0)
    # t=0: write v41 with ttl=60
    c.safe_write("scratch.plan", "v41", ttl_s=60, now=0.0)
    # t=60: expiry; tombstone committed at t=65 (async propagation)
    c.record_tombstone("scratch.plan", expiry_time=60.0, commit_time=65.0)
    # t=71: agent attempts re-write -> must raise, not silently succeed
    try:
        c.safe_write("scratch.plan", "v42", ttl_s=600, now=71.0)
    except ResurrectionWindowError as e:
        # Fork instead
        forked_key = write_plan_with_fork_fallback(c, "scratch.plan", "v42", 600.0, now=71.0)
        assert forked_key != "scratch.plan"
        assert forked_key.startswith("scratch.plan.")
    # t=400: window has closed; original key is writable again
    c.safe_write("scratch.plan", "v43", ttl_s=600, now=400.0)
