# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-branch-divergence-before-an-optimistic-tool-side-effect-becomes-irreversible.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-branch-divergence-before-an-optimistic-tool-side-effect-becomes-irreversible.warrant.json
# Markdown SHA-256:   ced6a5c3d5b5f7f7c1990d10a425e8f307dcc9c7defecd25038de69dc36b1835
# Code AST SHA-256:   f0d87d9c97293cd6c9ac0f8c38863017c6d9fc88c03270736fca978676c5fde0
# Verified Classes:   IrreversibleSpeculationError, ToolContract
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ToolContract:
    def __init__(self, name: str, reversible: bool, compensable: bool, annotated: bool):
        self.name = name
        self.reversible = reversible
        self.compensable = compensable
        self.annotated = annotated


def dispatch_speculative(branch_id: str, tool: ToolContract, args: dict,
                         merge_committed: bool, effect_log: list) -> dict:
    # Fail-closed: an unannotated tool is treated as irreversible.
    if not tool.annotated:
        if not merge_committed:
            raise IrreversibleSpeculationError(
                f"branch {branch_id}: tool '{tool.name}' has no reversibility "
                f"annotation; refusing optimistic invocation without merge commit"
            )
    elif not tool.reversible and not merge_committed:
        raise IrreversibleSpeculationError(
            f"branch {branch_id}: tool '{tool.name}' is irreversible and branch "
            f"is not merge-committed; speculation would leak a ghost effect"
        )

    result = _invoke(tool.name, args)  # external side effect happens here
    if tool.compensable:
        effect_log.append({
            "branch": branch_id,
            "tool": tool.name,
            "compensation": _make_compensation(tool.name, result),
        })
    return result


def rollback_branch(branch_id: str, effect_log: list) -> None:
    # Effect-aware rollback: replay compensations in reverse before discarding.
    branch_effects = [e for e in effect_log if e["branch"] == branch_id]
    for effect in reversed(branch_effects):
        if effect["compensation"] is None:
            raise IrreversibleSpeculationError(
                f"branch {branch_id}: cannot roll back '{effect['tool']}' — "
                f"no compensation handle was recorded at invocation time"
            )
        _apply(effect["compensation"])
    effect_log[:] = [e for e in effect_log if e["branch"] != branch_id]


def _invoke(name, args):
    return {"id": 8842}

def _make_compensation(name, result):
    return ("delete", result["id"])

def _apply(comp):
    pass
