# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-rollouts-from-committing-side-effects-that-survive-rollback-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-rollouts-from-committing-side-effects-that-survive-rollback-reconciliation.warrant.json
# Markdown SHA-256:   e367c9ea6a094a3446d21bc904452be3a80eb58bddf7f4181fd59d5f9d4a337c
# Code AST SHA-256:   e78bafc47f59fc33cd08c97ab860e77dd16c5bace1b6a4ef0695a9293623fdef
# Verified Classes:   UnreconcilableEffectError, EffectClass, ToolDescriptor, EffectRecord, BranchLedger, SpeculativeOrchestrator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class UnreconcilableEffectError(RuntimeError):
    """Raised when a discarded branch left an effect with no compensating inverse."""
    pass


class EffectClass(Enum):
    PURE = "pure"
    BUFFERED = "buffered"
    IDEMPOTENT = "idempotent"
    IRREVERSIBLE = "irreversible"


@dataclass(frozen=True)
class ToolDescriptor:
    name: str
    effect_class: EffectClass
    inverse_tool: Optional[str] = None
    keyed_on: Optional[str] = None  # resource key for single-flight


@dataclass
class EffectRecord:
    branch_id: str
    tool: str
    key: Optional[str]
    handle: Optional[str]  # returned handle for inverse invocation


@dataclass
class BranchLedger:
    branch_id: str
    effects: list[EffectRecord] = field(default_factory=list)


class SpeculativeOrchestrator:
    def __init__(self, descriptors: dict[str, ToolDescriptor]):
        self.descriptors = descriptors
        self._leases: dict[str, str] = {}  # key -> branch holding lease
        self._ledgers: dict[str, BranchLedger] = {}

    def _ledger(self, branch_id: str) -> BranchLedger:
        return self._ledgers.setdefault(branch_id, BranchLedger(branch_id))

    def dispatch(self, branch_id: str, tool: str, key: Optional[str], args: dict) -> str:
        desc = self.descriptors[tool]
        # Guardrail 1: forbid irreversible-no-inverse during speculation.
        if desc.effect_class is EffectClass.IRREVERSIBLE and desc.inverse_tool is None:
            raise UnreconcilableEffectError(
                f"tool {tool!r} is irreversible with no inverse; "
                f"branch {branch_id} must replan or defer to post-selection commit"
            )
        # Guardrail 2: single-flight on shared keys.
        if desc.keyed_on and key is not None:
            holder = self._leases.get(key)
            if holder is not None and holder != branch_id:
                raise UnreconcilableEffectError(
                    f"key {key!r} already leased by branch {holder}; "
                    f"branch {branch_id} must fork or wait"
                )
            self._leases[key] = branch_id
        handle = f"h:{branch_id}:{tool}:{len(self._ledger(branch_id).effects)}"
        self._ledger(branch_id).effects.append(
            EffectRecord(branch_id, tool, key, handle)
        )
        return handle

    def discard(self, branch_id: str, invoke_inverse: Callable[[str, str], None]) -> None:
        """Roll back a losing branch. Raises if any effect cannot be compensated."""
        ledger = self._ledger(branch_id)
        for rec in reversed(ledger.effects):
            desc = self.descriptors[rec.tool]
            if desc.effect_class in (EffectClass.PURE, EffectClass.BUFFERED):
                continue
            if desc.effect_class is EffectClass.IRREVERSIBLE and desc.inverse_tool is None:
                raise UnreconcilableEffectError(
                    f"branch {branch_id} left irreversible effect via {rec.tool!r} "
                    f"(handle {rec.handle}); continuation blocked pending compensation"
                )
            if desc.inverse_tool is not None:
                invoke_inverse(desc.inverse_tool, rec.handle)
            if desc.keyed_on and rec.key is not None:
                self._leases.pop(rec.key, None)
        ledger.effects.clear()

    def surviving_effects(self, winner_id: str) -> list[EffectRecord]:
        """Seed the continuation agent with the winner's live effects."""
        return list(self._ledger(winner_id).effects)
