# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-invalidate-a-speculative-checkpoint-when-a-sibling-branch-has-already-committed-the-write-ahead-divergence-ledg.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-invalidate-a-speculative-checkpoint-when-a-sibling-branch-has-already-committed-the-write-ahead-divergence-ledg.warrant.json
# Markdown SHA-256:   d931fea9de1b1ca352f9a85c2c06957828e23576e84052aaca0f8e911b7bcdc7
# Code AST SHA-256:   bcd8db9c3d922915a7c9aea6ffdf1a7d1ed84a671933315989e7587bb396fec1
# Verified Classes:   StaleCheckpointError, Commit, Checkpoint, DivergenceLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, List, Optional
import time


class StaleCheckpointError(RuntimeError):
    """Raised when a checkpoint restore would reinstate a falsified read-set."""
    pass


@dataclass(frozen=True)
class Commit:
    branch_id: str
    write_set: FrozenSet[str]
    committed_at: float


@dataclass
class Checkpoint:
    branch_id: str
    checkpoint_id: str
    read_set: FrozenSet[str]
    forked_at: float


class DivergenceLedger:
    """Append-only write-ahead ledger of committed sibling writes."""

    def __init__(self) -> None:
        self._commits: List[Commit] = []

    def record_commit(self, branch_id: str, write_set: FrozenSet[str]) -> None:
        self._commits.append(
            Commit(branch_id=branch_id, write_set=write_set, committed_at=time.time())
        )

    def committed_since(self, fork_time: float) -> FrozenSet[str]:
        touched: set = set()
        for c in self._commits:
            if c.committed_at > fork_time:
                touched |= c.write_set
        return frozenset(touched)


def restore_checkpoint(
    checkpoint: Checkpoint,
    ledger: DivergenceLedger,
) -> None:
    """
    Restore a speculative checkpoint ONLY if no sibling commit since the
    fork has intersected the branch's read-set. Otherwise the checkpoint
    is a poisoned resume point and must be invalidated, not restored.
    """
    sibling_writes = ledger.committed_since(checkpoint.forked_at)
    collision = checkpoint.read_set & sibling_writes

    if collision:
        # Do NOT restore. The branch's premises were falsified by a sibling.
        raise StaleCheckpointError(
            f"Checkpoint {checkpoint.checkpoint_id} for branch "
            f"{checkpoint.branch_id} is invalid: read-set intersects "
            f"sibling commits {sorted(collision)}. Invalidate and re-fork "
            f"from committed head; do not retry from this checkpoint."
        )

    # Safe: read-set is still a subset of the committed world.
    # Perform the actual state restore here.
    return None


def orchestrate_rollback(
    checkpoint: Checkpoint,
    ledger: DivergenceLedger,
) -> str:
    try:
        restore_checkpoint(checkpoint, ledger)
        return "restored"
    except StaleCheckpointError:
        # Correct response: invalidate, re-fork, force fresh reads.
        return "invalidated_and_reforked"
