# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-resumable-agents-from-resurrecting-verifiably-deleted-memory-across-checkpoint-restore.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-resumable-agents-from-resurrecting-verifiably-deleted-memory-across-checkpoint-restore.warrant.json
# Markdown SHA-256:   e59ac66c2acc335c19ff0b0bb335faabec1c7a995eed5689bf9155d3e8fde223
# Code AST SHA-256:   f5f7df8e9a0984abb25b0705456c35ddd8e5754b9fd8594dff5be596debeb6c0
# Verified Classes:   PoisonedCheckpointError, Tombstone, ContextSpan, Checkpoint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class PoisonedCheckpointError(RuntimeError):
    """Raised when a checkpoint would rehydrate payloads for keys forgotten after it was taken."""


@dataclass(frozen=True)
class Tombstone:
    key: str
    forgotten_at: int


@dataclass
class ContextSpan:
    text: str
    derived_from: frozenset[str] = field(default_factory=frozenset)


@dataclass
class Checkpoint:
    taken_at: int
    spans: list[ContextSpan]
    pending_writes: list[tuple[str, str, frozenset[str]]]  # (artifact, payload, keys_in_payload)


def rehydrate_safely(ckpt: Checkpoint, tombstones: Iterable[Tombstone], now: int) -> Checkpoint:
    """Apply post-checkpoint forget events to a checkpoint before the agent resumes.

    Invariant enforced: no span or pending write may carry the payload of a key
    tombstoned at t_f with t_f > ckpt.taken_at.
    """
    forgotten = {t.key for t in tombstones if ckpt.taken_at < t.forgotten_at <= now}

    if not forgotten:
        return ckpt

    # A span that interpolated a forgotten key cannot be safely redacted in place
    # without provenance-preserving rewrite; fail closed rather than guess.
    for span in ckpt.spans:
        hit = span.derived_from & forgotten
        if hit:
            raise PoisonedCheckpointError(
                f"checkpoint@{ckpt.taken_at} rehydrates payload for forgotten key(s) "
                f"{sorted(hit)} tombstoned after checkpoint; refuse resume or cold-restart subgoal"
            )

    for artifact, _payload, keys in ckpt.pending_writes:
        hit = keys & forgotten
        if hit:
            raise PoisonedCheckpointError(
                f"pending write to {artifact!r} embeds forgotten key(s) {sorted(hit)}; "
                f"replaying it would disclose deleted data"
            )

    return ckpt


def resume(ckpt: Checkpoint, tombstones: list[Tombstone], now: int) -> Checkpoint:
    try:
        return rehydrate_safely(ckpt, tombstones, now)
    except PoisonedCheckpointError:
        # Fail closed: drop the poisoned checkpoint; caller must cold-restart.
        raise
