Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(model-hub): ignore an invalid price override entry alone (#2190)
Call White1612f9b8983d
diff --git a/core/handlers/model_hub/pricing.py b/core/handlers/model_hub/pricing.pyindex 4c6ca8dcd..7d80f246c 100644--- a/core/handlers/model_hub/pricing.py+++ b/core/handlers/model_hub/pricing.py@@ -34,6 +34,7 @@ CURRENCY: Final = "USD"_MAX_PRICE_PER_MTOK: Final = 100_000.0_MAX_FEE_USD: Final = 100_000.0_MAX_KEY_CHARS: Final = 128+_MAX_INT_DIGITS: Final = 400 # below Python's lowest settable int-to-str digit limit (640)# An alias may point at another alias, but not forever._MAX_ALIAS_HOPS: Final = 4# One-hour cache writes cost twice the input price where the table says nothing.@@ -104,15 +105,24 @@ class ModelPrice:charges_cache_writes: bool = False-def _price(value: object) -> Optional[float]:+def _bounded(value: object, ceiling: float) -> Optional[float]:+ """A number in [0, ceiling], or None. An int too large for a float is out of range, not an error."""+if isinstance(value, bool) or not isinstance(value, (int, float)):return None- number = float(value)- if not math.isfinite(number) or number < 0 or number > _MAX_PRICE_PER_MTOK:+ try:+ number = float(value)+ except OverflowError:+ return None+ if not math.isfinite(number) or number < 0 or number > ceiling:return Nonereturn number+def _price(value: object) -> Optional[float]:+ return _bounded(value, _MAX_PRICE_PER_MTOK)++def model_price(cost: object) -> Optional[ModelPrice]:"""Read one models.dev-shaped `cost` object, or None when it has no usable price.@@ -223,17 +233,12 @@ class PriceTable:self._fees = dict(PLAN_FEES_USD)plans = overrides.get("plans")if isinstance(plans, Mapping):- for key, entry in plans.items():- fee = entry.get("fee_usd") if isinstance(entry, Mapping) else None- if (- isinstance(key, str)- and 0 < len(key) <= 64- and not isinstance(fee, bool)- and isinstance(fee, (int, float))- and math.isfinite(fee)- and 0 <= fee <= _MAX_FEE_USD- ):- self._fees[key] = float(fee)+ # Keys are trimmed like a Source's `plan`; an exact key wins over a padded one.+ for key, entry in sorted(plans.items(), key=lambda item: isinstance(item[0], str) and item[0] == item[0].strip()):+ key = key.strip() if isinstance(key, str) else None+ fee = _bounded(entry.get("fee_usd"), _MAX_FEE_USD) if isinstance(entry, Mapping) else None+ if key and len(key) <= 64 and fee is not None:+ self._fees[key] = feeself._sources: dict[str, SourcePlan] = {}sources = overrides.get("sources")if isinstance(sources, Mapping):@@ -241,9 +246,10 @@ class PriceTable:if not isinstance(source_id, str) or not isinstance(entry, Mapping):continueplan = entry.get("plan")+ plan = plan.strip()[:64] if isinstance(plan, str) else Noneday = entry.get("renewal_day")self._sources[source_id] = SourcePlan(- plan=plan[:64] if isinstance(plan, str) and plan.strip() else None,+ plan=plan or None,renewal_day=(dayif isinstance(day, int) and not isinstance(day, bool) and 1 <= day <= 31@@ -380,9 +386,21 @@ def billing_period(today: date, renewal_day: Optional[int]) -> tuple[str, date,return "billing_cycle", start, renews+def _parse_int(digits: str) -> int | float:+ # Any integer that cannot convert, whatever the interpreter's digit limit, is out of range.+ if len(digits) > _MAX_INT_DIGITS:+ return math.inf+ try:+ return int(digits)+ except ValueError:+ return math.inf++def _read_overrides(path: Path) -> dict[str, Any]:try:- payload = json.loads(path.read_text(encoding="utf-8"))+ # An integer too long for the parser's digit limit becomes an out-of-range+ # number, so only its entry is rejected rather than the whole file.+ payload = json.loads(path.read_text(encoding="utf-8"), parse_int=_parse_int)except FileNotFoundError:return {}except (OSError, ValueError, RecursionError) as exc:diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex cbeb51130..13976d282 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -1519,7 +1519,11 @@ that could not see all usage: a degraded ledger read (rows dropped), or an hourlbucket, and the 24-hour totals over it, whose `history_complete` is false.The override file is optional and read on every summary; an unreadable file is-ignored with a warning. Every member is optional:+ignored with a warning. An invalid entry is ignored on its own and the rest still+apply: a price or fee that is not a finite number in range (including a JSON+integer too large for a float or too long to convert), or a `models` key longer+than 128 characters. A Source's `plan` and the `plans` keys are trimmed of+surrounding whitespace; an exact key wins over a padded one. Every member is optional:```json{diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex e8e58d7fa..9c6c80b6b 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -1036,6 +1036,12 @@ scenarios:kind: safetylayer: unittest: tests/test_model_hub_pricing.py::test_no_aggregate_over_an_unknown_part_is_published_as_exact+ - id: MH-PRICE-013+ name: An invalid price override entry (huge, non-finite, or an over-long model key) is ignored alone, and a Source plan is whitespace-trimmed+ status: covered+ kind: recovery+ layer: unit+ test: tests/test_model_hub_pricing.py::test_an_invalid_override_entry_is_ignored_and_the_rest_still_apply- id: MH-RES-LIVE-001name: Live turn retries an eligible backup before streaming startsstatus: covereddiff --git a/tests/test_model_hub_pricing.py b/tests/test_model_hub_pricing.pyindex 8817bd352..fdc729dbd 100644--- a/tests/test_model_hub_pricing.py+++ b/tests/test_model_hub_pricing.py@@ -310,6 +310,100 @@ def test_override_file_sets_a_sources_plan_fee_and_renewal_day():assert table.source_plan("src_a").renewal_day == 31+def test_an_invalid_override_entry_is_ignored_and_the_rest_still_apply(tmp_path):+ """MH-PRICE-013: A huge, non-finite, or over-long override entry is dropped alone; the other entries still apply."""++ huge = 10**400 # a JSON integer too large for a float+ (tmp_path / PRICE_OVERRIDE_FILENAME).write_text(+ json.dumps({+ "models": {+ "claude-opus-5": {"input": huge, "output": 25},+ "claude-haiku-4-5": {"input": 1e308 * 10, "output": 5},+ "x" * 129: {"input": 1, "output": 2},+ "claude-fable-5-1": {"input": 7, "output": 8},+ },+ "plans": {"claude_max_20x": {"fee_usd": huge}, "team_seat": {"fee_usd": 30}},+ "sources": {"src_a": {"plan": " team_seat \n", "renewal_day": 14}, "src_b": {"plan": " "}},+ }),+ encoding="utf-8",+ )+ table = load_price_table(tmp_path, catalog_loader=lambda: (CATALOG, FETCHED_AT), vendor_map_loader=lambda: VENDOR_MAP)++ # Rejected entries fall through to models.dev, as an absent override would.+ assert table.price("claude-opus-5").input == 5+ assert table.price("claude-haiku-4-5").input == 1+ assert table.price("x" * 129) is None+ assert table.fee("claude_max_20x") == 200+ # Their neighbours still apply.+ assert table.price("claude-fable-5-1").input == 7+ assert table.fee("team_seat") == 30+ assert table.source_plan("src_a").plan == "team_seat"+ assert table.resolve_plan_key("src_a", "anthropic", None) == "team_seat"+ assert table.source_plan("src_a").renewal_day == 14+ assert table.source_plan("src_b").plan is None+++def test_an_integer_past_the_json_digit_limit_is_ignored_alone(tmp_path):+ """MH-PRICE-013: An integer too long for the JSON parser drops only its entry, not the file."""++ digits = "9" * 5000+ (tmp_path / PRICE_OVERRIDE_FILENAME).write_text(+ '{"models": {"claude-opus-5": {"input": %s, "output": 25}, "claude-fable-5-1": {"input": 7, "output": 8}},'+ ' "plans": {"claude_max_20x": {"fee_usd": %s}, "team_seat": {"fee_usd": 30}}}' % (digits, digits),+ encoding="utf-8",+ )+ table = load_price_table(tmp_path, catalog_loader=lambda: (CATALOG, FETCHED_AT), vendor_map_loader=lambda: VENDOR_MAP)+ assert table.price("claude-opus-5").input == 5+ assert table.price("claude-fable-5-1").input == 7+ assert table.fee("claude_max_20x") == 200+ assert table.fee("team_seat") == 30+++def test_an_integer_past_a_lowered_interpreter_digit_limit_is_ignored_alone(tmp_path, monkeypatch):+ """MH-PRICE-013: The per-entry rejection holds when the interpreter's int digit limit is set lower."""++ import sys++ if not hasattr(sys, "set_int_max_str_digits"):+ pytest.skip("interpreter has no int digit limit")+ previous = sys.get_int_max_str_digits()+ sys.set_int_max_str_digits(640)+ try:+ # Force the conversion path past the cheap length check.+ monkeypatch.setattr("core.handlers.model_hub.pricing._MAX_INT_DIGITS", 10_000)+ (tmp_path / PRICE_OVERRIDE_FILENAME).write_text(+ '{"models": {"claude-opus-5": {"input": %s, "output": 25}, "claude-fable-5-1": {"input": 7, "output": 8}}}'+ % ("9" * 700),+ encoding="utf-8",+ )+ table = load_price_table(tmp_path, catalog_loader=lambda: (CATALOG, FETCHED_AT), vendor_map_loader=lambda: VENDOR_MAP)+ finally:+ sys.set_int_max_str_digits(previous)+ assert table.price("claude-opus-5").input == 5+ assert table.price("claude-fable-5-1").input == 7+++def test_a_padded_plan_key_still_matches_the_source_plan_that_names_it():+ """MH-PRICE-013: Plan keys are trimmed like a Source's plan, and an exact key wins over a padded one."""++ table = _table({+ "plans": {" team ": {"fee_usd": 30}, " solo ": {"fee_usd": 10}, "solo": {"fee_usd": 12}},+ "sources": {"src_a": {"plan": " team "}, "src_b": {"plan": "solo"}},+ })+ assert table.resolve_plan_key("src_a", "anthropic", None) == "team"+ assert table.fee("team") == 30+ assert table.fee("solo") == 12+++def test_a_128_character_override_model_key_is_the_longest_honoured():+ """MH-PRICE-013: A model key of up to 128 characters takes an override; a longer one is ignored alone."""++ at_limit, over = "m" * 128, "n" * 129+ table = _table({"models": {at_limit: {"input": 1, "output": 2}, over: {"input": 3, "output": 4}}})+ assert table.price(at_limit).input == 1+ assert table.price(over) is None++@pytest.mark.parametrize(("today", "renewal_day", "expected"),[