# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-tombstones-a-scoped-memory-key-that-a-peer-is-mid-write-against-consent-deletion-races-under-ttl-bounded-retention.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-tombstones-a-scoped-memory-key-that-a-peer-is-mid-write-against-consent-deletion-races-under-ttl-bounded-retention.warrant.json
# Markdown SHA-256:   a2f3561de985295b32187a719302dbf4d2e5b3ae927902856157146eb517db6d
# Code AST SHA-256:   fc9328c9881b5e137a28c190a69e3b2ae111e694dfddf247b06fc2ba5ec87ac0
# Verified Classes:   ConsentRevokedError, PurposeConflictError, Regime, Tombstone, MemoryStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class ConsentRevokedError(RuntimeError):
    """Raised when a write targets a tombstoned (consent-revoked) scope."""
    def __init__(self, scope: str, tombstone_until: float):
        super().__init__(f"write to tombstoned scope {scope!r} until {tombstone_until}")
        self.scope = scope
        self.tombstone_until = tombstone_until
        self.retryable = False


class PurposeConflictError(RuntimeError):
    """Raised when a write names both advisory and authoritative purposes."""
    pass


class Regime(Enum):
    ADVISORY = "advisory"      # TTL-only, best-effort
    AUTHORITATIVE = "authoritative"  # consent-bound, tombstone dominates


CONSENT_BOUND_PURPOSES = {"pii", "session-summary", "distillation-audit"}


@dataclass
class Tombstone:
    scope_prefix: str
    until: float


class MemoryStore:
    def __init__(self):
        self._values: dict[str, dict] = {}
        self._tombstones: list[Tombstone] = []

    def _regime(self, purposes: set[str]) -> Regime:
        if purposes & CONSENT_BOUND_PURPOSES:
            return Regime.AUTHORITATIVE
        return Regime.ADVISORY

    def _tombstone_for(self, scope: str) -> Tombstone | None:
        for t in self._tombstones:
            if scope == t.scope_prefix or scope.startswith(t.scope_prefix + "/"):
                return t
        return None

    def write(self, scope: str, purposes: set[str], value, expires_at: float | None):
        if purposes & CONSENT_BOUND_PURPOSES and purposes - CONSENT_BOUND_PURPOSES:
            raise PurposeConflictError(
                f"scope {scope!r} mixes advisory and authoritative purposes: {purposes}"
            )
        # Tombstone check precedes any TTL application — invariant (2).
        tomb = self._tombstone_for(scope)
        if tomb is not None:
            raise ConsentRevokedError(tomb.scope_prefix, tomb.until)
        self._values[scope] = {"value": value, "expires_at": expires_at}

    def forget(self, scope: str, until: float):
        # Prefix-keyed tombstone closes derived-scope resurrection — invariant (1).
        self._tombstones.append(Tombstone(scope_prefix=scope, until=until))
        for k in [k for k in self._values if k == scope or k.startswith(scope + "/")]:
            del self._values[k]


def extractor_write(store: MemoryStore, scope: str, purposes: set[str], value, expires_at):
    """Peer-side writer that must classify rejections as terminal, not contention."""
    try:
        store.write(scope, purposes, value, expires_at)
    except ConsentRevokedError as e:
        # Terminal: escalate to orchestrator for re-consent; never retry.
        if e.retryable:
            raise  # defensive: tombstone rejections must be non-retryable
        raise ConsentRevokedError(e.scope, e.tombstone_until) from None
