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: optimize N+1 queries and O(n²) searches (#2003)

LearningCircuit1e969fdf8206
diff --git a/src/local_deep_research/research_library/routes/library_routes.py b/src/local_deep_research/research_library/routes/library_routes.py
index 2d52cd40d8..a8ae6c0316 100644
--- a/src/local_deep_research/research_library/routes/library_routes.py
+++ b/src/local_deep_research/research_library/routes/library_routes.py
@@ -712,13 +712,21 @@ def download_all_text():
txt_path = Path(download_service.library_root) / "txt"
resources_to_process = []
+ # Pre-scan directory once to get all existing resource IDs
+ existing_resource_ids = set()
+ if txt_path.exists():
+ for txt_file in txt_path.glob("*.txt"):
+ # Extract resource ID from filename pattern *_{id}.txt
+ parts = txt_file.stem.rsplit("_", 1)
+ if len(parts) == 2:
+ try:
+ existing_resource_ids.add(int(parts[1]))
+ except ValueError:
+ pass
+
for resource in resources:
- # Check if text file already exists
- if txt_path.exists():
- existing = list(txt_path.glob(f"*_{resource.id}.txt"))
- if not existing:
- resources_to_process.append(resource)
- else:
+ # Check if text file already exists using preloaded set
+ if resource.id not in existing_resource_ids:
resources_to_process.append(resource)
total = len(resources_to_process)
@@ -1121,12 +1129,12 @@ def queue_all_undownloaded():
research_ids = set()
skipped_count = 0
+ # Convert filter_results to dict for O(1) lookup instead of O(n²)
+ filter_results_by_id = {r.resource_id: r for r in filter_results}
+
for resource in undownloaded:
# Check if resource passed the smart filter
- filter_result = next(
- (r for r in filter_results if r.resource_id == resource.id),
- None,
- )
+ filter_result = filter_results_by_id.get(resource.id)
if not filter_result or not filter_result.can_retry:
skipped_count += 1
diff --git a/src/local_deep_research/research_library/services/library_service.py b/src/local_deep_research/research_library/services/library_service.py
index 734abe89e7..eda48facf9 100644
--- a/src/local_deep_research/research_library/services/library_service.py
+++ b/src/local_deep_research/research_library/services/library_service.py
@@ -466,6 +466,17 @@ class LibraryService:
.all()
)
+ # Preload all ratings to avoid N+1 queries
+ research_ids = [r[0].id for r in results]
+ all_ratings = (
+ session.query(ResearchRating)
+ .filter(ResearchRating.research_id.in_(research_ids))
+ .all()
+ if research_ids
+ else []
+ )
+ ratings_by_research = {r.research_id: r for r in all_ratings}
+
research_list = []
for (
research,
@@ -473,12 +484,8 @@ class LibraryService:
downloaded_count,
downloadable_count,
) in results:
- # Get rating if exists
- rating = (
- session.query(ResearchRating)
- .filter_by(research_id=research.id)
- .first()
- )
+ # Get rating from preloaded dict
+ rating = ratings_by_research.get(research.id)
# Get domain breakdown - simplified version
# Extract domain from URLs using SQL case statements
diff --git a/src/local_deep_research/web/routes/metrics_routes.py b/src/local_deep_research/web/routes/metrics_routes.py
index 65e14ce795..22ac9c55e2 100644
--- a/src/local_deep_research/web/routes/metrics_routes.py
+++ b/src/local_deep_research/web/routes/metrics_routes.py
@@ -708,6 +708,10 @@ def get_rate_limiting_analytics(period="30d", username=None):
)
engine_types = [row.engine_type for row in engine_types_query.all()]
+ # Preload all estimates to avoid N+1 queries
+ all_estimates = session.query(RateLimitEstimate).all()
+ estimates_by_engine = {e.engine_type: e for e in all_estimates}
+
for engine_type in engine_types:
engine_attempts_list = [
a for a in attempts if a.engine_type == engine_type
@@ -717,12 +721,8 @@ def get_rate_limiting_analytics(period="30d", username=None):
[a for a in engine_attempts_list if a.success]
)
- # Get estimate if exists
- estimate = (
- session.query(RateLimitEstimate)
- .filter(RateLimitEstimate.engine_type == engine_type)
- .first()
- )
+ # Get estimate from preloaded dict
+ estimate = estimates_by_engine.get(engine_type)
# Calculate recent success rate
recent_success_rate = (
diff --git a/tests/research_library/routes/test_library_routes.py b/tests/research_library/routes/test_library_routes.py
index 727b89426b..df378d2e69 100644
--- a/tests/research_library/routes/test_library_routes.py
+++ b/tests/research_library/routes/test_library_routes.py
@@ -5,6 +5,8 @@ Tests cover:
- is_downloadable_domain function
- get_authenticated_user_password function
- API routes
+- Resource ID extraction from filenames (N+1 fix)
+- Filter results dict conversion (O(n²) → O(n) fix)
"""
import pytest
@@ -1319,3 +1321,114 @@ class TestDownloadSource:
content_type="application/json",
)
assert response.status_code in [200, 302, 400, 401, 403, 500]
+
+
+class TestResourceIdExtractionFromFilenames:
+ """Tests for pre-scan directory logic that extracts resource IDs from filenames.
+
+ The pattern is *_{id}.txt where id is an integer.
+ This replaces per-resource glob calls with a single directory scan.
+ """
+
+ def test_extracts_id_from_standard_filename(self, tmp_path):
+ """Should extract resource ID from filename like 'article_42.txt'."""
+ txt_dir = tmp_path / "txt"
+ txt_dir.mkdir()
+ (txt_dir / "article_42.txt").touch()
+ (txt_dir / "paper_100.txt").touch()
+
+ existing_resource_ids = set()
+ for txt_file in txt_dir.glob("*.txt"):
+ parts = txt_file.stem.rsplit("_", 1)
+ if len(parts) == 2:
+ try:
+ existing_resource_ids.add(int(parts[1]))
+ except ValueError:
+ pass
+
+ assert existing_resource_ids == {42, 100}
+
+ def test_ignores_non_numeric_suffix(self, tmp_path):
+ """Should skip filenames without numeric ID suffix."""
+ txt_dir = tmp_path / "txt"
+ txt_dir.mkdir()
+ (txt_dir / "readme.txt").touch()
+ (txt_dir / "notes_abc.txt").touch()
+
+ existing_resource_ids = set()
+ for txt_file in txt_dir.glob("*.txt"):
+ parts = txt_file.stem.rsplit("_", 1)
+ if len(parts) == 2:
+ try:
+ existing_resource_ids.add(int(parts[1]))
+ except ValueError:
+ pass
+
+ assert existing_resource_ids == set()
+
+ def test_handles_empty_directory(self, tmp_path):
+ """Should return empty set for empty directory."""
+ txt_dir = tmp_path / "txt"
+ txt_dir.mkdir()
+
+ existing_resource_ids = set()
+ if txt_dir.exists():
+ for txt_file in txt_dir.glob("*.txt"):
+ parts = txt_file.stem.rsplit("_", 1)
+ if len(parts) == 2:
+ try:
+ existing_resource_ids.add(int(parts[1]))
+ except ValueError:
+ pass
+
+ assert existing_resource_ids == set()
+
+ def test_handles_nonexistent_directory(self, tmp_path):
+ """Should return empty set when directory doesn't exist."""
+ txt_dir = tmp_path / "txt"
+
+ existing_resource_ids = set()
+ if txt_dir.exists():
+ for txt_file in txt_dir.glob("*.txt"):
+ parts = txt_file.stem.rsplit("_", 1)
+ if len(parts) == 2:
+ try:
+ existing_resource_ids.add(int(parts[1]))
+ except ValueError:
+ pass
+
+ assert existing_resource_ids == set()
+
+
+class TestFilterResultsDictConversion:
+ """Tests for O(1) dict lookup replacing O(n²) list scan in queue_all_undownloaded."""
+
+ def test_dict_lookup_matches_list_scan(self):
+ """Dict-based lookup should find same results as linear scan."""
+ filter_results = []
+ for i in range(5):
+ fr = Mock()
+ fr.resource_id = i + 1
+ fr.can_retry = i % 2 == 0
+ filter_results.append(fr)
+
+ # New approach: dict lookup
+ filter_results_by_id = {r.resource_id: r for r in filter_results}
+
+ for resource_id in [1, 2, 3, 4, 5]:
+ # Old approach: linear scan
+ old_result = next(
+ (r for r in filter_results if r.resource_id == resource_id),
+ None,
+ )
+ # New approach: dict lookup
+ new_result = filter_results_by_id.get(resource_id)
+ assert old_result is new_result
+
+ def test_missing_resource_returns_none(self):
+ """Dict lookup returns None for missing resource IDs."""
+ filter_results = [Mock(resource_id=1), Mock(resource_id=3)]
+ filter_results_by_id = {r.resource_id: r for r in filter_results}
+
+ assert filter_results_by_id.get(2) is None
+ assert filter_results_by_id.get(99) is None
diff --git a/tests/research_library/services/test_library_service.py b/tests/research_library/services/test_library_service.py
index 0332ce0a93..b4f7a9e85b 100644
--- a/tests/research_library/services/test_library_service.py
+++ b/tests/research_library/services/test_library_service.py
@@ -628,6 +628,84 @@ class TestLibraryServiceGetResearchListWithStats:
assert isinstance(result, list)
+class TestGetResearchListRatingsPreload:
+ """Tests for batch-preloaded ratings in get_research_list_with_stats (N+1 fix)."""
+
+ def test_ratings_fetched_in_single_batch_query(self, mocker):
+ """Ratings should be preloaded via .in_() query, not per-research."""
+ from local_deep_research.research_library.services.library_service import (
+ LibraryService,
+ )
+
+ mock_session_context = mocker.patch(
+ "local_deep_research.research_library.services.library_service.get_user_db_session"
+ )
+ mock_session = MagicMock()
+ mock_session.__enter__ = Mock(return_value=mock_session)
+ mock_session.__exit__ = Mock(return_value=False)
+
+ # Create mock research results (tuples of research, total, downloaded, downloadable)
+ mock_research1 = Mock()
+ mock_research1.id = 1
+ mock_research2 = Mock()
+ mock_research2.id = 2
+
+ # Set up main query to return two research results
+ mock_main_query = Mock()
+ mock_main_query.outerjoin.return_value = mock_main_query
+ mock_main_query.group_by.return_value = mock_main_query
+ mock_main_query.order_by.return_value = mock_main_query
+ mock_main_query.all.return_value = [
+ (mock_research1, 5, 3, 5),
+ (mock_research2, 10, 8, 10),
+ ]
+
+ # Set up ratings query (preloaded batch)
+ mock_rating = Mock()
+ mock_rating.research_id = 1
+ mock_rating.rating = 4
+ mock_rating.notes = "Good"
+
+ mock_ratings_query = Mock()
+ mock_ratings_query.filter.return_value = mock_ratings_query
+ mock_ratings_query.all.return_value = [mock_rating]
+
+ # Set up domain query chain (used inside loop for domain breakdown)
+ mock_domain_query = Mock()
+ mock_domain_query.filter.return_value = mock_domain_query
+ mock_domain_query.group_by.return_value = mock_domain_query
+ mock_domain_query.limit.return_value = mock_domain_query
+ mock_domain_query.all.return_value = []
+
+ call_count = {"n": 0}
+
+ def query_side_effect(*args):
+ call_count["n"] += 1
+ if call_count["n"] == 1:
+ return mock_main_query # Main research query
+ elif call_count["n"] == 2:
+ return mock_ratings_query # Batch ratings query
+ else:
+ return mock_domain_query # Domain breakdown queries
+
+ mock_session.query.side_effect = query_side_effect
+ mock_session_context.return_value = mock_session
+
+ with patch.object(
+ LibraryService, "__init__", lambda self, username: None
+ ):
+ service = LibraryService.__new__(LibraryService)
+ service.username = "test_user"
+
+ result = service.get_research_list_with_stats()
+
+ assert isinstance(result, list)
+ assert len(result) == 2
+ # The ratings query (call #2) should use .filter() with .in_(),
+ # not be called per-research inside the loop
+ mock_ratings_query.filter.assert_called_once()
+
+
class TestLibraryServiceOpenFileLocation:
"""Tests for open_file_location method."""