# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-memory-write-it-just-committed-the-provenance-revocation-race-in-read-write-forget-memory-tool-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-memory-write-it-just-committed-the-provenance-revocation-race-in-read-write-forget-memory-tool-apis.warrant.json
# Markdown SHA-256:   c88314c29ac83217b5e8243eaecc3c55a8c154cf8224adaf196206145e93f4db
# Code AST SHA-256:   633b44156aa48ad44d73303dde270943367b0950059d9bf85e053715e509be56
# Verified Classes:   RevokedWarrantError, StaleHandleError, MemoryRecord, MemoryClient
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class RevokedWarrantError(RuntimeError):
    """Raised when a commitment is attempted against a warrant that is no longer live."""


class StaleHandleError(RuntimeError):
    """Raised when a write is attempted under a handle whose warrant has been revoked."""


@dataclass
class MemoryRecord:
    key: str
    value: object
    warrant: str
    handle: str
    written_at: float
    ttl_s: int


class MemoryClient:
    """Minimal model of a read/write/forget store with asynchronous revocation."""

    def __init__(self, propagation_bound_s: float = 90.0):
        self._records: dict[str, MemoryRecord] = {}
        self._live_warrants: set[str] = set()
        self._revoked_at: dict[str, float] = {}
        self.propagation_bound_s = propagation_bound_s

    def write(self, key: str, value: object, warrant: str, ttl_s: int) -> str:
        if warrant in self._revoked_at:
            raise StaleHandleError(
                f"write rejected: warrant {warrant!r} revoked at "
                f"{self._revoked_at[warrant]:.0f}"
            )
        self._live_warrants.add(warrant)
        handle = f"mem_{abs(hash((key, warrant, time.time()))) % 10**6:06d}"
        self._records[key] = MemoryRecord(
            key=key, value=value, warrant=warrant, handle=handle,
            written_at=time.time(), ttl_s=ttl_s,
        )
        return handle

    def read(self, key: str) -> Optional[MemoryRecord]:
        rec = self._records.get(key)
        if rec is None:
            return None
        if time.time() - rec.written_at > rec.ttl_s:
            del self._records[key]
            return None
        return rec

    def revoke_provenance(self, warrant: str) -> None:
        # Marks the warrant dead immediately; value rows lag the sweep.
        self._revoked_at[warrant] = time.time()
        self._live_warrants.discard(warrant)

    def check_warrant(self, warrant: str) -> bool:
        """Read-synchronous liveness check, independent of the value row."""
        return warrant in self._live_warrants


def commit_under_warrant(client: MemoryClient, key: str, action) -> None:
    """Re-validate provenance at the commitment boundary, not at read time."""
    rec = client.read(key)
    if rec is None:
        raise RevokedWarrantError(f"no live record for {key!r} at commit time")

    # The value row's stale flag may lag; the warrant endpoint does not.
    if not client.check_warrant(rec.warrant):
        raise RevokedWarrantError(
            f"commit aborted: warrant {rec.warrant!r} for {key!r} is revoked "
            f"(value still present, stale flag may be false)"
        )

    # Guard the window between re-validation and action.
    if time.time() - client._revoked_at.get(rec.warrant, 0) < client.propagation_bound_s:
        # Within the lag window we cannot prove liveness is stable; abort.
        raise RevokedWarrantError(
            f"commit aborted: {key!r} inside revocation propagation window"
        )

    action(rec.value)
