# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-revokes-a-memory-record-that-a-concurrent-sub-agent-is-mid-read-on.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-revokes-a-memory-record-that-a-concurrent-sub-agent-is-mid-read-on.warrant.json
# Markdown SHA-256:   2ecc2df293a6a1daeff4add08e102473b41d246ea0ee4782ea60e21552033f3e
# Code AST SHA-256:   d1f764d519dd21d87c7fd648bbbbb0a5454447608d3a31400b098a7f814af286
# Verified Classes:   RevokedLeaseError, StaleLeaseError, Tombstone, Lease, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class RevokedLeaseError(RuntimeError):
    """Non-retryable: the lease's record has a tombstone newer than the lease.

    The reader must re-read, observe revoked=true, and either abandon or
    re-assert with a fresh provenance root (derived_from=[]).
    """
    pass


class StaleLeaseError(RuntimeError):
    """Retryable: tombstone not yet propagated to the reader's cache view.

    The lease predates the tombstone but the tombstone's issued_at is within
    the cache TTL window. Retry after cache refresh.
    """
    pass


@dataclass
class Tombstone:
    tombstone_id: str
    record_id: str
    issued_at: float
    signer: str


@dataclass
class Lease:
    lease_id: str
    record_id: str
    issued_at: float
    provenance_chain: list = field(default_factory=list)
    revoked_snapshot: bool = False


@dataclass
class MemoryStore:
    tombstones: dict = field(default_factory=dict)   # record_id -> Tombstone
    cache_ttl: float = 5.0

    def write(self, key: str, value, derived_from: list, now: Optional[float] = None):
        now = now if now is not None else time.time()
        for lease in derived_from:
            tomb = self.tombstones.get(lease.record_id)
            if tomb is None:
                continue
            if tomb.issued_at <= lease.issued_at:
                # Lease was issued before the tombstone existed: the reader
                # snapshotted a pre-revocation state. This is the resurrection
                # vector. Reject unconditionally.
                raise RevokedLeaseError(
                    f"lease {lease.lease_id} on record {lease.record_id} "
                    f"predates tombstone {tomb.tombstone_id} "
                    f"(issued {tomb.issued_at:.3f}, lease {lease.issued_at:.3f}); "
                    f"re-read required, re-assert with derived_from=[]"
                )
            if now - tomb.issued_at < self.cache_ttl:
                # Tombstone is fresh; the reader's cache may not have it yet.
                # Retryable after cache refresh.
                raise StaleLeaseError(
                    f"lease {lease.lease_id} observed tombstone "
                    f"{tomb.tombstone_id} within cache TTL; retry after refresh"
                )
        # Fresh-root re-assertion is the only path that survives revocation.
        return {"key": key, "value": value, "provenance_root": "fresh" if not derived_from else "inherited"}
