# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-scoped-memory-forget-as-a-tombstone-rather-than-a-delete-and-reconcile-re-materialization-before-resuming.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-scoped-memory-forget-as-a-tombstone-rather-than-a-delete-and-reconcile-re-materialization-before-resuming.warrant.json
# Markdown SHA-256:   7f8302bf88019983a9341ebb1414df593ee1ad4a868292d45014ec0d27cb383a
# Code AST SHA-256:   67f555c84b9f04a04c28c09fb0f9c8e7801541d2431baaf09f989791fe7251e3
# Verified Classes:   ReMaterializedAfterForget, Tombstone, MemoryClient
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ReMaterializedAfterForget(RuntimeError):
    """A read resolved a value from a tier downstream of a tombstoned tier.

    The value may be a pre-forget artifact that survived consolidation or
    replication. It MUST NOT be used as live state until reconciled.
    """


@dataclass
class Tombstone:
    scope: str
    key: str
    tier: str  # tier that owns the retraction
    seq: int   # monotonic; higher = later


@dataclass
class MemoryClient:
    # tier name -> {(scope, key): value}
    tiers: dict[str, dict[tuple[str, str], str]] = field(default_factory=dict)
    tombstones: list[Tombstone] = field(default_factory=list)
    _seq: int = 0

    def forget(self, scope: str, key: str, tier: str) -> Tombstone:
        self._seq += 1
        ts = Tombstone(scope=scope, key=key, tier=tier, seq=self._seq)
        self.tombstones.append(ts)
        # Only the owning tier is retracted; derived tiers survive.
        self.tiers.get(tier, {}).pop((scope, key), None)
        return ts

    def _latest_tombstone(self, scope: str, key: str) -> Optional[Tombstone]:
        hits = [t for t in self.tombstones if t.scope == scope and t.key == key]
        return max(hits, key=lambda t: t.seq) if hits else None

    def read(self, scope: str, key: str, tier_order: list[str]) -> str:
        ts = self._latest_tombstone(scope, key)
        for tier in tier_order:
            store = self.tiers.get(tier, {})
            if (scope, key) in store:
                value = store[(scope, key)]
                # A hit in a tier that is downstream of the tombstoned tier
                # is provisional: it may be a pre-forget artifact.
                if ts is not None and tier != ts.tier:
                    raise ReMaterializedAfterForget(
                        f"read({scope!r}, {key!r}) resolved from tier {tier!r} "
                        f"but a tombstone exists at tier {ts.tier!r} (seq {ts.seq}). "
                        f"Reconcile before use."
                    )
                return value
        raise KeyError(f"{scope}/{key} not found in any tier")


def resume_and_read(client: MemoryClient, scope: str, key: str,
                    tier_order: list[str]) -> str:
    """Called after a checkpoint/resume. Reconciles tombstones first."""
    ts = client._latest_tombstone(scope, key)
    if ts is not None:
        # Retraction is durable state: re-verify it survived the resume.
        # If the value is only reachable downstream, refuse to treat it as live.
        for tier in tier_order:
            if tier == ts.tier:
                continue
            if (scope, key) in client.tiers.get(tier, {}):
                raise ReMaterializedAfterForget(
                    f"resume: {scope}/{key} re-materialized at {tier!r} "
                    f"after forget at {ts.tier!r}; must re-forget derived record "
                    f"or escalate before resuming task."
                )
    return client.read(scope, key, tier_order)
