# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-ttl-expiry-against-deletion-provenance-when-a-forget-call-races-a-concurrent-re-derivation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-ttl-expiry-against-deletion-provenance-when-a-forget-call-races-a-concurrent-re-derivation.warrant.json
# Markdown SHA-256:   72147f15ac7baf270aa26d9d9d0600c3ffa6268cd67ca11fde1611683bf51b26
# Code AST SHA-256:   c3a6b9a3fd687805b74b9c1717bee32de8cce874ad530e74b15caaa81815827b
# Verified Classes:   ResurrectionViolation, Tombstone, MemoryStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ResurrectionViolation(RuntimeError):
    """Raised when a write would re-materialize a forgotten scope."""
    pass


@dataclass
class Tombstone:
    warrant_id: str
    canonical_scope: str  # content/entity hash, not key string


@dataclass
class MemoryStore:
    records: dict = field(default_factory=dict)
    tombstones: dict = field(default_factory=dict)  # canonical_scope -> Tombstone

    def _canonicalize(self, key: str, value: str) -> str:
        # Scope binds to entity, not key string, so renames cannot evade.
        return f"scope::{value.strip().lower()}"

    def forget(self, key: str, value: str, warrant_id: str) -> Tombstone:
        scope = self._canonicalize(key, value)
        ts = Tombstone(warrant_id=warrant_id, canonical_scope=scope)
        self.tombstones[scope] = ts
        self.records.pop(key, None)
        return ts

    def read(self, key: str) -> dict:
        if key in self.records:
            return {"status": "LIVE", "value": self.records[key]}
        # Absence must be classified; bare None is forbidden.
        return {"status": "ABSENT_UNCLASSIFIED"}

    def write(self, key: str, value: str, ttl: int, provenance: str) -> dict:
        scope = self._canonicalize(key, value)
        if scope in self.tombstones:
            ts = self.tombstones[scope]
            raise ResurrectionViolation(
                f"write to key={key!r} re-derives scope barred by "
                f"warrant={ts.warrant_id}; provenance={provenance!r} "
                f"does not re-attest the deletion scope"
            )
        self.records[key] = value
        return {"status": "WRITTEN", "key": key, "ttl": ttl}


def safe_re_derive(store: MemoryStore, key: str, inferred_value: str,
                   provenance: str, ttl: int) -> dict:
    """Agent-side helper: classify absence before re-deriving."""
    prior = store.read(key)
    if prior["status"] == "ABSENT_UNCLASSIFIED":
        # Cannot prove expiry; must attempt governed write, which fails closed.
        try:
            return store.write(key, inferred_value, ttl, provenance)
        except ResurrectionViolation as e:
            return {"status": "BLOCKED", "reason": str(e)}
    return {"status": "SKIPPED", "reason": "record already live"}
