# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-its-cost-model-mid-episode-routing-hysteresis-collapse-at-the-sla-cliff.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-its-cost-model-mid-episode-routing-hysteresis-collapse-at-the-sla-cliff.warrant.json
# Markdown SHA-256:   dac848198b477324f94785319dd3ffca2ef4ebba146aa004c535d850aa418c4c
# Code AST SHA-256:   98d294c259d352bc1d29ebbe6896f92cfccd056b2a5faaea79f48c0eb85e52c5
# Verified Classes:   BudgetInvariantViolation, RouterState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class BudgetInvariantViolation(RuntimeError):
    """Raised when a routing decision would spend budget the episode cannot recover."""
    pass


@dataclass
class RouterState:
    tokens_in: int
    remaining_budget: float
    steps_remaining: int
    sla_ms: int


def cost_at(model, tokens_in: int) -> float:
    # Cost is monotone in context length; the bucket key is NOT the estimate.
    return model.price_per_1k * (tokens_in / 1000.0)


def latency_at(model, tokens_in: int) -> int:
    return model.base_latency_ms + int(model.prefill_ms_per_1k * (tokens_in / 1000.0))


def authorize_escalation(state: RouterState, large, small, expected_out_tokens: int,
                         expected_tool_tokens: int, success_prob: float,
                         threshold: float = 0.85) -> str:
    projected = state.tokens_in + expected_out_tokens + expected_tool_tokens

    # Re-derive the cost model at the context length the action will PRODUCE.
    marginal_large = cost_at(large, projected)
    marginal_small = cost_at(small, projected)

    # Reserve for every remaining step at the projected (grown) context.
    reserve = state.steps_remaining * marginal_large

    if latency_at(large, projected) > state.sla_ms:
        raise BudgetInvariantViolation(
            f"large-tier latency {latency_at(large, projected)}ms at projected "
            f"context {projected} exceeds SLA {state.sla_ms}ms; escalation infeasible"
        )

    if success_prob < threshold:
        return "small"

    if state.remaining_budget < reserve:
        # Escalation is locally attractive but globally unfundable.
        # Fall through to the degraded-but-completable path.
        if state.remaining_budget < marginal_small * state.steps_remaining:
            raise BudgetInvariantViolation(
                f"budget {state.remaining_budget:.3f} cannot fund even small-tier "
                f"reserve {marginal_small * state.steps_remaining:.3f} at projected "
                f"context {projected}; episode must re-plan or abort"
            )
        return "small"

    return "large"
