~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): configurable busy_timeout + retry helper for short writers (#6718)
S43061a14ebff
diff --git a/changelog.d/6718.bugfix.md b/changelog.d/6718.bugfix.mdnew file mode 100644index 0000000000..25d286bc32--- /dev/null+++ b/changelog.d/6718.bugfix.md@@ -0,0 +1,20 @@+Bumped the SQLite `busy_timeout` default from 10 s to 30 s and made it+configurable via `LDR_DB_CONFIG_BUSY_TIMEOUT_MS` (or the legacy+`LDR_DB_BUSY_TIMEOUT_MS` alias). The document scheduler's PDF-download+loop can hold a session across multi-second downloads; under the old+10 s default, any short writer landing inside the scheduler's+transaction failed with `database is locked` after ~10 s, even though+the commit would have succeeded a few hundred milliseconds later. 30 s+gives those short writers enough headroom to land their commit during+normal contention. The `backup_service` honors the same+operator-configurable value (it previously hardcoded 10 s, so a backup+racing the scheduler could die silently for no operator-tunable+reason). Added a small `retry_on_db_lock` helper (`sqlcipher_utils.py`)+that wraps the `token_counter` metrics writer (the rate-limit tracker's+persistence path is owned by #6566 and already protected by SAVEPOINT+isolation) with exponential backoff on transient `database is locked`+errors so a quick blip no longer turns into a permanent+`Failed to persist ...` warning. The helper catches+`sqlalchemy.exc.OperationalError` (the wrapped form SQLAlchemy emits+when a session commit hits `SQLITE_BUSY`) in addition to the unwrapped+DBAPI variants.diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex ba7702d35f..3f8e401597 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -26,6 +26,7 @@ They are not available in the Web UI because they are needed to start the applic| `LDR_BOOTSTRAP_ENCRYPTION_KEY` | Secret | `None` | No | | Database encryption key | Bootstrap | || `LDR_BOOTSTRAP_LOG_DIR` | Path | `None` | No | | Log directory path | Bootstrap | || `LDR_BOOTSTRAP_SECRET_KEY` | Secret | `None` | No | | Application secret key for session encryption | Bootstrap | |+| `LDR_DB_CONFIG_BUSY_TIMEOUT_MS` | Integer | `30000` | No | 100..300000 | SQLite busy_timeout in milliseconds -- how long a writer waits for the database lock before giving up with 'database is locked'. Set above the p99 latency of in-flight transactions (the background document scheduler can hold a session across multi-second PDF downloads; 30s gives the rate-limit tracker and other short writers enough headroom to land their commit instead of swallowing the error). | Db Config | LDR_DB_BUSY_TIMEOUT_MS || `LDR_DB_CONFIG_CACHE_SIZE_MB` | Integer | `64` | No | 1..10000 | SQLite cache size in MB | Db Config | LDR_DB_CACHE_SIZE_MB || `LDR_DB_CONFIG_CIPHER_MEMORY_SECURITY` | Enum | `'OFF'` | No | OFF, ON | SQLCipher memory security (ON=clear memory after use + mlock, OFF=faster). ON requires IPC_LOCK in Docker. | Db Config | || `LDR_DB_CONFIG_HMAC_ALGORITHM` | Enum | `'HMAC_SHA512'` | No | HMAC_SHA1, HMAC_SHA256, HMAC_SHA512 | HMAC algorithm for database integrity | Db Config | LDR_DB_HMAC_ALGORITHM |diff --git a/src/local_deep_research/database/backup/backup_service.py b/src/local_deep_research/database/backup/backup_service.pyindex 0f146a6d0c..20d92cb91d 100644--- a/src/local_deep_research/database/backup/backup_service.py+++ b/src/local_deep_research/database/backup/backup_service.py@@ -23,6 +23,7 @@ from ...config.paths import (get_user_database_filename,)from ..sqlcipher_utils import (+ apply_performance_pragmas,apply_sqlcipher_pragmas,create_sqlcipher_connection,get_key_from_password,@@ -254,8 +255,17 @@ class BackupService:conn = create_sqlcipher_connection(str(self.db_path), self.password)cursor = conn.cursor()- # Set busy timeout so concurrent writers don't cause instant failure- cursor.execute("PRAGMA busy_timeout = 10000")+ # Honour the operator-configured ``db_config.busy_timeout_ms``+ # (default 30 s) instead of the previous hardcoded 10 s.+ # The source DB already had this applied on its own+ # connection; this backup connection is a separate one and+ # the SQLCipher `creator` only sets the cipher defaults+ # before the key -- a backup racing the background document+ # scheduler's PDF-download transaction used to die at+ # 10 s while the source DB's writer rode out 30 s, leaving+ # the backup silently failing for no operator-tunable+ # reason.+ apply_performance_pragmas(cursor)try:# Use sqlcipher_export() to create an encrypted backupdiff --git a/src/local_deep_research/database/sqlcipher_utils.py b/src/local_deep_research/database/sqlcipher_utils.pyindex 93015aa6eb..98233d88d7 100644--- a/src/local_deep_research/database/sqlcipher_utils.py+++ b/src/local_deep_research/database/sqlcipher_utils.py@@ -7,11 +7,12 @@ consistent password handling and PRAGMA settings across the codebase.import osimport secrets+import sqlite3import threadingimport timefrom hashlib import pbkdf2_hmacfrom pathlib import Path-from typing import Any, Dict, Optional, Union+from typing import Any, Callable, Dict, Optional, Tuple, Type, TypeVar, Unionfrom loguru import logger@@ -614,7 +615,29 @@ def apply_performance_pragmas(cursor_or_conn: Any) -> None:"""# Default values that are always appliedcursor_or_conn.execute("PRAGMA temp_store = MEMORY")- cursor_or_conn.execute("PRAGMA busy_timeout = 10000") # 10 second timeout++ # SQLite serialises all writes through a single file lock, so any+ # in-flight transaction blocks every other writer until it commits+ # or rolls back. ``busy_timeout`` is the wall-clock budget the+ # SQLite driver waits for that lock before failing with+ # ``SQLITE_BUSY`` ("database is locked"). The background document+ # scheduler can hold a session across multi-second PDF downloads+ # (it queries ResearchHistory, then iterates calling+ # DownloadService.download_as_text per resource, then commits the+ # ``last_run`` update); a 10 s budget used to fail the rate-limit+ # tracker's persistence path -- and the scheduler's per-resource+ # processing -- every time the rate-limit write landed inside the+ # scheduler's transaction. 30 s gives those short writers enough+ # headroom to land their commit instead of swallowing the error.+ # Operators who want to tune this further can override+ # ``db_config.busy_timeout_ms``; the lower bound (100 ms) keeps+ # the negative-control contention test fast (it has to drive a+ # writer-against-holder race to a real timeout) without being so+ # tight that the spinner can't ride out even a single held+ # transaction, and the upper bound (300 s) caps tail latency if a+ # query goes pathological.+ busy_timeout_ms = int(get_env_setting("db_config.busy_timeout_ms", 30000))+ cursor_or_conn.execute(f"PRAGMA busy_timeout = {busy_timeout_ms}")# SQLite defaults foreign_keys to OFF — without this every# ondelete="CASCADE"/"SET NULL" declared on an FK is inert,@@ -657,6 +680,144 @@ def apply_performance_pragmas(cursor_or_conn: Any) -> None:cursor_or_conn.execute(f"PRAGMA wal_autocheckpoint = {wal_autocheckpoint}")+# ---------------------------------------------------------------------------+# Transient-lock retry helper+# ---------------------------------------------------------------------------+#+# SQLite serialises all writes through a single file lock, and any+# writer that lands inside a long-running transaction has to wait for+# ``busy_timeout`` before either getting the lock or failing with+# ``SQLITE_BUSY`` ("database is locked"). ``apply_performance_pragmas``+# above bumps the default timeout from 10 s to 30 s, which gives a+# short writer (e.g. the rate-limit tracker's per-engine estimate+# persistence) enough headroom to land its commit during a long+# in-flight transaction like the document scheduler's PDF-download+# loop.+#+# ``busy_timeout`` only protects a single ``BEGIN IMMEDIATE`` /+# ``COMMIT`` pair -- if the holder runs longer than the timeout, the+# writer's first commit attempt still fails. The helper below catches+# that exact failure and retries the callable with exponential+# backoff, so the caller's outer ``except Exception`` log (the rate-limit+# tracker's "Failed to persist rate limit estimate") only fires when+# every retry is exhausted, not on the first transient lock contention.++_T = TypeVar("_T")+++def _db_lock_error_types() -> Tuple[Type[BaseException], ...]:+ """Return the exception classes that signal ``database is locked``.++ The stdlib ``sqlite3`` module and ``sqlcipher3`` have *separate*+ exception hierarchies -- ``sqlcipher3.dbapi2.OperationalError``+ does NOT inherit from ``sqlite3.OperationalError`` -- so a+ defensive retry helper has to catch both. We also include+ ``sqlalchemy.exc.OperationalError`` because the production call+ site (``rate_limit_tracker._persist_estimate``) commits through a+ SQLAlchemy session, and SQLAlchemy wraps the DBAPI lock error in+ its own ``OperationalError`` subclass that does NOT inherit from+ either DBAPI class -- without it the helper would silently be a+ no-op on the wrapped path and the retry would never fire. The+ ``"locked" in str(exc)`` message guard below filters the SQLAlchemy+ subclass correctly: on a ``SQLITE_BUSY`` the wrapped message+ preserves the substring; on every other ``OperationalError``+ (broken pipe, schema error, etc.) it does not.+ """+ types: list[Type[BaseException]] = [sqlite3.OperationalError]+ try:+ from sqlcipher3 import dbapi2 as _sqlcipher_dbapi2++ types.append(_sqlcipher_dbapi2.OperationalError)+ except ImportError:+ pass+ try:+ from sqlalchemy.exc import OperationalError as _SQLAOperationalError++ types.append(_SQLAOperationalError)+ except ImportError:+ pass+ return tuple(types)+++_DB_LOCK_ERROR_TYPES = _db_lock_error_types()+++def retry_on_db_lock(+ callable_: Callable[[], _T],+ *,+ attempts: int = 3,+ base_delay_seconds: float = 0.1,+) -> _T:+ """Run ``callable_``, retrying on SQLite ``database is locked`` errors.++ Only retries ``OperationalError`` whose message contains+ ``"locked"`` -- every other exception (connection errors,+ IntegrityError, ProgrammingError, plain ``OperationalError`` without+ ``"locked"`` in the message, etc.) propagates immediately so the+ caller can decide how to handle it.++ The total wall-clock budget before the helper gives up is bounded+ by ``attempts * busy_timeout + (attempts - 1) * base_delay_seconds *+ (2**(attempts-1) - 1)``: each attempt can wait up to the connection's+ ``busy_timeout`` for the writer lock, and the helper itself sleeps+ ``base_delay_seconds * 2 ** (n - 1)`` between attempts. At the+ defaults (3 attempts, 0.1 s base delay, 30 s busy_timeout) that's+ at most ``3 * 30 + 0.1 + 0.2 = 90.3 s`` of waiting before the+ terminal ``database is locked`` raises to the caller. That upper+ bound is conservative: the connection's spinner waits the full+ timeout only on the very last attempt, and earlier attempts usually+ succeed while the holder's transaction is still in flight.++ This helper does not open, close, or pool database connections+ itself. ``callable_`` is responsible for its own connection+ lifecycle (open the SQLAlchemy session, ``with metrics_writer.get_session(...)``,+ etc.); on retry the helper simply calls ``callable_()`` again, so+ a caller that opens a fresh connection per call naturally gets a+ fresh attempt each time. Reusing a connection that already failed+ with ``SQLITE_BUSY`` is fine -- ``busy_timeout`` is reapplied per+ connection and the SQLite driver clears the busy state on the next+ BEGIN -- but most callers already pool short-lived sessions and+ don't need to special-case this.++ Args:+ callable_: The no-argument callable to run. Each attempt calls+ it fresh -- any partial state must be inside the callable's+ own context manager (e.g. a ``with metrics_writer.get_session(...)``).+ attempts: Maximum number of attempts (including the first).+ ``1`` disables the retry behaviour.+ base_delay_seconds: Initial backoff. The delay between+ attempts is ``base_delay_seconds * 2 ** (attempt - 1)`` --+ 0.1 s, 0.2 s, 0.4 s by default.++ Returns:+ Whatever ``callable_`` returns on the first successful run.++ Raises:+ sqlite3.OperationalError / sqlcipher3.OperationalError /+ sqlalchemy.exc.OperationalError: ``database is locked`` if+ every attempt is exhausted. Other exceptions propagate+ without retry (the message-substring guard filters the+ SQLAlchemy wrapper to lock errors specifically).+ """+ for attempt in range(1, attempts + 1):+ try:+ return callable_()+ except _DB_LOCK_ERROR_TYPES as exc:+ if "locked" not in str(exc).lower() or attempt >= attempts:+ raise+ logger.debug(+ "SQLite 'database is locked' on attempt "+ f"{attempt}/{attempts}; retrying in "+ f"{base_delay_seconds * (2 ** (attempt - 1)):.2f}s"+ )+ time.sleep(base_delay_seconds * (2 ** (attempt - 1)))+ # Unreachable: the loop returns on success or raises on the final+ # attempt. The explicit ``raise`` above satisfies the type checker.+ raise RuntimeError( # pragma: no cover -- defensive+ "retry_on_db_lock: loop exited without returning or raising"+ )++def verify_sqlcipher_connection(cursor_or_conn: Any) -> bool:"""Verify that the SQLCipher connection is working correctly.diff --git a/src/local_deep_research/metrics/token_counter.py b/src/local_deep_research/metrics/token_counter.pyindex 9b8086fde4..b37b9a9952 100644--- a/src/local_deep_research/metrics/token_counter.py+++ b/src/local_deep_research/metrics/token_counter.py@@ -855,14 +855,25 @@ class TokenCountingCallback(BaseCallbackHandler):# Write metrics directly using thread-safe databasetry:from ..database.thread_metrics import metrics_writer+ from ..database.sqlcipher_utils import retry_on_db_lock# Set password for this threadmetrics_writer.set_user_password(username, password)- # Write metrics to encrypted database- metrics_writer.write_token_metrics(- username, self.research_id, token_data- )+ # ``write_token_metrics`` commits through a SQLAlchemy+ # session, so the lock error arrives wrapped as+ # ``sqlalchemy.exc.OperationalError``. ``retry_on_db_lock``+ # catches that subclass (and the unwrapped DBAPI+ # variants) and retries with exponential backoff so a+ # short blip from the background document scheduler's+ # PDF-download loop doesn't surface as a permanent+ # "Failed to write metrics from thread" warning.+ def _write_metrics():+ metrics_writer.write_token_metrics(+ username, self.research_id, token_data+ )++ retry_on_db_lock(_write_metrics)except Exception as e:# Deferred import to avoid potential circular imports during module initializationfrom ..security.log_sanitizer import scrub_errordiff --git a/src/local_deep_research/settings/env_definitions/db_config.py b/src/local_deep_research/settings/env_definitions/db_config.pyindex fd3b8eb656..f05c5aa9e6 100644--- a/src/local_deep_research/settings/env_definitions/db_config.py+++ b/src/local_deep_research/settings/env_definitions/db_config.py@@ -57,6 +57,25 @@ DB_CONFIG_SETTINGS = [max_value=10000,default=250,),+ IntegerSetting(+ key="db_config.busy_timeout_ms",+ description=(+ "SQLite busy_timeout in milliseconds -- how long a writer waits "+ "for the database lock before giving up with 'database is locked'. "+ "Set above the p99 latency of in-flight transactions (the background "+ "document scheduler can hold a session across multi-second PDF "+ "downloads; 30s gives the rate-limit tracker and other short writers "+ "enough headroom to land their commit instead of swallowing the error)."+ ),+ # Lower bound 100 ms: anything below that is effectively a no-op+ # anyway (the holder's transaction has to release the lock in the+ # 100 ms window), and tests need to drop it further to keep the+ # negative-control timeout test fast.+ min_value=100,+ max_value=300000,+ default=30000,+ deprecated_env_var="LDR_DB_BUSY_TIMEOUT_MS",+ ),# Storage settingsIntegerSetting(key="db_config.page_size",diff --git a/tests/auth_tests/test_encrypted_db.py b/tests/auth_tests/test_encrypted_db.pyindex 655b63ebaf..3505ec8ffa 100644--- a/tests/auth_tests/test_encrypted_db.py+++ b/tests/auth_tests/test_encrypted_db.py@@ -397,8 +397,8 @@ class TestConnectionVerification:)busy_timeout = conn.execute(text("PRAGMA busy_timeout")).scalar()- assert busy_timeout == 10000, (- f"busy_timeout should be 10000, got {busy_timeout}"+ assert busy_timeout == 30000, (+ f"busy_timeout should be 30000, got {busy_timeout}")synchronous = conn.execute(text("PRAGMA synchronous")).scalar()diff --git a/tests/auth_tests/test_sqlcipher_performance.py b/tests/auth_tests/test_sqlcipher_performance.pyindex 6df23d92a8..e05ab76cbc 100644--- a/tests/auth_tests/test_sqlcipher_performance.py+++ b/tests/auth_tests/test_sqlcipher_performance.py@@ -146,8 +146,8 @@ class TestBusyTimeout:"""Verify busy_timeout is set to prevent immediate lock failures."""result = configured_connection.execute("PRAGMA busy_timeout").fetchone()assert result is not None- assert result[0] == 10000, (- f"Expected busy_timeout=10000, got {result[0]}"+ assert result[0] == 30000, (+ f"Expected busy_timeout=30000, got {result[0]}")configured_connection.close()@@ -172,7 +172,7 @@ class TestBusyTimeout:# The busy_timeout should allow retries# This is a basic test that the setting is appliedresult = conn1.execute("PRAGMA busy_timeout").fetchone()- assert result[0] == 10000+ assert result[0] == 30000conn1.close()@@ -199,7 +199,7 @@ class TestPerformanceIntegration:pragmas = {"journal_mode": lambda x: x.lower() == "wal","temp_store": lambda x: x == 2,- "busy_timeout": lambda x: x == 10000,+ "busy_timeout": lambda x: x == 30000,"synchronous": lambda x: x == 1,}@@ -244,7 +244,7 @@ class TestPerformanceIntegration:# Other settings are per-connection but should still be appliedresult = conn2.execute("PRAGMA busy_timeout").fetchone()- assert result[0] == 10000+ assert result[0] == 30000conn2.close()diff --git a/tests/auth_tests/test_sqlcipher_settings.py b/tests/auth_tests/test_sqlcipher_settings.pyindex 0f146cd0e7..9775ac5acf 100644--- a/tests/auth_tests/test_sqlcipher_settings.py+++ b/tests/auth_tests/test_sqlcipher_settings.py@@ -232,7 +232,15 @@ class TestPerformancePragmaSettings:def test_default_busy_timeout(self, sqlcipher_module, temp_db_path, clean_env):- """Verify busy_timeout is set to 10000ms."""+ """Verify the default busy_timeout is the documented 30000ms.++ The default is now 30 s (was 10 s). The bump was made because the+ background document scheduler holds a session across multi-second+ PDF downloads; under the old default, short writers like the+ rate-limit tracker hit ``database is locked`` after ~10 s and+ gave up, even though their commit would have succeeded a few+ hundred milliseconds later.+ """conn = sqlcipher_module.connect(str(temp_db_path))cursor = conn.cursor()apply_cipher_defaults_before_key(cursor)@@ -242,7 +250,7 @@ class TestPerformancePragmaSettings:result = conn.execute("PRAGMA busy_timeout").fetchone()assert result is not None- assert result[0] == 10000, f"Expected 10000, got {result[0]}"+ assert result[0] == 30000, f"Expected 30000, got {result[0]}"conn.close()diff --git a/tests/config/test_db_config_high_value.py b/tests/config/test_db_config_high_value.pyindex b42e2a4c67..ca48f1e5f8 100644--- a/tests/config/test_db_config_high_value.py+++ b/tests/config/test_db_config_high_value.py@@ -37,7 +37,7 @@ class TestDbConfigRegistry:def test_setting_count(self):"""DB_CONFIG_SETTINGS contains the expected number of settings."""- assert len(DB_CONFIG_SETTINGS) == 9+ assert len(DB_CONFIG_SETTINGS) == 10def test_all_keys_start_with_db_config(self):"""Every key should use the 'db_config.' prefix."""diff --git a/tests/database/test_busy_timeout_contention.py b/tests/database/test_busy_timeout_contention.pynew file mode 100644index 0000000000..2dae5ffd6c--- /dev/null+++ b/tests/database/test_busy_timeout_contention.py@@ -0,0 +1,427 @@+"""Regression tests for the ``db_config.busy_timeout_ms`` setting.++Background+----------+SQLite serialises all writes through a single file lock. When a writer+tries to commit while another transaction holds the lock, SQLite blocks+the writer for up to ``busy_timeout`` milliseconds before failing with+``SQLITE_BUSY`` ("database is locked").++The background document scheduler holds a session across multi-second+PDF downloads (it queries ``ResearchHistory``, then iterates calling+``DownloadService.download_as_text`` per resource, then commits the+``last_run`` update). Under the old default of ``busy_timeout=10000`` (10 s),+short writers like the rate-limit tracker would fail after ~10 s of+waiting and the failure was logged as+``Failed to persist rate limit estimate`` -- even though their commit+would have succeeded a few hundred milliseconds later if they'd been+allowed to wait.++This file pins three things:++1. **Default value** is now ``30000`` ms (30 s) -- gives short writers+ enough headroom to land their commit during a long in-flight+ transaction.+2. **Env var override** -- ``LDR_DB_CONFIG_BUSY_TIMEOUT_MS`` (and the+ deprecated alias ``LDR_DB_BUSY_TIMEOUT_MS``) lets operators tune the+ timeout for their workload without recompiling.+3. **Under contention** -- a writer that lands inside another writer's+ transaction waits up to the configured timeout, then succeeds.++The integration test (``test_writer_waits_for_long_transaction``) uses+two threads on the same SQLite file to reproduce the production pattern:+one thread holds a write transaction for longer than the writer's+``busy_timeout`` would be in the buggy version, then commits; the other+thread's commit waits, then succeeds.+"""++import shutil+import tempfile+import threading+import time+from pathlib import Path++import pytest++from local_deep_research.database.sqlcipher_compat import (+ get_sqlcipher_module,+)+from local_deep_research.database.sqlcipher_utils import (+ apply_cipher_defaults_before_key,+ apply_performance_pragmas,+ set_sqlcipher_key,+)+++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------+++def temp_db_path():+ """A fresh database path; cleaned up at the end."""+ temp_dir = tempfile.mkdtemp()+ db_path = Path(temp_dir) / "test_busy_timeout.db"+ yield db_path+ shutil.rmtree(temp_dir, ignore_errors=True)+++def sqlcipher_module():+ """The SQLCipher module (sqlcipher3 or sqlite3 fallback)."""+ return get_sqlcipher_module()++[email protected](autouse=True)+def _clean_env(monkeypatch):+ """Strip any operator-supplied busy_timeout override so tests get+ the default. Tests that need to override set the variable themselves.+ """+ for var in (+ "LDR_DB_CONFIG_BUSY_TIMEOUT_MS",+ "LDR_DB_BUSY_TIMEOUT_MS",+ ):+ monkeypatch.delenv(var, raising=False)+++def _open_and_configure(sqlcipher_module, db_path, password="pw"):+ """Open a SQLCipher connection with the full production pragma set."""+ conn = sqlcipher_module.connect(str(db_path))+ cursor = conn.cursor()+ apply_cipher_defaults_before_key(cursor)+ set_sqlcipher_key(cursor, password)+ apply_performance_pragmas(cursor)+ cursor.close()+ return conn+++# ---------------------------------------------------------------------------+# Default + env var+# ---------------------------------------------------------------------------+++class TestBusyTimeoutDefault:+ """The default bumps from 10 s to 30 s, with a comment explaining why."""++ def test_default_is_30000ms(self, sqlcipher_module, temp_db_path):+ """The production default is 30 s. The bump from 10 s gives short+ writers like the rate-limit tracker enough headroom to land their+ commit during a long in-flight transaction.+ """+ conn = _open_and_configure(sqlcipher_module, temp_db_path)+ try:+ result = conn.execute("PRAGMA busy_timeout").fetchone()+ assert result is not None+ assert result[0] == 30000, (+ f"Expected default busy_timeout=30000, got {result[0]}. "+ "If this is 10000, the production fix has been reverted."+ )+ finally:+ conn.close()++ def test_env_var_can_raise_it(+ self, sqlcipher_module, temp_db_path, monkeypatch+ ):+ """Operators who want even more headroom set the env var."""+ monkeypatch.setenv("LDR_DB_CONFIG_BUSY_TIMEOUT_MS", "60000")+ conn = _open_and_configure(sqlcipher_module, temp_db_path)+ try:+ result = conn.execute("PRAGMA busy_timeout").fetchone()+ assert result[0] == 60000+ finally:+ conn.close()++ def test_env_var_can_lower_it(+ self, sqlcipher_module, temp_db_path, monkeypatch+ ):+ """Operators on hardware where 30 s is too generous can shorten it."""+ monkeypatch.setenv("LDR_DB_CONFIG_BUSY_TIMEOUT_MS", "5000")+ conn = _open_and_configure(sqlcipher_module, temp_db_path)+ try:+ result = conn.execute("PRAGMA busy_timeout").fetchone()+ assert result[0] == 5000+ finally:+ conn.close()++ def test_deprecated_alias_still_works(+ self, sqlcipher_module, temp_db_path, monkeypatch+ ):+ """The legacy ``LDR_DB_BUSY_TIMEOUT_MS`` alias still wins when set."""+ monkeypatch.delenv("LDR_DB_CONFIG_BUSY_TIMEOUT_MS", raising=False)+ monkeypatch.setenv("LDR_DB_BUSY_TIMEOUT_MS", "15000")+ conn = _open_and_configure(sqlcipher_module, temp_db_path)+ try:+ result = conn.execute("PRAGMA busy_timeout").fetchone()+ assert result[0] == 15000+ finally:+ conn.close()++ def test_out_of_range_env_value_falls_back_to_default(+ self, sqlcipher_module, temp_db_path, monkeypatch+ ):+ """Out-of-range ``busy_timeout`` values (below 100 ms or above+ 300 000 ms) silently fall back to the production default of+ 30 000 ms. ``SettingsRegistry.get`` catches the resulting+ ``EnvironmentValueRangeError`` (a ``ValueError`` subclass)+ and returns the setting's ``default`` so the connection+ doesn't crash on open.++ Pinning this so a future refactor that switches to a+ fail-loud policy (e.g. ``raise`` instead of fallback) is+ intentional rather than silent: the only safe alternative+ is to abort startup, not to clamp the value without telling+ the operator.+ """+ for var in (+ "LDR_DB_CONFIG_BUSY_TIMEOUT_MS",+ "LDR_DB_BUSY_TIMEOUT_MS",+ ):+ monkeypatch.setenv(var, "50") # below the 100 ms minimum+ conn = _open_and_configure(sqlcipher_module, temp_db_path)+ try:+ result = conn.execute("PRAGMA busy_timeout").fetchone()+ assert result[0] == 30000, (+ f"Out-of-range {var}=50 should fall back to the "+ f"30000 default; got {result[0]}. If this is 50, "+ "the registry started honouring the bad value "+ "instead of falling back."+ )+ finally:+ conn.close()+ monkeypatch.delenv(var, raising=False)++ for var in (+ "LDR_DB_CONFIG_BUSY_TIMEOUT_MS",+ "LDR_DB_BUSY_TIMEOUT_MS",+ ):+ monkeypatch.setenv(var, "999999") # above the 300000 max+ conn = _open_and_configure(sqlcipher_module, temp_db_path)+ try:+ result = conn.execute("PRAGMA busy_timeout").fetchone()+ assert result[0] == 30000, (+ f"Out-of-range {var}=999999 should fall back to "+ f"the 30000 default; got {result[0]}. If this is "+ "999999, the registry started honouring the bad "+ "value instead of falling back."+ )+ finally:+ conn.close()+ monkeypatch.delenv(var, raising=False)++ def test_non_numeric_env_value_falls_back_to_default(+ self, sqlcipher_module, temp_db_path, monkeypatch+ ):+ """Non-numeric ``busy_timeout`` values (the typical+ operator typo: ``LDR_DB_CONFIG_BUSY_TIMEOUT_MS=thirty``)+ silently fall back to the 30 s default. The+ ``IntegerSetting._convert_value`` warning path fires; we+ don't fail loud because the operator's mainline behaviour+ is the DB still opens.+ """+ monkeypatch.setenv("LDR_DB_CONFIG_BUSY_TIMEOUT_MS", "thirty")+ conn = _open_and_configure(sqlcipher_module, temp_db_path)+ try:+ result = conn.execute("PRAGMA busy_timeout").fetchone()+ assert result[0] == 30000+ finally:+ conn.close()+++# ---------------------------------------------------------------------------+# Integration: a writer inside a long transaction waits and succeeds+# ---------------------------------------------------------------------------+++class TestBusyTimeoutUnderContention:+ """Reproduce the production pattern: one writer's long transaction+ forces another writer to wait up to ``busy_timeout`` before its+ commit can land."""++ @staticmethod+ def _init_db(sqlcipher_module, db_path):+ conn = _open_and_configure(sqlcipher_module, db_path)+ conn.execute(+ "CREATE TABLE IF NOT EXISTS counters ("+ " id INTEGER PRIMARY KEY,"+ " n INTEGER NOT NULL"+ ")"+ )+ conn.execute("INSERT OR REPLACE INTO counters (id, n) VALUES (1, 0)")+ conn.commit()+ conn.close()++ def test_writer_waits_for_long_transaction(+ self, sqlcipher_module, temp_db_path, monkeypatch+ ):+ """The production bug was: a short writer (the rate-limit+ tracker) would fail with ``database is locked`` after+ ``busy_timeout`` ms if it landed inside a long transaction (the+ document scheduler's PDF-download loop). The fix sets the+ default ``busy_timeout`` to 30 000 ms so short writers get+ enough headroom to land their commit.++ This test reproduces the pattern with two threads sharing a+ single SQLite file. ``thread_holder`` opens a write+ transaction and sleeps for ``holder_duration`` before+ committing; ``thread_writer`` tries to commit a counter+ increment immediately after. We pin two properties:++ 1. **The writer waits** -- its elapsed time is at least+ ``holder_duration`` (proving it actually blocked on the+ holder's transaction rather than failing fast or running+ concurrently).+ 2. **The writer commits** -- the elapsed time is below+ ``busy_timeout`` (proving the timeout was large enough for+ the commit to land).++ We force ``busy_timeout`` to 2 s via the env var so the test+ runs in seconds, not the default 30 s. ``holder_duration`` is+ 1 s -- well inside the timeout, so the writer's commit lands+ while the holder is still sleeping. The default-value test+ (``TestBusyTimeoutDefault::test_default_is_30000ms``) pins+ the production default.+ """+ # Force a tight timeout so the test runs in seconds, not the+ # default 30 s.+ monkeypatch.setenv("LDR_DB_CONFIG_BUSY_TIMEOUT_MS", "2000")+ self._init_db(sqlcipher_module, temp_db_path)++ holder_duration = 1.0 # seconds -- well within the 2 s timeout+ writer_result = {"elapsed": None, "error": None}++ def holder():+ conn = _open_and_configure(sqlcipher_module, temp_db_path)+ try:+ conn.execute("BEGIN IMMEDIATE")+ conn.execute("UPDATE counters SET n = n + 100 WHERE id = 1")+ # Hold the writer lock across a sleep. SQLite blocks+ # any concurrent writer until COMMIT.+ time.sleep(holder_duration)+ conn.execute("UPDATE counters SET n = n + 1000 WHERE id = 1")+ conn.commit()+ finally:+ conn.close()++ def writer():+ start = time.monotonic()+ try:+ conn = _open_and_configure(sqlcipher_module, temp_db_path)+ try:+ conn.execute("UPDATE counters SET n = n + 1 WHERE id = 1")+ conn.commit()+ finally:+ conn.close()+ except Exception as e: # pragma: no cover -- failure path+ writer_result["error"] = e+ writer_result["elapsed"] = time.monotonic() - start++ t_holder = threading.Thread(target=holder)+ t_writer = threading.Thread(target=writer)+ # Start the holder first so its write transaction is in flight+ # before the writer tries to commit. The small sleep gives the+ # holder's BEGIN IMMEDIATE a chance to acquire the writer lock.+ t_holder.start()+ time.sleep(0.1)+ t_writer.start()+ t_holder.join()+ t_writer.join()++ # The writer must have waited for the holder to commit, not+ # failed. If the writer finished in less than+ # ``holder_duration``, the lock wasn't actually held and the+ # test is degenerate -- surface that as a failure rather+ # than passing silently.+ assert writer_result["error"] is None, (+ f"Writer raised {writer_result['error']!r}; the configured "+ "busy_timeout (2 s) should have been long enough to wait "+ f"out the holder's {holder_duration}s lock."+ )+ assert writer_result["elapsed"] >= holder_duration * 0.8, (+ f"Writer elapsed ({writer_result['elapsed']:.2f}s) was much "+ f"shorter than the holder's lock-hold ({holder_duration}s); "+ "the test isn't actually exercising lock contention -- the "+ "holder's BEGIN IMMEDIATE may have lost the writer lock."+ )+ # And the writer landed inside the timeout (otherwise the+ # previous assertion's contract is moot).+ assert writer_result["elapsed"] < 2.0, (+ f"Writer elapsed ({writer_result['elapsed']:.2f}s) was not "+ "less than the configured busy_timeout (2.0 s); the holder "+ "may not have held the writer lock for the full duration."+ )++ def test_writer_times_out_when_holder_exceeds_timeout(+ self, sqlcipher_module, temp_db_path, monkeypatch+ ):+ """The complementary failure-path test: when the holder's+ transaction runs longer than ``busy_timeout``, a concurrent+ writer must fail with ``database is locked`` -- not block+ forever.++ Production corollary: this is the scenario the rate-limit+ tracker hit in 2026-09-21. The fix is to give writers enough+ timeout to ride out normal contention (30 s), not to make the+ timeout infinite. If a transaction runs longer than+ ``busy_timeout``, the writer's commit failing is the correct+ behaviour -- it surfaces the long-running transaction rather+ than masking it behind an indefinite hang.+ """+ # Tight timeout for a fast test.+ monkeypatch.setenv("LDR_DB_CONFIG_BUSY_TIMEOUT_MS", "500")+ self._init_db(sqlcipher_module, temp_db_path)++ # Hold for longer than the timeout so the writer is guaranteed+ # to hit it.+ holder_duration = 1.5 # seconds+ writer_result = {"elapsed": None, "error": None}++ def holder():+ conn = _open_and_configure(sqlcipher_module, temp_db_path)+ try:+ conn.execute("BEGIN IMMEDIATE")+ conn.execute("UPDATE counters SET n = n + 100 WHERE id = 1")+ time.sleep(holder_duration)+ conn.execute("UPDATE counters SET n = n + 1000 WHERE id = 1")+ conn.commit()+ finally:+ conn.close()++ def writer():+ start = time.monotonic()+ try:+ conn = _open_and_configure(sqlcipher_module, temp_db_path)+ try:+ conn.execute("UPDATE counters SET n = n + 1 WHERE id = 1")+ conn.commit()+ finally:+ conn.close()+ except Exception as e:+ writer_result["error"] = e+ writer_result["elapsed"] = time.monotonic() - start++ t_holder = threading.Thread(target=holder)+ t_writer = threading.Thread(target=writer)+ t_holder.start()+ time.sleep(0.1)+ t_writer.start()+ t_holder.join()+ t_writer.join()++ # The writer must have failed with a "database is locked" error+ # after waiting approximately ``busy_timeout`` (0.5 s here).+ assert writer_result["error"] is not None, (+ "Writer did not raise; a 1.5 s holder against a 0.5 s "+ "busy_timeout should have caused the writer to time out."+ )+ error_msg = str(writer_result["error"])+ assert "locked" in error_msg.lower(), (+ f"Expected 'database is locked' error, got {error_msg!r}"+ )+ # The writer waited roughly the timeout duration before failing,+ # proving it tried to wait rather than failing immediately.+ assert writer_result["elapsed"] >= 0.4, (+ f"Writer elapsed ({writer_result['elapsed']:.2f}s) was "+ "much shorter than the configured busy_timeout (0.5 s); "+ "the writer may not have actually waited."+ )diff --git a/tests/database/test_retry_on_db_lock.py b/tests/database/test_retry_on_db_lock.pynew file mode 100644index 0000000000..9338ec4470--- /dev/null+++ b/tests/database/test_retry_on_db_lock.py@@ -0,0 +1,546 @@+"""Unit tests for ``retry_on_db_lock``.++The helper is the production answer to the rate-limit tracker's+cascading ``database is locked`` failures (2026-09-21). It retries the+wrapped callable on ``OperationalError`` whose message contains+``"locked"``, and only on that exception class -- every other failure+(IntegrityError, ProgrammingError, plain ConnectionError, etc.)+propagates immediately so the caller can decide how to handle it.++These tests pin the contract:++1. **Locks retry** -- the helper runs the callable multiple times when+ the failure is a "database is locked" error, and the total number+ of calls is bounded by ``attempts``.+2. **Backoff is exponential** -- the gap between attempts grows.+3. **Other errors propagate immediately** -- only the lock error is+ retryable.+4. **Successful first try is fast** -- zero backoff, zero retries.+5. **Returns the callable's value** -- not None, not a re-raised+ sentinel.+"""++import sqlite3+import threading+import time+from pathlib import Path++import pytest+from sqlalchemy import create_engine, event+from sqlalchemy.exc import OperationalError as SAOperationalError+from sqlalchemy.orm import sessionmaker++from local_deep_research.database.sqlcipher_compat import (+ get_sqlcipher_module,+)+from local_deep_research.database.sqlcipher_utils import (+ _db_lock_error_types,+ apply_cipher_defaults_before_key,+ apply_performance_pragmas,+ retry_on_db_lock,+ set_sqlcipher_key,+)+++# ---------------------------------------------------------------------------+# Pure-Python unit tests (no DB needed)+# ---------------------------------------------------------------------------+++class TestRetryOnLockContract:+ """Pin the helper's behaviour without touching a database."""++ def test_returns_callable_value_on_first_success(self):+ """A happy-path callable returns its value untouched; the helper+ does not wrap or transform it.+ """+ result = retry_on_db_lock(lambda: 42)+ assert result == 42++ def test_does_not_retry_on_non_lock_operationalerror(self):+ """``OperationalError`` without ``'locked'`` in the message is+ NOT a transient lock -- it propagates on the first failure.+ Other classes of error (``ValueError``, ``KeyError``, etc.) also+ propagate unchanged.+ """+ calls = []++ def raises_value_error():+ calls.append(1)+ raise ValueError("not a lock error")++ with pytest.raises(ValueError, match="not a lock error"):+ retry_on_db_lock(raises_value_error)+ assert calls == [1], (+ "Non-lock errors must propagate on the first attempt; the "+ f"helper called the callable {len(calls)} times."+ )++ def test_does_not_retry_on_lock_without_substring_match(self):+ """An ``OperationalError`` whose message does NOT contain the+ substring ``'locked'`` must propagate on the first attempt.+ Pinning this prevents a future SQLCipher driver change (which+ might rename the error message) from accidentally turning the+ helper into a generic OperationalError retry.+ """+ calls = []++ def raises_other_op_error():+ calls.append(1)+ raise sqlite3.OperationalError("readonly database")++ with pytest.raises(sqlite3.OperationalError, match="readonly"):+ retry_on_db_lock(raises_other_op_error)+ assert calls == [1]++ def test_retries_until_success(self):+ """The callable fails with a lock error N-1 times, then+ succeeds on the Nth attempt -- the helper returns the success+ value.+ """+ attempts_before_success = [3]+ calls = []++ def fails_then_succeeds():+ calls.append(1)+ if len(calls) < attempts_before_success[0]:+ raise sqlite3.OperationalError("database is locked")+ return "ok"++ result = retry_on_db_lock(+ fails_then_succeeds, attempts=5, base_delay_seconds=0+ )+ assert result == "ok"+ assert len(calls) == attempts_before_success[0]++ def test_gives_up_after_attempts(self):+ """When every attempt raises the lock error, the helper raises+ after ``attempts`` total calls -- not silently swallowing.+ """+ calls = []++ def always_fails():+ calls.append(1)+ raise sqlite3.OperationalError("database is locked")++ with pytest.raises(sqlite3.OperationalError, match="locked"):+ retry_on_db_lock(always_fails, attempts=4, base_delay_seconds=0)+ assert len(calls) == 4, (+ f"Expected 4 calls (one per attempt), got {len(calls)}."+ )++ def test_attempts_one_disables_retry(self):+ """``attempts=1`` makes the helper a transparent wrapper. Useful+ for callers who want the lock-detection logic but not the+ retry behaviour.+ """+ calls = []++ def fails():+ calls.append(1)+ raise sqlite3.OperationalError("database is locked")++ with pytest.raises(sqlite3.OperationalError):+ retry_on_db_lock(fails, attempts=1)+ assert calls == [1]++ def test_exponential_backoff(self):+ """The gap between attempts grows. With ``base_delay_seconds=0.05``+ the three gaps should be 0.05, 0.10, 0.20 seconds (1x, 2x, 4x).+ We use 50 ms / 100 ms / 200 ms rather than 100 ms / 200 ms / 400 ms+ to keep the test fast.+ """+ timestamps = []++ def record_and_fail():+ timestamps.append(time.monotonic())+ raise sqlite3.OperationalError("database is locked")++ with pytest.raises(sqlite3.OperationalError):+ retry_on_db_lock(+ record_and_fail, attempts=4, base_delay_seconds=0.05+ )++ assert len(timestamps) == 4+ gap_1 = timestamps[1] - timestamps[0]+ gap_2 = timestamps[2] - timestamps[1]+ gap_3 = timestamps[3] - timestamps[2]++ # Generous lower bounds because the OS scheduler adds noise.+ # The strict invariant we care about is *monotonic growth* --+ # if a future refactor regressed to a constant sleep, the+ # growth assertion would fail even if the absolute timings+ # drifted.+ assert gap_1 >= 0.04, f"First gap {gap_1:.3f}s too small"+ assert gap_2 >= gap_1 * 1.5, (+ f"Second gap {gap_2:.3f}s did not grow vs first {gap_1:.3f}s"+ )+ assert gap_3 >= gap_2 * 1.5, (+ f"Third gap {gap_3:.3f}s did not grow vs second {gap_2:.3f}s"+ )+++# ---------------------------------------------------------------------------+# Integration test: real SQLCipher + real contention+# ---------------------------------------------------------------------------+++class TestRetryOnLockIntegration:+ """Reproduce the production pattern end-to-end: a writer inside a+ SQLite database hits ``database is locked``, the helper retries,+ and the next attempt succeeds."""++ @pytest.fixture+ def sqlcipher_module(self):+ """Local fixture: this file lives under ``tests/database/`` and+ doesn't inherit the ``sqlcipher_module`` fixture from+ ``tests/auth_tests/conftest.py``.+ """+ return get_sqlcipher_module()++ @staticmethod+ def _open_with_tight_timeout(+ sqlcipher_module, db_path, password="pw", busy_timeout_ms=200+ ):+ conn = sqlcipher_module.connect(str(db_path))+ cursor = conn.cursor()+ apply_cipher_defaults_before_key(cursor)+ set_sqlcipher_key(cursor, password)+ apply_performance_pragmas(cursor)+ cursor.close()+ # Override busy_timeout so the test fails fast when the holder+ # doesn't release the lock.+ conn.execute(f"PRAGMA busy_timeout = {busy_timeout_ms}")+ return conn++ @pytest.mark.slow+ def test_retries_locked_error_then_succeeds(+ self, sqlcipher_module, tmp_path: Path+ ):+ """Integration: the helper catches a real ``database is locked``+ error from a SQLCipher session and retries the callable. On+ the second attempt (after the holder's transaction releases+ the lock) the commit lands and the helper returns normally.++ ``busy_timeout`` only applies to the spinner that waits for+ the writer lock. With Python sqlite3's default *deferred*+ transactions, the lock is acquired at the first write, not at+ BEGIN; some Python wrappers don't surface busy_timeout's+ deadline on that path. The test pins the writer to+ ``BEGIN IMMEDIATE`` so the writer actually waits for the lock+ and the timeout is honoured -- same pattern the production+ rate-limit tracker's session ends up in via+ ``metrics_writer.get_session``.+ """+ db_path = tmp_path / "test_retry_on_lock.db"+ # Init the schema.+ conn = self._open_with_tight_timeout(sqlcipher_module, db_path)+ conn.execute(+ "CREATE TABLE counters (id INTEGER PRIMARY KEY, n INTEGER)"+ )+ conn.execute("INSERT INTO counters (id, n) VALUES (1, 0)")+ conn.commit()+ conn.close()++ holder_started = threading.Event()+ holder_release = threading.Event()+ call_count = []++ def holder():+ """Hold a write transaction until the test signals."""+ c = self._open_with_tight_timeout(+ sqlcipher_module, db_path, busy_timeout_ms=200+ )+ try:+ c.execute("BEGIN IMMEDIATE")+ c.execute("INSERT INTO counters (id, n) VALUES (2, 100)")+ holder_started.set()+ # Hold the writer lock until the test releases us.+ holder_release.wait(timeout=5.0)+ c.commit()+ finally:+ c.close()++ def writer_callable():+ """Open a fresh session, do an ``UPDATE`` inside an+ ``IMMEDIATE`` transaction, and commit.++ ``IMMEDIATE`` is what makes ``busy_timeout`` apply: it+ acquires the writer lock at BEGIN, so a contended writer+ hits the spinner that ``busy_timeout`` bounds. With+ ``DEFERRED`` (the default), the write transaction would+ acquire the lock at the first UPDATE and SQLite would+ block the writer through the COMMIT call -- but the lock+ is only released at COMMIT, so the holder's release after+ 300 ms actually lets the first attempt squeeze through+ without tripping ``busy_timeout``.+ """+ call_count.append(1)+ c = self._open_with_tight_timeout(+ sqlcipher_module, db_path, busy_timeout_ms=200+ )+ try:+ c.execute("BEGIN IMMEDIATE")+ c.execute("UPDATE counters SET n = n + 1 WHERE id = 1")+ c.commit()+ return "committed"+ finally:+ c.close()++ t_holder = threading.Thread(target=holder)+ t_holder.start()+ # Make sure the holder is in its BEGIN IMMEDIATE before the+ # writer's first attempt.+ assert holder_started.wait(timeout=2.0)++ # Schedule the holder to release 500 ms from now -- well past+ # busy_timeout (200 ms) so the writer's first attempt+ # genuinely times out before the holder releases. The retry+ # then lands inside the gap between the busy_timeout expiry+ # (t ≈ 0.2 s) and the holder's COMMIT (t ≈ 0.5 s).+ def release_holder():+ time.sleep(+ 0.5+ ) # allow: unmarked-sleep -- thread-coordination delay, not a slow assertion+ holder_release.set()++ t_release = threading.Thread(target=release_holder)+ t_release.start()++ # Now invoke the helper -- first attempt fails (busy_timeout+ # = 200 ms vs holder's 500 ms hold), then we sleep 0.1 s+ # backoff, second attempt succeeds (the holder has released+ # in the meantime).+ result = retry_on_db_lock(+ writer_callable, attempts=3, base_delay_seconds=0.1+ )+ assert result == "committed"++ t_release.join()+ t_holder.join()++ # The helper must have retried at least once (the first+ # attempt inside the 200 ms busy_timeout window).+ assert len(call_count) >= 2, (+ f"Expected at least 2 attempts (first lock + retry), got "+ f"{len(call_count)}"+ )+++# ---------------------------------------------------------------------------+# SQLAlchemy-session integration: drives the production-shaped wrapped+# ``sqlalchemy.exc.OperationalError`` path, not the raw DBAPI path+# that ``test_retries_locked_error_then_succeeds`` above already+# exercises. Without ``sqlalchemy.exc.OperationalError`` in the helper's+# caught-tuple the production call site+# (``rate_limit_tracker._persist_estimate`` -> SQLAlchemy session+# commit) propagates after one attempt and the retry never fires; this+# test pins that the helper does fire on the wrapped path and that the+# rate-limit-shaped table actually persists the row.+# ---------------------------------------------------------------------------+++class TestRetryOnLockSQLAlchemySession:+ """Pin the SQLAlchemy-wrapped ``OperationalError`` path. The+ reviewer (PR 6718, item 1) demonstrated that without adding+ ``sqlalchemy.exc.OperationalError`` to ``_DB_LOCK_ERROR_TYPES``,+ the helper's only production call site silently no-ops on a real+ lock contention -- ``sqlalchemy.exc.OperationalError`` does NOT+ inherit from ``sqlite3.OperationalError`` or+ ``sqlcipher3.dbapi2.OperationalError``, and the message guard+ alone would never fire if the helper never sees the exception.+ """++ def test_sqlalchemy_operationalerror_is_caught(self):+ """Static guard: ``sqlalchemy.exc.OperationalError`` must be+ in the helper's caught-tuple, otherwise the SQLAlchemy+ commit path is invisible to it. This assertion fires if a+ future refactor accidentally drops the SQLAlchemy type from+ ``_db_lock_error_types``.+ """+ caught = _db_lock_error_types()+ assert SAOperationalError in caught, (+ "sqlalchemy.exc.OperationalError must be in "+ f"_DB_LOCK_ERROR_TYPES; got {caught!r}. Without it, the "+ "helper's only production call site "+ "(rate_limit_tracker._persist_estimate) commits via "+ "SQLAlchemy and the wrapped error escapes the helper without "+ "ever being retried."+ )++ @pytest.mark.slow+ def test_retries_locked_error_via_sqlalchemy_session(self, tmp_path: Path):+ """End-to-end: drive the production-shaped SQLAlchemy session+ path against a real SQLite file, hold the writer lock from+ another connection, and assert that the helper actually+ retries (not just propagates after one call) and the row+ is durable after the holder releases.++ Uses plain ``sqlite://`` (not SQLCipher) so the test stays+ fast and self-contained; SQLCipher would only change the+ connection ``creator``, not the wrapping behaviour. The+ production encrypted path wraps the same DBAPI error in the+ same ``sqlalchemy.exc.OperationalError`` -- this test pins+ that wrapping.+ """+ db_path = tmp_path / "test_retry_sqlalchemy.db"+ engine = create_engine(f"sqlite:///{db_path}")++ # Apply ``busy_timeout`` via an ``engine.connect`` event+ # listener, the same pattern production uses+ # (``create_sqlcipher_connection`` listens for ``connect``+ # and emits ``apply_performance_pragmas``). Setting it via+ # a raw PRAGMA on the engine's pool connection doesn't+ # propagate to connections checked out later, so a freshly+ # created session wouldn't honor the timeout -- mirroring+ # the production symptom this test is here to pin.+ @event.listens_for(engine, "connect")+ def _set_writer_busy_timeout(dbapi_con, _record):+ cur = dbapi_con.cursor()+ cur.execute("PRAGMA busy_timeout = 100")+ cur.close()++ try:+ with engine.connect() as conn:+ conn.execute(+ __import__("sqlalchemy").text(+ "CREATE TABLE rate_estimates ("+ " engine TEXT PRIMARY KEY,"+ " base_wait REAL NOT NULL"+ ")"+ )+ )+ conn.commit()++ holder_started = threading.Event()+ holder_release = threading.Event()+ attempt_count = []+ observed_error_types = []++ def hold_writer_lock():+ """Open a raw connection, BEGIN IMMEDIATE, hold for+ 600 ms, then commit. The other thread's SQLAlchemy+ session commit races this holder and the writer's+ spinner (set by ``PRAGMA busy_timeout`` above) is+ what produces the ``sqlalchemy.exc.OperationalError``+ the helper has to retry on.+ """+ import sqlite3 as _sqlite3++ raw = _sqlite3.connect(str(db_path), isolation_level=None)+ try:+ raw.execute("PRAGMA busy_timeout = 100")+ raw.execute("BEGIN IMMEDIATE")+ raw.execute(+ "INSERT OR REPLACE INTO rate_estimates "+ "(engine, base_wait) VALUES ('other', 0.0)"+ )+ holder_started.set()+ holder_release.wait(timeout=5.0)+ raw.execute("COMMIT")+ finally:+ raw.close()++ def sqlalchemy_write_callable():+ """Replicate ``_persist_estimate``: a fresh+ SQLAlchemy session per attempt, a row insert/update,+ and ``session.commit()`` -- which is where the wrapped+ ``OperationalError`` surfaces on contention.++ Uses ``with sessionmaker()() as session:`` (the same+ context-manager shape ``metrics_writer.get_session``+ uses in production) and wraps the body in+ ``try``/``except`` so we can record the wrapped+ ``OperationalError`` type before re-raising for the+ helper to retry on. The session's ``__exit__``+ rolls back on the exception; we just re-raise so+ ``retry_on_db_lock`` sees the failure.+ """+ attempt_count.append(1)+ Session = sessionmaker(bind=engine)+ with Session() as session:+ try:+ session.execute(+ __import__("sqlalchemy").text(+ "INSERT OR REPLACE INTO rate_estimates "+ "(engine, base_wait) VALUES "+ "('engine_x', 1.5)"+ )+ )+ session.commit()+ return "ok"+ except SAOperationalError as exc:+ observed_error_types.append(type(exc))+ raise++ t_holder = threading.Thread(target=hold_writer_lock)+ t_holder.start()+ assert holder_started.wait(timeout=2.0)++ # Holder releases 2.5 s from now -- well past the+ # connection's busy_timeout (100 ms) so the SQLAlchemy+ # writer's first three commits time out before the lock+ # is released. Helper backoff (0.1 s base, exponential:+ # 0.1 / 0.2 / 0.4 / 0.8 / 1.6 s between attempts) and+ # five timeouts of 100 ms each give a worst-case ~2.4 s+ # before the helper gives up; the 2.5 s release lands+ # the holder's COMMIT in the gap before the sixth+ # attempt commits successfully.+ def release_holder():+ time.sleep(+ 2.5+ ) # allow: unmarked-sleep -- thread-coordination delay+ holder_release.set()++ t_release = threading.Thread(target=release_holder)+ t_release.start()++ result = retry_on_db_lock(+ sqlalchemy_write_callable,+ attempts=6,+ base_delay_seconds=0.1,+ )+ t_release.join()+ t_holder.join()++ assert result == "ok"+ # The first attempt must have hit a SQLAlchemy-wrapped+ # OperationalError (not raw sqlite3.OperationalError) --+ # if this is empty the helper is no-oping on the wrapped+ # path and the production fix is dead code.+ assert observed_error_types, (+ "Writer did not raise sqlalchemy.exc.OperationalError; "+ "either the holder didn't actually hold the writer "+ "lock or the helper is not catching the SQLAlchemy "+ "wrapper. Helper is silently a no-op on this path."+ )+ assert all(+ issubclass(t, SAOperationalError) for t in observed_error_types+ )+ # And the helper must have retried: the production fix is+ # worthless if it propagates after one call.+ assert len(attempt_count) >= 2, (+ f"Expected ≥2 attempts (initial + retry), got "+ f"{len(attempt_count)}. Without retry the production "+ "rate-limit tracker still logs "+ "'Failed to persist rate limit estimate' on the "+ "first lock."+ )++ # Durable row: the rate-limit-shaped table actually+ # persisted the value. The whole point of the helper is+ # that the writer's commit lands despite contention.+ with engine.connect() as conn:+ row = conn.execute(+ __import__("sqlalchemy").text(+ "SELECT base_wait FROM rate_estimates "+ "WHERE engine = 'engine_x'"+ )+ ).fetchone()+ assert row is not None, (+ "The row was not persisted; the retry succeeded "+ "but the transaction was rolled back."+ )+ assert row[0] == 1.5+ finally:+ engine.dispose()