# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-deletes-a-memory-it-is-about-to-read-back-tombstone-free-forget-apis-and-the-read-after-forget-resurrection-window.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-deletes-a-memory-it-is-about-to-read-back-tombstone-free-forget-apis-and-the-read-after-forget-resurrection-window.warrant.json
# Markdown SHA-256:   781f0074db4e01e622420b54d5313df6b000095901eb95366d1e6187b1772485
# Code AST SHA-256:   a1e5f3158908fc1c6e51867677b97bd05ceb8e0b46c4ea382d9dc0f53d22e429
# Verified Classes:   ForgetResurrectionError, MemoryStore, ForgetBarrierAgent
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ForgetResurrectionError(RuntimeError):
    """Raised when an agent attempts to write a key it has forgotten in the
    same trace, or treats a stale post-forget read as delete failure."""


@dataclass
class MemoryStore:
    # primary holds live values and tombstones; read path may lag.
    primary: dict = field(default_factory=dict)
    tombstones: dict = field(default_factory=dict)
    read_replica_lag: dict = field(default_factory=dict)  # key -> stale value served by read path

    def forget(self, key: str) -> dict:
        self.tombstones[key] = True
        # simulate: read path still serves old value until compaction
        if key in self.primary:
            self.read_replica_lag[key] = self.primary.pop(key)
        return {"status": "ok", "deleted": True}

    def read(self, key: str) -> dict:
        if key in self.read_replica_lag:
            return {"status": "ok", "value": self.read_replica_lag[key], "stale_possible": True}
        if key in self.tombstones:
            return {"status": "not_found"}
        if key in self.primary:
            return {"status": "ok", "value": self.primary[key], "stale_possible": False}
        return {"status": "not_found"}

    def write(self, key: str, value) -> dict:
        self.primary[key] = value
        self.tombstones.pop(key, None)  # write clears tombstone -> resurrection
        self.read_replica_lag.pop(key, None)
        return {"status": "ok"}


class ForgetBarrierAgent:
    def __init__(self, store: MemoryStore):
        self.store = store
        self.forgotten_this_trace: set[str] = set()

    def forget_then_verify(self, key: str, max_waits: int = 3) -> str:
        ack = self.store.forget(key)
        if not ack.get("deleted"):
            # idempotent: already tombstoned, NOT "never existed"
            self.forgotten_this_trace.add(key)
            return "already_forgotten"
        self.forgotten_this_trace.add(key)
        for _ in range(max_waits):
            r = self.store.read(key)
            if r["status"] == "not_found":
                return "confirmed_gone"
            # stale read: wait, do NOT write
            time.sleep(0.01)
        return "pending_compaction"  # defer verification to later session

    def write(self, key: str, value) -> dict:
        if key in self.forgotten_this_trace:
            raise ForgetResurrectionError(
                f"refusing to write key {key!r}: forgotten in this trace. "
                f"A post-forget read returning a value is stale, not a delete failure. "
                f"Do not re-write forgotten content."
            )
        return self.store.write(key, value)


# --- trace that would resurrect without the barrier ---
store = MemoryStore(primary={"plan/budget": "40% cut scenario"})
agent = ForgetBarrierAgent(store)

agent.forget_then_verify("plan/budget")
# naive agent: read returned value -> "delete failed" -> write to repair
try:
    agent.write("plan/budget", "40% cut scenario")  # resurrection attempt
except ForgetResurrectionError as e:
    print(f"barrier held: {e}")

assert store.read("plan/budget")["status"] == "not_found" or \
       store.read("plan/budget").get("stale_possible"), "tombstone intact"
