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: address code review round 2 — broken tests, thread safety, dead code

LearningCircuit358cf9fc4ac8
diff --git a/src/local_deep_research/domain_classifier/classifier.py b/src/local_deep_research/domain_classifier/classifier.py
index 56d6b01ced..ee380acaa1 100644
--- a/src/local_deep_research/domain_classifier/classifier.py
+++ b/src/local_deep_research/domain_classifier/classifier.py
@@ -3,7 +3,6 @@
import json
from typing import Dict, List, Optional
-from cachetools import TTLCache
from loguru import logger
from sqlalchemy.orm import Session
@@ -95,9 +94,6 @@ class DomainClassifier:
self.username = username
self.settings_snapshot = settings_snapshot
self.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."""
@@ -406,22 +402,13 @@ 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:
- classification = (
+ return (
session.query(DomainClassification)
.filter_by(domain=domain)
.first()
)
- # Cache the result if found
- if classification is not None:
- self._classification_cache[domain] = classification
- return classification
except Exception:
logger.exception(f"Error getting classification for {domain}")
return None
diff --git a/src/local_deep_research/metrics/token_counter.py b/src/local_deep_research/metrics/token_counter.py
index 6ea5a6cb59..7f133be2e7 100644
--- a/src/local_deep_research/metrics/token_counter.py
+++ b/src/local_deep_research/metrics/token_counter.py
@@ -907,6 +907,7 @@ class TokenCounter:
TokenUsage.research_id.in_(recent_research_ids),
TokenUsage.research_query.isnot(None),
)
+ .order_by(TokenUsage.id)
.all()
)
for research_id, research_query in query_results:
diff --git a/src/local_deep_research/web/routes/metrics_routes.py b/src/local_deep_research/web/routes/metrics_routes.py
index 73c00416d0..f1a551759f 100644
--- a/src/local_deep_research/web/routes/metrics_routes.py
+++ b/src/local_deep_research/web/routes/metrics_routes.py
@@ -11,6 +11,7 @@ from ...database.models import (
RateLimitAttempt,
RateLimitEstimate,
Research,
+ ResearchHistory,
ResearchRating,
ResearchResource,
ResearchStrategy,
@@ -340,8 +341,8 @@ def get_link_analytics(period="30d", username=None):
:3
] # Get up to 3 recent researches
researches = (
- session.query(Research)
- .filter(Research.id.in_(research_ids))
+ session.query(ResearchHistory)
+ .filter(ResearchHistory.id.in_(research_ids))
.all()
)
domain_recent_research[domain] = [
diff --git a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
index 2d41ea46e2..add8b08908 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
@@ -3,6 +3,7 @@ Adaptive rate limit tracker that learns optimal retry wait times for each search
"""
import random
+import threading
import time
from collections import deque
from typing import Dict, List, Optional, Tuple
@@ -97,6 +98,8 @@ class AdaptiveRateLimitTracker:
self._apply_profile(profile)
# Bounded in-memory caches for fast access (prevent memory leaks)
+ # Lock required: LRUCache is not thread-safe (mutates on read via LRU reordering)
+ self._cache_lock = threading.Lock()
self.recent_attempts: LRUCache = LRUCache(maxsize=100)
self.current_estimates: LRUCache = LRUCache(maxsize=100)
@@ -258,23 +261,24 @@ class AdaptiveRateLimitTracker:
# Ensure estimates are loaded from database
self._ensure_estimates_loaded()
- if engine_type not in self.current_estimates:
- # First time seeing this engine - start optimistic and learn from real responses
- # Use engine-specific optimistic defaults only for what we know for sure
- optimistic_defaults = {
- "SearXNGSearchEngine": 0.1, # Self-hosted default engine
- }
+ with self._cache_lock:
+ if engine_type not in self.current_estimates:
+ # First time seeing this engine - start optimistic and learn from real responses
+ # Use engine-specific optimistic defaults only for what we know for sure
+ optimistic_defaults = {
+ "SearXNGSearchEngine": 0.1, # Self-hosted default engine
+ }
- wait_time = optimistic_defaults.get(
- engine_type, 0.1
- ) # Default optimistic for others
- logger.info(
- f"No rate limit data for {engine_type}, starting optimistic with {wait_time}s"
- )
- return wait_time
+ wait_time = optimistic_defaults.get(
+ engine_type, 0.1
+ ) # Default optimistic for others
+ logger.info(
+ f"No rate limit data for {engine_type}, starting optimistic with {wait_time}s"
+ )
+ return wait_time
- estimate = self.current_estimates[engine_type]
- base_wait = estimate["base"]
+ estimate = self.current_estimates[engine_type]
+ base_wait = estimate["base"]
# Security: random used for non-security rate-limit jitter, not tokens or secrets
# Exploration vs exploitation
@@ -353,47 +357,51 @@ class AdaptiveRateLimitTracker:
# Historical rate limit data is not persisted to DB.
# Update in-memory tracking
- if engine_type not in self.recent_attempts:
- # Get current memory window setting from thread context
- settings_context = get_settings_context()
- if settings_context:
- current_memory_window = int(
- settings_context.get_setting(
- "rate_limiting.memory_window", self.memory_window
+ with self._cache_lock:
+ if engine_type not in self.recent_attempts:
+ # Get current memory window setting from thread context
+ settings_context = get_settings_context()
+ if settings_context:
+ current_memory_window = int(
+ settings_context.get_setting(
+ "rate_limiting.memory_window", self.memory_window
+ )
)
+ else:
+ current_memory_window = self.memory_window
+
+ self.recent_attempts[engine_type] = deque(
+ maxlen=current_memory_window
)
- else:
- current_memory_window = self.memory_window
- self.recent_attempts[engine_type] = deque(
- maxlen=current_memory_window
+ self.recent_attempts[engine_type].append(
+ {
+ "wait_time": wait_time,
+ "success": success,
+ "timestamp": timestamp,
+ "retry_count": retry_count,
+ "search_result_count": search_result_count,
+ }
)
- self.recent_attempts[engine_type].append(
- {
- "wait_time": wait_time,
- "success": success,
- "timestamp": timestamp,
- "retry_count": retry_count,
- "search_result_count": search_result_count,
- }
- )
-
# Update estimates
self._update_estimate(engine_type)
def _update_estimate(self, engine_type: str) -> None:
"""Update wait time estimate based on recent attempts."""
- if (
- engine_type not in self.recent_attempts
- or len(self.recent_attempts[engine_type]) < 3
- ):
- logger.info(
- f"Not updating estimate for {engine_type} - only {len(self.recent_attempts.get(engine_type, []))} attempts (need 3)"
- )
- return
+ with self._cache_lock:
+ if (
+ engine_type not in self.recent_attempts
+ or len(self.recent_attempts[engine_type]) < 3
+ ):
+ attempt_count = len(self.recent_attempts.get(engine_type) or [])
+ logger.info(
+ f"Not updating estimate for {engine_type} - only {attempt_count} attempts (need 3)"
+ )
+ return
- attempts = list(self.recent_attempts[engine_type])
+ attempts = list(self.recent_attempts[engine_type])
+ old_estimate = self.current_estimates.get(engine_type)
# Calculate success rate and optimal wait time
successful_waits = [a["wait_time"] for a in attempts if a["success"]]
@@ -414,8 +422,8 @@ class AdaptiveRateLimitTracker:
new_base = percentile_50
# Update estimate with learning rate (exponential moving average)
- if engine_type in self.current_estimates:
- old_base = self.current_estimates[engine_type]["base"]
+ if old_estimate is not None:
+ old_base = old_estimate["base"]
# Get current learning rate from settings context
settings_context = get_settings_context()
if settings_context:
@@ -439,12 +447,13 @@ class AdaptiveRateLimitTracker:
max_wait = min(10.0, new_base * 3.0) # Max 10 seconds absolute cap
# Update in memory
- self.current_estimates[engine_type] = {
- "base": new_base,
- "min": min_wait,
- "max": max_wait,
- "confidence": min(len(attempts) / 20.0, 1.0),
- }
+ with self._cache_lock:
+ self.current_estimates[engine_type] = {
+ "base": new_base,
+ "min": min_wait,
+ "max": max_wait,
+ "confidence": min(len(attempts) / 20.0, 1.0),
+ }
# Persist to database (skip in fallback mode)
success_rate = len(successful_waits) / len(attempts) if attempts else 0
@@ -532,26 +541,29 @@ class AdaptiveRateLimitTracker:
if use_fallback_llm() or is_ci_environment():
logger.debug("Skipping database stats in test/CI mode")
# Return stats from in-memory estimates
- stats = []
- engines_to_check = (
- [engine_type]
- if engine_type
- else list(self.current_estimates.keys())
- )
- for engine in engines_to_check:
- if engine in self.current_estimates:
- est = self.current_estimates[engine]
- stats.append(
- (
- engine,
- est["base"],
- est["min"],
- est["max"],
- time.time(),
- len(self.recent_attempts.get(engine, [])),
- est.get("confidence", 0.0),
+ with self._cache_lock:
+ stats = []
+ engines_to_check = (
+ [engine_type]
+ if engine_type
+ else list(self.current_estimates.keys())
+ )
+ for engine in engines_to_check:
+ if engine in self.current_estimates:
+ est = self.current_estimates[engine]
+ attempts = self.recent_attempts.get(engine)
+ attempt_count = len(attempts) if attempts else 0
+ stats.append(
+ (
+ engine,
+ est["base"],
+ est["min"],
+ est["max"],
+ time.time(),
+ attempt_count,
+ est.get("confidence", 0.0),
+ )
)
- )
return stats
# Skip database operations in programmatic mode
@@ -602,10 +614,11 @@ class AdaptiveRateLimitTracker:
engine_type: Engine to reset
"""
# Always clear from memory first
- if engine_type in self.recent_attempts:
- del self.recent_attempts[engine_type]
- if engine_type in self.current_estimates:
- del self.current_estimates[engine_type]
+ with self._cache_lock:
+ if engine_type in self.recent_attempts:
+ del self.recent_attempts[engine_type]
+ if engine_type in self.current_estimates:
+ del self.current_estimates[engine_type]
# Skip database operations in programmatic mode
if self.programmatic_mode:
@@ -663,15 +676,19 @@ class AdaptiveRateLimitTracker:
"""
stats = []
- engines_to_check = (
- [engine_type] if engine_type else list(self.recent_attempts.keys())
- )
-
- for engine in engines_to_check:
- if engine not in self.recent_attempts:
- continue
+ with self._cache_lock:
+ engines_to_check = (
+ [engine_type]
+ if engine_type
+ else list(self.recent_attempts.keys())
+ )
+ # Snapshot the data under lock, then process outside
+ engine_attempts = {}
+ for engine in engines_to_check:
+ if engine in self.recent_attempts:
+ engine_attempts[engine] = list(self.recent_attempts[engine])
- recent = list(self.recent_attempts[engine])
+ for engine, recent in engine_attempts.items():
search_counts = [
attempt.get("search_result_count", 0)
for attempt in recent
diff --git a/tests/domain_classifier/test_classifier.py b/tests/domain_classifier/test_classifier.py
index aa824b585a..38fb731657 100644
--- a/tests/domain_classifier/test_classifier.py
+++ b/tests/domain_classifier/test_classifier.py
@@ -2,8 +2,6 @@
from unittest.mock import MagicMock, patch
-from cachetools import TTLCache
-
from local_deep_research.domain_classifier.classifier import (
DOMAIN_CATEGORIES,
DomainClassifier,
@@ -62,13 +60,6 @@ class TestDomainClassifierInit:
classifier = DomainClassifier(username="testuser")
assert classifier.llm is None
- def test_classification_cache_initialized(self):
- """Should initialize bounded TTLCache for classifications."""
- classifier = DomainClassifier(username="testuser")
- assert isinstance(classifier._classification_cache, TTLCache)
- assert classifier._classification_cache.maxsize == 500
- assert classifier._classification_cache.ttl == 300
-
class TestGetLlm:
"""Tests for _get_llm method."""
@@ -261,64 +252,6 @@ class TestGetClassification:
assert result is None
- def test_caches_result_on_db_hit(self, mock_domain_classification):
- """Should cache DB result in _classification_cache."""
- classifier = DomainClassifier(username="testuser")
-
- with patch(
- "local_deep_research.domain_classifier.classifier.get_user_db_session"
- ) as mock_session_ctx:
- mock_session = MagicMock()
- mock_session_ctx.return_value.__enter__ = MagicMock(
- return_value=mock_session
- )
- mock_session_ctx.return_value.__exit__ = MagicMock(
- return_value=None
- )
- mock_session.query.return_value.filter_by.return_value.first.return_value = mock_domain_classification
-
- classifier.get_classification("example.com")
-
- assert (
- classifier._classification_cache.get("example.com")
- is mock_domain_classification
- )
-
- def test_returns_cached_without_db_query(self, mock_domain_classification):
- """Should return cached result without hitting DB."""
- classifier = DomainClassifier(username="testuser")
- classifier._classification_cache["example.com"] = (
- mock_domain_classification
- )
-
- with patch(
- "local_deep_research.domain_classifier.classifier.get_user_db_session"
- ) as mock_session_ctx:
- result = classifier.get_classification("example.com")
-
- mock_session_ctx.assert_not_called()
- assert result is mock_domain_classification
-
- def test_does_not_cache_none_result(self):
- """Should not cache None results (domain not found)."""
- classifier = DomainClassifier(username="testuser")
-
- with patch(
- "local_deep_research.domain_classifier.classifier.get_user_db_session"
- ) as mock_session_ctx:
- mock_session = MagicMock()
- mock_session_ctx.return_value.__enter__ = MagicMock(
- return_value=mock_session
- )
- mock_session_ctx.return_value.__exit__ = MagicMock(
- return_value=None
- )
- mock_session.query.return_value.filter_by.return_value.first.return_value = None
-
- classifier.get_classification("unknown.com")
-
- assert classifier._classification_cache.get("unknown.com") is None
-
class TestGetAllClassifications:
"""Tests for get_all_classifications method."""
diff --git a/tests/metrics/test_pricing_edge_cases.py b/tests/metrics/test_pricing_edge_cases.py
index 6b3ba50f3a..07c0d8d6b1 100644
--- a/tests/metrics/test_pricing_edge_cases.py
+++ b/tests/metrics/test_pricing_edge_cases.py
@@ -1,33 +1,5 @@
"""Edge-case tests for pricing modules — boundary, sync, and provider lookups."""
-from unittest.mock import patch
-
-
-class TestIsExpiredBoundaryExactlyAtTTL:
- """Verify strict '>' comparison: at exactly TTL seconds, entry is NOT expired."""
-
- def test_is_expired_boundary_exactly_at_ttl(self):
- """At exactly TTL seconds elapsed, _is_expired must return False (strict >)."""
- from local_deep_research.metrics.pricing.pricing_cache import (
- PricingCache,
- )
-
- cache = PricingCache(cache_ttl=100)
- now = 1000.0
-
- with patch(
- "local_deep_research.metrics.pricing.pricing_cache.time"
- ) as mock_time:
- mock_time.time.return_value = now
- # Timestamp is exactly TTL seconds in the past: now - timestamp == TTL
- timestamp = now - 100 # exactly 100 seconds ago
- result = cache._is_expired(timestamp)
-
- # (1000 - 900) > 100 → 100 > 100 → False
- assert result is False, (
- "At exactly TTL, entry should NOT be expired (strict >)"
- )
-
class TestSyncModelWithMultipleSlashes:
"""Verify split('/')[-1] correctly extracts model from multi-slash names."""
diff --git a/tests/metrics/test_pricing_high_value.py b/tests/metrics/test_pricing_high_value.py
index 53ef57efc0..a6d89488f3 100644
--- a/tests/metrics/test_pricing_high_value.py
+++ b/tests/metrics/test_pricing_high_value.py
@@ -1,12 +1,10 @@
"""High-value tests for metrics/pricing module.
Covers gaps in PricingCache and CostCalculator not addressed by existing tests:
-- Cache TTL expiration, lazy eviction, overwrite behavior
+- Cache overwrite behavior, TTL-based expiration
- CostCalculator.calculate_cost_sync exact arithmetic and edge cases
"""
-import time
-
import pytest
from local_deep_research.metrics.pricing.pricing_cache import PricingCache
@@ -23,15 +21,6 @@ class TestPricingCacheOverwrite:
cache.set("k", {"new": True})
assert cache.get("k") == {"new": True}
- def test_set_overwrites_refreshes_timestamp(self):
- """Overwriting a key updates the timestamp."""
- cache = PricingCache(cache_ttl=3600)
- cache.set("k", "v1")
- ts1 = cache._cache["k"]["timestamp"]
- cache.set("k", "v2")
- ts2 = cache._cache["k"]["timestamp"]
- assert ts2 >= ts1
-
def test_get_with_primitive_value_round_trips(self):
"""Non-dict values (strings) are preserved through set/get."""
cache = PricingCache(cache_ttl=3600)
@@ -39,35 +28,15 @@ class TestPricingCacheOverwrite:
assert cache.get("k") == "hello"
-class TestPricingCacheLazyEviction:
- """Test lazy eviction on get() for expired entries."""
+class TestPricingCacheTTLExpiration:
+ """Test TTL-based expiration via cachetools.TTLCache."""
- def test_get_removes_expired_entry_from_internal_dict(self):
- """get() on expired key removes it from _cache."""
- cache = PricingCache(cache_ttl=3600)
+ def test_zero_ttl_makes_every_entry_expired(self):
+ """With cache_ttl=0, entries are immediately expired."""
+ cache = PricingCache(cache_ttl=0)
cache.set("k", "data")
- # Backdate the timestamp
- cache._cache["k"]["timestamp"] = time.time() - 7200
+ # Give a tiny amount of time for clock to advance
assert cache.get("k") is None
- assert "k" not in cache._cache
-
- def test_stats_after_lazy_eviction(self):
- """After lazy eviction via get(), stats reflect removal."""
- cache = PricingCache(cache_ttl=3600)
- cache.set("k", "data")
- cache._cache["k"]["timestamp"] = time.time() - 7200
- # Before eviction, stats show 1 expired
- stats = cache.get_cache_stats()
- assert stats["expired_entries"] == 1
- # Trigger lazy eviction
- cache.get("k")
- stats = cache.get_cache_stats()
- assert stats["total_entries"] == 0
- assert stats["expired_entries"] == 0
-
-
-class TestPricingCacheClearAndStats:
- """Test clear/clear_expired interaction with stats."""
def test_clear_then_stats_all_zeros(self):
"""After clear(), stats show zero entries."""
@@ -77,39 +46,6 @@ class TestPricingCacheClearAndStats:
cache.clear()
stats = cache.get_cache_stats()
assert stats["total_entries"] == 0
- assert stats["valid_entries"] == 0
-
- def test_clear_expired_drops_expired_count(self):
- """After clear_expired(), expired count drops to zero."""
- cache = PricingCache(cache_ttl=3600)
- cache.set("fresh", "data")
- cache.set("old", "data")
- cache._cache["old"]["timestamp"] = time.time() - 7200
- cache.clear_expired()
- stats = cache.get_cache_stats()
- assert stats["expired_entries"] == 0
- assert stats["valid_entries"] == 1
-
- def test_stats_invariant_valid_plus_expired_equals_total(self):
- """valid_entries + expired_entries always equals total_entries."""
- cache = PricingCache(cache_ttl=3600)
- cache.set("a", 1)
- cache.set("b", 2)
- cache.set("c", 3)
- # Expire one
- cache._cache["b"]["timestamp"] = time.time() - 7200
- stats = cache.get_cache_stats()
- assert (
- stats["valid_entries"] + stats["expired_entries"]
- == stats["total_entries"]
- )
-
- def test_zero_ttl_makes_every_entry_expired(self):
- """With cache_ttl=0, entries are immediately expired."""
- cache = PricingCache(cache_ttl=0)
- cache.set("k", "data")
- # Give a tiny amount of time for clock to advance
- assert cache.get("k") is None
class TestCostCalculatorSync: