# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-plan-branch-before-commit-cost-bounded-multi-agent-planning-and-the-phantom-budget-divergence.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-plan-branch-before-commit-cost-bounded-multi-agent-planning-and-the-phantom-budget-divergence.warrant.json
# Markdown SHA-256:   b550200aca44fed0eb1cc6ca60acf5c51bd39618cfb17f5f4bef52688b7cabfe
# Code AST SHA-256:   aff58f7318774c44f99d22b404140b282ff2667996fd51c394b9920a4fc0f374
# Verified Classes:   PhantomBudgetDivergence, Ledger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class PhantomBudgetDivergence(RuntimeError):
    """Raised when a commit decision is based on a planner-local budget
    that diverges from the authoritative ledger."""
    pass


class Ledger:
    def __init__(self, total: int):
        self.total = total
        self.reserved = 0
        self.consumed = 0

    def remaining(self) -> int:
        return self.total - self.reserved - self.consumed

    def reserve(self, amount: int) -> None:
        if amount > self.remaining():
            raise PhantomBudgetDivergence(
                f"reservation {amount} exceeds remaining {self.remaining()}"
            )
        self.reserved += amount

    def release(self, amount: int) -> None:
        self.reserved = max(0, self.reserved - amount)

    def debit(self, amount: int) -> None:
        self.consumed += amount
        self.reserved = max(0, self.reserved - amount)


SAFETY_FACTOR = 2.1  # empirical right-tail ratio from observed traces


def admissible_width(ledger: Ledger, max_estimate: int) -> int:
    per_branch = int(max_estimate * SAFETY_FACTOR)
    if per_branch <= 0:
        return 0
    return ledger.remaining() // per_branch


def commit_branch(ledger: Ledger, planner_remaining: int, branch_ceiling: int) -> None:
    """Gate: the planner's own remaining-budget figure is advisory only.
    If it disagrees with the ledger, the planner has diverged and the
    commit must be refused."""
    actual = ledger.remaining()
    if planner_remaining != actual:
        raise PhantomBudgetDivergence(
            f"planner believes remaining={planner_remaining}, "
            f"ledger says {actual}; refusing commit"
        )
    if branch_ceiling > actual:
        raise PhantomBudgetDivergence(
            f"branch ceiling {branch_ceiling} exceeds ledger remaining {actual}"
        )
    ledger.debit(branch_ceiling)


def plan(ledger: Ledger, estimates: list[int]) -> None:
    max_est = max(estimates)
    width = admissible_width(ledger, max_est)
    if len(estimates) > width:
        raise PhantomBudgetDivergence(
            f"fan-out width {len(estimates)} exceeds admissible {width} "
            f"under safety factor {SAFETY_FACTOR}"
        )
    for est in estimates:
        ledger.reserve(int(est * SAFETY_FACTOR))
