# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-speculative-branch-fan-out-when-a-consensus-gated-commit-s-quorum-cost-exceeds-the-marginal-value-of-the-spec.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-speculative-branch-fan-out-when-a-consensus-gated-commit-s-quorum-cost-exceeds-the-marginal-value-of-the-spec.warrant.json
# Markdown SHA-256:   a162861a0a69e3cf869c0729f6d5c1569957dc1ed10958294e854a229a774ced
# Code AST SHA-256:   6ac46bc0832640995dfdaa4517ec69ebc668369d72eebf7eb0ab593acef39ae4
# Verified Classes:   QuorumInfeasibleError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class QuorumInfeasibleError(RuntimeError):
    """Raised when speculative fan-out has produced more divergent
    commit-relevant states than the consensus gate can converge on
    within the reserved quorum budget."""
    pass


def should_spawn_branch(
    live_branches: int,
    distinct_hashes: int,
    quorum_size: int,
    dissent_slack: int,
    branch_cost: float,
    quorum_cost_estimate: float,
    expected_hedge_value: float,
    budget_remaining: float,
) -> bool:
    # Convergence capacity: how many distinct candidate states the gate
    # can adjudicate before it can no longer reach threshold.
    max_adjudicable = quorum_size - dissent_slack

    if distinct_hashes >= max_adjudicable:
        # The gate already faces too many divergent states; another branch
        # cannot converge and will only inflate quorum cost.
        raise QuorumInfeasibleError(
            f"distinct_hashes={distinct_hashes} >= max_adjudicable="
            f"{max_adjudicable}; fan-out would deadlock the gate"
        )

    # Marginal quorum cost induced by one more divergent branch.
    marginal_quorum = quorum_cost_estimate * (1 + live_branches) / max(1, live_branches)
    reserved = quorum_cost_estimate * 2  # reserve for one reconcile re-run

    if budget_remaining - branch_cost - reserved <= 0:
        raise QuorumInfeasibleError(
            f"budget_remaining={budget_remaining:.0f} cannot cover "
            f"branch_cost={branch_cost:.0f} plus reserved quorum={reserved:.0f}"
        )

    marginal_value = expected_hedge_value - branch_cost - marginal_quorum
    return marginal_value > 0
