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-limiting analytics from RateLimitEstimate (dead panel) (#4576)

LearningCircuitd85034330699
diff --git a/changelog.d/4576.bugfix.md b/changelog.d/4576.bugfix.md
new file mode 100644
index 0000000000..01b7637a8a
--- /dev/null
+++ b/changelog.d/4576.bugfix.md
@@ -0,0 +1 @@
+Fixed the rate-limiting panel on /metrics showing all zeros (no tracked engines, no wait times) for every user. The analytics read the `RateLimitAttempt` table, but raw attempt persistence was disabled to prevent database locking under parallel search, so that table is never populated. The panel now derives engine health, wait-time estimates, success rates, and recent attempt counts from the `RateLimitEstimate` data that rate limiting actually persists. (A few raw-attempt-only metrics — rate-limit-event counts and true per-attempt average wait — cannot be reconstructed and are reported as 0 / the learned base wait.)
diff --git a/src/local_deep_research/web/routes/metrics_routes.py b/src/local_deep_research/web/routes/metrics_routes.py
index ecea3fa11e..4cd32a486c 100644
--- a/src/local_deep_research/web/routes/metrics_routes.py
+++ b/src/local_deep_research/web/routes/metrics_routes.py
@@ -12,7 +12,6 @@ from ...database.models import (
Journal,
Paper,
PaperAppearance,
- RateLimitAttempt,
RateLimitEstimate,
Research,
ResearchHistory,
@@ -603,161 +602,95 @@ def get_rate_limiting_analytics(period="30d", username=None):
cutoff_time = 0
with get_user_db_session(username) as session:
- # Get rate limit attempts
- rate_limit_query = session.query(RateLimitAttempt)
-
- # Apply time filter
+ # Rate-limit analytics are derived from RateLimitEstimate, the
+ # learned per-engine wait-time model that production code
+ # actually persists. The raw per-attempt table
+ # (RateLimitAttempt) is intentionally NOT written — attempt
+ # persistence was disabled (commit fef359be9) to avoid DB
+ # locking under parallel search — so the previous code, which
+ # read RateLimitAttempt, always returned an empty panel.
+ #
+ # Limitations of deriving from estimates (documented so the
+ # numbers aren't mistaken for raw-attempt counts):
+ # - total_attempts is each engine's recent rolling window
+ # (capped at rate_limiting.memory_window, default 100), not
+ # a lifetime count.
+ # - rate_limit_events (RateLimitError-specific failures) and a
+ # true per-attempt average wait cannot be reconstructed and
+ # are reported as 0 / the learned base wait respectively.
+ estimates_query = session.query(RateLimitEstimate)
+
+ # Recency filter uses the estimate's last_updated (epoch
+ # seconds); there is no per-attempt timestamp history.
if cutoff_time > 0:
- rate_limit_query = rate_limit_query.filter(
- RateLimitAttempt.timestamp >= cutoff_time
- )
-
- # Get rate limit statistics
- total_attempts = rate_limit_query.count()
- successful_attempts = rate_limit_query.filter(
- RateLimitAttempt.success
- ).count()
- failed_attempts = total_attempts - successful_attempts
-
- # Count rate limiting events (failures with RateLimitError)
- rate_limit_events = rate_limit_query.filter(
- ~RateLimitAttempt.success,
- RateLimitAttempt.error_type == "RateLimitError",
- ).count()
-
- logger.info(
- f"Rate limit attempts in database: total={total_attempts}, successful={successful_attempts}"
- )
-
- # Get all attempts for detailed calculations
- attempts = rate_limit_query.all()
-
- # Calculate average wait times
- if attempts:
- avg_wait_time = sum(a.wait_time for a in attempts) / len(
- attempts
- )
- successful_wait_times = [
- a.wait_time for a in attempts if a.success
- ]
- avg_successful_wait = (
- sum(successful_wait_times) / len(successful_wait_times)
- if successful_wait_times
- else 0
+ estimates_query = estimates_query.filter(
+ RateLimitEstimate.last_updated >= cutoff_time
)
- else:
- avg_wait_time = 0
- avg_successful_wait = 0
- # Get tracked engines - count distinct engine types from attempts
- tracked_engines_query = session.query(
- func.count(func.distinct(RateLimitAttempt.engine_type))
- )
- if cutoff_time > 0:
- tracked_engines_query = tracked_engines_query.filter(
- RateLimitAttempt.timestamp >= cutoff_time
- )
- tracked_engines = tracked_engines_query.scalar() or 0
+ estimates = estimates_query.all()
- # Get engine-specific stats from attempts
engine_stats = []
-
- # Get distinct engine types from attempts
- engine_types_query = session.query(
- RateLimitAttempt.engine_type
- ).distinct()
- if cutoff_time > 0:
- engine_types_query = engine_types_query.filter(
- RateLimitAttempt.timestamp >= cutoff_time
- )
- engine_types = [row.engine_type for row in engine_types_query.all()]
-
- # Preload estimates for relevant engines to avoid N+1 queries
- estimates_by_engine = {}
- if engine_types:
- all_estimates = (
- session.query(RateLimitEstimate)
- .filter(RateLimitEstimate.engine_type.in_(engine_types))
- .all()
- )
- estimates_by_engine = {e.engine_type: e for e in all_estimates}
-
- for engine_type in engine_types:
- engine_attempts_list = [
- a for a in attempts if a.engine_type == engine_type
- ]
- engine_attempts = len(engine_attempts_list)
- engine_success = len(
- [a for a in engine_attempts_list if a.success]
+ total_attempts = 0
+ successful_attempts = 0
+ base_wait_sum = 0.0
+
+ for estimate in estimates:
+ # success_rate is stored as a 0..1 fraction.
+ success_rate_pct = round(estimate.success_rate * 100, 1)
+ engine_attempts = estimate.total_attempts or 0
+ engine_success = round(engine_attempts * estimate.success_rate)
+
+ total_attempts += engine_attempts
+ successful_attempts += engine_success
+ base_wait_sum += estimate.base_wait_seconds
+
+ status = (
+ "healthy"
+ if estimate.success_rate > 0.8
+ else "degraded"
+ if estimate.success_rate > 0.5
+ else "poor"
)
- # Get estimate from preloaded dict
- estimate = estimates_by_engine.get(engine_type)
-
- # Calculate recent success rate
- recent_success_rate = (
- (engine_success / engine_attempts * 100)
- if engine_attempts > 0
- else 0
+ engine_stats.append(
+ {
+ "engine": estimate.engine_type,
+ "base_wait": estimate.base_wait_seconds,
+ "base_wait_seconds": round(
+ estimate.base_wait_seconds, 2
+ ),
+ "min_wait_seconds": round(estimate.min_wait_seconds, 2),
+ "max_wait_seconds": round(estimate.max_wait_seconds, 2),
+ "success_rate": success_rate_pct,
+ "total_attempts": engine_attempts,
+ "recent_attempts": engine_attempts,
+ "recent_success_rate": success_rate_pct,
+ "attempts": engine_attempts,
+ "status": status,
+ # ISO format already includes timezone
+ "last_updated": datetime.fromtimestamp(
+ estimate.last_updated, UTC
+ ).isoformat(),
+ }
)
- # Determine status based on success rate
- if estimate:
- status = (
- "healthy"
- if estimate.success_rate > 0.8
- else "degraded"
- if estimate.success_rate > 0.5
- else "poor"
- )
- else:
- status = (
- "healthy"
- if recent_success_rate > 80
- else "degraded"
- if recent_success_rate > 50
- else "poor"
- )
-
- engine_stat = {
- "engine": engine_type,
- "base_wait": estimate.base_wait_seconds
- if estimate
- else 0.0,
- "base_wait_seconds": round(
- estimate.base_wait_seconds if estimate else 0.0, 2
- ),
- "min_wait_seconds": round(
- estimate.min_wait_seconds if estimate else 0.0, 2
- ),
- "max_wait_seconds": round(
- estimate.max_wait_seconds if estimate else 0.0, 2
- ),
- "success_rate": round(estimate.success_rate * 100, 1)
- if estimate
- else recent_success_rate,
- "total_attempts": estimate.total_attempts
- if estimate
- else engine_attempts,
- "recent_attempts": engine_attempts,
- "recent_success_rate": round(recent_success_rate, 1),
- "attempts": engine_attempts,
- "status": status,
- }
-
- if estimate:
- from datetime import datetime
-
- engine_stat["last_updated"] = datetime.fromtimestamp(
- estimate.last_updated, UTC
- ).isoformat() # ISO format already includes timezone
- else:
- engine_stat["last_updated"] = "Never"
-
- engine_stats.append(engine_stat)
+ tracked_engines = len(engine_stats)
+ failed_attempts = total_attempts - successful_attempts
+ # base_wait_seconds is the learned optimal (median of recent
+ # successful waits), so it represents both the typical wait and
+ # the typical successful wait; a true per-attempt average needs
+ # the raw attempts table.
+ avg_wait_time = (
+ base_wait_sum / tracked_engines if tracked_engines else 0
+ )
+ avg_successful_wait = avg_wait_time
+ # Not derivable from estimates (needs the raw attempts table).
+ rate_limit_events = 0
logger.info(
- f"Tracked engines: {tracked_engines}, engine_stats: {engine_stats}"
+ f"Rate limiting analytics from estimates: "
+ f"tracked_engines={tracked_engines}, "
+ f"total_attempts(recent)={total_attempts}"
)
result = {
diff --git a/tests/web/routes/test_metrics_routes_coverage.py b/tests/web/routes/test_metrics_routes_coverage.py
index dcbcfd10e1..b3cd054d91 100644
--- a/tests/web/routes/test_metrics_routes_coverage.py
+++ b/tests/web/routes/test_metrics_routes_coverage.py
@@ -89,22 +89,6 @@ def _make_classification(
return c
-def _make_rate_limit_attempt(
- engine_type="google",
- success=True,
- wait_time=1.0,
- timestamp=None,
- error_type=None,
-):
- a = MagicMock()
- a.engine_type = engine_type
- a.success = success
- a.wait_time = wait_time
- a.timestamp = timestamp or time.time()
- a.error_type = error_type
- return a
-
-
def _make_rate_limit_estimate(
engine_type="google",
base_wait_seconds=1.0,
@@ -392,50 +376,81 @@ class TestGetRateLimitingAnalytics:
assert result["rate_limiting"]["error"] == "No user session"
@patch("local_deep_research.web.routes.metrics_routes.get_user_db_session")
- def test_with_attempts_and_estimates(self, mock_db):
- attempts = [
- _make_rate_limit_attempt("google", True, 0.5),
- _make_rate_limit_attempt(
- "google", False, 1.0, error_type="RateLimitError"
+ def test_estimates_populate_engine_stats(self, mock_db):
+ """Analytics are derived from RateLimitEstimate, NOT the
+ never-written RateLimitAttempt table (#4457 follow-up). Two persisted
+ estimates should surface both engines, classify health from the
+ stored success_rate, and aggregate the recent-window attempt counts.
+ """
+ google_updated = 1_700_000_000.0 # fixed epoch for a deterministic ISO
+ estimates = [
+ _make_rate_limit_estimate(
+ "google",
+ success_rate=0.9,
+ total_attempts=100,
+ last_updated=google_updated,
+ ),
+ _make_rate_limit_estimate(
+ "bing", success_rate=0.4, total_attempts=50
),
- _make_rate_limit_attempt("bing", True, 0.3),
]
- estimate = _make_rate_limit_estimate("google", success_rate=0.9)
mock_session = MagicMock()
+ q = MagicMock()
+ mock_session.query.return_value = q
+ q.filter.return_value = q # recency filter returns the same query
+ q.all.return_value = estimates
- # Main query chain
- rate_query = MagicMock()
- mock_session.query.return_value = rate_query
+ mock_db.return_value.__enter__ = MagicMock(return_value=mock_session)
+ mock_db.return_value.__exit__ = MagicMock(return_value=False)
- # filter chain
- rate_query.filter.return_value = rate_query
- rate_query.count.side_effect = [
- 3,
- 2,
- 1,
- ] # total, successful, rate_limit_events
- rate_query.all.return_value = attempts
-
- # tracked engines scalar
- rate_query.scalar.return_value = 2
-
- # distinct engine types
- engine_row_1 = MagicMock()
- engine_row_1.engine_type = "google"
- engine_row_2 = MagicMock()
- engine_row_2.engine_type = "bing"
- rate_query.distinct.return_value = rate_query
- rate_query.all.return_value = [engine_row_1, engine_row_2]
+ result = get_rate_limiting_analytics(period="30d", username="testuser")
+ rl = result["rate_limiting"]
+
+ assert rl["tracked_engines"] == 2
+ assert len(rl["engine_stats"]) == 2
+ # success_rate 0.9 -> healthy; 0.4 -> poor
+ assert rl["healthy_engines"] == 1
+ assert rl["poor_engines"] == 1
+ assert rl["degraded_engines"] == 0
+ # total_attempts is the sum of each estimate's recent window
+ assert rl["total_attempts"] == 150
+ # successful = round(100*0.9) + round(50*0.4) = 90 + 20
+ assert rl["successful_attempts"] == 110
+ assert rl["failed_attempts"] == 40
+ # Not derivable from estimates — must stay 0, not crash.
+ assert rl["rate_limit_events"] == 0
+
+ google = next(s for s in rl["engine_stats"] if s["engine"] == "google")
+ assert google["success_rate"] == 90.0
+ assert google["status"] == "healthy"
+ assert google["base_wait_seconds"] == 1.0
+ # last_updated is the estimate's epoch rendered as an ISO-8601 UTC
+ # string; assert it round-trips to the exact stored timestamp.
+ assert (
+ google["last_updated"]
+ == datetime.fromtimestamp(google_updated, UTC).isoformat()
+ )
- # Estimates query
- rate_query.filter.return_value.all.return_value = [estimate]
+ @patch("local_deep_research.web.routes.metrics_routes.get_user_db_session")
+ def test_no_estimates_returns_zeroed_panel(self, mock_db):
+ """No persisted estimates -> a clean all-zero panel (no crash)."""
+ mock_session = MagicMock()
+ q = MagicMock()
+ mock_session.query.return_value = q
+ q.filter.return_value = q
+ q.all.return_value = []
mock_db.return_value.__enter__ = MagicMock(return_value=mock_session)
mock_db.return_value.__exit__ = MagicMock(return_value=False)
result = get_rate_limiting_analytics(period="30d", username="testuser")
- assert "rate_limiting" in result
+ rl = result["rate_limiting"]
+ assert rl["tracked_engines"] == 0
+ assert rl["engine_stats"] == []
+ assert rl["total_attempts"] == 0
+ assert rl["avg_wait_time"] == 0
+ assert "error" not in rl
@patch("local_deep_research.web.routes.metrics_routes.get_user_db_session")
def test_period_all(self, mock_db):
diff --git a/tests/web/routes/test_metrics_strategy_rate_limiting.py b/tests/web/routes/test_metrics_strategy_rate_limiting.py
index 636217de35..5063f76674 100644
--- a/tests/web/routes/test_metrics_strategy_rate_limiting.py
+++ b/tests/web/routes/test_metrics_strategy_rate_limiting.py
@@ -216,19 +216,6 @@ class TestGetStrategyAnalytics:
# ---------------------------------------------------------------------------
-def _make_attempt(
- engine_type, success, wait_time, error_type=None, timestamp=100.0
-):
- """Create a mock RateLimitAttempt."""
- a = Mock()
- a.engine_type = engine_type
- a.success = success
- a.wait_time = wait_time
- a.error_type = error_type
- a.timestamp = timestamp
- return a
-
-
def _make_estimate(
engine_type,
success_rate,
@@ -267,10 +254,7 @@ class TestGetRateLimitingAnalytics:
session = MagicMock()
query = session.query.return_value
query.filter.return_value = query
- query.count.return_value = 0
query.all.return_value = []
- query.scalar.return_value = 0
- query.distinct.return_value = query
_mock_session_ctx(mock_ctx, session)
result = get_rate_limiting_analytics(period="30d", username="alice")
@@ -284,87 +268,63 @@ class TestGetRateLimitingAnalytics:
@patch(f"{_MOD}.get_user_db_session")
@patch("time.time", return_value=1_000_000.0)
def test_mixed_success_failure(self, mock_time, mock_ctx):
+ """total/successful/failed counts and success_rate are derived from
+ an estimate's recent-window total_attempts and stored success_rate."""
session = MagicMock()
- attempts = [
- _make_attempt("google", True, 0.5),
- _make_attempt("google", True, 0.3),
- _make_attempt("google", False, 1.0, error_type="RateLimitError"),
- ]
-
query = session.query.return_value
query.filter.return_value = query
- query.distinct.return_value = query
- query.count.side_effect = iter([3, 2, 1]).__next__
- query.scalar.return_value = 1
- # .all() call order: (1) attempts, (2) engine_types, (3) estimates
- query.all.side_effect = [
- attempts,
- [Mock(engine_type="google")],
- [], # no estimates
+ query.all.return_value = [
+ _make_estimate(
+ "google", success_rate=2 / 3, total_attempts=3, base_wait=0.6
+ ),
]
_mock_session_ctx(mock_ctx, session)
result = get_rate_limiting_analytics(period="30d", username="alice")
rl = result["rate_limiting"]
assert rl["total_attempts"] == 3
- assert rl["successful_attempts"] == 2
+ assert rl["successful_attempts"] == 2 # round(3 * 2/3) == 2
assert rl["failed_attempts"] == 1
assert rl["success_rate"] == pytest.approx(66.67, abs=0.1)
+ # avg_wait_time is the learned base wait (no per-attempt history).
assert rl["avg_wait_time"] == pytest.approx(0.6, abs=0.01)
@patch(f"{_MOD}.get_user_db_session")
@patch("time.time", return_value=1_000_000.0)
- def test_rate_limit_events_count(self, mock_time, mock_ctx):
- """Failures with error_type='RateLimitError' are counted as rate_limit_events."""
-
+ def test_rate_limit_events_always_zero(self, mock_time, mock_ctx):
+ """rate_limit_events (RateLimitError-specific failures) can't be
+ reconstructed from estimates — the per-attempt error_type is gone —
+ so it is always reported as 0, never crashing."""
session = MagicMock()
- attempts = [
- _make_attempt("bing", False, 2.0, error_type="RateLimitError"),
- _make_attempt("bing", False, 1.0, error_type="TimeoutError"),
- _make_attempt("bing", True, 0.5),
- ]
-
query = session.query.return_value
query.filter.return_value = query
- query.distinct.return_value = query
- query.count.side_effect = iter([3, 1, 1]).__next__
- query.scalar.return_value = 1
- query.all.side_effect = [
- attempts,
- [Mock(engine_type="bing")],
- [],
- ]
+ query.all.return_value = [_make_estimate("bing", success_rate=0.3)]
_mock_session_ctx(mock_ctx, session)
result = get_rate_limiting_analytics(period="30d", username="alice")
- assert result["rate_limiting"]["rate_limit_events"] == 1
+ assert result["rate_limiting"]["rate_limit_events"] == 0
@patch(f"{_MOD}.get_user_db_session")
@patch("time.time", return_value=1_000_000.0)
- def test_avg_successful_wait(self, mock_time, mock_ctx):
+ def test_avg_successful_wait_is_learned_base_wait(
+ self, mock_time, mock_ctx
+ ):
+ """No raw per-attempt waits exist, so avg_successful_wait mirrors the
+ mean learned base wait (== avg_wait_time)."""
session = MagicMock()
- attempts = [
- _make_attempt("google", True, 0.4),
- _make_attempt("google", True, 0.6),
- _make_attempt("google", False, 2.0),
- ]
-
query = session.query.return_value
query.filter.return_value = query
- query.distinct.return_value = query
- query.count.side_effect = iter([3, 2, 0]).__next__
- query.scalar.return_value = 1
- query.all.side_effect = [
- attempts,
- [Mock(engine_type="google")],
- [],
+ query.all.return_value = [
+ _make_estimate("google", success_rate=0.9, base_wait=0.4),
+ _make_estimate("bing", success_rate=0.9, base_wait=0.6),
]
_mock_session_ctx(mock_ctx, session)
result = get_rate_limiting_analytics(period="30d", username="alice")
rl = result["rate_limiting"]
- assert rl["avg_successful_wait"] == pytest.approx(0.5, abs=0.01)
- assert rl["avg_wait_time"] == pytest.approx(1.0, abs=0.01)
+ # mean of the two base waits: (0.4 + 0.6) / 2 == 0.5
+ assert rl["avg_wait_time"] == pytest.approx(0.5, abs=0.01)
+ assert rl["avg_successful_wait"] == rl["avg_wait_time"]
@patch(f"{_MOD}.get_user_db_session")
@patch("time.time", return_value=1_000_000.0)
@@ -372,19 +332,9 @@ class TestGetRateLimitingAnalytics:
"""estimate.success_rate > 0.8 → 'healthy'."""
session = MagicMock()
- attempts = [_make_attempt("google", True, 0.5)]
-
query = session.query.return_value
query.filter.return_value = query
- query.distinct.return_value = query
- query.count.side_effect = iter([1, 1, 0]).__next__
- query.scalar.return_value = 1
- # .all() order: (1) attempts, (2) engine_types, (3) estimates
- query.all.side_effect = [
- attempts,
- [Mock(engine_type="google")],
- [_make_estimate("google", 0.9)],
- ]
+ query.all.return_value = [_make_estimate("google", success_rate=0.9)]
_mock_session_ctx(mock_ctx, session)
result = get_rate_limiting_analytics(period="30d", username="alice")
@@ -399,18 +349,9 @@ class TestGetRateLimitingAnalytics:
"""0.5 < estimate.success_rate <= 0.8 → 'degraded'."""
session = MagicMock()
- attempts = [_make_attempt("google", True, 0.5)]
-
query = session.query.return_value
query.filter.return_value = query
- query.distinct.return_value = query
- query.count.side_effect = iter([1, 1, 0]).__next__
- query.scalar.return_value = 1
- query.all.side_effect = [
- attempts,
- [Mock(engine_type="google")],
- [_make_estimate("google", 0.7)],
- ]
+ query.all.return_value = [_make_estimate("google", success_rate=0.7)]
_mock_session_ctx(mock_ctx, session)
result = get_rate_limiting_analytics(period="30d", username="alice")
@@ -425,18 +366,9 @@ class TestGetRateLimitingAnalytics:
"""estimate.success_rate <= 0.5 → 'poor'."""
session = MagicMock()
- attempts = [_make_attempt("google", False, 2.0)]
-
query = session.query.return_value
query.filter.return_value = query
- query.distinct.return_value = query
- query.count.side_effect = iter([1, 0, 1]).__next__
- query.scalar.return_value = 1
- query.all.side_effect = [
- attempts,
- [Mock(engine_type="google")],
- [_make_estimate("google", 0.3)],
- ]
+ query.all.return_value = [_make_estimate("google", success_rate=0.3)]
_mock_session_ctx(mock_ctx, session)
result = get_rate_limiting_analytics(period="30d", username="alice")
@@ -445,52 +377,34 @@ class TestGetRateLimitingAnalytics:
@patch(f"{_MOD}.get_user_db_session")
@patch("time.time", return_value=1_000_000.0)
- def test_no_estimate_falls_back_to_recent_rate(self, mock_time, mock_ctx):
- """No estimate → uses recent_success_rate with 80/50 thresholds."""
-
+ def test_status_thresholds_are_strict(self, mock_time, mock_ctx):
+ """Health thresholds are strict (>): success_rate 0.8 is degraded
+ (not healthy) and 0.5 is poor (not degraded)."""
session = MagicMock()
- # 1 out of 2 = 50% → poor (not > 50)
- attempts = [
- _make_attempt("bing", True, 0.5),
- _make_attempt("bing", False, 1.0),
- ]
-
query = session.query.return_value
query.filter.return_value = query
- query.distinct.return_value = query
- query.count.side_effect = iter([2, 1, 0]).__next__
- query.scalar.return_value = 1
- query.all.side_effect = [
- attempts,
- [Mock(engine_type="bing")],
- [], # no estimates
+ query.all.return_value = [
+ _make_estimate("edge_high", success_rate=0.8),
+ _make_estimate("edge_low", success_rate=0.5),
]
_mock_session_ctx(mock_ctx, session)
result = get_rate_limiting_analytics(period="30d", username="alice")
- engine_stat = result["rate_limiting"]["engine_stats"][0]
- assert engine_stat["status"] == "poor"
- assert engine_stat["recent_success_rate"] == 50.0
+ engines = {
+ s["engine"]: s for s in result["rate_limiting"]["engine_stats"]
+ }
+ assert engines["edge_high"]["status"] == "degraded"
+ assert engines["edge_low"]["status"] == "poor"
@patch(f"{_MOD}.get_user_db_session")
@patch("time.time", return_value=1_000_000.0)
def test_multiple_engines_aggregated(self, mock_time, mock_ctx):
session = MagicMock()
- attempts = [
- _make_attempt("google", True, 0.3),
- _make_attempt("bing", True, 0.5),
- _make_attempt("bing", False, 1.0),
- ]
-
query = session.query.return_value
query.filter.return_value = query
- query.distinct.return_value = query
- query.count.side_effect = iter([3, 2, 0]).__next__
- query.scalar.return_value = 2
- query.all.side_effect = [
- attempts,
- [Mock(engine_type="google"), Mock(engine_type="bing")],
- [], # no estimates
+ query.all.return_value = [
+ _make_estimate("google", success_rate=1.0, total_attempts=4),
+ _make_estimate("bing", success_rate=0.5, total_attempts=4),
]
_mock_session_ctx(mock_ctx, session)
@@ -503,20 +417,40 @@ class TestGetRateLimitingAnalytics:
@patch(f"{_MOD}.get_user_db_session")
@patch("time.time", return_value=1_000_000.0)
- def test_period_all_cutoff_zero(self, mock_time, mock_ctx):
- """period='all' → cutoff_time=0 → no time filter applied."""
+ def test_period_all_skips_recency_filter(self, mock_time, mock_ctx):
+ """period='all' → cutoff_time=0 → no last_updated filter applied."""
session = MagicMock()
query = session.query.return_value
query.filter.return_value = query
- query.distinct.return_value = query
- query.count.return_value = 0
query.all.return_value = []
- query.scalar.return_value = 0
_mock_session_ctx(mock_ctx, session)
result = get_rate_limiting_analytics(period="all", username="alice")
assert "rate_limiting" in result
+ # No recency cutoff means the estimates query is never filtered.
+ query.filter.assert_not_called()
+
+ @patch(f"{_MOD}.get_user_db_session")
+ @patch("time.time", return_value=1_000_000.0)
+ def test_time_window_applies_last_updated_cutoff(self, mock_time, mock_ctx):
+ """A bounded period filters estimates by last_updated >= cutoff."""
+
+ session = MagicMock()
+ query = session.query.return_value
+ query.filter.return_value = query
+ query.all.return_value = []
+ _mock_session_ctx(mock_ctx, session)
+
+ get_rate_limiting_analytics(period="7d", username="alice")
+
+ query.filter.assert_called_once()
+ # The filter is `RateLimitEstimate.last_updated >= now - 7d`; verify
+ # both the column and the bound cutoff value.
+ criterion = query.filter.call_args.args[0]
+ assert "last_updated" in str(criterion)
+ expected_cutoff = 1_000_000.0 - (7 * 24 * 3600)
+ assert criterion.right.value == pytest.approx(expected_cutoff)
@patch(f"{_MOD}.get_user_db_session")
def test_exception_returns_fallback(self, mock_ctx):