# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-abandon-a-speculative-branch-that-already-committed-an-irreversible-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-abandon-a-speculative-branch-that-already-committed-an-irreversible-side-effect.warrant.json
# Markdown SHA-256:   a2269677a8d70ed350598a13678256c584180f15b83fd16dc0830ed82b56aec5
# Code AST SHA-256:   512348a04cf34bf5f45323dde358a08266b7f402f36a120e1d026d0caa79baac
# Verified Classes:   Irreversibility, SpeculativeRollbackError, Effect, EffectLog
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List


class Irreversibility(Enum):
    REVERSIBLE = "reversible"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


class SpeculativeRollbackError(RuntimeError):
    """Raised when rollback would erase a committed effect or when an
    irreversible tool is invoked optimistically before reconciliation."""
    pass


@dataclass
class Effect:
    branch_id: str
    tool: str
    args: dict
    irreversibility: Irreversibility
    compensation: dict | None = None


@dataclass
class EffectLog:
    # Deliberately OUTSIDE the checkpoint boundary: never rewound.
    entries: List[Effect] = field(default_factory=list)

    def record(self, effect: Effect) -> None:
        self.entries.append(effect)

    def orphaned_for(self, winner_id: str) -> List[Effect]:
        return [e for e in self.entries if e.branch_id != winner_id]


def invoke_tool(
    branch_id: str,
    tool: str,
    args: dict,
    irreversibility: Irreversibility,
    reconciled: bool,
    log: EffectLog,
) -> Effect:
    if irreversibility is Irreversibility.IRREVERSIBLE and not reconciled:
        # Commit barrier: irreversible tools may not run speculatively.
        raise SpeculativeRollbackError(
            f"branch {branch_id} attempted irreversible tool {tool!r} "
            f"before reconciliation; refusing optimistic invocation"
        )
    effect = Effect(branch_id, tool, args, irreversibility)
    log.record(effect)
    return effect


def restore_checkpoint(branch_id: str, log: EffectLog) -> None:
    # Rewinds reasoning state only. If the caller expects this to also
    # undo world effects, that expectation is the bug.
    committed = [e for e in log.entries if e.branch_id == branch_id]
    irreversible = [e for e in committed if e.irreversibility is Irreversibility.IRREVERSIBLE]
    if irreversible:
        raise SpeculativeRollbackError(
            f"cannot roll back branch {branch_id}: "
            f"{len(irreversible)} irreversible effect(s) already committed; "
            f"compensation required, not rewind"
        )
    # Context/scratchpad rewind happens here; effect log is untouched.


def reconcile(winner_id: str, log: EffectLog) -> List[dict]:
    """Issue compensations for orphaned compensable effects. Returns the
    compensation actions the orchestrator must execute forward."""
    compensations = []
    for effect in log.orphaned_for(winner_id):
        if effect.irreversibility is Irreversibility.COMPENSABLE:
            if effect.compensation is None:
                raise SpeculativeRollbackError(
                    f"orphaned effect {effect.tool!r} from {effect.branch_id} "
                    f"has no recorded compensation; world-state divergence is unbounded"
                )
            compensations.append(effect.compensation)
        elif effect.irreversibility is Irreversibility.IRREVERSIBLE:
            # Should be unreachable if invoke_tool enforced the barrier.
            raise SpeculativeRollbackError(
                f"irreversible effect from losing branch {effect.branch_id} "
                f"survived into reconciliation; commit barrier was bypassed"
            )
    return compensations
