Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(metrics): drive rate-limit endpoints from RateLimitEstimate (dead APIs) (#4721)

LearningCircuit5da70cce9597
diff --git a/changelog.d/4721.bugfix.md b/changelog.d/4721.bugfix.md
new file mode 100644
index 0000000000..023e017cd9
--- /dev/null
+++ b/changelog.d/4721.bugfix.md
@@ -0,0 +1 @@
+Fixed three rate-limiting API endpoints (`/api/rate-limiting/current`, `/api/rate-limiting/status`, `/api/search-quality`) that always returned empty or per-process-cached data because they read from the in-memory `get_tracker()` singleton, which is freshly built per request and never sees other workers' state. They now read directly from the persisted `RateLimitEstimate` table — the same source the `/metrics` panel was switched to in #4576. Together with that change, every rate-limiting analytics surface is now driven by the same authoritative data. Raw `RateLimitAttempt` writes remain disabled (deliberately, per #4576); only the per-engine estimates the rate limiter actually learns are exposed. The `/api/search-quality` response shape changed in the process (`recent_avg_results` / `min_recent_results` / `max_recent_results` / `sample_size` are gone, replaced by `success_rate`); the benchmark page's status-warning JS was updated to consume the new shape, and the old "Very low results" warning (whose underlying per-attempt search-result-count data was never persisted) is replaced by a "High rate-limit failures" warning driven by `success_rate` and `status`.
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_routes.py b/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
index a68a7d233e..31a0611cec 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_routes.py
@@ -1014,12 +1014,36 @@ def validate_config():
@limiter.exempt
@login_required
def get_search_quality():
- """Get current search quality metrics from rate limiting tracker."""
+ """Get current search quality metrics from rate limiting data."""
try:
- from ...web_search_engines.rate_limiting import get_tracker
+ from flask import session as flask_session
+
+ from ...database.models import RateLimitEstimate
+
+ username = flask_session["username"]
+ quality_stats = []
- tracker = get_tracker()
- quality_stats = tracker.get_search_quality_stats()
+ with get_user_db_session(username) as db_session:
+ estimates = db_session.query(RateLimitEstimate).all()
+ for est in estimates:
+ quality_stats.append(
+ {
+ "engine_type": est.engine_type,
+ "total_attempts": est.total_attempts,
+ "success_rate": round(est.success_rate * 100, 1),
+ "status": (
+ "EXCELLENT"
+ if est.success_rate >= 0.95
+ else "GOOD"
+ if est.success_rate >= 0.9
+ else "CAUTION"
+ if est.success_rate >= 0.75
+ else "WARNING"
+ if est.success_rate >= 0.5
+ else "CRITICAL"
+ ),
+ }
+ )
return jsonify(
{
diff --git a/src/local_deep_research/web/routes/metrics_routes.py b/src/local_deep_research/web/routes/metrics_routes.py
index 751f3ed33c..b65d586860 100644
--- a/src/local_deep_research/web/routes/metrics_routes.py
+++ b/src/local_deep_research/web/routes/metrics_routes.py
@@ -30,7 +30,6 @@ from ...metrics.query_utils import (
get_time_filter_condition,
)
from ...metrics.search_tracker import get_search_tracker
-from ...web_search_engines.rate_limiting import get_tracker
from ...security.decorators import require_json_body
from ...security.rate_limiter import journal_data_limit, journals_read_limit
from ..auth.decorators import login_required
@@ -930,39 +929,36 @@ def api_rate_limiting_metrics():
def api_current_rate_limits():
"""Get current rate limit estimates for all engines."""
try:
- tracker = get_tracker()
- stats = tracker.get_stats()
-
- current_limits = []
- for stat in stats:
- (
- engine_type,
- base_wait,
- min_wait,
- max_wait,
- last_updated,
- total_attempts,
- success_rate,
- ) = stat
- current_limits.append(
- {
- "engine_type": engine_type,
- "base_wait_seconds": round(base_wait, 2),
- "min_wait_seconds": round(min_wait, 2),
- "max_wait_seconds": round(max_wait, 2),
- "success_rate": round(success_rate * 100, 1),
- "total_attempts": total_attempts,
- "last_updated": datetime.fromtimestamp(
- last_updated, UTC
- ).isoformat(), # ISO format already includes timezone
- "status": "healthy"
- if success_rate > 0.8
- else "degraded"
- if success_rate > 0.5
- else "poor",
- }
+ username = flask_session["username"]
+
+ with get_user_db_session(username) as session:
+ estimates = (
+ session.query(RateLimitEstimate)
+ .order_by(RateLimitEstimate.engine_type)
+ .all()
)
+ current_limits = []
+ for est in estimates:
+ current_limits.append(
+ {
+ "engine_type": est.engine_type,
+ "base_wait_seconds": round(est.base_wait_seconds, 2),
+ "min_wait_seconds": round(est.min_wait_seconds, 2),
+ "max_wait_seconds": round(est.max_wait_seconds, 2),
+ "success_rate": round(est.success_rate * 100, 1),
+ "total_attempts": est.total_attempts,
+ "last_updated": datetime.fromtimestamp(
+ est.last_updated, UTC
+ ).isoformat(),
+ "status": "healthy"
+ if est.success_rate > 0.8
+ else "degraded"
+ if est.success_rate > 0.5
+ else "poor",
+ }
+ )
+
return jsonify(
{
"status": "success",
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index 7585288646..31502e4bcd 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -60,7 +60,7 @@ from sqlalchemy.orm import Session
from ...config.constants import DEFAULT_OLLAMA_URL
from ...llm.providers.base import normalize_provider
from ...config.paths import get_data_directory, get_encrypted_database_path
-from ...database.models import Setting, SettingType
+from ...database.models import RateLimitEstimate, Setting, SettingType
from ...database.session_context import get_user_db_session
from ...database.encrypted_db import db_manager
from ...utilities.db_utils import get_settings_manager
@@ -2197,46 +2197,56 @@ def check_ollama_status():
def api_get_rate_limiting_status():
"""Get current rate limiting status and statistics"""
try:
- from ...web_search_engines.rate_limiting import get_tracker
-
- tracker = get_tracker()
+ username = session["username"]
- # Get basic status
+ # exploration_rate / learning_rate are the *configured* settings, not
+ # the effective operating values: AdaptiveRateLimitTracker._apply_profile
+ # scales them by the active profile (conservative ~0.5x/0.7x, aggressive
+ # ~1.5x/1.3x, each capped). The profile is reported alongside so a
+ # consumer can tell which transform the running tracker applies; we
+ # deliberately don't duplicate that scaling math here.
status = {
- "enabled": tracker.enabled,
- "exploration_rate": tracker.exploration_rate,
- "learning_rate": tracker.learning_rate,
- "memory_window": tracker.memory_window,
+ # Default True to match the schema default (default_settings.json)
+ # and the tracker's web-mode default; the prior endpoint reported
+ # the tracker's effective enabled state, which was on by default.
+ "enabled": _get_setting_from_session(
+ "rate_limiting.enabled", True
+ ),
+ "profile": _get_setting_from_session(
+ "rate_limiting.profile", "balanced"
+ ),
+ "exploration_rate": _get_setting_from_session(
+ "rate_limiting.exploration_rate", 0.1
+ ),
+ "learning_rate": _get_setting_from_session(
+ "rate_limiting.learning_rate", 0.45
+ ),
+ "memory_window": _get_setting_from_session(
+ "rate_limiting.memory_window", 100
+ ),
}
- # Get engine statistics
- engine_stats = tracker.get_stats()
- engines = []
-
- for stat in engine_stats:
- (
- engine_type,
- base_wait,
- min_wait,
- max_wait,
- last_updated,
- total_attempts,
- success_rate,
- ) = stat
- engines.append(
- {
- "engine_type": engine_type,
- "base_wait_seconds": round(base_wait, 2),
- "min_wait_seconds": round(min_wait, 2),
- "max_wait_seconds": round(max_wait, 2),
- "last_updated": last_updated,
- "total_attempts": total_attempts,
- "success_rate": (
- round(success_rate * 100, 1) if success_rate else 0.0
- ),
- }
+ with get_user_db_session(username) as db_session:
+ estimates = (
+ db_session.query(RateLimitEstimate)
+ .order_by(RateLimitEstimate.engine_type)
+ .all()
)
+ engines = []
+ for est in estimates:
+ engines.append(
+ {
+ "engine_type": est.engine_type,
+ "base_wait_seconds": round(est.base_wait_seconds, 2),
+ "min_wait_seconds": round(est.min_wait_seconds, 2),
+ "max_wait_seconds": round(est.max_wait_seconds, 2),
+ "last_updated": est.last_updated,
+ "total_attempts": est.total_attempts,
+ "success_rate": round(est.success_rate * 100, 1),
+ }
+ )
+
return jsonify({"status": status, "engines": engines})
except Exception:
diff --git a/src/local_deep_research/web/templates/pages/benchmark.html b/src/local_deep_research/web/templates/pages/benchmark.html
index d19200c237..46a9b533c2 100644
--- a/src/local_deep_research/web/templates/pages/benchmark.html
+++ b/src/local_deep_research/web/templates/pages/benchmark.html
@@ -1708,13 +1708,14 @@ async function updateRateLimitingStatus() {
stat.engine_type.toLowerCase().includes('searxng')
);
- if (searxngStats && searxngStats.recent_avg_results < 2) {
- // Show warning when search results are critically low
- console.warn('Low search results detected:', searxngStats);
+ if (searxngStats && (searxngStats.status === 'WARNING' || searxngStats.status === 'CRITICAL')) {
+ // Show warning when the rate limiter is frequently blocking requests
+ console.warn('High rate-limit failure rate detected:', searxngStats);
const statusDetails = document.getElementById('search-status-details');
- if (statusDetails && !statusDetails.textContent.includes('Very low results')) {
- statusDetails.textContent += ` Very low results: ${searxngStats.recent_avg_results.toFixed(1)} avg.`;
+ const failureRate = (100 - searxngStats.success_rate).toFixed(1);
+ if (statusDetails && !statusDetails.textContent.includes('High rate-limit failures')) {
+ statusDetails.textContent += ` High rate-limit failures: ${failureRate}% of requests throttled.`;
}
}
}
diff --git a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
index b919b9ec3a..7c8333a894 100644
--- a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
+++ b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
@@ -708,6 +708,14 @@ class AdaptiveRateLimitTracker:
"""
Get basic search quality statistics for monitoring.
+ Note: no HTTP route consumes this method any more —
+ ``/benchmark/api/search-quality`` now reports success_rate from the
+ persisted ``RateLimitEstimate`` table instead of this in-memory,
+ per-process view. It is retained as a tracker diagnostic capability
+ (with its own test coverage) for CLI / programmatic use; the
+ ``recent_avg_results`` / ``sample_size`` shape it returns is no longer
+ exposed over the API.
+
Args:
engine_type: Specific engine to get stats for, or None for all
diff --git a/tests/benchmarks/web_api/test_benchmark_routes_coverage.py b/tests/benchmarks/web_api/test_benchmark_routes_coverage.py
index e119c06adf..56e4bd9e31 100644
--- a/tests/benchmarks/web_api/test_benchmark_routes_coverage.py
+++ b/tests/benchmarks/web_api/test_benchmark_routes_coverage.py
@@ -1385,39 +1385,119 @@ class TestValidateConfig:
class TestGetSearchQuality:
- def test_search_quality_success(self):
+ """Tests for /benchmark/api/search-quality.
+
+ The route reads RateLimitEstimate rows from the user DB and maps each
+ to {engine_type, total_attempts, success_rate (0-100 scale), status
+ (EXCELLENT/GOOD/CAUTION/WARNING/CRITICAL)}.
+ """
+
+ @staticmethod
+ def _make_estimate(engine_type, success_rate, total_attempts=100):
+ est = MagicMock()
+ est.engine_type = engine_type
+ est.total_attempts = total_attempts
+ est.success_rate = success_rate
+ return est
+
+ @staticmethod
+ def _fetch(estimates):
+ """Run the route with the given estimates and return (resp, json)."""
app = _make_app()
- with _patch_auth_and_db() as (mock_svc, mgr, _):
- with patch(
- "local_deep_research.web_search_engines.rate_limiting.get_tracker"
- ) as mock_get_tracker:
- mock_tracker = MagicMock()
- mock_tracker.get_search_quality_stats.return_value = {
- "total": 100,
- "successful": 95,
- }
- mock_get_tracker.return_value = mock_tracker
- with app.test_client() as client:
- with client.session_transaction() as sess:
- sess["username"] = "testuser"
- resp = client.get("/benchmark/api/search-quality")
- assert resp.status_code == 200
- data = resp.get_json()
- assert data["success"] is True
- assert "timestamp" in data
+ with _patch_auth_and_db() as (_svc, _mgr, mock_db):
+ mock_db.query.return_value.all.return_value = estimates
+ with app.test_client() as client:
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ resp = client.get("/benchmark/api/search-quality")
+ return resp, resp.get_json()
+
+ def test_requires_authentication(self):
+ app = _make_app()
+ with _patch_auth_and_db():
+ with app.test_client() as client:
+ resp = client.get("/benchmark/api/search-quality")
+ assert resp.status_code in (401, 302)
+
+ def test_status_tier_excellent(self):
+ resp, data = self._fetch([self._make_estimate("pubmed", 0.95)])
+ assert resp.status_code == 200
+ assert data["success"] is True
+ assert "timestamp" in data
+ row = data["search_quality"][0]
+ assert row["engine_type"] == "pubmed"
+ assert row["status"] == "EXCELLENT"
+ assert row["success_rate"] == 95.0
+ assert row["total_attempts"] == 100
+
+ def test_status_tier_good(self):
+ _resp, data = self._fetch([self._make_estimate("google", 0.90)])
+ assert data["search_quality"][0]["status"] == "GOOD"
+ assert data["search_quality"][0]["success_rate"] == 90.0
+
+ def test_status_tier_caution(self):
+ _resp, data = self._fetch([self._make_estimate("google", 0.75)])
+ assert data["search_quality"][0]["status"] == "CAUTION"
+
+ def test_status_tier_warning(self):
+ _resp, data = self._fetch([self._make_estimate("google", 0.50)])
+ assert data["search_quality"][0]["status"] == "WARNING"
+
+ def test_status_tier_critical(self):
+ _resp, data = self._fetch([self._make_estimate("google", 0.30)])
+ assert data["search_quality"][0]["status"] == "CRITICAL"
+
+ def test_success_rate_unit_conversion(self):
+ # success_rate is stored as 0-1 in the DB; route multiplies by 100.
+ _resp, data = self._fetch([self._make_estimate("google", 0.873)])
+ assert data["search_quality"][0]["success_rate"] == 87.3
+
+ def test_multiple_engines(self):
+ resp, data = self._fetch(
+ [
+ self._make_estimate("bing", 0.6),
+ self._make_estimate("google", 0.95),
+ ]
+ )
+ assert resp.status_code == 200
+ assert len(data["search_quality"]) == 2
+ assert {r["engine_type"] for r in data["search_quality"]} == {
+ "bing",
+ "google",
+ }
+
+ def test_empty_engines(self):
+ resp, data = self._fetch([])
+ assert resp.status_code == 200
+ assert data["success"] is True
+ assert data["search_quality"] == []
+
+ def test_shape_excludes_legacy_fields(self):
+ # Regression guard: the old get_search_quality_stats shape included
+ # recent_avg_results / min_recent_results / max_recent_results /
+ # sample_size. Those are gone (the underlying data lived only in
+ # the per-request in-memory tracker). Asserting their absence
+ # protects the benchmark.html JS from accidentally depending on
+ # them again.
+ _resp, data = self._fetch([self._make_estimate("google", 0.95)])
+ assert set(data["search_quality"][0].keys()) == {
+ "engine_type",
+ "total_attempts",
+ "success_rate",
+ "status",
+ }
def test_search_quality_exception(self):
+ # The route now reads RateLimitEstimate rows from the user DB
+ # (no get_tracker call), so a DB error is what surfaces a 500.
app = _make_app()
- with _patch_auth_and_db() as (mock_svc, mgr, _):
- with patch(
- "local_deep_research.web_search_engines.rate_limiting.get_tracker",
- side_effect=RuntimeError("no tracker"),
- ):
- with app.test_client() as client:
- with client.session_transaction() as sess:
- sess["username"] = "testuser"
- resp = client.get("/benchmark/api/search-quality")
- assert resp.status_code == 500
+ with _patch_auth_and_db() as (mock_svc, mgr, mock_db):
+ mock_db.query.side_effect = RuntimeError("db error")
+ with app.test_client() as client:
+ with client.session_transaction() as sess:
+ sess["username"] = "testuser"
+ resp = client.get("/benchmark/api/search-quality")
+ assert resp.status_code == 500
# ---------------------------------------------------------------------------
diff --git a/tests/web/routes/test_metrics_routes.py b/tests/web/routes/test_metrics_routes.py
index fe08bdfc65..ccbfc6462d 100644
--- a/tests/web/routes/test_metrics_routes.py
+++ b/tests/web/routes/test_metrics_routes.py
@@ -1,5 +1,7 @@
"""Tests for metrics_routes module - Metrics dashboard endpoints."""
+from contextlib import contextmanager
+from types import SimpleNamespace
from unittest.mock import patch, MagicMock
from datetime import datetime, UTC
@@ -10,6 +12,45 @@ import pytest
METRICS_PREFIX = "/metrics"
+def _fake_estimate(
+ engine_type,
+ base_wait,
+ min_wait,
+ max_wait,
+ total_attempts,
+ success_rate,
+ last_updated=1704067200.0,
+):
+ """Build a RateLimitEstimate-shaped row for the DB-backed routes."""
+ return SimpleNamespace(
+ engine_type=engine_type,
+ base_wait_seconds=base_wait,
+ min_wait_seconds=min_wait,
+ max_wait_seconds=max_wait,
+ total_attempts=total_attempts,
+ success_rate=success_rate,
+ last_updated=last_updated,
+ )
+
+
+@contextmanager
+def _patch_estimates(module_path, estimates):
+ """Patch ``get_user_db_session`` in *module_path* so a route's
+ ``session.query(RateLimitEstimate).order_by(...).all()`` returns
+ *estimates*."""
+ session = MagicMock()
+ session.query.return_value.order_by.return_value.all.return_value = (
+ estimates
+ )
+
+ @contextmanager
+ def _ctx(username, password=None):
+ yield session
+
+ with patch(f"{module_path}.get_user_db_session", side_effect=_ctx):
+ yield session
+
+
class TestMetricsDashboard:
"""Tests for /metrics/ endpoint."""
@@ -112,17 +153,16 @@ class TestApiCurrentRateLimits:
assert response.status_code == 401, response.status_code
def test_returns_current_limits(self, authenticated_client):
- """Should return current rate limits."""
- with patch(
- "local_deep_research.web.routes.metrics_routes.get_tracker"
- ) as mock_tracker:
- mock_tracker_instance = MagicMock()
- mock_tracker_instance.get_stats.return_value = [
- ("pubmed", 1.0, 0.5, 2.0, 1704067200.0, 100, 0.95),
- ("semantic_scholar", 0.5, 0.2, 1.0, 1704067200.0, 50, 0.90),
- ]
- mock_tracker.return_value = mock_tracker_instance
-
+ """Should return current rate limits read from persisted
+ RateLimitEstimate rows (the route is now DB-backed, not tracker-
+ backed)."""
+ estimates = [
+ _fake_estimate("pubmed", 1.0, 0.5, 2.0, 100, 0.95),
+ _fake_estimate("semantic_scholar", 0.5, 0.2, 1.0, 50, 0.90),
+ ]
+ with _patch_estimates(
+ "local_deep_research.web.routes.metrics_routes", estimates
+ ):
response = authenticated_client.get(
f"{METRICS_PREFIX}/api/rate-limiting/current"
)
@@ -132,6 +172,8 @@ class TestApiCurrentRateLimits:
assert data["status"] == "success"
assert "current_limits" in data
assert len(data["current_limits"]) == 2
+ assert data["current_limits"][0]["engine_type"] == "pubmed"
+ assert data["current_limits"][0]["success_rate"] == 95.0
class TestApiResearchMetrics:
diff --git a/tests/web/routes/test_metrics_routes_coverage.py b/tests/web/routes/test_metrics_routes_coverage.py
index b3cd054d91..76b177b571 100644
--- a/tests/web/routes/test_metrics_routes_coverage.py
+++ b/tests/web/routes/test_metrics_routes_coverage.py
@@ -821,13 +821,30 @@ class TestApiRateLimiting:
class TestApiCurrentRateLimits:
- @patch("local_deep_research.web.routes.metrics_routes.get_tracker")
- def test_success_healthy(self, mock_get_tracker, authed_client):
- mock_tracker = MagicMock()
- mock_tracker.get_stats.return_value = [
- ("google", 1.0, 0.5, 2.0, time.time(), 100, 0.9),
- ]
- mock_get_tracker.return_value = mock_tracker
+ @staticmethod
+ def _make_estimate(engine_type, success_rate, base_wait=1.0):
+ est = MagicMock()
+ est.engine_type = engine_type
+ est.base_wait_seconds = base_wait
+ est.min_wait_seconds = base_wait * 0.5
+ est.max_wait_seconds = base_wait * 2.0
+ est.success_rate = success_rate
+ est.total_attempts = 50
+ est.last_updated = time.time()
+ return est
+
+ @staticmethod
+ def _wire_session(mock_db, estimates):
+ session = MagicMock()
+ session.query.return_value.order_by.return_value.all.return_value = (
+ estimates
+ )
+ mock_db.return_value.__enter__ = MagicMock(return_value=session)
+ mock_db.return_value.__exit__ = MagicMock(return_value=False)
+
+ @patch("local_deep_research.web.routes.metrics_routes.get_user_db_session")
+ def test_success_healthy(self, mock_db, authed_client):
+ self._wire_session(mock_db, [self._make_estimate("google", 0.9)])
resp = authed_client.get("/metrics/api/rate-limiting/current")
assert resp.status_code == 200
@@ -836,33 +853,28 @@ class TestApiCurrentRateLimits:
assert len(data["current_limits"]) == 1
assert data["current_limits"][0]["status"] == "healthy"
- @patch("local_deep_research.web.routes.metrics_routes.get_tracker")
- def test_degraded_status(self, mock_get_tracker, authed_client):
- mock_tracker = MagicMock()
- mock_tracker.get_stats.return_value = [
- ("bing", 2.0, 1.0, 4.0, time.time(), 50, 0.6),
- ]
- mock_get_tracker.return_value = mock_tracker
+ @patch("local_deep_research.web.routes.metrics_routes.get_user_db_session")
+ def test_degraded_status(self, mock_db, authed_client):
+ self._wire_session(mock_db, [self._make_estimate("bing", 0.6)])
resp = authed_client.get("/metrics/api/rate-limiting/current")
data = resp.get_json()
assert data["current_limits"][0]["status"] == "degraded"
- @patch("local_deep_research.web.routes.metrics_routes.get_tracker")
- def test_poor_status(self, mock_get_tracker, authed_client):
- mock_tracker = MagicMock()
- mock_tracker.get_stats.return_value = [
- ("duckduckgo", 5.0, 3.0, 10.0, time.time(), 20, 0.3),
- ]
- mock_get_tracker.return_value = mock_tracker
+ @patch("local_deep_research.web.routes.metrics_routes.get_user_db_session")
+ def test_poor_status(self, mock_db, authed_client):
+ self._wire_session(mock_db, [self._make_estimate("duckduckgo", 0.3)])
resp = authed_client.get("/metrics/api/rate-limiting/current")
data = resp.get_json()
assert data["current_limits"][0]["status"] == "poor"
- @patch("local_deep_research.web.routes.metrics_routes.get_tracker")
- def test_exception(self, mock_get_tracker, authed_client):
- mock_get_tracker.side_effect = Exception("fail")
+ @patch("local_deep_research.web.routes.metrics_routes.get_user_db_session")
+ def test_exception(self, mock_db, authed_client):
+ mock_db.return_value.__enter__ = MagicMock(
+ side_effect=Exception("fail")
+ )
+ mock_db.return_value.__exit__ = MagicMock(return_value=False)
resp = authed_client.get("/metrics/api/rate-limiting/current")
assert resp.status_code == 500
diff --git a/tests/web/routes/test_metrics_routes_rate_limits.py b/tests/web/routes/test_metrics_routes_rate_limits.py
index 6248a0aafe..f5bb63f158 100644
--- a/tests/web/routes/test_metrics_routes_rate_limits.py
+++ b/tests/web/routes/test_metrics_routes_rate_limits.py
@@ -2,11 +2,27 @@
"""Tests for api_current_rate_limits and api_cost_calculation in metrics_routes.py."""
import time
+from contextlib import contextmanager
from unittest.mock import patch, MagicMock
METRICS_PREFIX = "/metrics"
+def _make_estimate(
+ engine_type, base_wait, min_wait, max_wait, ts, attempts, rate
+):
+ """Create a mock RateLimitEstimate object."""
+ est = MagicMock()
+ est.engine_type = engine_type
+ est.base_wait_seconds = base_wait
+ est.min_wait_seconds = min_wait
+ est.max_wait_seconds = max_wait
+ est.last_updated = ts
+ est.total_attempts = attempts
+ est.success_rate = rate
+ return est
+
+
class TestApiCurrentRateLimits:
"""Tests for /api/rate-limiting/current endpoint."""
@@ -14,17 +30,22 @@ class TestApiCurrentRateLimits:
response = client.get(f"{METRICS_PREFIX}/api/rate-limiting/current")
assert response.status_code in [401, 302]
- @patch("local_deep_research.web.routes.metrics_routes.get_tracker")
+ @patch("local_deep_research.web.routes.metrics_routes.get_user_db_session")
def test_returns_current_limits(
- self, mock_get_tracker, authenticated_client
+ self, mock_get_session, authenticated_client
):
now = time.time()
- mock_tracker = MagicMock()
- mock_tracker.get_stats.return_value = [
- ("google", 2.0, 1.0, 5.0, now, 100, 0.95),
- ("bing", 1.5, 0.5, 3.0, now, 50, 0.6),
+ mock_session = MagicMock()
+ mock_session.query.return_value.order_by.return_value.all.return_value = [
+ _make_estimate("google", 2.0, 1.0, 5.0, now, 100, 0.95),
+ _make_estimate("bing", 1.5, 0.5, 3.0, now, 50, 0.6),
]
- mock_get_tracker.return_value = mock_tracker
+
+ @contextmanager
+ def _ctx(username):
+ yield mock_session
+
+ mock_get_session.side_effect = _ctx
response = authenticated_client.get(
f"{METRICS_PREFIX}/api/rate-limiting/current"
@@ -43,16 +64,21 @@ class TestApiCurrentRateLimits:
bing = data["current_limits"][1]
assert bing["status"] == "degraded"
- @patch("local_deep_research.web.routes.metrics_routes.get_tracker")
+ @patch("local_deep_research.web.routes.metrics_routes.get_user_db_session")
def test_poor_status_threshold(
- self, mock_get_tracker, authenticated_client
+ self, mock_get_session, authenticated_client
):
now = time.time()
- mock_tracker = MagicMock()
- mock_tracker.get_stats.return_value = [
- ("failing_engine", 10.0, 5.0, 30.0, now, 200, 0.3),
+ mock_session = MagicMock()
+ mock_session.query.return_value.order_by.return_value.all.return_value = [
+ _make_estimate("failing_engine", 10.0, 5.0, 30.0, now, 200, 0.3),
]
- mock_get_tracker.return_value = mock_tracker
+
+ @contextmanager
+ def _ctx(username):
+ yield mock_session
+
+ mock_get_session.side_effect = _ctx
response = authenticated_client.get(
f"{METRICS_PREFIX}/api/rate-limiting/current"
@@ -60,11 +86,16 @@ class TestApiCurrentRateLimits:
data = response.get_json()
assert data["current_limits"][0]["status"] == "poor"
- @patch("local_deep_research.web.routes.metrics_routes.get_tracker")
- def test_empty_stats(self, mock_get_tracker, authenticated_client):
- mock_tracker = MagicMock()
- mock_tracker.get_stats.return_value = []
- mock_get_tracker.return_value = mock_tracker
+ @patch("local_deep_research.web.routes.metrics_routes.get_user_db_session")
+ def test_empty_stats(self, mock_get_session, authenticated_client):
+ mock_session = MagicMock()
+ mock_session.query.return_value.order_by.return_value.all.return_value = []
+
+ @contextmanager
+ def _ctx(username):
+ yield mock_session
+
+ mock_get_session.side_effect = _ctx
response = authenticated_client.get(
f"{METRICS_PREFIX}/api/rate-limiting/current"
@@ -73,9 +104,9 @@ class TestApiCurrentRateLimits:
assert data["status"] == "success"
assert data["current_limits"] == []
- @patch("local_deep_research.web.routes.metrics_routes.get_tracker")
- def test_error_returns_500(self, mock_get_tracker, authenticated_client):
- mock_get_tracker.side_effect = RuntimeError("tracker error")
+ @patch("local_deep_research.web.routes.metrics_routes.get_user_db_session")
+ def test_error_returns_500(self, mock_get_session, authenticated_client):
+ mock_get_session.side_effect = RuntimeError("db error")
response = authenticated_client.get(
f"{METRICS_PREFIX}/api/rate-limiting/current"
diff --git a/tests/web/routes/test_settings_routes_rate_limiting.py b/tests/web/routes/test_settings_routes_rate_limiting.py
index ec00d5bf47..eb4252b6f4 100644
--- a/tests/web/routes/test_settings_routes_rate_limiting.py
+++ b/tests/web/routes/test_settings_routes_rate_limiting.py
@@ -1,6 +1,8 @@
# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client
"""Tests for rate limiting and notification endpoints in settings_routes.py."""
+from contextlib import contextmanager
+from types import SimpleNamespace
from unittest.mock import patch, MagicMock
import time
@@ -9,6 +11,42 @@ import pytest
SETTINGS_PREFIX = "/settings"
+def _fake_estimate(engine_type, success_rate, total_attempts=10):
+ """Build a RateLimitEstimate-shaped row for the DB-backed route."""
+ return SimpleNamespace(
+ engine_type=engine_type,
+ base_wait_seconds=2.0,
+ min_wait_seconds=1.0,
+ max_wait_seconds=5.0,
+ last_updated=time.time(),
+ total_attempts=total_attempts,
+ success_rate=success_rate,
+ )
+
+
+@contextmanager
+def _patch_estimates(estimates=None, query_error=None):
+ """Patch settings_routes.get_user_db_session so the rate-limiting
+ status route reads *estimates* (or raises *query_error*)."""
+ session = MagicMock()
+ if query_error is not None:
+ session.query.side_effect = query_error
+ else:
+ session.query.return_value.order_by.return_value.all.return_value = (
+ estimates or []
+ )
+
+ @contextmanager
+ def _ctx(username, password=None):
+ yield session
+
+ with patch(
+ "local_deep_research.web.routes.settings_routes.get_user_db_session",
+ side_effect=_ctx,
+ ):
+ yield session
+
+
class TestApiGetRateLimitingStatus:
"""Tests for /api/rate-limiting/status endpoint."""
@@ -16,58 +54,91 @@ class TestApiGetRateLimitingStatus:
response = client.get(f"{SETTINGS_PREFIX}/api/rate-limiting/status")
assert response.status_code == 401, response.status_code
- @patch("local_deep_research.web_search_engines.rate_limiting.get_tracker")
- def test_returns_status_and_engines(
- self, mock_get_tracker, authenticated_client
- ):
- mock_tracker = MagicMock()
- mock_tracker.enabled = True
- mock_tracker.exploration_rate = 0.1
- mock_tracker.learning_rate = 0.05
- mock_tracker.memory_window = 100
- mock_tracker.get_stats.return_value = [
- ("google", 2.0, 1.0, 5.0, time.time(), 50, 0.95),
- ("bing", 1.5, 0.5, 3.0, time.time(), 30, 0.8),
+ def test_returns_status_and_engines(self, authenticated_client):
+ # The route reads engine rows from persisted RateLimitEstimate
+ # records (DB-backed), and the status block from the user's
+ # settings — no get_tracker call anymore.
+ estimates = [
+ _fake_estimate("bing", 0.8, total_attempts=30),
+ _fake_estimate("google", 0.95, total_attempts=50),
]
- mock_get_tracker.return_value = mock_tracker
-
- response = authenticated_client.get(
- f"{SETTINGS_PREFIX}/api/rate-limiting/status"
- )
+ with _patch_estimates(estimates):
+ response = authenticated_client.get(
+ f"{SETTINGS_PREFIX}/api/rate-limiting/status"
+ )
assert response.status_code == 200
data = response.get_json()
- assert data["status"]["enabled"] is True
+ # status carries the rate-limiting settings block (exact key set)
+ assert set(data["status"].keys()) == {
+ "enabled",
+ "profile",
+ "exploration_rate",
+ "learning_rate",
+ "memory_window",
+ }
assert len(data["engines"]) == 2
- assert data["engines"][0]["engine_type"] == "google"
- assert data["engines"][0]["success_rate"] == 95.0
+ # ordered by engine_type -> bing first
+ assert data["engines"][0]["engine_type"] == "bing"
+ assert data["engines"][1]["engine_type"] == "google"
+ assert data["engines"][1]["success_rate"] == 95.0
- @patch("local_deep_research.web_search_engines.rate_limiting.get_tracker")
- def test_handles_none_success_rate(
- self, mock_get_tracker, authenticated_client
+ def test_status_block_surfaces_settings_and_defaults(
+ self, authenticated_client
):
- mock_tracker = MagicMock()
- mock_tracker.enabled = True
- mock_tracker.exploration_rate = 0.1
- mock_tracker.learning_rate = 0.05
- mock_tracker.memory_window = 100
- mock_tracker.get_stats.return_value = [
- ("new_engine", 1.0, 0.5, 2.0, time.time(), 0, None),
- ]
- mock_get_tracker.return_value = mock_tracker
+ """Guard the rate_limiting.* status block this PR added/fixed: the
+ new ``profile`` key, the ``enabled: True`` fallback default (the
+ sole reason for this PR's final commit), and that configured values
+ flow through rather than being hardcoded.
+
+ ``enabled`` and ``profile`` are omitted from the patched settings so
+ the route's own fallback defaults (True / "balanced") must apply;
+ the rest are configured to non-defaults to prove flow-through.
+ """
+
+ configured = {
+ "rate_limiting.exploration_rate": 0.2,
+ "rate_limiting.learning_rate": 0.5,
+ "rate_limiting.memory_window": 50,
+ }
- response = authenticated_client.get(
- f"{SETTINGS_PREFIX}/api/rate-limiting/status"
- )
+ def fake_get(key, default=None):
+ return configured.get(key, default)
+
+ with _patch_estimates([]), patch(
+ "local_deep_research.web.routes.settings_routes._get_setting_from_session",
+ side_effect=fake_get,
+ ):
+ response = authenticated_client.get(
+ f"{SETTINGS_PREFIX}/api/rate-limiting/status"
+ )
+
+ assert response.status_code == 200
+ status = response.get_json()["status"]
+ assert status == {
+ "enabled": True, # PR-fixed fallback default (was False)
+ "profile": "balanced", # fallback default
+ "exploration_rate": 0.2, # configured -> flows through
+ "learning_rate": 0.5,
+ "memory_window": 50,
+ }
+
+ def test_handles_zero_attempt_engine(self, authenticated_client):
+ # A freshly-tracked engine has success_rate 0.0 (the column is
+ # NOT NULL with default 0.0), which renders as 0.0 - there is no
+ # None case to handle now that the route is DB-backed.
+ estimates = [_fake_estimate("new_engine", 0.0, total_attempts=0)]
+ with _patch_estimates(estimates):
+ response = authenticated_client.get(
+ f"{SETTINGS_PREFIX}/api/rate-limiting/status"
+ )
data = response.get_json()
assert data["engines"][0]["success_rate"] == 0.0
- @patch("local_deep_research.web_search_engines.rate_limiting.get_tracker")
- def test_error_returns_500(self, mock_get_tracker, authenticated_client):
- mock_get_tracker.side_effect = RuntimeError("tracker init failed")
-
- response = authenticated_client.get(
- f"{SETTINGS_PREFIX}/api/rate-limiting/status"
- )
+ def test_error_returns_500(self, authenticated_client):
+ with _patch_estimates(query_error=RuntimeError("db error")):
+ response = authenticated_client.get(
+ f"{SETTINGS_PREFIX}/api/rate-limiting/status"
+ )
assert response.status_code == 500
data = response.get_json()
assert "error" in data