# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-a-branch-and-its-compensating-rollback-is-not-idempotent-under-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-a-branch-and-its-compensating-rollback-is-not-idempotent-under-replay.warrant.json
# Markdown SHA-256:   d0e2625746cc007e875ff1e961e5010f4a9089b98f6f9ba6ecf9ea3a397a8e94
# Code AST SHA-256:   fed081d8b8607c182e26c3077334c1fa79d4f1b4acafd201f2e1a82e1ad5c8ab
# Verified Classes:   SpeculationRejected, CompensatorPreconditionFailed, Effect, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class SpeculationRejected(RuntimeError):
    """Raised when a branch proposes an effect that cannot be safely compensated."""


class CompensatorPreconditionFailed(RuntimeError):
    """Raised when a rollback's target state no longer matches the applied post-state."""


@dataclass(frozen=True)
class Effect:
    handle: str            # minted at apply time, never reconstructed
    reversible: bool
    post_version: int      # world version immediately after this effect applied


@dataclass
class Branch:
    branch_id: str
    effects: list[Effect]


def validate_fork(branch: Branch) -> None:
    """Reject forks that contain irreversible effects before any side effect runs."""
    for e in branch.effects:
        if not e.reversible:
            raise SpeculationRejected(
                f"branch {branch.branch_id} contains irreversible effect {e.handle}; "
                "hoist to post-merge commit phase"
            )


def compensate(branch: Branch, world_version: int, expected: Effect) -> None:
    """Conditional inverse: only mutate if the world still matches the applied post-state."""
    if world_version != expected.post_version:
        # A winner's commit (or another rollback) moved the world; do NOT replay intent.
        raise CompensatorPreconditionFailed(
            f"branch {branch.branch_id}: effect {expected.handle} expected version "
            f"{expected.post_version}, world at {world_version}; aborting to avoid clobbering commit"
        )
    # ... issue inverse addressed strictly by expected.handle ...


def merge_and_rollback(winner: Branch, losers: list[Branch], world_version: int) -> int:
    for b in [winner, *losers]:
        validate_fork(b)
    committed_version = world_version + 1          # merge is the serialization point
    for b in losers:
        for e in b.effects:
            compensate(b, committed_version, e)    # will abort on any version drift
    return committed_version
