# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-branch-divergence-before-rollback-reconciliation-corrupts-the-committed-state-tree.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-branch-divergence-before-rollback-reconciliation-corrupts-the-committed-state-tree.warrant.json
# Markdown SHA-256:   b1c9b8185a86de5ff8d5cd8b0fea3c5d57f079fb33c233782bece1ebb692ced7
# Code AST SHA-256:   b42dd8730ff50235bc867723186ab24fecf0541a5fd2ac3b7d3e368662a84605
# Verified Classes:   CrossBranchContaminationError, StateValue
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CrossBranchContaminationError(RuntimeError):
    """Raised when a speculative branch reads state written by a sibling branch,
    or when reconciliation attempts to compensate against a non-checkpoint prior."""
    pass


@dataclass(frozen=True)
class StateValue:
    value: object
    provenance_branch: Optional[str]  # None == fork checkpoint ck_0
    parent_checkpoint: str
    seq: int


def read_state(branch_id: str, fork_checkpoint: str, key: str, store: dict) -> StateValue:
    sv = store.get(key)
    if sv is None:
        raise CrossBranchContaminationError(f"missing state {key!r} for branch {branch_id}")
    # Isolation invariant: a read must resolve to ck_0 or to this branch's own writes.
    if sv.parent_checkpoint != fork_checkpoint:
        raise CrossBranchContaminationError(
            f"branch {branch_id} read {key!r} grounded in {sv.parent_checkpoint}, "
            f"expected fork {fork_checkpoint}"
        )
    if sv.provenance_branch is not None and sv.provenance_branch != branch_id:
        raise CrossBranchContaminationError(
            f"branch {branch_id} read {key!r} written by sibling "
            f"{sv.provenance_branch}; branch is INVALID_FOR_SELECTION"
        )
    return sv


def reconcile_rollback(
    losing_branch: str, fork_checkpoint: str, action_log: list, store: dict
) -> None:
    for action in reversed(action_log):
        key, prior = action["key"], action["prior"]
        if prior is None:
            continue
        if prior.parent_checkpoint != fork_checkpoint or (
            prior.provenance_branch is not None and prior.provenance_branch != losing_branch
        ):
            # Prior is a ghost from a sibling's speculative write. Do not compensate.
            raise CrossBranchContaminationError(
                f"refusing to compensate {key!r} for {losing_branch}: prior grounded in "
                f"{prior.parent_checkpoint}/{prior.provenance_branch}; escalate to re-fork"
            )
        store[key] = prior
