# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-scoped-forget-that-spans-a-live-checkpoint-the-tombstone-checkpoint-divergence-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-scoped-forget-that-spans-a-live-checkpoint-the-tombstone-checkpoint-divergence-invariant.warrant.json
# Markdown SHA-256:   54020f80d770c146e2d1e74c3baf59fdd44d13b74bc940edea5d0bbb58e26258
# Code AST SHA-256:   2b402df7c997420776075d0fbe4580e3c118bd87352fca4b26c24f1769f2881d
# Verified Classes:   TombstoneDivergenceError, Tombstone, Checkpoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class TombstoneDivergenceError(RuntimeError):
    """Raised when a checkpoint cannot be resumed without violating an erasure tombstone."""


@dataclass(frozen=True)
class Tombstone:
    subject: str
    epoch: int


@dataclass(frozen=True)
class Checkpoint:
    task_id: str
    epoch: int
    referenced_subjects: frozenset[str]
    pending_writes: tuple[tuple[str, str], ...]  # (subject, kind)


def admit_resume(
    checkpoint: Checkpoint,
    tombstones: dict[str, Tombstone],
    *,
    allow_redaction: bool,
) -> Checkpoint:
    """
    Gate checkpoint resume against committed tombstones.

    A checkpoint is resumable only if every subject it references has no
    tombstone newer than the checkpoint's epoch, and no pending write targets
    a tombstoned subject. Tainted checkpoints are either redacted (if the
    caller permits) or rejected; they are never resumed as-is.
    """
    tainted: set[str] = set()
    for subject in checkpoint.referenced_subjects:
        ts = tombstones.get(subject)
        if ts is not None and ts.epoch > checkpoint.epoch:
            tainted.add(subject)

    blocked_writes = tuple(
        (s, k) for (s, k) in checkpoint.pending_writes if s in tombstones
    )

    if not tainted and not blocked_writes:
        return checkpoint

    if not allow_redaction:
        raise TombstoneDivergenceError(
            f"checkpoint {checkpoint.task_id} (epoch={checkpoint.epoch}) is tainted by "
            f"tombstones for {sorted(tainted)} and blocked writes {blocked_writes}; "
            f"refusing to resume without redaction"
        )

    # Redaction path: strip subject references and drop blocked writes.
    # If the plan's precondition was the subject data itself, this is incoherent
    # and the caller must abort instead — detect via empty pending set after drop.
    remaining_writes = tuple(w for w in checkpoint.pending_writes if w not in blocked_writes)
    if checkpoint.pending_writes and not remaining_writes:
        raise TombstoneDivergenceError(
            f"checkpoint {checkpoint.task_id} cannot be redacted: all pending writes "
            f"target tombstoned subjects {sorted(tainted)}; abort and re-plan"
        )

    return Checkpoint(
        task_id=checkpoint.task_id,
        epoch=checkpoint.epoch,
        referenced_subjects=frozenset(checkpoint.referenced_subjects - tainted),
        pending_writes=remaining_writes,
    )
