# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-contract-net-bid-it-cannot-settle-the-escrowed-budget-overcommitment-boundary-in-auction-based-agent-task-allocation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-contract-net-bid-it-cannot-settle-the-escrowed-budget-overcommitment-boundary-in-auction-based-agent-task-allocation.warrant.json
# Markdown SHA-256:   9e0bf7e290f5a00094d67f6c634d10cbee1f8c518194154bcd77981739447bb3
# Code AST SHA-256:   13c7f19dcfe67ebaec52466745aef6bea816936b414e468799785cce76d9863b
# Verified Classes:   CapacityExceeded, ReservationUnderSpecified, ReservationVector, Bidder
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict


class CapacityExceeded(RuntimeError):
    """Raised when an award-confirm would violate a binding resource constraint."""
    pass


class ReservationUnderSpecified(RuntimeError):
    """Raised when a bidder emits a bid without reserving all binding dimensions."""
    pass


@dataclass
class ReservationVector:
    cost: float = 0.0
    latency: float = 0.0
    slots: int = 0
    rate_tokens: int = 0

    def __add__(self, other: "ReservationVector") -> "ReservationVector":
        return ReservationVector(
            cost=self.cost + other.cost,
            latency=self.latency + other.latency,
            slots=self.slots + other.slots,
            rate_tokens=self.rate_tokens + other.rate_tokens,
        )

    def exceeds(self, cap: "ReservationVector") -> bool:
        return (
            self.cost > cap.cost
            or self.latency > cap.latency
            or self.slots > cap.slots
            or self.rate_tokens > cap.rate_tokens
        )


@dataclass
class Bidder:
    capacity: ReservationVector
    committed: ReservationVector = field(default_factory=ReservationVector)
    soft_reserved: Dict[str, ReservationVector] = field(default_factory=dict)

    def bid(self, bid_id: str, reserve: ReservationVector) -> None:
        # Phase 1: reserve every binding dimension, not just cost.
        if reserve.slots == 0 or reserve.latency == 0.0:
            raise ReservationUnderSpecified(
                f"bid {bid_id} reserves cost={reserve.cost} but not slots/latency; "
                "capacity overcommitment is unbounded"
            )
        projected = self.committed
        for r in self.soft_reserved.values():
            projected = projected + r
        projected = projected + reserve
        if projected.exceeds(self.capacity):
            # Abstain from the CFP rather than emit an unsettleable bid.
            return
        self.soft_reserved[bid_id] = reserve

    def confirm_award(self, bid_id: str) -> None:
        # Phase 2: settlement gate. Re-validate against current committed state.
        reserve = self.soft_reserved.pop(bid_id, None)
        if reserve is None:
            raise CapacityExceeded(f"award {bid_id} has no matching soft reservation")
        projected = self.committed + reserve
        if projected.exceeds(self.capacity):
            raise CapacityExceeded(
                f"award {bid_id} would commit {projected} against capacity {self.capacity}"
            )
        self.committed = projected

    def release_soft(self) -> None:
        # Collection window closed; unconfirmed bids release their soft claims.
        self.soft_reserved.clear()


def simulate_incremental_award_window() -> None:
    b = Bidder(capacity=ReservationVector(cost=100, latency=4.0, slots=2, rate_tokens=1000))
    bid_vec = ReservationVector(cost=12, latency=2.1, slots=1, rate_tokens=100)

    # Three concurrent bids in one collection window. The third must abstain:
    # 3 slots > 2-slot capacity, even though 36 cost <= 100 budget.
    for i in range(3):
        b.bid(f"T{i+1}", bid_vec)

    if len(b.soft_reserved) != 2:
        raise CapacityExceeded(
            f"expected 2 settleable bids, got {len(b.soft_reserved)}; "
            "capacity gate is not bounding concurrent bid emission"
        )

    # Confirm both. A third confirm must fail loudly, not silently queue.
    b.confirm_award("T1")
    b.confirm_award("T2")
    try:
        b.confirm_award("T3")
    except CapacityExceeded:
        return
    raise CapacityExceeded("T3 settled despite exhausted slot capacity")


if __name__ == "__main__":
    simulate_incremental_award_window()
