# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-resurrect-a-tombstoned-memory-provenance-weighted-ttl-expiry-versus-retrieval-time-resurrection-in-agent-memory-tool-a.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-resurrect-a-tombstoned-memory-provenance-weighted-ttl-expiry-versus-retrieval-time-resurrection-in-agent-memory-tool-a.warrant.json
# Markdown SHA-256:   4bfc015d7dde0093cab925d4e5b13c625c7ee20e4f91b1a992ee6c6a80e980b9
# Code AST SHA-256:   337b3dcdaa8f6de42d14825c75bb321012e94345c65e172fb19f54420f64654f
# Verified Classes:   TombstoneResurrectionError, Disposition, Provenance, Record, Tombstone, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class TombstoneResurrectionError(RuntimeError):
    """Raised when a read would reconstruct a fact through a live tombstone."""


class Disposition(Enum):
    LIVE = "live"
    DELETED = "deleted"
    ABSENT = "absent"
    UNRECONSTRUCTABLE = "unreconstructable"


@dataclass
class Provenance:
    source: str
    rank: int  # higher = stronger; user_statement > tool > summary


@dataclass
class Record:
    key: str
    value: str
    provenance: Provenance
    expires_at: float


@dataclass
class Tombstone:
    key: str
    reason: str
    deleted_at: float
    deletion_provenance: Provenance
    expires_at: float  # MUST be >= reconstruction horizon


@dataclass
class MemoryStore:
    live: dict[str, Record] = field(default_factory=dict)
    tombstones: dict[str, Tombstone] = field(default_factory=dict)
    reconstruction_horizon_s: float = 90 * 86400.0

    def forget(self, key: str, reason: str, prov: Provenance) -> None:
        rec = self.live.pop(key, None)
        # Tombstone TTL is derived from the horizon, never a fixed default.
        self.tombstones[key] = Tombstone(
            key=key,
            reason=reason,
            deleted_at=time.time(),
            deletion_provenance=prov,
            expires_at=time.time() + self.reconstruction_horizon_s,
        )
        if rec is not None:
            rec.expires_at = 0.0  # invalidate live index entry

    def _live_tombstone(self, key: str) -> Optional[Tombstone]:
        ts = self.tombstones.get(key)
        if ts is not None and time.time() < ts.expires_at:
            return ts
        return None

    def read(self, key: str, *, allow_reconstruct: bool = True) -> tuple[Disposition, Optional[str]]:
        ts = self._live_tombstone(key)
        if ts is not None:
            if allow_reconstruct:
                # Reconstruction through a live tombstone is the exact bug.
                raise TombstoneResurrectionError(
                    f"read({key!r}) would reconstruct through live tombstone "
                    f"(reason={ts.reason!r}, deleted_at={ts.deleted_at:.0f})"
                )
            return Disposition.DELETED, None
        rec = self.live.get(key)
        if rec is not None and time.time() < rec.expires_at:
            return Disposition.LIVE, rec.value
        if self.tombstones.get(key) is not None:
            # Tombstone expired but within horizon: block semantic fallback.
            return Disposition.UNRECONSTRUCTABLE, None
        return Disposition.ABSENT, None

    def reassert(self, key: str, value: str, prov: Provenance) -> None:
        ts = self._live_tombstone(key)
        if ts is not None:
            if prov.rank <= ts.deletion_provenance.rank:
                raise TombstoneResurrectionError(
                    f"reassert({key!r}) provenance rank {prov.rank} does not "
                    f"supersede deletion rank {ts.deletion_provenance.rank}"
                )
            self.tombstones.pop(key, None)  # audited supersede, not silent
        self.live[key] = Record(key, value, prov, time.time() + 30 * 86400.0)


def demo() -> None:
    store = MemoryStore()
    store.live["user.home_city"] = Record(
        "user.home_city", "Rotterdam", Provenance("tool:geo_lookup@v3", 1),
        time.time() + 30 * 86400.0,
    )
    store.forget("user.home_city", "user_retraction_sensitive", Provenance("user", 3))
    # Correct behavior: a reconstructing read must fail loudly.
    try:
        store.read("user.home_city", allow_reconstruct=True)
    except TombstoneResurrectionError as e:
        print(f"guardrail fired: {e}")
    disp, _ = store.read("user.home_city", allow_reconstruct=False)
    assert disp is Disposition.DELETED
    # Weaker provenance cannot resurrect.
    try:
        store.reassert("user.home_city", "Rotterdam", Provenance("summary", 0))
    except TombstoneResurrectionError as e:
        print(f"supersede refused: {e}")


if __name__ == "__main__":
    demo()
