~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
perf: fix N+1 queries and add bounded caches
LearningCircuit750c5912d60b
diff --git a/src/local_deep_research/domain_classifier/classifier.py b/src/local_deep_research/domain_classifier/classifier.pyindex 42fc1d82b8..56d6b01ced 100644--- a/src/local_deep_research/domain_classifier/classifier.py+++ b/src/local_deep_research/domain_classifier/classifier.py@@ -1,14 +1,17 @@"""Domain classifier using LLM for categorization."""import json-from typing import List, Dict, Optional+from typing import Dict, List, Optional++from cachetools import TTLCachefrom loguru import loggerfrom sqlalchemy.orm import Session-from ..database.session_context import get_user_db_session-from ..database.models import ResearchResource-from .models import DomainClassification+from ..config.llm_config import get_llm+from ..database.models import ResearchResource+from ..database.session_context import get_user_db_sessionfrom ..utilities.json_utils import extract_json, get_llm_response_text+from .models import DomainClassification# Predefined categories for domain classification@@ -92,6 +95,9 @@ class DomainClassifier:self.username = usernameself.settings_snapshot = settings_snapshotself.llm = None+ # Bounded instance-level cache for domain classifications+ # TTL of 300 seconds (5 minutes) to avoid stale data while reducing DB lookups+ self._classification_cache: TTLCache = TTLCache(maxsize=500, ttl=300)def _get_llm(self):"""Get or initialize LLM instance."""@@ -400,13 +406,22 @@ JSON Response:"""Returns:DomainClassification object or None if not found"""+ # Check instance-level cache first+ cached = self._classification_cache.get(domain)+ if cached is not None:+ return cached+try:with get_user_db_session(self.username) as session:- return (+ classification = (session.query(DomainClassification).filter_by(domain=domain).first())+ # Cache the result if found+ if classification is not None:+ self._classification_cache[domain] = classification+ return classificationexcept Exception:logger.exception(f"Error getting classification for {domain}")return Nonediff --git a/src/local_deep_research/metrics/pricing/pricing_cache.py b/src/local_deep_research/metrics/pricing/pricing_cache.pyindex 6ee577e339..bd018bfb53 100644--- a/src/local_deep_research/metrics/pricing/pricing_cache.py+++ b/src/local_deep_research/metrics/pricing/pricing_cache.py@@ -2,12 +2,12 @@Pricing Cache SystemCaches pricing data to avoid repeated API calls and improve performance.-Includes cache expiration and refresh mechanisms.+Uses bounded TTLCache to prevent memory leaks."""-import timefrom typing import Any, Dict, Optional+from cachetools import TTLCachefrom loguru import logger@@ -23,9 +23,9 @@ class PricingCache:cache_ttl: Cache time-to-live in seconds (default: 1 hour)"""self.cache_ttl = cache_ttl- # In-memory cache only - no file operations- self._cache = {}- logger.info("PricingCache initialized with in-memory storage only")+ # Bounded TTLCache to prevent memory leaks+ self._cache: TTLCache = TTLCache(maxsize=500, ttl=cache_ttl)+ logger.info("PricingCache initialized with bounded TTLCache")def _load_cache(self):"""DEPRECATED: No longer loads from disk."""@@ -35,26 +35,13 @@ class PricingCache:"""DEPRECATED: No longer saves to disk."""pass- def _is_expired(self, timestamp: float) -> bool:- """Check if cache entry is expired."""- return (time.time() - timestamp) > self.cache_ttl-def get(self, key: str) -> Optional[Any]:- """Get cached pricing data."""- if key not in self._cache:- return None-- entry = self._cache[key]- if self._is_expired(entry["timestamp"]):- # Remove expired entry- del self._cache[key]- return None-- return entry["data"]+ """Get cached pricing data. TTLCache handles expiration automatically."""+ return self._cache.get(key)def set(self, key: str, data: Any):"""Set cached pricing data."""- self._cache[key] = {"data": data, "timestamp": time.time()}+ self._cache[key] = datadef get_model_pricing(self, model_name: str) -> Optional[Dict[str, float]]:"""Get cached pricing for a specific model."""@@ -74,35 +61,21 @@ class PricingCache:def clear(self):"""Clear all cached data."""- self._cache = {}+ self._cache.clear()logger.info("Pricing cache cleared")def clear_expired(self):- """Remove expired cache entries."""- expired_keys = []- for key, entry in self._cache.items():- if self._is_expired(entry["timestamp"]):- expired_keys.append(key)-- for key in expired_keys:- del self._cache[key]-- if expired_keys:- logger.info(f"Removed {len(expired_keys)} expired cache entries")+ """Remove expired cache entries. TTLCache handles this automatically via expire()."""+ self._cache.expire()+ logger.debug("Expired cache entries cleared")def get_cache_stats(self) -> Dict[str, Any]:"""Get cache statistics."""- total_entries = len(self._cache)- expired_count = 0-- for entry in self._cache.values():- if self._is_expired(entry["timestamp"]):- expired_count += 1-+ # TTLCache automatically evicts expired entries on access+ self._cache.expire()return {- "total_entries": total_entries,- "expired_entries": expired_count,- "valid_entries": total_entries - expired_count,- "cache_type": "in-memory",+ "total_entries": len(self._cache),+ "max_entries": self._cache.maxsize,+ "cache_type": "TTLCache","cache_ttl": self.cache_ttl,}diff --git a/src/local_deep_research/metrics/token_counter.py b/src/local_deep_research/metrics/token_counter.pyindex 21573d5f9c..993628b809 100644--- a/src/local_deep_research/metrics/token_counter.py+++ b/src/local_deep_research/metrics/token_counter.py@@ -839,20 +839,23 @@ class TokenCounter:.all())- # Get provider info from ModelUsage table+ # Batch load provider info from ModelUsage table (fix N+1)+ model_names = [stat.model_name for stat in model_stats]+ provider_map = {}+ if model_names:+ provider_results = (+ session.query(+ ModelUsage.model_name, ModelUsage.model_provider+ )+ .filter(ModelUsage.model_name.in_(model_names))+ .all()+ )+ for model_name, model_provider in provider_results:+ provider_map[model_name] = model_provider+by_model = []for stat in model_stats:- # Try to get provider from ModelUsage table- provider_info = (- session.query(ModelUsage.model_provider)- .filter(ModelUsage.model_name == stat.model_name)- .first()- )- provider = (- provider_info.model_provider- if provider_info- else "unknown"- )+ provider = provider_map.get(stat.model_name, "unknown")by_model.append({@@ -889,22 +892,32 @@ class TokenCounter:.all())- recent_researches = []- for research_data in recent_research_data:- # Get research query from token_usage table if available- research_query_data = (- session.query(TokenUsage.research_query)+ # Batch load research queries for recent researches (fix N+1)+ recent_research_ids = [+ r.research_id for r in recent_research_data+ ]+ research_query_map = {}+ if recent_research_ids:+ # Get first non-null research_query for each research_id+ query_results = (+ session.query(+ TokenUsage.research_id, TokenUsage.research_query+ ).filter(- TokenUsage.research_id == research_data.research_id,+ TokenUsage.research_id.in_(recent_research_ids),TokenUsage.research_query.isnot(None),)- .first()+ .all())+ for research_id, research_query in query_results:+ if research_id not in research_query_map:+ research_query_map[research_id] = research_query- query_text = (- research_query_data.research_query- if research_query_data- else f"Research {research_data.research_id}"+ recent_researches = []+ for research_data in recent_research_data:+ query_text = research_query_map.get(+ research_data.research_id,+ f"Research {research_data.research_id}",)recent_researches.append(diff --git a/src/local_deep_research/utilities/search_cache.py b/src/local_deep_research/utilities/search_cache.pyindex 52ebe608f7..5d035f51c3 100644--- a/src/local_deep_research/utilities/search_cache.py+++ b/src/local_deep_research/utilities/search_cache.py@@ -11,6 +11,7 @@ from functools import lru_cachefrom pathlib import Pathfrom typing import Any, Dict, List, Optional+from cachetools import TTLCachefrom loguru import loggerfrom sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmaker@@ -58,13 +59,14 @@ class SearchCache:self._memory_cache = {}self._access_times = {}- # Stampede protection: events and locks for each query being fetched- self._fetch_events = {} # query_hash -> threading.Event (signals completion)- self._fetch_locks = {} # query_hash -> threading.Lock (prevents concurrent fetch)+ # Stampede protection: bounded TTL caches for events, locks, and results+ # TTL of 60 seconds to auto-cleanup stale entries+ self._fetch_events: TTLCache = TTLCache(maxsize=1000, ttl=60)+ self._fetch_locks: TTLCache = TTLCache(maxsize=1000, ttl=60)self._fetch_locks_lock = (threading.Lock()) # Protects the fetch dictionaries- self._fetch_results = {} # query_hash -> results (temporary storage during fetch)+ self._fetch_results: TTLCache = TTLCache(maxsize=1000, ttl=60)def _init_db(self):"""Initialize SQLite database for persistent cache using SQLAlchemy."""diff --git a/src/local_deep_research/web/routes/metrics_routes.py b/src/local_deep_research/web/routes/metrics_routes.pyindex 9c488fd445..df2927cf32 100644--- a/src/local_deep_research/web/routes/metrics_routes.py+++ b/src/local_deep_research/web/routes/metrics_routes.py@@ -185,7 +185,6 @@ def get_link_analytics(period="30d", username=None):# Extract domains from URLsfrom urllib.parse import urlparse- from ...domain_classifier.classifier import DomainClassifierdomain_counts = {}domain_researches = {} # Track which researches used each domain@@ -196,8 +195,6 @@ def get_link_analytics(period="30d", username=None):# Generic category counting from LLM classificationscategory_counts = {}- # Initialize domain classifier for LLM-based categorization- domain_classifier = DomainClassifier(username=username)quality_metrics = {"with_title": 0,"with_preview": 0,@@ -205,6 +202,33 @@ def get_link_analytics(period="30d", username=None):"total": 0,}+ # First pass: collect all domains from resources+ all_domains = set()+ for resource in resources:+ if resource.url:+ try:+ parsed = urlparse(resource.url)+ domain = parsed.netloc.lower()+ if domain.startswith("www."):+ domain = domain[4:]+ if domain:+ all_domains.add(domain)+ except Exception:+ pass++ # Batch load all domain classifications in one query (fix N+1)+ domain_classifications_map = {}+ all_classifications = (+ session.query(DomainClassification)+ .filter(DomainClassification.domain.in_(all_domains))+ .all()+ )+ for classification in all_classifications:+ domain_classifications_map[classification.domain] = (+ classification+ )++ # Second pass: process resources with pre-loaded classificationsfor resource in resources:if resource.url:try:@@ -231,10 +255,8 @@ def get_link_analytics(period="30d", username=None):temporal_data.get(date_str, 0) + 1)- # Count categories from LLM classification- classification = domain_classifier.get_classification(- domain- )+ # Count categories from pre-loaded classifications (no N+1)+ classification = domain_classifications_map.get(domain)if classification:category = classification.categorycategory_counts[category] = (@@ -298,38 +320,34 @@ def get_link_analytics(period="30d", username=None):# Get most recent research for each top domain and classificationsdomain_recent_research = {}- domain_classifications = {}- with get_user_db_session(username) as session:- from ...database.models import Research-- # Get classifications for all domains- all_classifications = session.query(DomainClassification).all()- for classification in all_classifications:- domain_classifications[classification.domain] = {- "category": classification.category,- "subcategory": classification.subcategory,- "confidence": classification.confidence,- }+ # Build domain_classifications dict from pre-loaded data+ domain_classifications = {+ domain: {+ "category": classification.category,+ "subcategory": classification.subcategory,+ "confidence": classification.confidence,+ }+ for domain, classification in domain_classifications_map.items()+ }- for domain, _ in top_10_domains:- if domain in domain_researches:- research_ids = list(domain_researches[domain])[- :3- ] # Get up to 3 recent researches- researches = (- session.query(Research)- .filter(Research.id.in_(research_ids))- .all()- )- domain_recent_research[domain] = [- {- "id": r.id,- "query": r.query[:50]- if r.query- else "Research",- }- for r in researches- ]+ # Get research details for top domains+ for domain, _ in top_10_domains:+ if domain in domain_researches:+ research_ids = list(domain_researches[domain])[+ :3+ ] # Get up to 3 recent researches+ researches = (+ session.query(Research)+ .filter(Research.id.in_(research_ids))+ .all()+ )+ domain_recent_research[domain] = [+ {+ "id": r.id,+ "query": r.query[:50] if r.query else "Research",+ }+ for r in researches+ ]return {"link_analytics": {@@ -1075,16 +1093,39 @@ def api_research_link_metrics(research_id):# Extract domain informationfrom urllib.parse import urlparse- from ...domain_classifier.classifier import DomainClassifierdomain_counts = {}# Generic category counting from LLM classificationscategory_counts = {}- # Initialize domain classifier for LLM-based categorization- domain_classifier = DomainClassifier(username=username)+ # First pass: collect all domains+ all_domains = set()+ for resource in resources:+ if resource.url:+ try:+ parsed = urlparse(resource.url)+ domain = parsed.netloc.lower()+ if domain.startswith("www."):+ domain = domain[4:]+ if domain:+ all_domains.add(domain)+ except:+ pass++ # Batch load all domain classifications in one query (fix N+1)+ domain_classifications_map = {}+ all_classifications = (+ session.query(DomainClassification)+ .filter(DomainClassification.domain.in_(all_domains))+ .all()+ )+ for classification in all_classifications:+ domain_classifications_map[classification.domain] = (+ classification+ )+ # Second pass: process resources with pre-loaded classificationsfor resource in resources:if resource.url:try:@@ -1095,10 +1136,8 @@ def api_research_link_metrics(research_id):domain_counts[domain] = domain_counts.get(domain, 0) + 1- # Count categories from LLM classification- classification = domain_classifier.get_classification(- domain- )+ # Count categories from pre-loaded classifications (no N+1)+ classification = domain_classifications_map.get(domain)if classification:category = classification.categorycategory_counts[category] = (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 c83a417fa0..2d41ea46e2 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@@ -7,15 +7,16 @@ import timefrom collections import dequefrom typing import Dict, List, Optional, Tuple+from cachetools import LRUCachefrom loguru import logger-from ...settings.env_registry import use_fallback_llm, is_ci_environment-from ...utilities.thread_context import get_search_contextfrom ...config.thread_settings import (- get_settings_context,- get_setting_from_snapshot,NoSettingsContextError,+ get_setting_from_snapshot,+ get_settings_context,)+from ...settings.env_registry import is_ci_environment, use_fallback_llm+from ...utilities.thread_context import get_search_context# Lazy imports to avoid database initialization in programmatic mode_db_imports = None@@ -95,9 +96,9 @@ class AdaptiveRateLimitTracker:# Apply rate limiting profileself._apply_profile(profile)- # In-memory cache for fast access- self.recent_attempts: Dict[str, deque] = {}- self.current_estimates: Dict[str, Dict[str, float]] = {}+ # Bounded in-memory caches for fast access (prevent memory leaks)+ self.recent_attempts: LRUCache = LRUCache(maxsize=100)+ self.current_estimates: LRUCache = LRUCache(maxsize=100)# Initialize the _estimates_loaded flagself._estimates_loaded = Falsediff --git a/tests/metrics/test_pricing_cache.py b/tests/metrics/test_pricing_cache.pyindex 69dd7b3782..fa85e19cbe 100644--- a/tests/metrics/test_pricing_cache.py+++ b/tests/metrics/test_pricing_cache.py@@ -22,13 +22,13 @@ class TestPricingCacheInit:def test_initializes_empty_cache(self):"""Should initialize with empty in-memory cache."""cache = PricingCache()- assert cache._cache == {}+ assert len(cache._cache) == 0def test_cache_dir_is_deprecated(self):"""Cache dir parameter should be ignored (deprecated)."""cache = PricingCache(cache_dir="/some/path")# Should not raise and should work normally- assert cache._cache == {}+ assert len(cache._cache) == 0class TestPricingCacheGetSet:@@ -40,14 +40,13 @@ class TestPricingCacheGetSet:result = cache.get("nonexistent")assert result is None- def test_set_stores_data_with_timestamp(self):- """Should store data with timestamp."""+ def test_set_stores_data(self):+ """Should store data in cache."""cache = PricingCache()cache.set("test_key", {"value": 123})assert "test_key" in cache._cache- assert cache._cache["test_key"]["data"] == {"value": 123}- assert "timestamp" in cache._cache["test_key"]+ assert cache._cache["test_key"] == {"value": 123}def test_get_returns_valid_data(self):"""Should return data for valid key."""@@ -86,7 +85,7 @@ class TestPricingCacheModelPricing:cache.set_model_pricing("gpt-4", pricing)assert "model:gpt-4" in cache._cache- assert cache._cache["model:gpt-4"]["data"] == pricing+ assert cache._cache["model:gpt-4"] == pricingdef test_get_model_pricing_retrieves_stored(self):"""Should retrieve stored model pricing."""@@ -117,7 +116,7 @@ class TestPricingCacheAllPricing:cache.set_all_pricing(all_pricing)assert "all_models" in cache._cache- assert cache._cache["all_models"]["data"] == all_pricing+ assert cache._cache["all_models"] == all_pricingdef test_get_all_pricing_retrieves_stored(self):"""Should retrieve stored all pricing."""@@ -142,7 +141,7 @@ class TestPricingCacheClear:cache.clear()- assert cache._cache == {}+ assert len(cache._cache) == 0def test_clear_expired_removes_only_expired(self):"""Should remove only expired entries."""@@ -164,7 +163,7 @@ class TestPricingCacheClear:"""Should handle empty cache without error."""cache = PricingCache()cache.clear_expired() # Should not raise- assert cache._cache == {}+ assert len(cache._cache) == 0class TestPricingCacheStats:@@ -176,8 +175,7 @@ class TestPricingCacheStats:stats = cache.get_cache_stats()assert "total_entries" in stats- assert "expired_entries" in stats- assert "valid_entries" in stats+ assert "max_entries" in statsassert "cache_type" in statsassert "cache_ttl" in stats@@ -191,11 +189,9 @@ class TestPricingCacheStats:stats = cache.get_cache_stats()assert stats["total_entries"] == 3- assert stats["valid_entries"] == 3- assert stats["expired_entries"] == 0- def test_get_cache_stats_counts_expired(self):- """Should count expired entries correctly."""+ def test_get_cache_stats_expired_entries_evicted(self):+ """TTLCache automatically evicts expired entries on get_cache_stats."""cache = PricingCache(cache_ttl=1)cache.set("key1", "value1")@@ -203,16 +199,15 @@ class TestPricingCacheStats:stats = cache.get_cache_stats()- assert stats["total_entries"] == 1- assert stats["expired_entries"] == 1- assert stats["valid_entries"] == 0+ # TTLCache evicts expired entries automatically when expire() is called+ assert stats["total_entries"] == 0def test_get_cache_stats_shows_cache_type(self):- """Should show in-memory cache type."""+ """Should show TTLCache cache type."""cache = PricingCache()stats = cache.get_cache_stats()- assert stats["cache_type"] == "in-memory"+ assert stats["cache_type"] == "TTLCache"def test_get_cache_stats_shows_ttl(self):"""Should show configured TTL."""@@ -222,34 +217,26 @@ class TestPricingCacheStats:assert stats["cache_ttl"] == 7200-class TestPricingCacheIsExpired:- """Tests for _is_expired method."""+class TestPricingCacheTTL:+ """Tests for TTLCache behavior."""- def test_is_expired_returns_false_for_recent(self):- """Should return False for recent timestamp."""- cache = PricingCache(cache_ttl=3600)- recent_time = time.time() - 100 # 100 seconds ago-- result = cache._is_expired(recent_time)-- assert result is False-- def test_is_expired_returns_true_for_old(self):- """Should return True for old timestamp."""- cache = PricingCache(cache_ttl=3600)- old_time = time.time() - 4000 # 4000 seconds ago-- result = cache._is_expired(old_time)+ def test_cache_respects_ttl(self):+ """Should respect TTL for entries."""+ cache = PricingCache(cache_ttl=1)+ cache.set("key1", "value1")- assert result is True+ # Entry should be available immediately+ assert cache.get("key1") == "value1"- def test_is_expired_boundary_condition(self):- """Should handle boundary condition correctly."""- cache = PricingCache(cache_ttl=100)- boundary_time = time.time() - 100+ # Wait for expiration+ time.sleep(1.1)- # At exactly TTL seconds, should be expired- result = cache._is_expired(boundary_time)+ # Entry should be expired+ assert cache.get("key1") is None- # This may be True or False depending on exact timing- assert isinstance(result, bool)+ def test_cache_respects_maxsize(self):+ """Should respect maxsize by evicting old entries."""+ # Create cache with small maxsize+ cache = PricingCache()+ # TTLCache with maxsize=500 is default+ assert cache._cache.maxsize == 500