# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-bid-validity-divergence-in-contract-net-award-races-before-committing-a-task-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-bid-validity-divergence-in-contract-net-award-races-before-committing-a-task-warrant.warrant.json
# Markdown SHA-256:   94e63741238445cf0a3dc4cb01d4cb0c158f297af5898600d5aec528648f49cd
# Code AST SHA-256:   e06d2465e5e2ea013bc031dfb930bb3d516ced092246f8201c04d1614c1cf35d
# Verified Classes:   BidDivergenceError, Bid, Attestation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass
from typing import Optional


class BidDivergenceError(RuntimeError):
    """Raised when a bid's preconditions no longer hold at award time."""
    pass


@dataclass
class Bid:
    bid_id: str
    task_id: str
    bidder: str
    cost_estimate: float
    ledger_hash_at_bid: str
    ttl_ms: int
    issued_at: float


@dataclass
class Attestation:
    bid_id: str
    bidder: str
    ledger_hash_now: str
    reservations: tuple
    signed_at: float


def _feasible(attestation: Attestation, bid: Bid) -> bool:
    # Feasibility requires the attested ledger to still contain the
    # reservations implied by the bid's cost estimate. A ledger hash
    # mismatch alone is not failure (append-only ledgers legitimately
    # change); the failure is a missing reservation.
    required_slots = int(bid.cost_estimate)
    return len(attestation.reservations) >= required_slots


def award_task(
    bid: Bid,
    attestation: Optional[Attestation],
    attestation_ttl_ms: int = 150,
) -> str:
    now = time.monotonic() * 1000.0

    if attestation is None:
        raise BidDivergenceError(
            f"award refused for bid {bid.bid_id}: no fresh attestation; "
            f"bid snapshot alone is unsound under reservation release"
        )

    if attestation.bid_id != bid.bid_id or attestation.bidder != bid.bidder:
        raise BidDivergenceError(
            f"attestation identity mismatch for bid {bid.bid_id}"
        )

    if (now - attestation.signed_at) > attestation_ttl_ms:
        raise BidDivergenceError(
            f"attestation for bid {bid.bid_id} stale "
            f"({now - attestation.signed_at:.1f}ms > {attestation_ttl_ms}ms)"
        )

    if not _feasible(attestation, bid):
        raise BidDivergenceError(
            f"bid {bid.bid_id} diverged: attested reservations "
            f"{len(attestation.reservations)} < required "
            f"{int(bid.cost_estimate)}; bidder {bid.bidder} released slots "
            f"between bid and award"
        )

    warrant = hashlib.sha256(
        f"{bid.bid_id}:{attestation.ledger_hash_now}".encode()
    ).hexdigest()
    return warrant


def award_round(
    ranked_bids: list,
    attestations: dict,
    attestation_ttl_ms: int = 150,
) -> dict:
    awards = {}
    diverged_bidders = set()
    for bid in ranked_bids:
        if bid.bidder in diverged_bidders:
            continue
        att = attestations.get(bid.bid_id)
        try:
            awards[bid.task_id] = award_task(bid, att, attestation_ttl_ms)
        except BidDivergenceError:
            diverged_bidders.add(bid.bidder)
            continue
    return awards
