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(db): retry rate-limit persist on SQLite lock, log exception class on DB failures (#7190)

S26337d89ecfc
diff --git a/changelog.d/+rate-limit-persist-retry-observability.bugfix.md b/changelog.d/+rate-limit-persist-retry-observability.bugfix.md
new file mode 100644
index 0000000000..9c8af1e840
--- /dev/null
+++ b/changelog.d/+rate-limit-persist-retry-observability.bugfix.md
@@ -0,0 +1 @@
+Retry transient SQLite lock errors when persisting rate-limit estimates and log the exception class on DB session/persist failures so lock timeouts are distinguishable from poisoned sessions and open failures.
diff --git a/src/local_deep_research/database/thread_metrics.py b/src/local_deep_research/database/thread_metrics.py
index 6ccfb757ff..cbe4678c31 100644
--- a/src/local_deep_research/database/thread_metrics.py
+++ b/src/local_deep_research/database/thread_metrics.py
@@ -98,15 +98,21 @@ class ThreadSafeMetricsWriter:
)
yield session
session.commit()
- except Exception:
+ except Exception as exc:
# ``logger.warning`` (no traceback) rather than
# ``logger.exception``: ``password`` is a live local in this
# frame, so rendering a traceback under ``diagnose=True``
# would dump the plaintext SQLCipher master password
# (unrecoverable — TRUST.md §5). The exception still
# propagates via the ``raise`` below, so no detail is
- # swallowed for the caller (#4182).
- logger.warning(f"Session error for {username}")
+ # swallowed for the caller (#4182). Only the exception
+ # CLASS is logged (never the message/traceback): it cannot
+ # carry the password, and without it every failure here
+ # (lock timeout vs poisoned session vs open failure) is
+ # indistinguishable in the logs.
+ logger.warning(
+ f"Session error for {username} (exc_class={type(exc).__name__})"
+ )
if session:
session.rollback()
raise
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 7f514b3706..8001fcbb11 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
@@ -669,50 +669,75 @@ class AdaptiveRateLimitTracker:
if username and password:
try:
- db_imports = _get_db_imports()
- RateLimitEstimate = (
- db_imports.get("RateLimitEstimate")
- if db_imports
- else None
- )
- if not RateLimitEstimate:
- return
-
- session_inner: "Session"
- with self._resolve_session(
- username, password
- ) as session_inner:
- with self._isolated_begin_nested(session_inner):
- # Check if estimate exists
- estimate: Any = (
- session_inner.query(RateLimitEstimate)
- .filter_by(engine_type=engine_type)
- .first()
- )
-
- if estimate:
- # Update existing estimate
- estimate.base_wait_seconds = new_base
- estimate.min_wait_seconds = min_wait
- estimate.max_wait_seconds = max_wait
- estimate.last_updated = time.time()
- estimate.total_attempts = len(attempts)
- estimate.success_rate = success_rate
- else:
- # Create new estimate
- estimate = RateLimitEstimate(
- engine_type=engine_type,
- base_wait_seconds=new_base,
- min_wait_seconds=min_wait,
- max_wait_seconds=max_wait,
- last_updated=time.time(),
- total_attempts=len(attempts),
- success_rate=success_rate,
+ from ...database.sqlcipher_utils import retry_on_db_lock
+
+ def _persist_estimate() -> None:
+ db_imports = _get_db_imports()
+ RateLimitEstimate = (
+ db_imports.get("RateLimitEstimate")
+ if db_imports
+ else None
+ )
+ if not RateLimitEstimate:
+ return
+
+ session_inner: "Session"
+ with self._resolve_session(
+ username, password
+ ) as session_inner:
+ with self._isolated_begin_nested(session_inner):
+ # Check if estimate exists
+ estimate: Any = (
+ session_inner.query(RateLimitEstimate)
+ .filter_by(engine_type=engine_type)
+ .first()
)
- session_inner.add(estimate)
- except Exception:
- logger.warning("Failed to persist rate limit estimate")
+ if estimate:
+ # Update existing estimate
+ estimate.base_wait_seconds = new_base
+ estimate.min_wait_seconds = min_wait
+ estimate.max_wait_seconds = max_wait
+ estimate.last_updated = time.time()
+ estimate.total_attempts = len(attempts)
+ estimate.success_rate = success_rate
+ else:
+ # Create new estimate
+ estimate = RateLimitEstimate(
+ engine_type=engine_type,
+ base_wait_seconds=new_base,
+ min_wait_seconds=min_wait,
+ max_wait_seconds=max_wait,
+ last_updated=time.time(),
+ total_attempts=len(attempts),
+ success_rate=success_rate,
+ )
+ session_inner.add(estimate)
+
+ # Retry transient SQLITE_BUSY ("database is locked")
+ # with backoff so a short overlap with another
+ # writer does not surface as a permanent failure
+ # outside a caller write-scope. Non-lock errors
+ # propagate immediately. Each attempt re-resolves
+ # its session; outside a caller scope that is a
+ # fresh session per attempt (the common case for
+ # engine threads), while inside a scope the shared
+ # session is reused without rolling back its open
+ # read snapshot, so retries may fail fast and any
+ # poisoned state surfaces (with its class logged
+ # below) instead of silently failing.
+ retry_on_db_lock(_persist_estimate)
+ except Exception as exc:
+ # Class only, never message/traceback: the DB
+ # password is a live local in the session frames
+ # below, and rendering them would leak it
+ # (TRUST.md §5). The class name alone
+ # distinguishes lock timeouts from poisoned
+ # sessions, open failures, and constraint errors.
+ logger.warning(
+ "Failed to persist rate limit estimate "
+ f"(exc_class={type(exc).__name__})"
+ )
else:
logger.debug(
"Skipping rate limit estimate save - no user context"
diff --git a/tests/database/test_thread_metrics_writer.py b/tests/database/test_thread_metrics_writer.py
index 5a5875c3b8..c48b80b4cf 100644
--- a/tests/database/test_thread_metrics_writer.py
+++ b/tests/database/test_thread_metrics_writer.py
@@ -220,6 +220,31 @@ class TestGetSession:
# session was None, so close should never be called on it
+ def test_session_error_warning_includes_exc_class(
+ self, writer_with_password, mock_db_manager
+ ):
+ """Session-error warning names the exception class (never message/traceback).
+
+ The class alone distinguishes lock timeouts from poisoned
+ sessions and open failures without risking the plaintext
+ SQLCipher password that lives in this frame (TRUST.md §5).
+ """
+ _mock_db, mock_session = mock_db_manager
+ mock_session.commit.side_effect = RuntimeError("boom")
+
+ with patch(
+ "local_deep_research.database.thread_metrics.logger"
+ ) as mock_logger:
+ with pytest.raises(RuntimeError, match="boom"):
+ with writer_with_password.get_session("testuser"):
+ pass
+
+ mock_logger.warning.assert_called_once()
+ (msg,), _ = mock_logger.warning.call_args
+ assert "Session error for testuser" in msg
+ assert "exc_class=RuntimeError" in msg
+ assert "boom" not in msg
+
# ===========================================================================
# write_token_metrics
diff --git a/tests/rate_limiting/test_rate_limiting.py b/tests/rate_limiting/test_rate_limiting.py
index 48635382c9..3cd2fe329e 100644
--- a/tests/rate_limiting/test_rate_limiting.py
+++ b/tests/rate_limiting/test_rate_limiting.py
@@ -1562,6 +1562,212 @@ class TestLatentSessionResolution(unittest.TestCase):
finally:
clear_search_context()
+ def _three_attempts(self):
+ return deque(
+ [
+ {
+ "wait_time": 1.0,
+ "success": True,
+ "timestamp": time.time(),
+ "retry_count": 1,
+ "search_result_count": 5,
+ },
+ {
+ "wait_time": 1.5,
+ "success": True,
+ "timestamp": time.time(),
+ "retry_count": 1,
+ "search_result_count": 5,
+ },
+ {
+ "wait_time": 2.0,
+ "success": True,
+ "timestamp": time.time(),
+ "retry_count": 1,
+ "search_result_count": 5,
+ },
+ ]
+ )
+
+ def test_update_estimate_persist_failure_logs_exc_class(self):
+ """Persist failure warning names the exception class (never message/traceback)."""
+ from local_deep_research.utilities.thread_context import (
+ clear_search_context,
+ set_search_context,
+ )
+
+ tracker = self._build_tracker()
+ tracker.recent_attempts["searxng"] = self._three_attempts()
+
+ set_search_context({"username": "testuser", "user_password": "secret"})
+ try:
+ with (
+ patch.object(
+ tracker,
+ "_resolve_session",
+ side_effect=ValueError("nope"),
+ ) as mock_resolve,
+ patch(f"{self.TRACKER_MOD}.logger") as mock_logger,
+ ):
+ # Must not raise: persistence is best-effort.
+ tracker._update_estimate("searxng")
+
+ self.assertEqual(mock_resolve.call_count, 1)
+ mock_logger.warning.assert_called_once()
+ (msg,), _ = mock_logger.warning.call_args
+ assert "Failed to persist rate limit estimate" in msg
+ assert "exc_class=ValueError" in msg
+ assert "nope" not in msg
+ finally:
+ clear_search_context()
+
+ def test_update_estimate_persist_retries_db_lock_then_succeeds(self):
+ """Transient SQLITE_BUSY is retried with backoff, then persists."""
+ from sqlalchemy.exc import OperationalError
+
+ from local_deep_research.utilities.thread_context import (
+ clear_search_context,
+ set_search_context,
+ )
+
+ tracker = self._build_tracker()
+ tracker.recent_attempts["searxng"] = self._three_attempts()
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+ lock_err = OperationalError(
+ "SELECT 1", {}, Exception("database is locked")
+ )
+
+ def _failing_cm():
+ cm = MagicMock()
+ cm.__enter__.side_effect = lock_err
+ return cm
+
+ working_cm = MagicMock()
+ working_cm.__enter__.return_value = mock_session
+
+ set_search_context({"username": "testuser", "user_password": "secret"})
+ try:
+ with (
+ patch(
+ f"{self.TRACKER_MOD}._get_db_imports",
+ return_value={"RateLimitEstimate": MagicMock()},
+ ),
+ patch.object(
+ tracker,
+ "_resolve_session",
+ side_effect=[
+ _failing_cm(),
+ _failing_cm(),
+ working_cm,
+ ],
+ ) as mock_resolve,
+ patch(f"{self.TRACKER_MOD}.logger") as mock_logger,
+ ):
+ tracker._update_estimate("searxng")
+
+ self.assertEqual(mock_resolve.call_count, 3)
+ mock_session.add.assert_called_once()
+ mock_logger.warning.assert_not_called()
+ finally:
+ clear_search_context()
+
+ def test_update_estimate_persist_lock_exhausted_warns_once(self):
+ """Exhausted SQLITE_BUSY retries surface one terminal warning (best-effort)."""
+ from sqlalchemy.exc import OperationalError
+
+ from local_deep_research.utilities.thread_context import (
+ clear_search_context,
+ set_search_context,
+ )
+
+ tracker = self._build_tracker()
+ tracker.recent_attempts["searxng"] = self._three_attempts()
+ lock_err = OperationalError(
+ "SELECT 1", {}, Exception("database is locked")
+ )
+
+ def _failing_cm():
+ cm = MagicMock()
+ cm.__enter__.side_effect = lock_err
+ return cm
+
+ set_search_context({"username": "testuser", "user_password": "secret"})
+ try:
+ with (
+ patch(
+ f"{self.TRACKER_MOD}._get_db_imports",
+ return_value={"RateLimitEstimate": MagicMock()},
+ ),
+ patch.object(
+ tracker,
+ "_resolve_session",
+ side_effect=[
+ _failing_cm(),
+ _failing_cm(),
+ _failing_cm(),
+ ],
+ ) as mock_resolve,
+ patch(f"{self.TRACKER_MOD}.logger") as mock_logger,
+ ):
+ # Must not raise: persistence is best-effort.
+ tracker._update_estimate("searxng")
+
+ self.assertEqual(mock_resolve.call_count, 3)
+ mock_logger.warning.assert_called_once()
+ (msg,), _ = mock_logger.warning.call_args
+ assert "Failed to persist rate limit estimate" in msg
+ assert "exc_class=OperationalError" in msg
+ assert "locked" not in msg
+ finally:
+ clear_search_context()
+
+ def test_update_estimate_persist_non_lock_error_not_retried(self):
+ """Non-lock OperationalError propagates immediately without retry."""
+ from sqlalchemy.exc import OperationalError
+
+ from local_deep_research.utilities.thread_context import (
+ clear_search_context,
+ set_search_context,
+ )
+
+ tracker = self._build_tracker()
+ tracker.recent_attempts["searxng"] = self._three_attempts()
+ non_lock_err = OperationalError(
+ "SELECT 1", {}, Exception("no such table: missing")
+ )
+
+ def _failing_cm():
+ cm = MagicMock()
+ cm.__enter__.side_effect = non_lock_err
+ return cm
+
+ set_search_context({"username": "testuser", "user_password": "secret"})
+ try:
+ with (
+ patch(
+ f"{self.TRACKER_MOD}._get_db_imports",
+ return_value={"RateLimitEstimate": MagicMock()},
+ ),
+ patch.object(
+ tracker,
+ "_resolve_session",
+ side_effect=[_failing_cm()],
+ ) as mock_resolve,
+ patch(f"{self.TRACKER_MOD}.logger") as mock_logger,
+ ):
+ # Must not raise: persistence is best-effort.
+ tracker._update_estimate("searxng")
+
+ self.assertEqual(mock_resolve.call_count, 1)
+ mock_logger.warning.assert_called_once()
+ (msg,), _ = mock_logger.warning.call_args
+ assert "Failed to persist rate limit estimate" in msg
+ assert "exc_class=OperationalError" in msg
+ assert "no such table" not in msg
+ finally:
+ clear_search_context()
+
def test_get_wait_time_cold_cache_inside_in_scope_write_session(self):
"""get_wait_time triggering _ensure_estimates_loaded on cold cache within active write session."""
from local_deep_research.utilities.thread_context import (