~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(metrics): derive the rate-limit cutoff from the shared period map (#6949)
LearningCircuitf7dbb55da624
diff --git a/changelog.d/6942.bugfix.md b/changelog.d/6942.bugfix.mdnew file mode 100644index 0000000000..4cdf31c11d--- /dev/null+++ b/changelog.d/6942.bugfix.md@@ -0,0 +1 @@+Rate-limit metrics now honor the full period vocabulary. `/metrics/api/metrics` and `/metrics/api/rate-limiting` (and `TokenCounter.get_overall_metrics`) previously computed their rate-limit numbers all-time for `period=90d`, `365d` or any unrecognised value while the token window in the same response was bounded; the rate-limit window now comes from the same `get_period_cutoff` helper, so `90d`/`365d` mean 90/365 days and an unrecognised period falls back to 30 days, matching the token window. The shipped dashboard only sends `7d`/`30d`/`3m`/`1y`/`all` to these endpoints, so only direct API callers were affected. The context-overflow endpoint's duplicate period ladder now uses the same helper too (no behaviour change there, since that endpoint already maps unknown periods to `30d`).diff --git a/src/local_deep_research/metrics/token_counter.py b/src/local_deep_research/metrics/token_counter.pyindex b37b9a9952..99ed2096f9 100644--- a/src/local_deep_research/metrics/token_counter.py+++ b/src/local_deep_research/metrics/token_counter.py@@ -1374,17 +1374,17 @@ class TokenCounter:# condition: 0, no cutoff, which is what period "all" means.cutoff_time = 0if time_condition is not None:- # RateLimitAttempt uses timestamp as float, not datetime- if period == "7d":- cutoff_time = time.time() - (7 * 24 * 3600)- elif period == "30d":- cutoff_time = time.time() - (30 * 24 * 3600)- elif period == "3m":- cutoff_time = time.time() - (90 * 24 * 3600)- elif period == "1y":- cutoff_time = time.time() - (365 * 24 * 3600)- else: # all- cutoff_time = 0+ # RateLimitAttempt uses timestamp as float, not datetime.+ # (#6942) Derive the window from the same single source+ # of truth as time_condition above (PERIOD_DAYS_MAP via+ # get_period_cutoff) instead of a local 7d/30d/3m/1y+ # ladder: the ladder did not know the '90d'/'365d'+ # aliases (or any unknown value, which time_condition+ # treats as 30 days) and silently widened those+ # rate-limit numbers to all-time under a bounded label.+ cutoff_dt = get_period_cutoff(period)+ if cutoff_dt is not None:+ cutoff_time = cutoff_dt.timestamp()if cutoff_time > 0:rate_limit_query = rate_limit_query.filter(diff --git a/src/local_deep_research/web/routers/context_overflow_api.py b/src/local_deep_research/web/routers/context_overflow_api.pyindex a7b001e743..2c15cc4be5 100644--- a/src/local_deep_research/web/routers/context_overflow_api.py+++ b/src/local_deep_research/web/routers/context_overflow_api.py@@ -4,13 +4,15 @@ from fastapi import APIRouter, Depends, Requestfrom fastapi.responses import JSONResponsefrom ..dependencies.auth import require_auth-from datetime import datetime, timedelta, timezonefrom sqlalchemy import func, descfrom loguru import loggerfrom ...database.session_context import get_user_db_sessionfrom ...database.models import TokenUsage-from ...metrics.query_utils import get_context_overflow_truncation_summary+from ...metrics.query_utils import (+ get_context_overflow_truncation_summary,+ get_period_cutoff,+)from ...settings import SettingsManagerfrom typing import Annotated@@ -68,24 +70,19 @@ def get_context_overflow_metrics(per_page = 50per_page = max(1, min(per_page, 500))- # Calculate date filter (use timezone-aware datetime)- start_date = None- if period != "all":- now = datetime.now(timezone.utc)- if period == "7d":- start_date = now - timedelta(days=7)- elif period == "30d":- start_date = now - timedelta(days=30)- elif period == "3m":- start_date = now - timedelta(days=90)- elif period == "1y":- start_date = now - timedelta(days=365)+ # Calculate date filter (timezone-aware UTC). Derived from the same+ # single source of truth as the truncation summary below+ # (PERIOD_DAYS_MAP via get_period_cutoff) rather than a local+ # 7d/30d/3m/1y ladder, so the two windows in this response cannot+ # drift apart (#6942). None means 'all' (no time limit).+ start_date = get_period_cutoff(period)with get_user_db_session(username) as session:# Truncation summary — shared with /metrics/api/metrics so the# main dashboard's at-a-glance numbers cannot disagree with this# endpoint's deep-dive. Helper internally uses- # get_time_filter_condition, equivalent to the start_date below.+ # get_time_filter_condition, which derives its cutoff from the+ # same get_period_cutoff as the start_date above.summary = get_context_overflow_truncation_summary(session, period)total_requests = summary["total_requests"]requests_with_context = summary["requests_with_context"]diff --git a/src/local_deep_research/web/routers/metrics.py b/src/local_deep_research/web/routers/metrics.pyindex fa5bfcb47e..dc61ea263e 100644--- a/src/local_deep_research/web/routers/metrics.py+++ b/src/local_deep_research/web/routers/metrics.py@@ -34,6 +34,7 @@ from ...database.session_context import get_user_db_sessionfrom ...metrics import TokenCounterfrom ...metrics.query_utils import (get_context_overflow_truncation_summary,+ get_period_cutoff,get_period_days,get_time_filter_condition,)@@ -625,19 +626,15 @@ def get_rate_limiting_analytics(period="30d", username=None):}}- # Calculate date range for timestamp filtering- import time-- if period == "7d":- cutoff_time = time.time() - (7 * 24 * 3600)- elif period == "30d":- cutoff_time = time.time() - (30 * 24 * 3600)- elif period == "3m":- cutoff_time = time.time() - (90 * 24 * 3600)- elif period == "1y":- cutoff_time = time.time() - (365 * 24 * 3600)- else: # all- cutoff_time = 0+ # Calculate date range for timestamp filtering. Same single source+ # of truth as the token window (PERIOD_DAYS_MAP via+ # get_period_cutoff) — the local 7d/30d/3m/1y ladder this replaces+ # computed ALL-TIME for any other period string ('90d', '365d', or+ # an unknown value) while the token window in the same /api/metrics+ # response was bounded (#6942). This dict is spread after the token+ # metrics there, so its 'rate_limiting' value is the one served.+ cutoff_dt = get_period_cutoff(period)+ cutoff_time = cutoff_dt.timestamp() if cutoff_dt is not None else 0with get_user_db_session(username) as session:# Rate-limit analytics are derived from RateLimitEstimate, thediff --git a/tests/metrics/test_token_counter_metrics_with_data.py b/tests/metrics/test_token_counter_metrics_with_data.pyindex 0b815ba725..baf67361ba 100644--- a/tests/metrics/test_token_counter_metrics_with_data.py+++ b/tests/metrics/test_token_counter_metrics_with_data.py@@ -10,6 +10,8 @@ import timefrom typing import Anyfrom unittest.mock import MagicMock, Mock, patch+import pytest+from local_deep_research.metrics.token_counter import TokenCounter@@ -264,6 +266,80 @@ class TestMetricsTimeFilters:assert "rate_limiting" in result+class TestRateLimitPeriodWindow:+ """#6942: the rate-limit cutoff must honor the full period vocabulary.++ ``PERIOD_DAYS_MAP`` accepts the ``90d``/``365d`` aliases, and an+ unknown period falls back to 30 days for the token window. The old+ local ``7d/30d/3m/1y`` ladder knew none of these, so the rate-limit+ rows in the same result were computed all-time under a bounded+ label. Here the session mock keys one query chain per queried model,+ so the ``RateLimitAttempt`` chain's filter calls can be inspected+ directly.+ """++ @pytest.mark.parametrize(+ "period,days", [("90d", 90), ("365d", 365), ("today", 30)]+ )+ def test_rate_limit_rows_respect_the_bounded_window(self, period, days):+ from local_deep_research.database.models import RateLimitAttempt++ counter = TokenCounter()+ chains: dict[Any, MagicMock] = {}++ def _query_for(*args, **kwargs):+ chain = chains.setdefault(args[0], MagicMock())+ for attr in (+ "filter",+ "filter_by",+ "with_entities",+ "group_by",+ "order_by",+ "limit",+ "distinct",+ ):+ getattr(chain, attr).return_value = chain+ chain.scalar.return_value = 0+ chain.count.return_value = 0+ chain.all.return_value = []+ chain.first.return_value = MagicMock(+ total_input_tokens=0,+ total_output_tokens=0,+ avg_input_tokens=0,+ avg_output_tokens=0,+ avg_total_tokens=0,+ )+ return chain++ mock_session = MagicMock()+ mock_session.query.side_effect = _query_for++ with patch(+ "local_deep_research.metrics.token_counter.get_current_username",+ return_value="testuser",+ ):+ with _patch_get_user_db_session(mock_session):+ result = counter._get_metrics_from_encrypted_db(period, "all")++ assert "rate_limiting" in result, "the full success path did not run"+ attempts_chain = chains[RateLimitAttempt]+ cutoffs = [+ condition.right.value+ for call in attempts_chain.filter.call_args_list+ for condition in call.args+ if "timestamp" in str(getattr(condition, "left", ""))+ ]+ assert cutoffs, (+ "no timestamp window was applied to the rate-limit rows: the "+ "period was silently widened to all-time"+ )+ expected = time.time() - days * 24 * 3600+ for cutoff in cutoffs:+ assert abs(cutoff - expected) < 300, (+ f"cutoff {cutoff} does not match the {period} window"+ )++class TestMetricsRateLimiting:"""Tests for rate limiting aggregation when data is present."""diff --git a/tests/web/routers/test_metrics_analytics_aggregation.py b/tests/web/routers/test_metrics_analytics_aggregation.pyindex 973626aa1c..85b7777e54 100644--- a/tests/web/routers/test_metrics_analytics_aggregation.py+++ b/tests/web/routers/test_metrics_analytics_aggregation.py@@ -46,6 +46,8 @@ branch, which is now the only path to that error dict.from unittest.mock import MagicMock, Mock, patch+from datetime import UTC, datetime+import pytestfrom local_deep_research.web.routers.metrics import (@@ -630,13 +632,26 @@ class TestGetRateLimitingAnalytics:query.filter.assert_not_called()@patch(f"{MODULE}.get_user_db_session")- @patch("time.time", return_value=1_000_000.0)+ @patch(+ f"{MODULE}.get_period_cutoff",+ return_value=datetime.fromtimestamp(1_000_000.0, tz=UTC),+ )def test_a_bounded_period_filters_on_last_updated_at_the_right_cutoff(- self, mock_time, mock_ctx+ self, mock_cutoff, mock_ctx):"""Both halves matter: the correct column, and the correct bound.A filter on the right column with the wrong window is the silent- failure this pins."""+ failure this pins.++ Premise updated alongside the shared-clock migration: the cutoff+ used to be computed from a local ``time.time()`` ladder in this+ router (hence the old ``@patch("time.time")`` seam); it now comes+ from ``get_period_cutoff`` (``datetime.now(UTC)`` inside+ query_utils), so the test pins the integration by stubbing the+ cutoff source — the window arithmetic itself is unit-tested next+ to ``get_period_cutoff``. Because the cutoff is stubbed, the test+ also asserts the period that was forwarded to it: a router that+ hard-codes or rewrites the period would otherwise still pass."""session, query = _estimates_session([])_mock_session_ctx(mock_ctx, session)@@ -645,9 +660,8 @@ class TestGetRateLimitingAnalytics:query.filter.assert_called_once()criterion = query.filter.call_args.args[0]assert "last_updated" in str(criterion)- assert criterion.right.value == pytest.approx(- 1_000_000.0 - (7 * 24 * 3600)- )+ assert criterion.right.value == pytest.approx(1_000_000.0)+ mock_cutoff.assert_called_once_with("7d")@patch(f"{MODULE}.get_user_db_session")def test_a_database_failure_degrades_to_the_zero_panel(self, mock_ctx):diff --git a/tests/web/routers/test_metrics_endpoint_edge_branches.py b/tests/web/routers/test_metrics_endpoint_edge_branches.pyindex 289c1def1e..d50dfd5b52 100644--- a/tests/web/routers/test_metrics_endpoint_edge_branches.py+++ b/tests/web/routers/test_metrics_endpoint_edge_branches.py@@ -6,6 +6,8 @@ from contextlib import AbstractContextManager, contextmanagerfrom types import SimpleNamespacefrom unittest.mock import MagicMock+from datetime import UTC, datetime+import pytestfrom fastapi.responses import JSONResponsefrom pytest_mock import MockerFixture@@ -124,20 +126,35 @@ def test_link_analytics_skips_resource_parser_error(assert parser.call_count == 2-def test_three_month_rate_limit_period_uses_ninety_day_cutoff(- mocker: MockerFixture,+ ("period", "days"),+ [+ ("7d", 7),+ ("30d", 30),+ ("3m", 90),+ ("90d", 90),+ ("1y", 365),+ ("365d", 365),+ # Unknown periods fall back to 30 days, matching the token window+ # (get_time_filter_condition) in the same /api/metrics response.+ ("today", 30),+ ("", 30),+ ],+)+def test_rate_limit_period_uses_the_shared_period_window(+ mocker: MockerFixture, period: str, days: int) -> None:- """``"3m"`` (metrics.py:626-627) is not covered by- ``test_metrics_analytics_aggregation.py``: that file pins the ``"all"``- cutoff and the ``"7d"`` cutoff with two separate tests- (``test_period_all_skips_the_recency_filter``, ~624, and- ``test_a_bounded_period_filters_on_last_updated_at_the_right_cutoff``,- ~634) rather than a parametrization, and neither one exercises ``"30d"``- or ``"3m"``. Guards mirror that file's bounded-period test so this is not- a weaker copy: exactly one filter call, on the ``last_updated`` column,- at the 90-day bound. Mutating the multiplier, the column, or routing- ``"3m"`` to the ``else: cutoff_time = 0`` arm (which skips the filter- entirely) fails one of the three.+ """#6942: every bounded period, including the ``90d``/``365d`` aliases+ the old local ``7d/30d/3m/1y`` ladder did not know, filters the+ ``RateLimitEstimate`` rows on ``last_updated`` at the right bound.++ The real ``get_period_cutoff`` runs here (no stub), so this pins the+ whole path from the router's period argument to the bound it applies:+ a router that hard-codes a period, allowlists only the old+ vocabulary, routes a period to the ``cutoff_time = 0`` (all-time)+ arm, or filters on the wrong column fails. ``"all"`` (no filter) is+ pinned by ``test_period_all_skips_the_recency_filter`` in+ ``test_metrics_analytics_aggregation.py``."""query = _chain_query()query.filter.return_value = query@@ -147,16 +164,16 @@ def test_three_month_rate_limit_period_uses_ninety_day_cutoff(mocker.patch.object(metrics, "get_user_db_session", side_effect=_db_factory(session))- mocker.patch("time.time", return_value=10_000_000.0)- metrics.get_rate_limiting_analytics("3m", username="alice")+ expected = datetime.now(UTC).timestamp() - days * 24 * 3600+ metrics.get_rate_limiting_analytics(period, username="alice")query.filter.assert_called_once()criterion = query.filter.call_args.args[0]assert "last_updated" in str(criterion)- assert criterion.right.value == pytest.approx(- 10_000_000.0 - (90 * 24 * 3600)- )+ # 300 s tolerance absorbs the wall clock moving during the call; the+ # nearest wrong window (30 vs 90 days) is ~60 days away.+ assert criterion.right.value == pytest.approx(expected, abs=300)def test_research_link_metrics_classifies_skips_and_recovers(