~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(journal_quality): switch to NullPool to eliminate SQLite Interfac… (#6013)
Faisal Hussaina8a718afe297
diff --git a/changelog.d/6013.bugfix.md b/changelog.d/6013.bugfix.mdnew file mode 100644index 0000000000..8df524f0dd--- /dev/null+++ b/changelog.d/6013.bugfix.md@@ -0,0 +1 @@+Fix concurrent journal-quality filtering failures caused by sharing a SQLite connection across threads.diff --git a/docs/developing/resource-cleanup.md b/docs/developing/resource-cleanup.mdindex bbb69360b9..f7cf0fc30c 100644--- a/docs/developing/resource-cleanup.md+++ b/docs/developing/resource-cleanup.md@@ -314,13 +314,11 @@ here is the full ledger:- **`auth_db` and `journal_quality` engines escapingthe `lifespan()` shutdown path in `web/fastapi_app.py`.** `auth_db` uses`QueuePool(pool_size=10, max_overflow=20)` and `journal_quality`- uses `StaticPool` with `immutable=1`. Both are **bounded** and do- not grow at runtime. Live `/proc` on the affected container showed- only 21 SQLite-related FDs total on PID 1 — well below the ~91-FD- ceiling these unmanaged engines could theoretically reach. The- kernel reclaims FDs at process exit regardless of `engine.dispose()`,- and SQLite WAL files auto-checkpoint on next open. Missing dispose- at exit is hygiene, not a leak.+ uses `NullPool` with `immutable=1`. Connections are opened on demand+ and closed after each session rather than retained in an idle pool.+ The kernel reclaims FDs at process exit regardless of+ `engine.dispose()`, and SQLite WAL files auto-checkpoint on next+ open. Missing dispose at exit is hygiene, not a leak.- **`LibraryRAGService` in three RAG SSE endpoints.**`rag_routes.py:693, 1054, 1827` do construct the service outsidethe generator and never close it, **but** `LibraryRAGService.close()`diff --git a/src/local_deep_research/journal_quality/db.py b/src/local_deep_research/journal_quality/db.pyindex cbae53c01b..c285fef2e3 100644--- a/src/local_deep_research/journal_quality/db.py+++ b/src/local_deep_research/journal_quality/db.py@@ -169,19 +169,22 @@ class JournalQualityDB:return sqlite3.connect(f"file:{path}?mode=ro&immutable=1",uri=True,- check_same_thread=False,)- # StaticPool: with immutable=1 SQLite skips locking and the- # OS page cache handles concurrency. A single shared connection- # is safe and avoids the default QueuePool's 15-connection- # footprint that offers no benefit for immutable reads.- from sqlalchemy.pool import StaticPool+ # NullPool: each Session checks out an isolated read-only+ # connection that is closed when the session context exits.+ # With mode=ro&immutable=1, SQLite connection opens are+ # trivial (no lock overhead) and the OS page cache+ # shares data across connections. NullPool ensures that+ # concurrent filter_results threads never share a single+ # sqlite3.Connection handle (eliminating the cursor race condition+ # that caused sqlite3.InterfaceError / IndexError under StaticPool).+ from sqlalchemy.pool import NullPoolengine = create_engine("sqlite://",creator=_make_ro_conn,- poolclass=StaticPool,+ poolclass=NullPool,echo=False,)session_local = sessionmaker(bind=engine, expire_on_commit=False)@@ -241,6 +244,7 @@ class JournalQualityDB:from ..utilities.resource_utils import safe_closeconn: Optional[sqlite3.Connection] = None+ is_valid = Falsetry:conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)version = conn.execute("PRAGMA user_version").fetchone()[0]@@ -250,25 +254,22 @@ class JournalQualityDB:f"expected {JOURNAL_QUALITY_SCHEMA_VERSION} — "f"rebuilding")- # NB: no explicit safe_close here — the finally block- # handles closing. Calling it twice produced a spurious- # "Cannot operate on a closed database" warning on- # every schema-triggered rebuild.- self._unlink_unusable_db(path)- return False- # Cheap sanity check — confirms the file is a valid DB.- conn.execute("SELECT 1 FROM sqlite_master LIMIT 1").fetchone()- return True+ else:+ # Cheap sanity check — confirms the file is a valid DB.+ conn.execute("SELECT 1 FROM sqlite_master LIMIT 1").fetchone()+ is_valid = Trueexcept (sqlite3.DatabaseError, OSError):logger.exception(f"journal_quality.db at {path} is unusable; rebuilding")- self._unlink_unusable_db(path)- return Falsefinally:if conn is not None:safe_close(conn, "journal_quality validate")+ if not is_valid:+ self._unlink_unusable_db(path)+ return is_valid+@staticmethoddef _unlink_unusable_db(path: Path) -> None:"""Best-effort cleanup of a corrupted / schema-drifted DB file.@@ -364,10 +365,9 @@ class JournalQualityDB:yield sexcept (OperationalError, DatabaseError):logger.exception("journal_quality.db error — resetting engine")- safe_close(s, "journal_quality session")self.reset()raise- else:+ finally:safe_close(s, "journal_quality session")@propertydiff --git a/tests/advanced_search_system/filters/test_journal_reputation_filter.py b/tests/advanced_search_system/filters/test_journal_reputation_filter.pyindex 796d89326f..bf16e1dfde 100644--- a/tests/advanced_search_system/filters/test_journal_reputation_filter.py+++ b/tests/advanced_search_system/filters/test_journal_reputation_filter.py@@ -1006,3 +1006,171 @@ class TestLlmCacheWriteUsesNfkcNormalization:)# Leading/trailing whitespace is stripped.assert normalize_name(" Cell ") == "cell"+++class TestConcurrentFilterResults:+ """Regression test for #5931: concurrent filter_results() executions on the+ shared JournalQualityDB must succeed without sqlite3.InterfaceError or IndexError.+ """++ @pytest.fixture+ def populated_journal_db(self, tmp_path):+ from sqlalchemy import create_engine+ from sqlalchemy.orm import sessionmaker++ from local_deep_research.journal_quality.db import (+ JOURNAL_QUALITY_SCHEMA_VERSION,+ )+ from local_deep_research.journal_quality.models import (+ JournalQualityBase,+ Source,+ )++ db_path = tmp_path / "journal_quality.db"+ engine = create_engine(f"sqlite:///{db_path}")+ JournalQualityBase.metadata.create_all(engine)++ with sessionmaker(bind=engine)() as session:+ session.add(+ Source(+ name="Nature",+ name_lower="nature",+ issn="00280836",+ h_index=1000,+ quartile="Q1",+ impact_factor=50.0,+ is_in_doaj=False,+ score_source="openalex",+ source_type="journal",+ )+ )+ session.commit()++ with engine.connect() as conn:+ conn.exec_driver_sql(+ f"PRAGMA user_version = {JOURNAL_QUALITY_SCHEMA_VERSION}"+ )+ conn.commit()++ engine.dispose()+ return db_path++ def test_concurrent_filter_results_execution(self, populated_journal_db):+ """Simulate parallel search engine threads invoking filter_results() concurrently+ against the shared JournalQualityDB singleton across multiple synchronized rounds.++ Note: filter_results() has an intentional fail-soft safety net (catches database+ exceptions and returns partial results to avoid crashing research runs). Under the+ pre-fix StaticPool race condition, database errors inside concurrent workers were+ caught by that safety net and returned empty result sets. This test therefore asserts+ the presence and correctness of the filtered output rather than requiring+ sqlite3.InterfaceError to escape.++ The barrier synchronizes all workers at the __score_journal() entry boundary immediately+ before SQLite queries execute, maximizing the opportunity for overlapping database+ operations across threads.+ """+ import threading+ from concurrent.futures import ThreadPoolExecutor+ from datetime import timedelta+ from unittest.mock import Mock, patch++ from local_deep_research.advanced_search_system.filters.journal_reputation_filter import (+ JournalReputationFilter,+ )+ from local_deep_research.journal_quality.db import get_db++ db = get_db()+ try:+ db.reset()+ num_workers = 12+ num_rounds = 3+ barrier = threading.Barrier(num_workers)++ def make_worker_filter():+ # Build a separate filter instance per logical worker (matching production search engines),+ # all sharing the singleton JournalQualityDB instance.+ filt = JournalReputationFilter(+ model=Mock(),+ reliability_threshold=4,+ max_context=3000,+ exclude_non_published=False,+ quality_reanalysis_period=timedelta(days=365),+ )+ real_score = filt._JournalReputationFilter__score_journal++ def synchronized_score(name, result):+ # Synchronize all workers at the threshold of SQLite queries,+ # maximizing the opportunity for overlapping DB operations.+ barrier.wait(timeout=10)+ return real_score(name, result)++ filt._JournalReputationFilter__score_journal = (+ synchronized_score+ )+ return filt++ with (+ patch.object(+ db, "_resolve_db_path", return_value=populated_journal_db+ ),+ patch(+ "local_deep_research.config.paths.get_journal_data_directory",+ return_value=populated_journal_db.parent,+ ),+ patch(+ "local_deep_research.advanced_search_system.filters.journal_reputation_filter.get_journal_data_manager",+ return_value=db,+ ),+ patch(+ "local_deep_research.advanced_search_system.filters.journal_reputation_filter.create_search_engine",+ return_value=Mock(is_available=False),+ ),+ patch(+ "local_deep_research.advanced_search_system.filters.journal_reputation_filter.get_llm",+ return_value=Mock(),+ ),+ patch(+ "local_deep_research.advanced_search_system.filters.journal_reputation_filter.get_user_db_session",+ return_value=None,+ ),+ ):+ filters = [make_worker_filter() for _ in range(num_workers)]++ def worker(worker_id: int, round_idx: int):+ filt = filters[worker_id]+ # Each worker receives a single journal result, so __score_journal is reached exactly once per round.+ batch = [+ {+ "title": f"Nature Paper {round_idx}_{worker_id}",+ "journal_ref": "Nature",+ "issn": "0028-0836",+ }+ ]+ return filt.filter_results(+ batch, f"concurrent query {round_idx}_{worker_id}"+ )++ with ThreadPoolExecutor(max_workers=num_workers) as executor:+ for round_idx in range(num_rounds):+ futures = [+ executor.submit(worker, worker_id, round_idx)+ for worker_id in range(num_workers)+ ]+ outputs = [f.result(timeout=10) for f in futures]++ for i, out in enumerate(outputs):+ assert len(out) == 1, (+ f"Round {round_idx} worker {i} returned degraded result: {out}"+ )+ assert (+ out[0]["title"]+ == f"Nature Paper {round_idx}_{i}"+ )+ assert out[0]["journal_quality"] >= 4+ assert (+ out[0]["journal_quality_source"] == "openalex"+ )+ assert out[0]["journal_name_matched"] == "Nature"+ finally:+ db.reset()