# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-speculate-branch-and-verify-rollback-under-cost-aware-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-speculate-branch-and-verify-rollback-under-cost-aware-fan-out.warrant.json
# Markdown SHA-256:   4947c7eaba6e5698829e46ec6e2bb11064c94a964e7f5d04286f7949aa5a030b
# Code AST SHA-256:   a8cf28f657e4acdc01644d82a7278a1a42583d3b60a0fc902516f76d458178c9
# Verified Classes:   UnsafeSpeculationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnsafeSpeculationError(RuntimeError):
    """Raised when a branch is admitted to speculative fan-out but its
    effect boundary is not provably below its verification boundary."""


def admit_branch(branch, verifier, *, deferrable_tools: set[str]) -> None:
    """Gate a branch into speculative fan-out.

    Speculation is sound only if every tool the branch may invoke is either
    read-only or deferred until after verification. Unknown or effectful
    tools must be serialized, never speculated.
    """
    if not getattr(branch, "tools_declared", False):
        raise UnsafeSpeculationError(
            f"branch {branch.id!r} has undeclared tools; effect boundary unknown"
        )

    for tool in branch.tools:
        if tool.is_read_only:
            continue
        if tool.name in deferrable_tools and tool.supports_deferral:
            continue
        raise UnsafeSpeculationError(
            f"branch {branch.id!r} may invoke effectful tool {tool.name!r} "
            f"before verification; serialize instead of speculating"
        )

    if not verifier.decides_on_proposal_only:
        raise UnsafeSpeculationError(
            f"verifier for branch {branch.id!r} inspects committed effects; "
            f"verification boundary is not above effect boundary"
        )
