# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-speculatively-invoke-a-tool-in-a-parallel-branch-commit-its-side-effect-and-then-discover-the-parent-orchestrator-rolled-back-to.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-speculatively-invoke-a-tool-in-a-parallel-branch-commit-its-side-effect-and-then-discover-the-parent-orchestrator-rolled-back-to.warrant.json
# Markdown SHA-256:   e34e9d305b1c9ff43365c235eb198b5c9c817a73da31474e2f5a522f1e6ae755
# Code AST SHA-256:   6e6ba1060e794dfda5e145ed682477badd639fbc9563f81f23ce40c6748f02a0
# Verified Classes:   SpeculativeEffectError, ToolKind, ToolSpec, EffectEntry, Branch, SpeculativeOrchestrator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class SpeculativeEffectError(RuntimeError):
    """Raised when a branch commits an external side effect before the
    orchestrator has committed that branch, or when a rollback leaves
    an un-compensated effect in the ledger."""


class ToolKind(Enum):
    READ_ONLY = "read_only"
    INVERTIBLE = "invertible"
    NON_INVERTIBLE = "non_invertible"


@dataclass
class ToolSpec:
    name: str
    kind: ToolKind
    compensator: str | None = None


@dataclass
class EffectEntry:
    branch_id: str
    tool_call_id: str
    idempotency_key: str
    tool: str
    compensated: bool = False


@dataclass
class Branch:
    branch_id: str
    committed: bool = False
    effects: List[EffectEntry] = field(default_factory=list)


class SpeculativeOrchestrator:
    def __init__(self, manifest: Dict[str, ToolSpec], run_id: str):
        self.manifest = manifest
        self.run_id = run_id
        self.branches: Dict[str, Branch] = {}
        self._seq = 0

    def fork(self, branch_id: str) -> Branch:
        b = Branch(branch_id=branch_id)
        self.branches[branch_id] = b
        return b

    def invoke(self, branch: Branch, tool: str, args: dict) -> dict:
        spec = self.manifest[tool]
        self._seq += 1
        call_id = f"call-{self._seq}"
        key = hashlib.sha256(
            f"{self.run_id}:{branch.branch_id}:{call_id}".encode()
        ).hexdigest()

        if spec.kind is ToolKind.READ_ONLY:
            return {"ok": True, "result": f"read({args})", "key": key}

        if not branch.committed:
            if spec.kind is ToolKind.NON_INVERTIBLE:
                raise SpeculativeEffectError(
                    f"branch {branch.branch_id} attempted non-invertible "
                    f"tool {tool!r} before commit; must use deferred execution"
                )
            # Invertible but speculative: record effect + compensator.
            branch.effects.append(
                EffectEntry(branch.branch_id, call_id, key, tool)
            )
        return {"ok": True, "result": f"exec({args})", "key": key}

    def commit(self, winner_id: str) -> Branch:
        for bid, b in self.branches.items():
            if bid != winner_id and b.effects:
                uncompensated = [e for e in b.effects if not e.compensated]
                if uncompensated:
                    raise SpeculativeEffectError(
                        f"cannot commit {winner_id!r}: loser {bid!r} has "
                        f"{len(uncompensated)} un-compensated effects"
                    )
        winner = self.branches[winner_id]
        winner.committed = True
        return winner

    def rollback(self, branch_id: str) -> None:
        b = self.branches[branch_id]
        for entry in reversed(b.effects):
            spec = self.manifest[entry.tool]
            if spec.compensator is None:
                raise SpeculativeEffectError(
                    f"no compensator for {entry.tool!r} on branch {branch_id}"
                )
            entry.compensated = True
        b.effects = [e for e in b.effects if not e.compensated]
