# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-speculative-branch-exploration-before-committing-a-plan-the-speculative-budget-shadow-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-speculative-branch-exploration-before-committing-a-plan-the-speculative-budget-shadow-invariant.warrant.json
# Markdown SHA-256:   e324749fdbc1f69d03b04c24fe83485cb9f35ffaabe47568515af17ae53378c8
# Code AST SHA-256:   eca8321799a40ae451951ac65d8c94d7891ff1f15ecb1493a85f0788c6ae2366
# Verified Classes:   SpeculativeBudgetShadowError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SpeculativeBudgetShadowError(RuntimeError):
    """Raised when committing a branch would violate the speculative-budget shadow invariant."""
    pass


def select_and_commit(
    branches,
    total_token_budget,
    total_latency_ms,
    committed_spec_tokens,
    committed_spec_ms,
    retained_provenance_tokens,
    tail_multiple=1.3,
):
    """
    branches: list of dicts with keys
        id, spec_tokens, spec_ms, est_exec_tokens, est_exec_ms,
        sigma_exec_tokens, sigma_exec_ms, explored_depth
    Returns the id of the branch to commit, or raises.
    """
    remaining_tokens = total_token_budget - committed_spec_tokens - retained_provenance_tokens
    remaining_ms = total_latency_ms - committed_spec_ms

    feasible = []
    for b in branches:
        # Inflate variance for shallowly explored branches: their estimates look
        # cheap but are low-confidence. explored_depth in [0,1].
        confidence = max(b["explored_depth"], 0.1)
        sigma_tok = b["sigma_exec_tokens"] / confidence
        sigma_ms = b["sigma_exec_ms"] / confidence

        need_tok = b["est_exec_tokens"] + tail_multiple * sigma_tok
        need_ms = b["est_exec_ms"] + tail_multiple * sigma_ms

        if need_tok <= remaining_tokens and need_ms <= remaining_ms:
            feasible.append((need_tok, need_ms, b["id"]))

    if not feasible:
        raise SpeculativeBudgetShadowError(
            f"No surviving branch satisfies the shadow invariant: "
            f"remaining_tokens={remaining_tokens}, remaining_ms={remaining_ms}, "
            f"committed_spec_tokens={committed_spec_tokens}, "
            f"retained_provenance_tokens={retained_provenance_tokens}. "
            f"Refusing to commit; truncation mid-execution is unrecoverable."
        )

    feasible.sort(key=lambda x: (x[0], x[1]))
    return feasible[0][2]
