# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-model-driven-context-pruning-has-silently-orphaned-a-reversible-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-model-driven-context-pruning-has-silently-orphaned-a-reversible-checkpoint.warrant.json
# Markdown SHA-256:   15287257a8cd2f604e0b49a1d9fb299d1a95be0f45a1c8063d90f9e2332856bf
# Code AST SHA-256:   02e6ebcf7a381900fc0771045336838b4d889b3505b2f4de86bcca504a5d6f8a
# Verified Classes:   OrphanedCheckpointError, Checkpoint
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class OrphanedCheckpointError(RuntimeError):
    """Raised when a checkpoint claims reversibility but its backing bytes
    no longer contain the pre-prune content the record promises."""


@dataclass
class Checkpoint:
    checkpoint_id: str
    covers: tuple            # (start_turn, end_turn)
    backing_ref: str
    digest: str              # sha256 over PRE-prune bytes, stored before overwrite
    witnesses: list = field(default_factory=list)  # high-entropy tokens from original span
    derived_from: str = None


def restore_checkpoint(ck: Checkpoint, fetch_bytes) -> bytes:
    raw = fetch_bytes(ck.backing_ref)
    if raw is None:
        raise OrphanedCheckpointError(
            f"{ck.checkpoint_id}: backing_ref {ck.backing_ref} unresolvable"
        )

    actual = hashlib.sha256(raw).hexdigest()
    if actual != ck.digest:
        raise OrphanedCheckpointError(
            f"{ck.checkpoint_id}: digest mismatch — segment was rewritten in place "
            f"(expected {ck.digest[:12]}, got {actual[:12]})"
        )

    # Digest can match a summary if the digest was computed post-prune.
    # Witnesses bind the record to the ORIGINAL span's content.
    text = raw.decode("utf-8", errors="replace")
    missing = [w for w in ck.witnesses if w not in text]
    if missing:
        raise OrphanedCheckpointError(
            f"{ck.checkpoint_id}: witness tokens missing {missing} — "
            f"checkpoint is a summary wearing a checkpoint schema; "
            f"re-fetch from external source before acting"
        )

    if ck.derived_from is not None:
        # Partial restore: content is itself derived. Do not treat as primary.
        raise OrphanedCheckpointError(
            f"{ck.checkpoint_id}: content derived_from {ck.derived_from}; "
            f"re-verify against source-of-truth before use"
        )

    return raw
