# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-a-scoped-forget-against-a-still-live-checkpoint-before-it-may-resume-and-why-does-a-tombstone-only-deletion-protocol.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-a-scoped-forget-against-a-still-live-checkpoint-before-it-may-resume-and-why-does-a-tombstone-only-deletion-protocol.warrant.json
# Markdown SHA-256:   70d09b4f2f58cb7a1c1c56aa2a78922b97ab57ee4780ef311b93ae1cad754014
# Code AST SHA-256:   07a71d2c3ce3ea7317ac587d6315624fbcd4e807beccebe9dc0b9e7079c15f9a
# Verified Classes:   ResurrectionOnResume, MemoryStore, Checkpoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ResurrectionOnResume(RuntimeError):
    """Raised when a tombstoned key reappears via checkpoint hydration."""
    pass


@dataclass
class MemoryStore:
    live: dict = field(default_factory=dict)
    tombstones: set = field(default_factory=set)

    def write(self, scope: str, key: str, value: str) -> None:
        self.live[(scope, key)] = value

    def forget(self, scope: str, key: str) -> str:
        # Tombstone-only deletion: record survives, shadowed on read.
        self.tombstones.add((scope, key))
        return "tombstone"

    def read(self, scope: str, key: str) -> Optional[str]:
        if (scope, key) in self.tombstones:
            return None
        return self.live.get((scope, key))


@dataclass
class Checkpoint:
    # Snapshot of hydrated working context, taken independently of the store.
    hydrated: dict


def resume(checkpoint: Checkpoint, store: MemoryStore) -> dict:
    """Re-hydrate working context, then re-apply tombstone log before use."""
    context = dict(checkpoint.hydrated)
    resurrected = {
        (scope, key)
        for (scope, key) in context
        if (scope, key) in store.tombstones
    }
    if resurrected:
        raise ResurrectionOnResume(
            f"tombstoned keys reappeared via checkpoint hydration: "
            f"{sorted(resurrected)}; invalidate checkpoint and re-derive"
        )
    return context


def run_trace() -> None:
    store = MemoryStore()
    store.write("task", "secrets.doc_token", "sk-live-abc123")

    # Agent forgets; live read confirms it is gone.
    store.forget("task", "secrets.doc_token")
    assert store.read("task", "secrets.doc_token") is None  # passes

    # But a checkpoint taken before the forget still holds the value.
    stale = Checkpoint(hydrated={("task", "secrets.doc_token"): "sk-live-abc123"})

    # Resume-path assertion is the only thing that catches the leak.
    resume(stale, store)  # raises ResurrectionOnResume


if __name__ == "__main__":
    run_trace()
