# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-bid-shading-drift-when-a-multi-agent-budget-auction-converges-on-a-stale-reserve-price.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-bid-shading-drift-when-a-multi-agent-budget-auction-converges-on-a-stale-reserve-price.warrant.json
# Markdown SHA-256:   371a75c319914ec2842f37f45abeb6e2412136c4643ee00434f6856a973e3d9d
# Code AST SHA-256:   489fcda33d257b766ba7c8b1a167a7f3df0d5009b0e31c47f781d82a641566e4
# Verified Classes:   StaleReserveConvergenceError, Round
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import statistics
from dataclasses import dataclass


class StaleReserveConvergenceError(RuntimeError):
    """Raised when an auction's convergence certificate is circular:
    the reserve and the bids converged together because bids were anchored
    to the prior reserve, not because valuations reached equilibrium."""
    pass


@dataclass
class Round:
    reserve: float          # reserve published at start of this round
    bids: list[float]       # bids submitted this round
    cleared_total: float    # sum of allocations granted
    budget: float           # total shared budget
    true_valuations: list[float]  # allocator's private estimate of real need


def detect_stale_reserve(
    rounds: list[Round],
    delta_reserve: float = 0.05,
    delta_bids: float = 0.05,
    delta_anchor: float = 0.10,
    stranded_frac: float = 0.90,
    starvation_ratio: float = 2.0,
) -> bool:
    """Return True iff the convergence is a stale fixed point (invalid)."""
    if len(rounds) < 2:
        return False
    prev, cur = rounds[-2], rounds[-1]

    reserve_stable = (
        abs(cur.reserve - prev.reserve) / max(prev.reserve, 1e-9) < delta_reserve
    )
    med_prev = statistics.median(prev.bids)
    med_cur = statistics.median(cur.bids)
    bids_stable = abs(med_cur - med_prev) / max(med_prev, 1e-9) < delta_bids

    anchored = all(
        abs(b - prev.reserve) / max(prev.reserve, 1e-9) < delta_anchor
        for b in cur.bids
    )

    stranded = cur.cleared_total < stranded_frac * cur.budget
    clearing_price = cur.cleared_total / max(len(cur.bids), 1)
    starved = any(v > starvation_ratio * clearing_price for v in cur.true_valuations)

    return reserve_stable and bids_stable and anchored and (stranded or starved)


def validate_auction(rounds: list[Round]) -> None:
    if detect_stale_reserve(rounds):
        cur = rounds[-1]
        raise StaleReserveConvergenceError(
            f"Auction converged to a stale fixed point: reserve={cur.reserve:.1f}, "
            f"cleared={cur.cleared_total:.1f}/{cur.budget:.1f}, "
            f"all bids within {100 * 0.10:.0f}% of prior reserve. "
            "Reject clearing; recompute reserve from budget ledger and "
            "re-elicit truthful valuations."
        )
    # Convergence accepted.


if __name__ == "__main__":
    # The observed failure trace from the article.
    trace = [
        Round(reserve=28_000, bids=[40_000, 35_000, 30_000, 25_000],
              cleared_total=100_000, budget=100_000,
              true_valuations=[40_000, 35_000, 30_000, 25_000]),
        Round(reserve=22_700, bids=[29_000, 28_500, 28_200, 28_100],
              cleared_total=100_000, budget=100_000,
              true_valuations=[40_000, 35_000, 30_000, 25_000]),
        Round(reserve=16_000, bids=[17_000, 17_000, 17_000, 17_000],
              cleared_total=68_000, budget=100_000,
              true_valuations=[40_000, 35_000, 30_000, 25_000]),
    ]
    validate_auction(trace)  # raises StaleReserveConvergenceError
