~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(db): retry the tracker's reset/cleanup deletes on SQLite lock blips (#6950)
LearningCircuit6e2215de5202
diff --git a/changelog.d/6945.bugfix.md b/changelog.d/6945.bugfix.mdnew file mode 100644index 0000000000..c81927aa69--- /dev/null+++ b/changelog.d/6945.bugfix.md@@ -0,0 +1 @@+Rate-limit resets and old-data cleanup now retry SQLite lock errors, releasing owned sessions between attempts while preserving caller-owned transactions.diff --git a/src/local_deep_research/web/routers/settings.py b/src/local_deep_research/web/routers/settings.pyindex 55add60587..be55d53629 100644--- a/src/local_deep_research/web/routers/settings.py+++ b/src/local_deep_research/web/routers/settings.py@@ -73,6 +73,7 @@ from ...database.models.rate_limiting import RateLimitEstimatefrom ...database.models.settings import Setting, SettingTypefrom ...database.session_context import get_user_db_sessionfrom ...database.encrypted_db import db_manager+from ...database.sqlcipher_utils import retry_on_db_lockfrom ...llm.providers.base import normalize_providerfrom ...security.egress.policy import (DEFAULT_EGRESS_SCOPE,@@ -4272,11 +4273,20 @@ def api_reset_engine_rate_limiting(estimate the ``/status`` and ``/current`` endpoints display (#4721)."""try:- with get_user_db_session(username) as db_session:- db_session.query(RateLimitEstimate).filter_by(- engine_type=engine_type- ).delete(synchronize_session=False)- db_session.commit()+ # (#6945) Same retry wrap the tracker's reset_engine got: a+ # transient SQLite writer-lock blip must not fail the request+ # on the first "database is locked". The closure opens a fresh+ # ``get_user_db_session`` per attempt so the writer lock is+ # released between tries; after retry exhaustion the existing+ # error handling below still applies.+ def _reset_db():+ with get_user_db_session(username) as db_session:+ db_session.query(RateLimitEstimate).filter_by(+ engine_type=engine_type+ ).delete(synchronize_session=False)+ db_session.commit()++ retry_on_db_lock(_reset_db)return {"message": f"Rate limiting data reset for {engine_type}"}@@ -4292,11 +4302,19 @@ def api_reset_engine_rate_limiting(def _cleanup_rate_limit_estimates_sync(username: str, cutoff: float) -> None:"""Delete persisted rate-limit estimates last updated before *cutoff*."""- with get_user_db_session(username) as db_session:- db_session.query(RateLimitEstimate).filter(- RateLimitEstimate.last_updated < cutoff- ).delete(synchronize_session=False)- db_session.commit()++ # (#6945) Same retry wrap the tracker's cleanup_old_data got — see+ # api_reset_engine_rate_limiting above for the rationale. Fresh+ # session per attempt; lock exhaustion propagates to the route's+ # existing error handling.+ def _cleanup_db():+ with get_user_db_session(username) as db_session:+ db_session.query(RateLimitEstimate).filter(+ RateLimitEstimate.last_updated < cutoff+ ).delete(synchronize_session=False)+ db_session.commit()++ retry_on_db_lock(_cleanup_db)@router.post("/api/rate-limiting/cleanup")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.pyindex de27488ff7..bc1a4d04cb 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@@ -900,18 +900,25 @@ class AdaptiveRateLimitTracker:if not RateLimitAttempt or not RateLimitEstimate:return- session_reset: "Session"- with self._resolve_session(username, password) as session_reset:- with self._isolated_begin_nested(session_reset):- # Delete historical attempts- session_reset.query(RateLimitAttempt).filter_by(- engine_type=engine_type- ).delete()-- # Delete estimates- session_reset.query(RateLimitEstimate).filter_by(- engine_type=engine_type- ).delete()+ from ...database.sqlcipher_utils import retry_on_db_lock++ # Resolve again per attempt: owned sessions close before backoff;+ # borrowed sessions keep main's savepoint and caller-state isolation.+ def _reset_db():+ session_reset: "Session"+ with self._resolve_session(username, password) as session_reset:+ with self._isolated_begin_nested(session_reset):+ # Delete historical attempts+ session_reset.query(RateLimitAttempt).filter_by(+ engine_type=engine_type+ ).delete()++ # Delete estimates+ session_reset.query(RateLimitEstimate).filter_by(+ engine_type=engine_type+ ).delete()++ retry_on_db_lock(_reset_db)logger.info(f"Reset rate limit data for {engine_type}")@@ -1032,16 +1039,20 @@ class AdaptiveRateLimitTracker:if not RateLimitAttempt:return- session_clean: "Session"- deleted_count = 0- with self._resolve_session(username, password) as session_clean:- with self._isolated_begin_nested(session_clean):- # Count and delete old attempts- old_attempts: Any = session_clean.query(- RateLimitAttempt- ).filter(RateLimitAttempt.timestamp < cutoff_time)- deleted_count = old_attempts.count()- old_attempts.delete()+ from ...database.sqlcipher_utils import retry_on_db_lock++ def _cleanup_db():+ session_clean: "Session"+ with self._resolve_session(username, password) as session_clean:+ with self._isolated_begin_nested(session_clean):+ old_attempts: Any = session_clean.query(+ RateLimitAttempt+ ).filter(RateLimitAttempt.timestamp < cutoff_time)+ deleted_count = old_attempts.count()+ old_attempts.delete()+ return deleted_count++ deleted_count = retry_on_db_lock(_cleanup_db)if deleted_count > 0:logger.info(f"Cleaned up {deleted_count} old retry attempts")diff --git a/tests/web/routers/test_settings_routes_rate_limiting_port.py b/tests/web/routers/test_settings_routes_rate_limiting_port.pyindex 05724c6beb..30bca5a436 100644--- a/tests/web/routers/test_settings_routes_rate_limiting_port.py+++ b/tests/web/routers/test_settings_routes_rate_limiting_port.py@@ -41,6 +41,7 @@ from types import SimpleNamespacefrom unittest.mock import MagicMock, patchimport pytest+from sqlalchemy.exc import OperationalErrorSETTINGS_PREFIX = "/settings"ROUTER = "local_deep_research.web.routers.settings"@@ -294,6 +295,83 @@ class TestApiCleanupRateLimiting:assert response.status_code == 400+def _locked_commit_error():+ """SQLAlchemy-wrapped SQLITE_BUSY, as a locked commit raises it."""+ return OperationalError(+ "DELETE FROM rate_limit_estimates",+ {},+ Exception("database is locked"),+ )+++@contextmanager+def _patch_sessions_lock_then_succeed(sessions, first_error):+ """Patch ``get_user_db_session`` to yield one FRESH mock session per+ entry, the first entry's commit raising *first_error* -- the shape a+ transient writer-lock blip produces on these routes (mirrors the+ tracker's retry tests in+ ``tests/web_search_engines/rate_limiting/test_tracker_coverage.py``)."""++ def _factory(username, password=None):+ @contextmanager+ def _cm():+ ms = MagicMock()+ if not sessions and first_error is not None:+ ms.commit.side_effect = first_error+ sessions.append(ms)+ yield ms++ return _cm()++ with patch(f"{ROUTER}.get_user_db_session", side_effect=_factory):+ yield sessions+++class TestRateLimitingRoutesLockRetry:+ """#6945: the live reset/cleanup routes must retry a SQLite+ writer-lock blip (the same wrap the tracker's reset_engine /+ cleanup_old_data got), opening a FRESH session per attempt instead+ of surfacing the first ``database is locked`` as a 500."""++ def test_reset_retries_locked_delete(self, authenticated_client):+ sessions = []+ with _patch_sessions_lock_then_succeed(+ sessions, _locked_commit_error()+ ):+ response = authenticated_client.post(+ f"{SETTINGS_PREFIX}/api/rate-limiting/engines/google/reset"+ )+ assert response.status_code == 200+ assert "google" in response.get_json()["message"]+ assert len(sessions) >= 2, (+ "the first 'database is locked' surfaced as a 500 instead of "+ "being retried on a fresh session"+ )+ sessions[+ -1+ ].query.return_value.filter_by.return_value.delete.assert_called_once()+ assert sessions[-1].commit.call_count == 1++ def test_cleanup_retries_locked_delete(self, authenticated_client):+ sessions = []+ with _patch_sessions_lock_then_succeed(+ sessions, _locked_commit_error()+ ):+ response = authenticated_client.post(+ f"{SETTINGS_PREFIX}/api/rate-limiting/cleanup"+ )+ assert response.status_code == 200+ assert "30 days" in response.get_json()["message"]+ assert len(sessions) >= 2, (+ "the first 'database is locked' surfaced as a 500 instead of "+ "being retried on a fresh session"+ )+ sessions[+ -1+ ].query.return_value.filter.return_value.delete.assert_called_once()+ assert sessions[-1].commit.call_count == 1++class TestCheckOllamaStatusSettings:"""GET /settings/api/ollama-status."""diff --git a/tests/web_search_engines/rate_limiting/test_tracker_coverage.py b/tests/web_search_engines/rate_limiting/test_tracker_coverage.pyindex a1baef7a87..507a8bd4ba 100644--- a/tests/web_search_engines/rate_limiting/test_tracker_coverage.py+++ b/tests/web_search_engines/rate_limiting/test_tracker_coverage.py@@ -7,6 +7,8 @@ from collections import dequefrom contextlib import contextmanagerfrom unittest.mock import MagicMock, patch+from sqlalchemy.exc import OperationalError+from local_deep_research.config.thread_settings import NoSettingsContextErrorMODULE = "local_deep_research.web_search_engines.rate_limiting.tracker"@@ -595,6 +597,126 @@ class TestCleanupOldDataDB:tracker.cleanup_old_data(days=30)+class TestTrackerLockRetry:+ """#6945: the DB blocks behind reset_engine / cleanup_old_data must+ retry a SQLite writer-lock blip (the wrapped shape #6718 gave+ token_counter's write path), opening a FRESH metrics_writer session+ per attempt so the lock is released between tries."""++ def _locked(self):+ return OperationalError(+ "DELETE FROM rate_limit_attempts",+ {},+ Exception("database is locked"),+ )++ def _session_factory(self, sessions, first_error, configure=None):+ """A get_session stand-in recording one fresh mock per entry."""++ @contextmanager+ def _cm(*args, **kwargs):+ ms = MagicMock()+ if configure is not None:+ configure(ms)+ if len(sessions) == 0 and first_error is not None:+ ms.commit.side_effect = first_error+ sessions.append(ms)+ yield ms+ # The owned metrics-writer context commits on successful exit.+ ms.commit()++ return _cm++ @patch(f"{MODULE}.is_ci_environment", return_value=False)+ @patch(+ f"{MODULE}.get_search_context",+ return_value={"username": "u", "user_password": "p"},+ )+ def test_reset_engine_retries_locked_delete(self, _ctx, _ci):+ """First commit hits the writer lock; the retry lands the durable+ delete on a second, fresh session instead of swallowing the+ first attempt with a warning."""+ tracker = _make_tracker(programmatic_mode=False)+ tracker.recent_attempts["Eng"] = deque(+ [_attempt(1.0, True)], maxlen=100+ )+ tracker.current_estimates["Eng"] = {+ "base": 1.0,+ "min": 0.5,+ "max": 2.0,+ "confidence": 0.5,+ }+ sessions = []+ mock_writer = MagicMock()+ mock_writer.get_session = self._session_factory(+ sessions, self._locked()+ )+ imports = {+ "RateLimitAttempt": MagicMock(),+ "RateLimitEstimate": MagicMock(),+ }+ with patch(f"{MODULE}._get_db_imports", return_value=imports):+ with patch(+ "local_deep_research.database.thread_metrics.metrics_writer",+ mock_writer,+ ):+ tracker.reset_engine("Eng")++ assert len(sessions) >= 2, (+ "the first 'database is locked' was swallowed after one "+ "attempt instead of being retried"+ )+ # The durable delete ran on the successful (fresh) session: both+ # the attempts and the estimates deletes were issued and its+ # commit landed without raising.+ sessions[+ -1+ ].query.return_value.filter_by.return_value.delete.assert_called()+ assert sessions[-1].commit.call_count == 1++ @patch(f"{MODULE}.is_ci_environment", return_value=False)+ @patch(+ f"{MODULE}.get_search_context",+ return_value={"username": "u", "user_password": "p"},+ )+ def test_cleanup_old_data_retries_locked_delete(self, _ctx, _ci):+ """Same shape for cleanup_old_data: count+delete survive a first+ -attempt lock on a second fresh session."""+ tracker = _make_tracker(programmatic_mode=False)+ sessions = []+ mock_writer = MagicMock()+ # timestamp must support ``<`` against the float cutoff (same+ # trick TestCleanupOldDataDB uses).+ mock_rla = MagicMock()+ mock_rla.timestamp.__lt__ = MagicMock(return_value=MagicMock())+ imports = {"RateLimitAttempt": mock_rla}++ def _stub_count(ms):+ # The post-retry success branch compares deleted_count+ # against 0; stub 42 so it actually runs (mirrors+ # TestCleanupOldDataDB.test_full_cleanup_deletes_old_rows).+ ms.query.return_value.filter.return_value.count.return_value = 42++ mock_writer.get_session = self._session_factory(+ sessions, self._locked(), configure=_stub_count+ )+ with patch(f"{MODULE}._get_db_imports", return_value=imports):+ with patch(+ "local_deep_research.database.thread_metrics.metrics_writer",+ mock_writer,+ ):+ tracker.cleanup_old_data(days=30)++ assert len(sessions) >= 2, (+ "the first 'database is locked' was swallowed after one "+ "attempt instead of being retried"+ )+ sessions[+ -1+ ].query.return_value.filter.return_value.delete.assert_called()+ assert sessions[-1].commit.call_count == 1++class TestGetTrackerFactory:"""Tests for get_tracker() factory."""