# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-speculative-multi-agent-execution-with-branch-and-verify-rollback-and-parallel-tool-call-racing-draw-the-boundary-between-re.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-speculative-multi-agent-execution-with-branch-and-verify-rollback-and-parallel-tool-call-racing-draw-the-boundary-between-re.warrant.json
# Markdown SHA-256:   a224960f4132b64ca1c20018c63f7b616ad2ca9231b81875e1edd660b05f741d
# Code AST SHA-256:   329d23b448b5be3e8cf1b26180a97a88c21628777d1ee33fce4cacdea24710de
# Verified Classes:   SpeculationVisibilityError, ToolEmissionClass
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculationVisibilityError(RuntimeError):
    """Raised when a speculative branch issues a tool call whose side effect
    may become externally observable before rollback can be guaranteed."""
    pass


class ToolEmissionClass:
    STAGED = "staged"          # effect held until commit token
    CANCELLABLE = "cancellable"  # emitted only after explicit release
    LEAKY = "leaky"            # may emit before cancellation ack


def assert_speculation_safe(tool_name: str, emission_class: str, is_speculative: bool) -> None:
    if not is_speculative:
        return
    if emission_class == ToolEmissionClass.LEAKY:
        raise SpeculationVisibilityError(
            f"tool {tool_name!r} classified LEAKY cannot be invoked from a "
            f"speculative branch; serialize behind the verifier or stage the effect"
        )
    if emission_class not in (ToolEmissionClass.STAGED, ToolEmissionClass.CANCELLABLE):
        raise SpeculationVisibilityError(
            f"tool {tool_name!r} has unknown emission class {emission_class!r}; "
            f"default to LEAKY and do not speculate"
        )


def race_branches(branches, tool_name, emission_class):
    for branch in branches:
        assert_speculation_safe(tool_name, emission_class, is_speculative=True)
        branch.execute(tool_name)
    # verifier selects winner; losers roll back
    return branches[0]
