# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-before-its-rollback-checkpoint-is-provably-consistent.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-before-its-rollback-checkpoint-is-provably-consistent.warrant.json
# Markdown SHA-256:   a0ad40f665f0f3a766db9c75cfe79e20f56596c19b8fd71e34dd8490c7ec34fd
# Code AST SHA-256:   6594fd2b238894f5bf2ffc9518aa0ce63f89c5fae27858430a3a39984bd945aa
# Verified Classes:   CheckpointDirtyError, EffectKind, Effect, Branch
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class CheckpointDirtyError(RuntimeError):
    """Raised when a branch attempts to abandon/merge/replay on a checkpoint
    whose rewind guarantee is not provable."""
    pass


class EffectKind(Enum):
    CAPTURED = "captured"
    COMPENSABLE = "compensable"
    UNCOMPENSABLE = "uncompensable"


@dataclass
class Effect:
    key: str
    kind: EffectKind
    inverse: Optional[str] = None


@dataclass
class Branch:
    branch_id: str
    checkpoint_id: str
    effects: list[Effect] = field(default_factory=list)
    read_set: set[str] = field(default_factory=set)
    compensated: set[str] = field(default_factory=set)
    replayed_diverged: bool = False

    def escaped_uncompensated(self) -> set[str]:
        return {
            e.key for e in self.effects
            if e.kind is EffectKind.UNCOMPENSABLE
            or (e.kind is EffectKind.COMPENSABLE and e.key not in self.compensated)
        }


def decide_branch_action(
    branch: Branch,
    concurrent_branches: list[Branch],
    checkpoint_certified_clean: bool,
) -> str:
    escaped = branch.escaped_uncompensated()

    # Guard 1: escaped, uncompensated effect -> checkpoint is dirty.
    if escaped:
        raise CheckpointDirtyError(
            f"branch {branch.branch_id} has escaped uncompensated effects "
            f"{sorted(escaped)}; checkpoint {branch.checkpoint_id} cannot "
            f"certify a clean rewind"
        )

    # Guard 3: non-idempotent rewind detected via divergent replay.
    if branch.replayed_diverged:
        raise CheckpointDirtyError(
            f"branch {branch.branch_id} replay diverged after rollback; "
            f"rewind is not idempotent"
        )

    # Guard 2: read-set / write-set intersection with concurrent branches.
    for other in concurrent_branches:
        if other.branch_id == branch.branch_id:
            continue
        overlap = branch.read_set & other.escaped_uncompensated()
        if overlap:
            raise CheckpointDirtyError(
                f"branch {branch.branch_id} read-set intersects escaped "
                f"write-set of {other.branch_id} on {sorted(overlap)}; "
                f"co-invalidation required"
            )

    if not checkpoint_certified_clean:
        raise CheckpointDirtyError(
            f"checkpoint {branch.checkpoint_id} not certified clean"
        )

    if branch.effects and all(
        e.kind is EffectKind.COMPENSABLE for e in branch.effects
    ):
        return "replay"
    return "merge"


def reconcile(planner_branches: list[Branch], clean_checkpoints: set[str]) -> str:
    winner = None
    for b in planner_branches:
        try:
            action = decide_branch_action(
                b, planner_branches, b.checkpoint_id in clean_checkpoints
            )
        except CheckpointDirtyError:
            # Invalidate branch and all read-dependents; do not merge.
            continue
        if action == "merge":
            winner = b.branch_id
            break
    if winner is None:
        raise CheckpointDirtyError(
            "no branch certified for merge; re-dispatch from last global checkpoint"
        )
    return winner
