# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-roll-back-a-self-pruned-context-window-the-summarization-commit-barrier-and-the-phantom-turn-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-roll-back-a-self-pruned-context-window-the-summarization-commit-barrier-and-the-phantom-turn-invariant.warrant.json
# Markdown SHA-256:   916422aae24f752aa195b623f1915ab3f854615693fd2ddc59369c4b70db756b
# Code AST SHA-256:   46146866f16cd81c1c8fcfba3ca3d96ae8c6d71baacd580d08edddfbffb69d35
# Verified Classes:   RollbackUnsafeError, Checkpoint, EventLog
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class RollbackUnsafeError(RuntimeError):
    """Raised when a checkpoint cannot be used as a true restore point."""


@dataclass
class Checkpoint:
    window_bytes: bytes
    digest_hash: str                      # hash of the summary text actually in window
    removed_span_ids: list[str]           # IDs into the external event log
    policy_seed: Optional[int]            # None => policy not replayable
    extracted_constraints: dict[str, str] # deterministic pass output
    rationale: str                        # model self-report; NOT trusted for validity


@dataclass
class EventLog:
    spans: dict[str, str] = field(default_factory=dict)

    def get(self, span_id: str) -> str:
        if span_id not in self.spans:
            raise RollbackUnsafeError(f"span {span_id} missing from event log")
        return self.spans[span_id]


def verify_checkpoint(cp: Checkpoint, log: EventLog) -> None:
    """Gate: a checkpoint is rollback-safe only if all four conditions hold."""
    actual = hashlib.sha256(cp.window_bytes).hexdigest()

    # 1. digest immutability: the bytes we would restore must match the recorded hash
    if actual != cp.digest_hash:
        raise RollbackUnsafeError(
            f"digest hash mismatch: recorded {cp.digest_hash[:12]} "
            f"!= actual {actual[:12]}"
        )

    # 2. provenance completeness: every removed span must still be addressable
    for span_id in cp.removed_span_ids:
        log.get(span_id)  # raises if absent

    # 3. policy determinism envelope: model-driven prunes must be pinned
    if cp.policy_seed is None:
        raise RollbackUnsafeError(
            "pruning policy is model-driven and unpinned; "
            "replay would not reproduce the decision"
        )

    # 4. constraint extraction is separable: must not be empty when spans were pruned
    if cp.removed_span_ids and not cp.extracted_constraints:
        raise RollbackUnsafeError(
            "spans were pruned but no deterministic constraint extraction was recorded; "
            "load-bearing facts may exist only inside the lossy digest"
        )


def attempt_rollback(cp: Checkpoint, log: EventLog, failing_decision_deps: set[str]) -> bytes:
    """
    Roll back to cp, or refuse and signal re-derivation.
    Never 'try and see': a phantom-turn resume is silent.
    """
    try:
        verify_checkpoint(cp, log)
    except RollbackUnsafeError as e:
        # If the failed decision touched pruned spans, re-derive from the log.
        touched_pruned = failing_decision_deps & set(cp.removed_span_ids)
        if touched_pruned:
            raise RollbackUnsafeError(
                f"checkpoint snapshot-only and failed decision depends on pruned spans "
                f"{sorted(touched_pruned)}; re-derive from event log, do not roll back"
            ) from e
        # Dependency set unknown or disjoint: refuse rather than fabricate a restore.
        raise RollbackUnsafeError(
            "checkpoint failed commit barrier; refusing rollback to avoid phantom-turn resume"
        ) from e

    return cp.window_bytes
