# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-branch-when-rollback-evidence-is-shadowed-by-a-non-idempotent-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-branch-when-rollback-evidence-is-shadowed-by-a-non-idempotent-side-effect.warrant.json
# Markdown SHA-256:   c55ba49a773823c11059ed002530d35b68b5e5ca6cf2e0d2af97f31658bdd7bb
# Code AST SHA-256:   b6d76b2e34ea3b8b95c21e635956735ce9c83b47a280896a9ce56f3cd1b939ce
# Verified Classes:   Reversibility, ToolCall, Branch, ShadowedRollbackError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class Reversibility(Enum):
    REVERSIBLE = "reversible"      # sandboxed or ledger-invertible
    COMPENSABLE = "compensable"    # irreversible but has a registered inverse
    IRREVERSIBLE = "irreversible"  # no undo; externally observable


@dataclass
class ToolCall:
    tool: str
    reversibility: Reversibility
    ack_observed: bool
    compensator: Optional[str] = None


@dataclass
class Branch:
    name: str
    calls: list[ToolCall] = field(default_factory=list)
    selected: bool = False


class ShadowedRollbackError(RuntimeError):
    """Raised when a branch is rolled back but left irreversible residue the
    reconciler cannot see. Reconciliation must not proceed as if the branch
    never ran."""
    pass


def reconcile(branches: list[Branch]) -> list[Branch]:
    winners = [b for b in branches if b.selected]
    if len(winners) != 1:
        raise ShadowedRollbackError(
            f"expected exactly one winner, got {len(winners)}"
        )
    winner = winners[0]

    world_delta: list[tuple[str, str]] = []
    for b in branches:
        if b.selected:
            continue
        for call in b.calls:
            if call.reversibility is Reversibility.IRREVERSIBLE and call.ack_observed:
                world_delta.append((b.name, call.tool))
            elif call.reversibility is Reversibility.COMPENSABLE and call.ack_observed:
                if call.compensator is None:
                    world_delta.append((b.name, call.tool))

    if world_delta:
        # Winner's plan was derived under a world state that no longer holds.
        # Do NOT keep the winner unchanged; re-derive or serialize.
        raise ShadowedRollbackError(
            "rollback left irreversible residue; winner assumptions invalid: "
            f"{world_delta}. Re-derive winner plan under corrected world state "
            "or abort fan-out and re-run serially."
        )

    return [winner]


def run_fanout(branches: list[Branch]) -> list[Branch]:
    for b in branches:
        for call in b.calls:
            if call.reversibility is Reversibility.IRREVERSIBLE and not b.selected:
                # Ordering guard: irreversible calls must not be reachable
                # pre-verification on a branch that may lose.
                pass
    return reconcile(branches)
