# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cost-aware-speculative-agents-from-committing-side-effects-under-consensus-gated-budgets.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cost-aware-speculative-agents-from-committing-side-effects-under-consensus-gated-budgets.warrant.json
# Markdown SHA-256:   9201bee80c667c570dcf17d73c3891130bc608ccf5cda164935be111cecd9d2b
# Code AST SHA-256:   e9997d77167315331f1c8ead988a198aefd6e73991dd762598c9ec2af71fe445
# Verified Classes:   InsufficientBallotError, PrunedBranchCommitError, Branch, ConsensusGate, Scheduler
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Sequence


class InsufficientBallotError(RuntimeError):
    """Raised when a consensus gate is asked to authorize a commit
    over a ballot smaller than its quorum. Cost pruning must never
    be allowed to shrink the ballot below quorum and then pass."""


class PrunedBranchCommitError(RuntimeError):
    """Raised when a branch pruned for cost appears in the commit set."""


@dataclass
class Branch:
    id: str
    score: float
    pruned_for_cost: bool = False


@dataclass
class ConsensusGate:
    quorum: int

    def authorize(self, ballot: Sequence[Branch]) -> bool:
        if len(ballot) < self.quorum:
            raise InsufficientBallotError(
                f"ballot size {len(ballot)} < quorum {self.quorum}; "
                "budget pruning cannot substitute for consensus"
            )
        return all(b.score > 0 for b in ballot)


@dataclass
class Scheduler:
    gate: ConsensusGate
    budget_remaining: int
    frontier: list[Branch] = field(default_factory=list)

    def try_commit(self, candidate: Branch) -> bool:
        if candidate.pruned_for_cost:
            raise PrunedBranchCommitError(
                f"branch {candidate.id} was pruned for cost and must not commit"
            )
        if self.budget_remaining <= 0 and len(self.frontier) < self.gate.quorum:
            raise InsufficientBallotError(
                f"budget exhausted with frontier size {len(self.frontier)} "
                f"< quorum {self.gate.quorum}; abort, do not promote"
            )
        return self.gate.authorize(self.frontier)


# Example: budget exhaustion collapses the frontier to a singleton.
gate = ConsensusGate(quorum=2)
sched = Scheduler(gate=gate, budget_remaining=0, frontier=[Branch("B", 0.9)])
sched.try_commit(Branch("B", 0.9))  # raises InsufficientBallotError
