# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-arbitrate-speculative-fork-commit-abort-when-the-cost-signal-is-itself-a-noisy-lagged-estimate.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-arbitrate-speculative-fork-commit-abort-when-the-cost-signal-is-itself-a-noisy-lagged-estimate.warrant.json
# Markdown SHA-256:   33729d951becade3f33432a65fd9c304deb55aec9d11cb133f1ec811873c2754
# Code AST SHA-256:   d25bfe1a763fb8826403bcddc42fcb7940a51d9eb5618244ceff58cda5257c67
# Verified Classes:   StaleEstimateCommitError, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class StaleEstimateCommitError(RuntimeError):
    """Raised when a commit decision is attempted on a value estimate that is
    older than the freshness bound, or when a branch would cross the
    point-of-no-return without budget to finalize."""
    pass


class Branch:
    def __init__(self, branch_id, value_estimate, estimate_token_pos,
                 sunk_cost, finalization_cost):
        self.branch_id = branch_id
        self.value_estimate = value_estimate
        self.estimate_token_pos = estimate_token_pos
        self.sunk_cost = sunk_cost
        self.finalization_cost = finalization_cost


def arbitrate_commit(branch: Branch, current_token_pos: int,
                     remaining_budget: float, delta_max: int) -> str:
    """Return 'commit' or 'abort', or raise if the decision is unsafe to make
    on the available evidence."""
    staleness = current_token_pos - branch.estimate_token_pos

    if staleness > delta_max:
        # Cached estimate describes a branch that no longer exists.
        raise StaleEstimateCommitError(
            f"branch {branch.branch_id}: estimate is {staleness} tokens stale "
            f"(max {delta_max}); refresh verifier before committing"
        )

    total_commit_cost = branch.sunk_cost + branch.finalization_cost
    if total_commit_cost > remaining_budget:
        # Point of no return already crossed; abort is forced, but the
        # arbiter should never have let the branch emit this far.
        raise StaleEstimateCommitError(
            f"branch {branch.branch_id}: commit cost {total_commit_cost:.2f} "
            f"exceeds remaining budget {remaining_budget:.2f}; "
            f"branch should have been aborted at its soft ceiling"
        )

    marginal = branch.value_estimate - total_commit_cost
    return "commit" if marginal > 0 else "abort"


def run_arbiter(branches, current_token_pos, remaining_budget, delta_max):
    decisions = {}
    for b in branches:
        try:
            decisions[b.branch_id] = arbitrate_commit(
                b, current_token_pos, remaining_budget, delta_max
            )
        except StaleEstimateCommitError as exc:
            # Conservative fallback: defer, force a verifier refresh.
            decisions[b.branch_id] = f"defer:refresh ({exc})"
    return decisions
