# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-roll-back-a-speculative-branch-after-a-side-effecting-tool-call-and-still-leave-the-effect-committed.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-roll-back-a-speculative-branch-after-a-side-effecting-tool-call-and-still-leave-the-effect-committed.warrant.json
# Markdown SHA-256:   6ec873dfb0ec0a0a5569c85577fff5e20b79be98930a9df4c59b2c8119988b0a
# Code AST SHA-256:   c05ddb2e098631f7662404276a55218f8326a0562b3202363758e68a0eb36c12
# Verified Classes:   SpeculativeRollbackViolation, EffectClass, ToolSpec, EffectRecord, Branch, SpeculativeExecutor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Callable, Dict, List, Optional


class SpeculativeRollbackViolation(RuntimeError):
    """Raised when a pruned speculative branch leaves a committed external effect."""


class EffectClass(Enum):
    IDEMPOTENT = "idempotent"
    COMPENSABLE = "compensable"
    DEFERRED = "deferred"
    UNRECOVERABLE = "unrecoverable"


@dataclass
class ToolSpec:
    name: str
    effect_class: EffectClass
    inverse: Optional[Callable[[Dict[str, Any]], None]] = None


@dataclass
class EffectRecord:
    branch_id: str
    tool: str
    args: Dict[str, Any]
    committed: bool


@dataclass
class Branch:
    branch_id: str
    checkpoint_id: str
    effects: List[EffectRecord] = field(default_factory=list)
    pruned: bool = False


class SpeculativeExecutor:
    def __init__(self, tools: Dict[str, ToolSpec]):
        self.tools = tools
        self.effect_log: List[EffectRecord] = []  # survives rollback

    def dispatch(self, branch: Branch, tool_name: str, args: Dict[str, Any]) -> Any:
        spec = self.tools.get(tool_name)
        if spec is None:
            raise SpeculativeRollbackViolation(f"unknown tool {tool_name!r}")

        # Admission check: block untagged side-effecting tools in a live branch.
        if spec.effect_class is EffectClass.UNRECOVERABLE and not branch.pruned:
            raise SpeculativeRollbackViolation(
                f"tool {tool_name!r} is UNRECOVERABLE and cannot run inside "
                f"speculative branch {branch.branch_id!r}; defer or compensate first"
            )

        # Execute and record the effect BEFORE returning, so it survives prune.
        record = EffectRecord(branch_id=branch.branch_id, tool=tool_name,
                              args=dict(args), committed=True)
        self.effect_log.append(record)
        branch.effects.append(record)
        return {"ok": True, "tool": tool_name}

    def prune(self, branch: Branch, reason: str) -> None:
        branch.pruned = True
        orphans = [e for e in self.effect_log
                   if e.branch_id == branch.branch_id and e.committed]
        for eff in orphans:
            spec = self.tools[eff.tool]
            if spec.effect_class is EffectClass.IDEMPOTENT:
                continue
            if spec.effect_class is EffectClass.COMPENSABLE and spec.inverse:
                spec.inverse(eff.args)
                continue
            # Deferred effects were never committed; nothing to do.
            if spec.effect_class is EffectClass.DEFERRED:
                continue
            raise SpeculativeRollbackViolation(
                f"pruning branch {branch.branch_id!r} ({reason}) leaves "
                f"orphaned committed effect from {eff.tool!r} with no inverse; "
                f"reconcile effect_log before resuming"
            )

    def reconcile_before_resume(self, restored_context: Dict[str, Any]) -> List[EffectRecord]:
        """Bind restored memory to the surviving effect log; surface orphans."""
        known = set(restored_context.get("effect_ids", []))
        return [e for e in self.effect_log if id(e) not in known and e.committed]
