# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-roll-back-to-a-checkpoint-that-has-already-been-invalidated-by-a-sibling-branch.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-roll-back-to-a-checkpoint-that-has-already-been-invalidated-by-a-sibling-branch.warrant.json
# Markdown SHA-256:   17edaf3439e2a302039cab793bc21e46375f2a19b0d792e78da7e435bf08564d
# Code AST SHA-256:   14cac0ad72cd3296552dbd045ce45ce8bbdce61c42ec1846ccf2927d1aae013e
# Verified Classes:   StaleCheckpointResumeError, Checkpoint, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class StaleCheckpointResumeError(RuntimeError):
    """Raised when a branch attempts to resume from a checkpoint that is no
    longer a lineage leaf because a sibling branch has committed past it."""


@dataclass
class Checkpoint:
    step: int
    ledger_hash: str
    lineage_head: str          # hash of the current committed head
    superseded_by: Optional[str] = None


@dataclass
class Branch:
    branch_id: str
    fork_checkpoint: Checkpoint
    read_live_state_after_fork: bool = False
    context_cursor: int = 0    # must track ledger cursor exactly


def resume_from_checkpoint(branch: Branch, current_head: str) -> Checkpoint:
    ck = branch.fork_checkpoint

    # Invariant 1: lineage guard. A checkpoint is a legal resume point only
    # while it is a leaf of the committed lineage DAG.
    if ck.superseded_by is not None or ck.lineage_hash_head() != current_head:
        raise StaleCheckpointResumeError(
            f"branch {branch.branch_id} cannot resume from step {ck.step}: "
            f"checkpoint superseded by {ck.superseded_by or current_head}; "
            f"re-fork from head or discard branch"
        )

    # Invariant 2: context quarantine. If the branch issued any live read
    # after fork, its context may contain post-fork observations even though
    # the ledger is being truncated. Refuse partial rollback.
    if branch.read_live_state_after_fork:
        raise StaleCheckpointResumeError(
            f"branch {branch.branch_id} performed live reads after fork; "
            f"context may be contaminated with sibling-committed state"
        )

    return ck


def _lineage_hash_head(self: Checkpoint) -> str:
    return self.lineage_head


Checkpoint.lineage_hash_head = _lineage_hash_head
