# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-optimistic-branch-and-verify-swarms-from-committing-side-effect-divergence-on-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-optimistic-branch-and-verify-swarms-from-committing-side-effect-divergence-on-rollback.warrant.json
# Markdown SHA-256:   1641437a39bae01018a06c3a891b5c93ea2698acc80752497bf55d6194a613f5
# Code AST SHA-256:   3c4bced57213868162745f222265d5ac8e9ae65fc4ece051ce739eb80a7f9089
# Verified Classes:   EffectDivergenceError, ToolRegistry, Branch
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class EffectDivergenceError(RuntimeError):
    """Raised when a branch attempts to commit or roll back effects it cannot account for."""
    pass


EFFECT_CLASSES = {"pure", "compensable", "irreversible"}


class ToolRegistry:
    def __init__(self):
        self._class = {}

    def register(self, name: str, effect_class: str):
        if effect_class not in EFFECT_CLASSES:
            raise EffectDivergenceError(f"unknown effect class {effect_class!r} for {name}")
        self._class[name] = effect_class

    def effect_class(self, name: str) -> str:
        # Untagged tools default to the most dangerous class, never to 'pure'.
        return self._class.get(name, "irreversible")


class Branch:
    def __init__(self, branch_id: str, registry: ToolRegistry):
        self.branch_id = branch_id
        self.registry = registry
        self.committed = False
        self.dispatched = []  # (tool, intent_id) for effects that left the process

    def pre_execute(self, tool: str, args: dict, commit_warrant: str | None):
        cls = self.registry.effect_class(tool)
        if cls == "irreversible" and not (commit_warrant and self.committed):
            # Optimism is illegal for irreversible effects without a commit warrant.
            raise EffectDivergenceError(
                f"branch {self.branch_id} attempted optimistic dispatch of "
                f"irreversible tool {tool!r} without a commit warrant"
            )
        intent_id = f"{self.branch_id}:{tool}:{len(self.dispatched)}"
        self.dispatched.append((tool, intent_id))
        return intent_id

    def rollback(self, compensation_ledger: dict):
        if self.committed:
            raise EffectDivergenceError(
                f"branch {self.branch_id} is committed; rollback would orphan committed effects"
            )
        for tool, intent_id in self.dispatched:
            cls = self.registry.effect_class(tool)
            if cls == "irreversible":
                raise EffectDivergenceError(
                    f"cannot roll back branch {self.branch_id}: irreversible effect "
                    f"{intent_id} already escaped; escalate to human reconciliation"
                )
            if intent_id not in compensation_ledger:
                raise EffectDivergenceError(
                    f"no registered compensation for {intent_id}; refusing state-only rollback"
                )
            compensation_ledger[intent_id]()  # apply inverse
        self.dispatched.clear()


def commit_branch(branch: Branch, warrant: str):
    if not warrant:
        raise EffectDivergenceError(f"branch {branch.branch_id} has no commit warrant")
    branch.committed = True
    return warrant
