Skip to content

The agent that grows with you

fix(usage-window): a model of unknown tier is never promised the earlier reset

Teknium5fd5f8b73a21
diff --git a/agent/credits_tracker.py b/agent/credits_tracker.py
index 7f5bb7260bf..f71a0b9d4e3 100644
--- a/agent/credits_tracker.py
+++ b/agent/credits_tracker.py
@@ -243,23 +243,25 @@ def _window_approach_text(g: WindowGauge) -> str:
return f"⚠ {pct}% of your {gauge_limit_name(g)} limit used{_resets(g.resets_at_ms)}"
-def _stop_gauge(state: CreditsState, *, model_is_top_tier: bool) -> Optional[WindowGauge]:
+def _stop_gauge(state: CreditsState, *, model_is_top_tier: Optional[bool]) -> Optional[WindowGauge]:
"""The full allowance behind the limit line, by :func:`agent.plan_limits.blocking_gauge` (the rule
``limit_hit`` reads, so the line, the retry time and the card agree). A full top-tier allowance counts only on
a refusal: the API stamps ``spend-source`` on every admitted request and never on a 402, so header-sourced
+ no source = this model was refused; an ``included`` source means the model is not top-tier and a seed
- cannot know the model. A refusal no all-scope allowance explains is the top-tier one (a cold catalog)."""
+ cannot know the model. A refusal no all-scope allowance explains is the top-tier one (a cold catalog).
+ ``model_is_top_tier=None`` (tier unknown) counts the top-tier allowance as one that may stop the model, so
+ of several full ones the later reset wins and no retry is promised before the model can run."""
if not state.is_usage_window:
return None
from agent.plan_limits import blocking_gauge
refused = state.from_header and state.spend_source is None
- g = blocking_gauge("", state.gauges, free=False, top_tier=refused and model_is_top_tier)
+ g = blocking_gauge("", state.gauges, free=False, top_tier=refused and model_is_top_tier is not False)
if g is None and refused and state.top_tier_exhausted:
return state.top_tier_gauge
return g
-def _window_hard_stop(state: CreditsState, *, model_is_free: bool, model_is_top_tier: bool = False) -> Optional[str]:
+def _window_hard_stop(state: CreditsState, *, model_is_free: bool, model_is_top_tier: Optional[bool] = False) -> Optional[str]:
"""Blocking copy for a usage-window account, or None. ``paid_access`` is the portal's word (dunning);
then: payment paused with no credits (credits keep a paused plan going whatever the setting says; a
card update restores included usage), the large-model allowance used with no pay path, the window used with no
@@ -285,7 +287,7 @@ def _window_hard_stop(state: CreditsState, *, model_is_free: bool, model_is_top_
return f"✕ You've hit your {gauge_limit_name(g)} limit{_resets(g.resets_at_ms)} · {action}"
-def window_stop_resets_at_ms(state: CreditsState, *, model_is_top_tier: bool = False) -> Optional[int]:
+def window_stop_resets_at_ms(state: CreditsState, *, model_is_top_tier: Optional[bool] = False) -> Optional[int]:
"""When the allowance behind :func:`_window_hard_stop`'s limit line frees up (the same gauge)."""
if state.unmetered:
return None
diff --git a/agent/plan_limits.py b/agent/plan_limits.py
index e356e49b6fd..ad5ff0a58ce 100644
--- a/agent/plan_limits.py
+++ b/agent/plan_limits.py
@@ -149,9 +149,15 @@ def blocking_gauge(model: str, gauges: Iterable[Any], *, free: bool, top_tier: b
return max(full, key=lambda g: g.resets_at_ms or 0) if full else None
-def current_model_is_top_tier(agent: Any) -> bool:
- """*agent*'s current model is top tier, by its own profile's cached catalog (see :func:`is_top_tier`)."""
- return is_top_tier(str(getattr(agent, "model", "") or ""), cached_pricing(str(getattr(agent, "base_url", "") or "")))
+def current_model_is_top_tier(agent: Any) -> Optional[bool]:
+ """*agent*'s current model is top tier, by its own profile's cached catalog (see :func:`is_top_tier`), or
+ None when the catalog has no row for it (cold, or its 300 s cache lapsed): the tier is unknown."""
+ model = str(getattr(agent, "model", "") or "")
+ return _top_tier_mark(model, cached_pricing(str(getattr(agent, "base_url", "") or "")))
+
+
+def _top_tier_mark(model: str, pricing: Optional[dict]) -> Optional[bool]:
+ return is_top_tier(model, pricing) if model in (pricing or {}) or is_free(model, pricing) else None
def is_blocked(model: str, gauges: Iterable[Any], pricing: Optional[dict]) -> bool:
@@ -253,7 +259,9 @@ def limit_hit(agent: Any, *, message: str, needed_tokens: Optional[int] = None)
base_url = str(getattr(agent, "base_url", "") or "")
pricing = cached_pricing(base_url)
gauges = tuple(getattr(state, "gauges", ()) or ())
- g = blocking_gauge(model, gauges, free=is_free(model, pricing), top_tier=is_top_tier(model, pricing))
+ # A model the cached catalog has no row for may be top tier: count its full top-tier gauge too, so
+ # the card never names an earlier reset than the one that frees it.
+ g = blocking_gauge(model, gauges, free=is_free(model, pricing), top_tier=_top_tier_mark(model, pricing) is not False)
if g is None:
# The 402 says this model was refused; without a top-tier mark in the cache a full top-tier
# gauge is still the only explanation.
diff --git a/tests/agent/test_credits_usage_window.py b/tests/agent/test_credits_usage_window.py
index 56529440519..fb337117dff 100644
--- a/tests/agent/test_credits_usage_window.py
+++ b/tests/agent/test_credits_usage_window.py
@@ -1223,17 +1223,32 @@ class TestRefusalReadsAsTheStopLine:
assert _usage_window_reset_context(self._agent()) == {"reset_at": DAY_RESET / 1000}
assert _usage_window_reset_context(SimpleNamespace(_credits_state=None)) == {}
- def test_a_regular_model_refused_by_its_day_names_the_day_everywhere(self):
+ def test_a_regular_model_refused_by_its_day_names_the_day_everywhere(self, monkeypatch):
"""Day and Large-model allowances both full on a 402 for a model that is not top tier: the line, the retry
time, the pool bench and the card all name the day (what stops this model), not the month-away reset."""
+ from agent import plan_limits as pl
from agent.conversation_loop import _usage_window_refusal
from agent.turn_recovery import _usage_window_reset_context
+ monkeypatch.setattr(pl, "cached_pricing", lambda base_url: {
+ "example/model-b": {"prompt": "0.0000004", "completion": "0.000004", "usage_level": "medium"}})
agent = self._agent(window_top_tier_used_bp=10_000, window_top_tier_resets_at_ms=MONTH_RESET)
text, resets_at, limit = _usage_window_refusal(agent, SimpleNamespace(error_context={"usage_window": True}))
assert text.startswith(f"You've hit your daily limit · resets {format_window_reset(DAY_RESET)}")
assert resets_at == DAY_RESET / 1000 and limit["gauge_id"] == "day"
assert _usage_window_reset_context(agent) == {"reset_at": DAY_RESET / 1000}
+ def test_a_model_of_unknown_tier_is_never_promised_the_earlier_reset(self):
+ """Day and Large-model allowances both full on a 402 while the catalog has no row for the model (cold, or
+ its 300 s cache lapsed): it may be Large, so the line, retry time, pool bench and card name the later
+ Large-model reset, never a daily one it would still be refused after."""
+ from agent.conversation_loop import _usage_window_refusal
+ from agent.turn_recovery import _usage_window_reset_context
+ agent = self._agent(window_top_tier_used_bp=10_000, window_top_tier_resets_at_ms=MONTH_RESET)
+ text, resets_at, limit = _usage_window_refusal(agent, SimpleNamespace(error_context={"usage_window": True}))
+ assert text.startswith(f"You've hit your monthly large-model limit · resets {format_window_reset(MONTH_RESET)}")
+ assert resets_at == MONTH_RESET / 1000 and limit["gauge_id"] == "top_tier"
+ assert _usage_window_reset_context(agent) == {"reset_at": MONTH_RESET / 1000}
+
def test_keep_going_off_with_no_balance_says_both_steps_everywhere(self):
"""A new subscriber's first limit (setting off by default, no top-up): the stop line, the next-steps
payload and the 402 guidance all name both steps, since either one alone is still refused."""