# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-cost-aware-sla-handoff-when-the-peer-s-advertised-price-curve-is-non-monotone-across-the-requested-batch-w.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-cost-aware-sla-handoff-when-the-peer-s-advertised-price-curve-is-non-monotone-across-the-requested-batch-w.warrant.json
# Markdown SHA-256:   71cfe82f7ae01a16b2c462de6b22d9c294b072cf7756eb49f2ae2f901e730168
# Code AST SHA-256:   105b4fcae8bcaa97bb5e3ef9f25b309bb47dbed758570547834770a72c01e4bf
# Verified Classes:   NonMonotonePriceCurveError, Probe, SlaOffer
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Callable, Sequence


class NonMonotonePriceCurveError(RuntimeError):
    """Raised when a delegating agent is asked to commit to a batch size
    whose price curve has not been adequately probed for tier inversions."""


@dataclass(frozen=True)
class Probe:
    n: int
    total_price: float

    @property
    def unit_price(self) -> float:
        if self.n <= 0:
            raise NonMonotonePriceCurveError(f"invalid probe size n={self.n}")
        return self.total_price / self.n


@dataclass(frozen=True)
class SlaOffer:
    peer_id: str
    price_fn: Callable[[int], float]
    declared_tier_granularity: int | None  # None => peer withheld granularity


def assert_commitment_safe(
    offer: SlaOffer,
    probes: Sequence[Probe],
    requested_n: int,
) -> None:
    """Guardrail: refuse to commit unless every gap between adjacent probes
    is narrower than the peer's declared tier granularity, and no per-unit
    inversion exists across the probed range."""
    if len(probes) < 2:
        raise NonMonotonePriceCurveError(
            f"peer {offer.peer_id}: fewer than 2 probes; curve structure unknown"
        )

    ordered = sorted(probes, key=lambda p: p.n)

    # 1. Per-unit inversion check: any n_i < n_j with unit(n_j) > unit(n_i)
    #    is the signature of a non-monotone tier the planner would miss.
    for i in range(len(ordered) - 1):
        a, b = ordered[i], ordered[i + 1]
        if b.unit_price > a.unit_price + 1e-12:
            raise NonMonotonePriceCurveError(
                f"peer {offer.peer_id}: per-unit inversion between n={a.n} "
                f"({a.unit_price:.4f}) and n={b.n} ({b.unit_price:.4f}); "
                f"planner would interpolate across a surcharge tier"
            )

    # 2. Granularity check: a gap wider than the declared tier size can hide
    #    an unsampled boundary, so commitment inside it is unsound.
    if offer.declared_tier_granularity is None:
        raise NonMonotonePriceCurveError(
            f"peer {offer.peer_id}: no tier granularity declared; "
            f"cannot bound unsampled structure"
        )
    for i in range(len(ordered) - 1):
        gap = ordered[i + 1].n - ordered[i].n
        if gap > offer.declared_tier_granularity:
            raise NonMonotonePriceCurveError(
                f"peer {offer.peer_id}: probe gap {ordered[i].n}->{ordered[i+1].n} "
                f"({gap}) exceeds declared granularity "
                f"{offer.declared_tier_granularity}; boundary may be hidden"
            )

    # 3. The requested commitment must fall on or below the last confirmed
    #    favorable probe; committing above it is an unverified extrapolation.
    if requested_n > ordered[-1].n:
        raise NonMonotonePriceCurveError(
            f"peer {offer.peer_id}: requested n={requested_n} exceeds "
            f"highest probe n={ordered[-1].n}; extrapolation unsound"
        )


def negotiate(
    offer: SlaOffer,
    probes: Sequence[Probe],
    requested_n: int,
) -> int:
    """Return the safe commitment size, shrinking to the highest probed n
    on the favorable side of the last confirmed boundary if the guardrail fires."""
    try:
        assert_commitment_safe(offer, probes, requested_n)
        return requested_n
    except NonMonotonePriceCurveError:
        # Fall back to the largest probed size at or below the request.
        safe = max((p.n for p in probes if p.n <= requested_n), default=None)
        if safe is None:
            raise NonMonotonePriceCurveError(
                f"peer {offer.peer_id}: no safe commitment available; "
                f"renegotiation required before delegation"
            )
        return safe
