# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-branch-before-reconciliation-commits-orphaned-side-effect-divergence-in-optimistic-multi-agent-pipelines.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-branch-before-reconciliation-commits-orphaned-side-effect-divergence-in-optimistic-multi-agent-pipelines.warrant.json
# Markdown SHA-256:   3aea7a69e071a6c4578c4e228ae3c9c04090140bed9ad0deb07864aa6df71d3b
# Code AST SHA-256:   22c16b427c95ac14970a233fb75f3f1eb802cd156a95fa175108f76eb4e2483c
# Verified Classes:   OrphanedEffectError, UnreachableCommitError, Effect, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class OrphanedEffectError(RuntimeError):
    """Raised when a losing branch left a non-compensable external effect."""


class UnreachableCommitError(RuntimeError):
    """Raised when committed state is not reconstructible from the winner's journal."""


@dataclass
class Effect:
    branch_id: str
    handle: str
    compensable: bool
    compensate: Callable[[], bool] | None = None


@dataclass
class Branch:
    branch_id: str
    effects: list[Effect] = field(default_factory=list)


def reconcile(winner: Branch, losers: list[Branch], checkpoint_state: dict,
              current_state: dict) -> dict:
    # Step 1: reject if any losing branch emitted a non-compensable effect.
    for loser in losers:
        for eff in loser.effects:
            if not eff.compensable:
                raise OrphanedEffectError(
                    f"branch {loser.branch_id} emitted non-compensable effect "
                    f"{eff.handle}; optimistic commit is invalid"
                )

    # Step 2: run compensations in reverse emit order, verify each.
    for loser in losers:
        for eff in reversed(loser.effects):
            if eff.compensate is None or not eff.compensate():
                raise OrphanedEffectError(
                    f"compensation for {eff.handle} on {loser.branch_id} failed verification"
                )

    # Step 3: committed state must equal checkpoint + winner's effects, nothing else.
    expected = apply_effects(checkpoint_state, winner.effects)
    if expected != current_state:
        raise UnreachableCommitError(
            "post-commit state diverges from winner-journal replay; "
            "an orphaned effect from a losing branch has leaked"
        )
    return current_state


def apply_effects(state: dict, effects: list[Effect]) -> dict:
    # Pure replay of a branch's journal against a checkpoint snapshot.
    new_state = dict(state)
    for eff in effects:
        new_state[eff.handle] = True
    return new_state
