# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-a-speculative-branch-be-forbidden-from-emitting-externally-observable-side-effects-and-what-breaks-when-the-rollback-boundar.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-a-speculative-branch-be-forbidden-from-emitting-externally-observable-side-effects-and-what-breaks-when-the-rollback-boundar.warrant.json
# Markdown SHA-256:   33f60e3ba5e5f537a1d32070946446ec01d53e1a623b3daeef514af7a6d9f9b7
# Code AST SHA-256:   b8e9a2506027711a96aee23231fa870bd59da6dd70fc5645848e3ee24ae11dd7
# Verified Classes:   SpeculationBoundaryError, ToolCall
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SpeculationBoundaryError(RuntimeError):
    """Raised when a speculative branch attempts an effect outside the rollback boundary."""
    pass


class ToolCall:
    def __init__(self, name, payload, externally_observable, compensable, stageable):
        self.name = name
        self.payload = payload
        self.externally_observable = externally_observable
        self.compensable = compensable
        self.stageable = stageable


def dispatch(branch, call, orchestrator):
    # Non-observable calls are inside the rollback boundary by construction.
    if not call.externally_observable:
        return orchestrator.execute(call)

    if branch.committed:
        return orchestrator.execute(call)

    # Speculative branch from here on.
    if call.compensable:
        # Register compensation BEFORE dispatch; a crash after dispatch
        # but before registration leaves an uncompensated effect.
        orchestrator.register_compensation(branch.token, call)
        return orchestrator.execute(call)

    if call.stageable:
        return orchestrator.stage(branch.token, call)

    raise SpeculationBoundaryError(
        f"branch {branch.token!r} attempted non-compensable, non-stageable "
        f"external effect {call.name!r}; defer to commit phase or forbid"
    )
