# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-was-reconciled-against-a-stale-sibling-checkpoint-and-why-does-rollback-ordering-silently-corrup.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-was-reconciled-against-a-stale-sibling-checkpoint-and-why-does-rollback-ordering-silently-corrup.warrant.json
# Markdown SHA-256:   2c2262fc514a6195857150b4ec0f391be29bd448f93e06eb9f8ac7cdcaf193c6
# Code AST SHA-256:   a92cc7701f093ec1b31521aa723a358d3109769873c75ec92a995dc7d9a0aa00
# Verified Classes:   StaleLineageCheckpointError, DivergentLineageError, Checkpoint, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class StaleLineageCheckpointError(RuntimeError):
    """Raised when a branch attempts to checkpoint against a parent hash
    that is not its own lineage tip — the signature of a sibling rollback
    having rewound a shared pointer."""


class DivergentLineageError(RuntimeError):
    """Raised when the checkpoint parent is neither the lineage tip nor an
    ancestor of it; the reconciliation DAG itself is corrupted."""


@dataclass
class Checkpoint:
    hash: str
    parent: Optional[str]
    ledger: list


@dataclass
class Branch:
    name: str
    lineage_tip: str
    working_ledger: list = field(default_factory=list)
    quarantined: bool = False


def _hash(parent: Optional[str], ledger: list) -> str:
    h = hashlib.sha256()
    h.update((parent or "ROOT").encode())
    h.update(repr(ledger).encode())
    return h.hexdigest()


def checkpoint_write(branch: Branch, parent_claimed: str,
                     ancestry: dict[str, Optional[str]]) -> Checkpoint:
    """CAS-guarded checkpoint write. ancestry maps hash -> parent hash and
    is the authoritative lineage DAG shared by the reconciler."""
    if branch.quarantined:
        raise StaleLineageCheckpointError(
            f"branch {branch.name} is quarantined; refusing write")

    if parent_claimed != branch.lineage_tip:
        # Walk ancestry to classify the mismatch.
        cursor = branch.lineage_tip
        is_ancestor = False
        while cursor is not None:
            if cursor == parent_claimed:
                is_ancestor = True
                break
            cursor = ancestry.get(cursor)
        if is_ancestor:
            branch.quarantined = True
            raise StaleLineageCheckpointError(
                f"branch {branch.name}: parent {parent_claimed[:8]} is an "
                f"ancestor of tip {branch.lineage_tip[:8]} — sibling rollback "
                f"rewound a shared pointer; working state is contaminated")
        raise DivergentLineageError(
            f"branch {branch.name}: parent {parent_claimed[:8]} diverges from "
            f"lineage tip {branch.lineage_tip[:8]} — DAG corrupted")

    new_hash = _hash(branch.lineage_tip, branch.working_ledger)
    cp = Checkpoint(hash=new_hash, parent=branch.lineage_tip,
                    ledger=list(branch.working_ledger))
    ancestry[new_hash] = branch.lineage_tip
    branch.lineage_tip = new_hash
    return cp


def branch_scoped_rollback(branch: Branch, target: str,
                           ancestry: dict[str, Optional[str]]) -> None:
    """Rewind ONLY this branch. Never mutate a global pointer."""
    cursor = branch.lineage_tip
    while cursor is not None and cursor != target:
        cursor = ancestry.get(cursor)
    if cursor is None:
        raise DivergentLineageError(
            f"branch {branch.name}: rollback target {target[:8]} not in lineage")
    branch.lineage_tip = target
    branch.working_ledger = []  # discard contaminated scratch
    # Sibling branches are untouched by construction.
