# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-handle-bid-sniping-inversions-in-contract-net-auctions-when-latency-budgets-compress-the-award-window-below-one-round-trip.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-handle-bid-sniping-inversions-in-contract-net-auctions-when-latency-budgets-compress-the-award-window-below-one-round-trip.warrant.json
# Markdown SHA-256:   d505b7ef1f5b6d4018c6467476adec2711d0e09145504016e0ccfb528d8678c6
# Code AST SHA-256:   e50c0fceab9721a15b410d27888e4594019d5cd7260bac4334bf08ac1943f04d
# Verified Classes:   UnsoundAuctionWindow, Bid, AuctionResult
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class UnsoundAuctionWindow(RuntimeError):
    """Raised when the award window cannot cover the bidder population's
    decision horizon and the required safety mechanisms are disabled."""
    pass


@dataclass
class Bid:
    bidder: str
    cost: Optional[float]          # None => negative bid (abstention)
    lower_bound: Optional[float]   # known achievable cost if it could commit
    send_time: float               # monotonic clock at initiator on receipt
    negative: bool = False


@dataclass
class AuctionResult:
    winner: Optional[str]
    cost: Optional[float]
    received: list
    excluded: list
    provisional: bool
    reason: str


def run_auction(
    eligible: list,
    bids: list,
    t_call: float,
    t_award: float,
    observed_bid_latency_p99: float,
    negative_bids_enabled: bool,
    provisional_awards_enabled: bool,
) -> AuctionResult:
    received = [b for b in bids if b.send_time <= t_award]
    late = [b for b in bids if b.send_time > t_award]
    excluded = [b.bidder for b in late]
    silent = [e for e in eligible if e not in {b.bidder for b in bids}]
    excluded.extend(silent)

    window = t_award - t_call
    if window < observed_bid_latency_p99:
        if not negative_bids_enabled or not provisional_awards_enabled:
            raise UnsoundAuctionWindow(
                f"window={window:.0f}ms < p99 bid latency={observed_bid_latency_p99:.0f}ms "
                f"and negative_bids={negative_bids_enabled} "
                f"provisional={provisional_awards_enabled}; "
                f"argmin over {len(received)}/{len(eligible)} bidders is biased"
            )

    # Negative bids carry lower bounds; a late positive bid is a negative bid
    # with an unknown lower bound, which cannot dominate the current award.
    candidates = [b for b in received if not b.negative and b.cost is not None]
    if not candidates:
        return AuctionResult(None, None, received, excluded, True,
                             "no viable positive bids within window")

    best = min(candidates, key=lambda b: b.cost)

    # A negative bid with a lower bound strictly below the award cost proves
    # the award is not the true argmin; the award must be provisional.
    dominated_by_negative = any(
        b.negative and b.lower_bound is not None and b.lower_bound < best.cost
        for b in received
    )
    dominated_by_late = any(
        b.lower_bound is not None and b.lower_bound < best.cost for b in late
    )
    provisional = dominated_by_negative or dominated_by_late or bool(silent)

    reason = "clean"
    if dominated_by_late:
        reason = f"late bidder {late[0].bidder} lower_bound={late[0].lower_bound} < award={best.cost}"
    elif dominated_by_negative:
        reason = "negative bid lower bound undercuts award"
    elif silent:
        reason = f"silent bidders {silent} — exclusion unproven"

    return AuctionResult(best.bidder, best.cost, received, excluded,
                         provisional, reason)
