diff --git a/CHANGELOG.md b/CHANGELOG.md index 05d2b5a..4f8c3b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,8 @@ All notable changes to QueryRouter++ are documented here. - Unused `RouterTrainer` and query-taxonomy loader classes. ### Fixed +- **Custom weights**: `optimize_for: "custom"` now rejects NaN/Infinity, negative or >1 weights and unknown keys with a 422. Before, `{"w_performance": 2, "w_cost": -1, ...}` or a `NaN` weight passed the sum check and crashed `/route` with a 500 on score validation. +- **API errors**: request bodies that echo `NaN` / `Infinity` / `1e999` back in a validation error now return 422 instead of a 500 from JSON serialization. - **Data loading**: non-finite CSV values (`inf`, `-inf`, `1e999`) are treated as missing like `nan`, instead of turning every min-max normalized score into NaN. - **OpenAI proxy**: tool-calling turns keep `tool_calls` / `tool_call_id`, standard OpenAI params (`stop`, `seed`, `tools`, `tool_choice`, `response_format`, penalties, `max_completion_tokens`...) are forwarded upstream, and an unreachable provider returns 502 instead of 500. - `QueryRouter()` without `data_dir` now finds `data_models/`. diff --git a/docs/openapi.json b/docs/openapi.json index 993efe1..1b54661 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -544,7 +544,7 @@ } ], "title": "Weights", - "description": "Weight vector {w_performance, w_cost, w_latency, w_ecology}. Sum must equal 1." + "description": "Weight vector {w_performance, w_cost, w_latency, w_ecology}. Each weight must be in [0, 1] and the sum must equal 1." }, "budget_per_query_usd": { "anyOf": [ diff --git a/docs/openapi.yaml b/docs/openapi.yaml index 1cc586b..7265f50 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -396,7 +396,7 @@ components: - type: 'null' title: Weights description: Weight vector {w_performance, w_cost, w_latency, w_ecology}. - Sum must equal 1. + Each weight must be in [0, 1] and the sum must equal 1. budget_per_query_usd: anyOf: - type: number diff --git a/src/queryrouter/api/main.py b/src/queryrouter/api/main.py index 8b11293..1b4ac6f 100644 --- a/src/queryrouter/api/main.py +++ b/src/queryrouter/api/main.py @@ -9,12 +9,16 @@ from __future__ import annotations +import math import os from typing import Any import uvicorn -from fastapi import FastAPI, HTTPException +from fastapi import FastAPI, HTTPException, Request +from fastapi.encoders import jsonable_encoder +from fastapi.exceptions import RequestValidationError from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import JSONResponse from queryrouter import __version__ from queryrouter.api.dependencies import get_router @@ -43,6 +47,33 @@ # Router factory is shared via api.dependencies to avoid duplication. +def _json_safe(value: Any) -> Any: + """Replace non-finite floats with their string form so the value is valid JSON.""" + if isinstance(value, float) and not math.isfinite(value): + return str(value) + if isinstance(value, dict): + return {k: _json_safe(v) for k, v in value.items()} + if isinstance(value, list | tuple): + return [_json_safe(v) for v in value] + return value + + +@app.exception_handler(RequestValidationError) +async def validation_exception_handler( + request: Request, exc: RequestValidationError +) -> JSONResponse: + """Return 422 for invalid bodies, even when they echo NaN or Infinity back. + + Python's JSON parser accepts ``NaN`` / ``Infinity`` / ``1e999``. FastAPI's default + handler echoes the rejected input, and serializing a non-finite float raises, + so a request that should be a 422 turned into a 500. + """ + return JSONResponse( + status_code=422, + content={"detail": _json_safe(jsonable_encoder(exc.errors()))}, + ) + + def _requested_strategy(request: RoutingRequest) -> Strategy: """Read ``context["strategy"]``; unknown values fall back to ``direct``. diff --git a/src/queryrouter/api/schemas.py b/src/queryrouter/api/schemas.py index 715b1b9..cda4188 100644 --- a/src/queryrouter/api/schemas.py +++ b/src/queryrouter/api/schemas.py @@ -9,6 +9,7 @@ from __future__ import annotations +import math from typing import Literal from pydantic import BaseModel, Field, model_validator @@ -83,7 +84,8 @@ class UserPreferences(BaseModel): weights: dict[str, float] | None = Field( default=None, description=( - "Weight vector {w_performance, w_cost, w_latency, w_ecology}. Sum must equal 1." + "Weight vector {w_performance, w_cost, w_latency, w_ecology}. " + "Each weight must be in [0, 1] and the sum must equal 1." ), ) budget_per_query_usd: float | None = Field( @@ -114,22 +116,31 @@ def resolve_weights(self) -> UserPreferences: """Resolve weights from preset or validate custom weights. For preset modes, auto-assigns the corresponding weight vector. - For custom mode, validates that weights are provided, contain the - correct keys, and sum to 1.0. + For custom mode, validates that weights are provided, contain exactly + the four axis keys, are finite values in [0, 1], and sum to 1.0. Returns: The validated UserPreferences instance. Raises: - ValueError: If custom weights are missing, have wrong keys, or - don't sum to 1. + ValueError: If custom weights are missing, have wrong or unknown + keys, are non-finite or outside [0, 1], or don't sum to 1. """ if self.optimize_for == "custom": if self.weights is None: raise ValueError("weights are required when optimize_for='custom'") missing = set(WEIGHT_KEYS) - set(self.weights.keys()) if missing: - raise ValueError(f"Missing weight keys: {missing}") + raise ValueError(f"Missing weight keys: {sorted(missing)}") + unknown = set(self.weights.keys()) - set(WEIGHT_KEYS) + if unknown: + raise ValueError(f"Unknown weight keys: {sorted(unknown)} (expected {WEIGHT_KEYS})") + for key in WEIGHT_KEYS: + value = self.weights[key] + # NaN slips through the sum check (abs(nan - 1) > eps is False) and + # negative weights can still sum to 1, so check each axis on its own. + if not math.isfinite(value) or not 0.0 <= value <= 1.0: + raise ValueError(f"{key} must be a finite number in [0, 1], got {value!r}") weight_sum = sum(self.weights[k] for k in WEIGHT_KEYS) if abs(weight_sum - 1.0) > 1e-6: raise ValueError(f"Weights must sum to 1.0, got {weight_sum:.6f}") diff --git a/tests/test_schemas.py b/tests/test_schemas.py new file mode 100644 index 0000000..18134ac --- /dev/null +++ b/tests/test_schemas.py @@ -0,0 +1,112 @@ +# MIT License +# Copyright (c) 2026 QueryRouter++ Team + +"""Validation tests for UserPreferences custom weights.""" + +import math + +import pytest +from fastapi.testclient import TestClient +from pydantic import ValidationError + +from queryrouter.api.main import app +from queryrouter.api.schemas import WEIGHT_KEYS, UserPreferences + +client = TestClient(app) + + +def _weights(**overrides: float) -> dict[str, float]: + weights = {"w_performance": 0.25, "w_cost": 0.25, "w_latency": 0.25, "w_ecology": 0.25} + weights.update(overrides) + return weights + + +class TestCustomWeights: + """UserPreferences(optimize_for="custom") weight validation.""" + + def test_valid_custom_weights(self) -> None: + prefs = UserPreferences(optimize_for="custom", weights=_weights()) + assert prefs.weights is not None + assert set(prefs.weights) == set(WEIGHT_KEYS) + + def test_single_axis_weight_of_one_is_valid(self) -> None: + weights = _weights(w_performance=1.0, w_cost=0.0, w_latency=0.0, w_ecology=0.0) + prefs = UserPreferences(optimize_for="custom", weights=weights) + assert prefs.weights == weights + + def test_missing_weights_rejected(self) -> None: + with pytest.raises(ValidationError, match="weights are required"): + UserPreferences(optimize_for="custom") + + def test_missing_key_rejected(self) -> None: + weights = _weights() + del weights["w_ecology"] + with pytest.raises(ValidationError, match="Missing weight keys"): + UserPreferences(optimize_for="custom", weights=weights) + + def test_unknown_key_rejected(self) -> None: + with pytest.raises(ValidationError, match="Unknown weight keys"): + UserPreferences(optimize_for="custom", weights=_weights(w_speed=0.0)) + + def test_negative_weight_rejected_even_if_sum_is_one(self) -> None: + weights = _weights(w_performance=1.0, w_cost=-0.5, w_latency=0.5, w_ecology=0.0) + with pytest.raises(ValidationError, match="w_cost must be a finite number"): + UserPreferences(optimize_for="custom", weights=weights) + + def test_weight_above_one_rejected(self) -> None: + weights = _weights(w_performance=2.0, w_cost=-1.0, w_latency=0.0, w_ecology=0.0) + with pytest.raises(ValidationError, match="w_performance must be a finite number"): + UserPreferences(optimize_for="custom", weights=weights) + + @pytest.mark.parametrize("value", [math.nan, math.inf, -math.inf]) + def test_non_finite_weight_rejected(self, value: float) -> None: + weights = _weights(w_performance=value, w_cost=0.0, w_latency=0.0, w_ecology=0.0) + with pytest.raises(ValidationError, match="must be a finite number"): + UserPreferences(optimize_for="custom", weights=weights) + + def test_sum_not_one_rejected(self) -> None: + with pytest.raises(ValidationError, match="must sum to 1.0"): + UserPreferences(optimize_for="custom", weights=_weights(w_ecology=0.5)) + + def test_preset_ignores_supplied_weights(self) -> None: + prefs = UserPreferences(optimize_for="cost", weights=_weights(w_speed=9.0)) + assert prefs.weights is not None + assert prefs.weights["w_cost"] == 0.7 + assert "w_speed" not in prefs.weights + + +class TestRouteRejectsBadWeights: + """Bad custom weights are a 422 client error, not a 500 from score validation.""" + + @pytest.mark.parametrize( + "weights_json", + [ + '{"w_performance": NaN, "w_cost": 0, "w_latency": 0, "w_ecology": 0}', + '{"w_performance": 1e999, "w_cost": 0, "w_latency": 0, "w_ecology": 0}', + '{"w_performance": 2, "w_cost": -1, "w_latency": 0, "w_ecology": 0}', + '{"w_performance": 1, "w_cost": 0, "w_latency": 0, "w_ecology": 0, "w_x": 0}', + ], + ) + def test_route_returns_422(self, weights_json: str) -> None: + body = ( + '{"query": "Write a Python function to sort a list", ' + '"preferences": {"optimize_for": "custom", "weights": ' + weights_json + "}}" + ) + response = client.post("/route", content=body, headers={"content-type": "application/json"}) + assert response.status_code == 422 + + def test_route_accepts_valid_custom_weights(self) -> None: + response = client.post( + "/route", + json={ + "query": "Write a Python function to sort a list", + "preferences": { + "optimize_for": "custom", + "weights": _weights( + w_performance=0.7, w_cost=0.1, w_latency=0.1, w_ecology=0.1 + ), + }, + }, + ) + assert response.status_code == 200 + assert all(0.0 <= s["score"] <= 1.0 for s in response.json()["scores"])