# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-speculative-parallel-branches-when-a-shared-tool-s-side-effects-are-non-idempotent-and-rollback-cannot-be.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-speculative-parallel-branches-when-a-shared-tool-s-side-effects-are-non-idempotent-and-rollback-cannot-be.warrant.json
# Markdown SHA-256:   ae883d02b80b7a573933fe73293f62d58a2885538c027f305e896707b62c27dd
# Code AST SHA-256:   086a74d26124252a87decfb69a758f479005cc5f8db657fab0ce099a46590691
# Verified Classes:   EffectClass, SpeculationBoundaryError, ToolCall, Branch, SpeculativeOrchestrator
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class EffectClass(Enum):
    IDEMPOTENT = "idempotent"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


class SpeculationBoundaryError(RuntimeError):
    """Raised when a speculative branch crosses the irreversible-effect boundary
    without a commit decision, or when compensation cannot be proven."""
    pass


@dataclass
class ToolCall:
    tool: str
    effect: EffectClass
    compensation_id: str | None = None  # lease id for compensable effects


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


class SpeculativeOrchestrator:
    def __init__(self):
        self.effect_ledger: dict[str, list[ToolCall]] = {}
        self.compensation_leases: set[str] = set()

    def record_call(self, branch: Branch, call: ToolCall) -> None:
        # Gate: an irreversible call may not execute inside a speculative branch
        # unless the branch has already been committed by the orchestrator.
        if call.effect is EffectClass.IRREVERSIBLE and not branch.committed:
            raise SpeculationBoundaryError(
                f"branch {branch.branch_id} attempted irreversible tool "
                f"'{call.tool}' before commit decision; rollback is unprovable"
            )
        branch.calls.append(call)
        self.effect_ledger.setdefault(branch.branch_id, []).append(call)

    def commit(self, winner: Branch) -> None:
        winner.committed = True  # only now may irreversible calls fire

    def rollback(self, loser: Branch) -> list[str]:
        unprovable: list[str] = []
        for call in loser.calls:
            if call.effect is EffectClass.IRREVERSIBLE:
                # Should be unreachable given record_call gate, but defend.
                unprovable.append(call.tool)
                continue
            if call.effect is EffectClass.COMPENSABLE:
                lease = call.compensation_id
                if lease is None or lease not in self.compensation_leases:
                    unprovable.append(call.tool)
                    continue
                self.compensation_leases.discard(lease)  # single-fire lease
        if unprovable:
            raise SpeculationBoundaryError(
                f"rollback of branch {loser.branch_id} cannot be proven; "
                f"effects {unprovable} require reconciliation, not discard"
            )
        return []

    def reconcile(self, branch: Branch, leaked: list[str]) -> None:
        # Accept the leaked effect, record it, re-plan winner around it.
        for tool in leaked:
            self.effect_ledger.setdefault("reconciled", []).append(
                ToolCall(tool=tool, effect=EffectClass.IRREVERSIBLE)
            )
