# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-merge-from-resurrecting-rolled-back-tool-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-merge-from-resurrecting-rolled-back-tool-effects.warrant.json
# Markdown SHA-256:   ea946474401da0dcdb2345570b340017b375d77286d08e6c99077c8c34614a07
# Code AST SHA-256:   c85abc6059eb5e5cf34dbd5b6a2e8893bf37b6fd846ad27917cd8833880d6fda
# Verified Classes:   EffectClass, IrreversibleInSpeculativeBranch, QuiesceTimeout, EffectEntry, ToolRegistry, Branch, Orchestrator
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Any


class EffectClass(Enum):
    BRANCH_REVERSIBLE = "branch_reversible"
    RESOURCE_REVERSIBLE = "resource_reversible"
    IRREVERSIBLE = "irreversible"


class IrreversibleInSpeculativeBranch(RuntimeError):
    """Raised when a speculative branch attempts an irreversible tool call."""


class QuiesceTimeout(RuntimeError):
    """Raised when a branch cannot be drained before commit."""


@dataclass
class EffectEntry:
    branch_id: str
    resource: str
    prior_value: Any
    new_value: Any
    seq: int


@dataclass
class ToolRegistry:
    classes: dict[str, EffectClass] = field(default_factory=dict)

    def register(self, name: str, cls: EffectClass) -> None:
        self.classes[name] = cls

    def class_of(self, name: str) -> EffectClass:
        if name not in self.classes:
            raise KeyError(f"unregistered tool: {name}")
        return self.classes[name]


@dataclass
class Branch:
    branch_id: str
    speculative: bool
    effect_log: list[EffectEntry] = field(default_factory=list)
    in_flight: int = 0
    cancelled: bool = False


class Orchestrator:
    def __init__(self, registry: ToolRegistry) -> None:
        self.registry = registry
        self.world: dict[str, Any] = {}
        self._seq = 0

    def call_tool(self, branch: Branch, tool: str, resource: str,
                  new_value: Any) -> None:
        cls = self.registry.class_of(tool)
        if branch.speculative and cls is EffectClass.IRREVERSIBLE:
            # Hard boundary: irreversible effects never run speculatively.
            raise IrreversibleInSpeculativeBranch(
                f"branch {branch.branch_id} attempted irreversible tool "
                f"{tool!r} on {resource!r} while speculative"
            )
        if branch.cancelled:
            raise IrreversibleInSpeculativeBranch(
                f"branch {branch.branch_id} cancelled; refusing {tool!r}"
            )
        branch.in_flight += 1
        try:
            prior = self.world.get(resource)
            self._seq += 1
            self.world[resource] = new_value
            branch.effect_log.append(
                EffectEntry(branch.branch_id, resource, prior, new_value,
                            self._seq)
            )
        finally:
            branch.in_flight -= 1

    def rollback(self, branch: Branch) -> None:
        for entry in reversed(branch.effect_log):
            current = self.world.get(entry.resource)
            if current != entry.new_value:
                # Superseded by another branch; do not clobber.
                raise IrreversibleInSpeculativeBranch(
                    f"cannot roll back {entry.resource!r}: superseded "
                    f"(expected {entry.new_value!r}, found {current!r})"
                )
            self.world[entry.resource] = entry.prior_value
        branch.effect_log.clear()

    def quiesce(self, branches: list[Branch], timeout_s: float) -> None:
        import time
        deadline = time.monotonic() + timeout_s
        for b in branches:
            b.cancelled = True
        while any(b.in_flight > 0 for b in branches):
            if time.monotonic() > deadline:
                stuck = [b.branch_id for b in branches if b.in_flight > 0]
                raise QuiesceTimeout(f"branches still in flight: {stuck}")
            time.sleep(0.01)

    def commit(self, winner: Branch, losers: list[Branch]) -> None:
        # Invariant: quiesce before commit; rollback losers; only then
        # execute the winner's deferred irreversible actions.
        self.quiesce(losers + [winner], timeout_s=5.0)
        for loser in losers:
            self.rollback(loser)
        # Winner's irreversible actions run here, serially, non-speculative.
        winner.speculative = False
