~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
refactor: remove unused dogpile cache and add stampede protection
LearningCircuit035ac84ae593
diff --git a/pyproject.toml b/pyproject.tomlindex 69b37df215..c17807371a 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -72,9 +72,6 @@ dependencies = ["rich~=14.2","click~=8.3","flask-login~=0.6",- "dogpile-cache~=1.5",- "redis~=7.1",- "msgpack~=1.1","sqlcipher3-binary~=0.5; sys_platform == \"linux\" and platform_machine == \"x86_64\"","sqlcipher3~=0.5; (platform_machine == \"aarch64\" or platform_machine == \"arm64\") and sys_platform == \"linux\"","sqlcipher3~=0.5; sys_platform != \"linux\"",diff --git a/src/local_deep_research/memory_cache/__init__.py b/src/local_deep_research/memory_cache/__init__.pydeleted file mode 100644index 4627a4b2b4..0000000000--- a/src/local_deep_research/memory_cache/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""Dogpile cache implementation for Local Deep Research."""diff --git a/src/local_deep_research/memory_cache/app_integration.py b/src/local_deep_research/memory_cache/app_integration.pydeleted file mode 100644index 24b10a4ad4..0000000000--- a/src/local_deep_research/memory_cache/app_integration.py+++ /dev/null@@ -1,36 +0,0 @@-"""Integration module to add dogpile cache to the Flask app.--This module provides a simple function to add to app_factory.py-to enable caching throughout the application.-"""--from flask import Flask-from loguru import logger--from .flask_integration import init_cache, cache_metrics_middleware---def setup_dogpile_cache(app: Flask) -> None:- """Set up dogpile cache for the Flask application.-- This function should be called in app_factory.py after- the database and authentication are configured.-- Args:- app: Flask application instance- """- # Initialize cache- init_cache(app)-- # Add cache metrics middleware if cache is enabled- if app.cache:- cache_metrics_middleware(app)- logger.info("Dogpile cache configured with metrics middleware")- else:- logger.warning("Cache is disabled or failed to initialize")-- # Log cache configuration- if app.cache:- logger.info("Cache configuration:")- logger.info(" Simple in-memory cache (1 hour TTL)")- logger.info(" Used for search results and API response caching")diff --git a/src/local_deep_research/memory_cache/cached_services.py b/src/local_deep_research/memory_cache/cached_services.pydeleted file mode 100644index 008105eaa7..0000000000--- a/src/local_deep_research/memory_cache/cached_services.py+++ /dev/null@@ -1,282 +0,0 @@-"""Cached service implementations using dogpile.cache.--This module provides cached versions of search and API cache functionality.-"""--from typing import Any, Dict, List, Optional-from dogpile.cache.api import NO_VALUE-from loguru import logger-from sqlalchemy.orm import Session--from .config import get_thread_local_cache---class CachedSearchCache:- """Replacement for search_cache.py using dogpile.cache."""-- def __init__(self, user_id: str):- """Initialize cached search cache.-- Args:- user_id: User identifier- """- self.user_id = str(user_id)- self.cache = get_thread_local_cache()-- def get(- self, search_query: str, search_engine: str- ) -> Optional[List[Dict[str, Any]]]:- """Get cached search results.-- Args:- search_query: Search query- search_engine: Search engine name-- Returns:- Cached search results or None- """- key = f"{search_engine}:{search_query}"- value = self.cache.get(self.user_id, "search_results", key)-- if value is NO_VALUE:- return None-- return value-- def set(- self,- search_query: str,- search_engine: str,- results: List[Dict[str, Any]],- ttl: int = 3600,- ) -> None:- """Cache search results.-- Args:- search_query: Search query- search_engine: Search engine name- results: Search results- ttl: Time to live in seconds- """- key = f"{search_engine}:{search_query}"- self.cache.set(- self.user_id, "search_results", key, results, expiration_time=ttl- )-- def invalidate_all(self) -> None:- """Invalidate all search results for user."""- self.cache.invalidate(self.user_id, "search_results")---class CachedAPICache:- """Replacement for database/models/cache.py using dogpile.cache."""-- def __init__(self, user_id: str):- """Initialize cached API cache.-- Args:- user_id: User identifier- """- self.user_id = str(user_id)- self.cache = get_thread_local_cache()-- def get(self, cache_key: str) -> Optional[Any]:- """Get cached API response.-- Args:- cache_key: Cache key-- Returns:- Cached value or None- """- value = self.cache.get(self.user_id, "api_cache", cache_key)-- if value is NO_VALUE:- return None-- return value-- def set(- self,- cache_key: str,- value: Any,- ttl: int = 86400, # 24 hours default- ) -> None:- """Cache API response.-- Args:- cache_key: Cache key- value: Value to cache- ttl: Time to live in seconds- """- self.cache.set(- self.user_id, "api_cache", cache_key, value, expiration_time=ttl- )-- def delete(self, cache_key: str) -> None:- """Delete specific cache entry.-- Args:- cache_key: Cache key to delete- """- # Dogpile doesn't have per-key deletion in our implementation- # This would need to be enhanced for production- logger.warning(f"Per-key deletion not implemented for {cache_key}")-- def get_hit_count(self, cache_key: str) -> int:- """Get hit count for cache key.-- Args:- cache_key: Cache key-- Returns:- Hit count (not tracked in dogpile by default)- """- # Would need custom implementation to track hit counts- return 0---class CachedResearchService:- """Cached service for research reports and data."""-- def __init__(self, session: Session, user_id: str):- """Initialize cached research service.-- Args:- session: SQLAlchemy session- user_id: User identifier- """- self.session = session- self.user_id = str(user_id)- self.cache = get_thread_local_cache()-- def save_report(- self,- research_id: str,- report_content: str,- metadata: Dict[str, Any] = None,- ) -> bool:- """Save research report to database and cache.-- Args:- research_id: Research ID- report_content: Report content in markdown- metadata: Optional metadata-- Returns:- True if successful- """- try:- from ..database.models import ResearchHistory-- # Update database- research = (- self.session.query(ResearchHistory)- .filter_by(id=research_id)- .first()- )-- if not research:- logger.error(f"Research {research_id} not found")- return False-- # Store report content in database- research.report_content = report_content-- # Update metadata if provided- if metadata:- if research.research_meta:- research.research_meta.update(metadata)- else:- research.research_meta = metadata-- self.session.commit()-- # Cache the report- self.cache.set(- self.user_id,- "research_reports",- research_id,- report_content,- expiration_time=86400, # 24 hours- )-- # Also cache metadata- if metadata:- self.cache.set(- self.user_id,- "research_metadata",- research_id,- metadata,- expiration_time=86400,- )-- logger.info(f"Saved report for research {research_id}")- return True-- except Exception:- logger.exception("Error saving research report")- self.session.rollback()- return False-- def get_report(- self, research_id: str, use_cache: bool = True- ) -> Optional[str]:- """Get research report from cache or database.-- Args:- research_id: Research ID- use_cache: Whether to use cache-- Returns:- Report content or None- """- if use_cache:- # Try cache first- value = self.cache.get(- self.user_id, "research_reports", research_id- )- if value is not NO_VALUE:- return value-- try:- from ..database.models import ResearchHistory-- # Get from database- research = (- self.session.query(ResearchHistory)- .filter_by(id=research_id)- .first()- )-- if not research or not research.report_content:- return None-- report_content = research.report_content-- # Cache it- if use_cache:- self.cache.set(- self.user_id,- "research_reports",- research_id,- report_content,- expiration_time=86400,- )-- return report_content-- except Exception:- logger.exception("Error getting research report")- return None-- def invalidate_report(self, research_id: str) -> None:- """Invalidate cached report.-- Args:- research_id: Research ID- """- # Invalidate specific report- # Note: dogpile doesn't support per-key invalidation in our setup- # Would need to enhance for production- logger.info(f"Invalidating cache for research {research_id}")diff --git a/src/local_deep_research/memory_cache/config.py b/src/local_deep_research/memory_cache/config.pydeleted file mode 100644index 966cad1c35..0000000000--- a/src/local_deep_research/memory_cache/config.py+++ /dev/null@@ -1,252 +0,0 @@-"""Dogpile cache configuration for SQLCipher-encrypted databases.--This module provides a simple in-memory caching system optimized for per-user-encrypted databases with SQLAlchemy and SQLCipher.-"""--import threading-from typing import Any, Dict, Optional, Union--from dogpile.cache import CacheRegion, make_region-from dogpile.cache.api import NO_VALUE-from loguru import logger--# Thread-local storage for cache regions (matches session pattern)-thread_local = threading.local()--# Cache configuration constants-DEFAULT_CACHE_TTL = 3600 # 1 hour---def get_namespaced_key(user_id: str, namespace: str, key: str) -> str:- """Create namespaced cache key.-- Args:- user_id: User identifier- namespace: Cache namespace (e.g., 'settings', 'api_keys')- key: Specific cache key-- Returns:- Namespaced cache key- """- # Simple string concatenation for in-memory cache keys- return f"ldr:{user_id}:{namespace}:{key}"---def create_null_cache_region() -> CacheRegion:- """Create a null cache region for testing/development."""- region = make_region()- region.configure("dogpile.cache.null")- return region---class SingleTierCache:- """Simple single-tier in-memory cache with configurable TTL."""-- def __init__(- self,- cache_region: Optional[CacheRegion] = None,- enable_metrics: bool = True,- default_ttl: int = DEFAULT_CACHE_TTL,- ):- """Initialize single-tier cache.-- Args:- cache_region: In-memory cache region (defaults to 1 hour TTL)- enable_metrics: Whether to track cache metrics- default_ttl: Default TTL in seconds if no cache_region provided- """- if cache_region:- self.cache = cache_region- else:- # Create a single cache with moderate TTL (1 hour by default)- self.cache = make_region()- self.cache.configure(- "dogpile.cache.memory",- expiration_time=default_ttl,- arguments={- "cache_dict": {},- "max_size": 10000, # Reasonable size for in-memory cache- },- )-- self.enable_metrics = enable_metrics- # Simplified metrics- self.metrics = {"hits": 0, "misses": 0, "errors": 0}-- def get(self, user_id: str, namespace: str, key: str) -> Any:- """Get value from cache.-- Args:- user_id: User identifier- namespace: Cache namespace- key: Cache key-- Returns:- Cached value or NO_VALUE if not found- """- cache_key = get_namespaced_key(user_id, namespace, key)-- try:- value = self.cache.get(cache_key)- if value is not NO_VALUE:- if self.enable_metrics:- self.metrics["hits"] += 1- return value- except Exception as e:- logger.warning(f"Cache error: {e}")- if self.enable_metrics:- self.metrics["errors"] += 1-- if self.enable_metrics:- self.metrics["misses"] += 1-- return NO_VALUE-- def set(- self,- user_id: str,- namespace: str,- key: str,- value: Any,- expiration_time: Optional[int] = None,- ) -> None:- """Set value in cache.-- Args:- user_id: User identifier- namespace: Cache namespace- key: Cache key- value: Value to cache- expiration_time: Optional TTL override (currently ignored - uses region TTL)- """- cache_key = get_namespaced_key(user_id, namespace, key)-- try:- self.cache.set(cache_key, value)- except Exception as e:- logger.warning(f"Failed to set cache: {e}")- if self.enable_metrics:- self.metrics["errors"] += 1-- def invalidate(- self,- user_id: str,- namespace: Optional[str] = None,- pattern: Optional[str] = None,- ) -> None:- """Invalidate cache entries for a user.-- Args:- user_id: User identifier- namespace: Optional namespace to invalidate (None = all)- pattern: Optional pattern within namespace (e.g., "llm.*")- """- # Since we're using memory caches, we need to iterate through keys- # This is less efficient than Redis SCAN but works for memory caches-- if pattern and namespace:- # Pattern-based invalidation within namespace- cache_pattern = f"ldr:{user_id}:{namespace}:"- logger.info(f"Invalidating cache pattern: {cache_pattern}{pattern}")-- # For memory caches, we need to check each key- # This is a limitation of dogpile's memory backend- self._invalidate_memory_pattern(cache_pattern, pattern)-- elif namespace:- # Invalidate entire namespace- cache_pattern = f"ldr:{user_id}:{namespace}:"- logger.info(f"Invalidating cache namespace: {cache_pattern}*")-- # For memory caches, clear matching keys- self._invalidate_memory_pattern(cache_pattern, "*")-- else:- # Invalidate all user data- cache_pattern = f"ldr:{user_id}:"- logger.info(f"Invalidating all cache for user: {cache_pattern}*")-- # For memory caches, clear matching keys- self._invalidate_memory_pattern(cache_pattern, "*")-- def _invalidate_memory_pattern(self, prefix: str, pattern: str) -> None:- """Invalidate keys matching pattern in memory caches.-- Args:- prefix: Key prefix to match- pattern: Pattern to match (supports * wildcard)- """- import fnmatch-- # Helper to check if key matches pattern- def matches_pattern(key: str, prefix: str, pattern: str) -> bool:- if not key.startswith(prefix):- return False-- if pattern == "*":- return True-- # Extract the part after prefix for pattern matching- key_suffix = key[len(prefix) :]-- # Convert pattern to fnmatch pattern- # Handle hierarchical patterns like "llm.*"- if pattern.endswith("*"):- # Match anything starting with the prefix- pattern_prefix = pattern[:-1]- return key_suffix.startswith(pattern_prefix)- else:- # Exact match or complex pattern- return fnmatch.fnmatch(key_suffix, pattern)-- # Invalidate in cache- try:- # Access the underlying cache dict for memory backend- if hasattr(self.cache.backend, "_cache"):- cache_dict = self.cache.backend._cache- keys_to_delete = [- k- for k in cache_dict.keys()- if matches_pattern(k, prefix, pattern)- ]- for key in keys_to_delete:- del cache_dict[key]- logger.debug(- f"Invalidated {len(keys_to_delete)} keys from cache"- )- except Exception as e:- logger.warning(f"Failed to invalidate cache pattern: {e}")-- def get_metrics(self) -> Dict[str, Union[int, float]]:- """Get cache performance metrics.-- Returns:- Dictionary of cache metrics- """- total_requests = self.metrics["hits"] + self.metrics["misses"]-- return {- "total_hits": self.metrics["hits"],- "total_misses": self.metrics["misses"],- "total_errors": self.metrics["errors"],- "total_requests": total_requests,- "hit_rate": self.metrics["hits"] / total_requests- if total_requests > 0- else 0,- }---# Compatibility alias for existing code-TwoTierCache = SingleTierCache---def get_thread_local_cache() -> SingleTierCache:- """Get or create thread-local cache instance.-- Returns:- Thread-local SingleTierCache instance- """- if not hasattr(thread_local, "cache"):- thread_local.cache = SingleTierCache()- return thread_local.cachediff --git a/src/local_deep_research/memory_cache/flask_integration.py b/src/local_deep_research/memory_cache/flask_integration.pydeleted file mode 100644index 23b20171fa..0000000000--- a/src/local_deep_research/memory_cache/flask_integration.py+++ /dev/null@@ -1,167 +0,0 @@-"""Flask integration for dogpile.cache.--This module provides Flask-specific integration for the caching system,-including app initialization, request hooks, and login handlers.-"""--from flask import Flask, g, current_app-from loguru import logger-from dogpile.cache.api import NO_VALUE--from .config import (- SingleTierCache,- TwoTierCache, # Alias for compatibility-)---def init_cache(app: Flask) -> None:- """Initialize caching for Flask application.-- Args:- app: Flask application instance- """- # Get cache configuration from app config or environment- enable_cache = app.config.get("ENABLE_CACHE", True)-- if not enable_cache:- logger.warning("Cache is disabled via configuration")- app.cache = None- return-- # Create single-tier cache at app level- try:- # Create single-tier cache with 1 hour TTL- app.cache = SingleTierCache(enable_metrics=True)-- logger.info("Cache initialized successfully")-- except Exception:- logger.exception("Failed to initialize cache")- # Fall back to null cache- app.cache = None-- # No cache invalidation or warming needed- # Settings and API keys are accessed directly without caching- logger.info("Cache configured - no warming or invalidation needed")-- # Register request handlers- _register_request_handlers(app)---def _register_request_handlers(app: Flask) -> None:- """Register request-level cache handlers.-- Args:- app: Flask application- """-- @app.before_request- def before_request():- """Make cache available in g."""- g.cache = current_app.cache-- @app.teardown_request- def teardown_request(exception=None):- """Clean up request-level cache data."""- # Clear any request-specific cache data- if hasattr(g, "cache_metrics"):- # Log cache metrics for this request- metrics = g.cache_metrics- if metrics and metrics.get("total_requests", 0) > 0:- logger.debug(- f"Request cache stats: "- f"hits={metrics.get('total_hits', 0)} "- f"hit_rate={metrics.get('hit_rate', 0):.2%}"- )---def get_cache() -> TwoTierCache:- """Get cache instance from Flask context.-- Returns:- TwoTierCache instance or None- """- if hasattr(g, "cache"):- return g.cache- elif hasattr(current_app, "cache"):- return current_app.cache- else:- logger.warning("No cache available in Flask context")- return None---def cache_metrics_middleware(app: Flask) -> None:- """Add cache metrics collection middleware.-- Args:- app: Flask application- """-- @app.before_request- def collect_cache_metrics():- """Start collecting cache metrics for request."""- cache = get_cache()- if cache:- g.cache_metrics_start = cache.get_metrics()-- @app.after_request- def log_cache_metrics(response):- """Log cache metrics for request."""- cache = get_cache()- if cache and hasattr(g, "cache_metrics_start"):- end_metrics = cache.get_metrics()-- # Calculate delta- request_hits = (- end_metrics["total_hits"] - g.cache_metrics_start["total_hits"]- )- request_total = (- end_metrics["total_requests"]- - g.cache_metrics_start["total_requests"]- )-- if request_total > 0:- request_hit_rate = request_hits / request_total- # Add custom header for monitoring- response.headers["X-Cache-Hit-Rate"] = f"{request_hit_rate:.2%}"-- return response---# Convenience decorators for views-def cached_view(namespace: str, expiration_time: int = 3600):- """Decorator to cache view results.-- Args:- namespace: Cache namespace- expiration_time: TTL in seconds- """-- def decorator(func):- def wrapper(*args, **kwargs):- cache = get_cache()- if not cache:- return func(*args, **kwargs)-- # Generate cache key from view and args- from flask import request-- user_id = str(g.user.id) if hasattr(g, "user") else "anonymous"- key = f"{func.__name__}:{request.path}:{request.query_string.decode()}"-- # Try cache- value = cache.get(user_id, namespace, key)- if value is not None and value != NO_VALUE:- return value-- # Compute value- value = func(*args, **kwargs)-- # Cache it- cache.set(user_id, namespace, key, value, expiration_time)-- return value-- return wrapper-- return decoratordiff --git a/src/local_deep_research/storage/database.py b/src/local_deep_research/storage/database.pyindex 9cae52f7fd..46a78d1dd9 100644--- a/src/local_deep_research/storage/database.py+++ b/src/local_deep_research/storage/database.py@@ -6,7 +6,6 @@ from sqlalchemy.orm import Sessionfrom .base import ReportStoragefrom ..database.models import ResearchHistory-from ..memory_cache.cached_services import CachedResearchServiceclass DatabaseReportStorage(ReportStorage):@@ -29,37 +28,27 @@ class DatabaseReportStorage(ReportStorage):) -> bool:"""Save report to database."""try:- if username:- # Use cached service if username is provided- cached_service = CachedResearchService(self.session, username)- return cached_service.save_report(- research_id, content, metadata- )- else:- # Direct database save without caching- research = (- self.session.query(ResearchHistory)- .filter_by(id=research_id)- .first()- )-- if not research:- logger.error(f"Research {research_id} not found")- return False-- research.report_content = content-- if metadata:- if research.research_meta:- research.research_meta.update(metadata)- else:- research.research_meta = metadata-- self.session.commit()- logger.info(- f"Saved report for research {research_id} to database"- )- return True+ research = (+ self.session.query(ResearchHistory)+ .filter_by(id=research_id)+ .first()+ )++ if not research:+ logger.error(f"Research {research_id} not found")+ return False++ research.report_content = content++ if metadata:+ if research.research_meta:+ research.research_meta.update(metadata)+ else:+ research.research_meta = metadata++ self.session.commit()+ logger.info(f"Saved report for research {research_id} to database")+ return Trueexcept Exception:logger.exception("Error saving report to database")@@ -71,22 +60,16 @@ class DatabaseReportStorage(ReportStorage):) -> Optional[str]:"""Get report from database."""try:- if username:- # Use cached service if username is provided- cached_service = CachedResearchService(self.session, username)- return cached_service.get_report(research_id)- else:- # Direct database read without caching- research = (- self.session.query(ResearchHistory)- .filter_by(id=research_id)- .first()- )-- if not research or not research.report_content:- return None-- return research.report_content+ research = (+ self.session.query(ResearchHistory)+ .filter_by(id=research_id)+ .first()+ )++ if not research or not research.report_content:+ return None++ return research.report_contentexcept Exception:logger.exception("Error getting report from database")@@ -137,11 +120,6 @@ class DatabaseReportStorage(ReportStorage):research.report_content = Noneself.session.commit()- if username:- # Invalidate cache if username is provided- cached_service = CachedResearchService(self.session, username)- cached_service.invalidate_report(research_id)-return Trueexcept Exception:diff --git a/src/local_deep_research/utilities/search_cache.py b/src/local_deep_research/utilities/search_cache.pyindex 88d31eec32..3de5470955 100644--- a/src/local_deep_research/utilities/search_cache.py+++ b/src/local_deep_research/utilities/search_cache.py@@ -5,6 +5,7 @@ Includes TTL, LRU eviction, and query normalization."""import hashlib+import threadingimport timefrom functools import lru_cachefrom pathlib import Path@@ -57,6 +58,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)+ self._fetch_locks_lock = (+ threading.Lock()+ ) # Protects the fetch dictionaries+ self._fetch_results = {} # query_hash -> results (temporary storage during fetch)+def _init_db(self):"""Initialize SQLite database for persistent cache using SQLAlchemy."""try:@@ -259,6 +268,128 @@ class SearchCache:logger.exception("Failed to store in search cache")return False+ def get_or_fetch(+ self,+ query: str,+ fetch_func,+ search_engine: str = "default",+ ttl: Optional[int] = None,+ ) -> Optional[List[Dict[str, Any]]]:+ """+ Get cached results or fetch with stampede protection.++ This is the recommended way to use the cache. It ensures only one thread+ fetches data for a given query, preventing cache stampedes.++ Args:+ query: Search query+ fetch_func: Function to call if cache miss (should return results list)+ search_engine: Search engine identifier+ ttl: Time-to-live for cached results++ Returns:+ Search results (from cache or freshly fetched)+ """+ query_hash = self._get_query_hash(query, search_engine)++ # Try to get from cache first+ results = self.get(query, search_engine)+ if results is not None:+ return results++ # Acquire lock for this query to prevent stampede+ with self._fetch_locks_lock:+ # Double-check after acquiring lock+ results = self.get(query, search_engine)+ if results is not None:+ return results++ # Check if another thread started fetching while we waited+ if query_hash in self._fetch_events:+ existing_event = self._fetch_events[query_hash]+ # Check if this is a stale event (already set means fetch completed)+ if existing_event.is_set():+ # Previous fetch completed, clean up and start fresh+ del self._fetch_events[query_hash]+ del self._fetch_locks[query_hash]+ if query_hash in self._fetch_results:+ del self._fetch_results[query_hash]+ # Create new event/lock for this fetch+ event = threading.Event()+ self._fetch_events[query_hash] = event+ self._fetch_locks[query_hash] = threading.Lock()+ event = None # Signal we should fetch+ else:+ # Another thread is actively fetching+ event = existing_event+ else:+ # We are the first thread to fetch this query+ event = threading.Event()+ self._fetch_events[query_hash] = event+ self._fetch_locks[query_hash] = threading.Lock()+ event = None # Signal we should fetch++ # If another thread is fetching, wait for it+ if event is not None:+ event.wait(timeout=30)+ if query_hash in self._fetch_results:+ result = self._fetch_results.get(query_hash)+ if result is not None:+ return result+ # Re-check cache, and if still miss, return None (fetch failed)+ return self.get(query, search_engine)++ # We are the thread that should fetch+ fetch_lock = self._fetch_locks[query_hash]+ fetch_event = self._fetch_events[query_hash]++ with fetch_lock:+ # Triple-check (another thread might have fetched while we waited for lock)+ results = self.get(query, search_engine)+ if results is not None:+ fetch_event.set() # Signal completion+ return results++ logger.debug(+ f"Fetching results for query: {query[:50]}... (stampede protected)"+ )++ try:+ # Fetch the results+ results = fetch_func()++ if results:+ # Store in cache+ self.put(query, results, search_engine, ttl)++ # Store temporarily for other waiting threads+ self._fetch_results[query_hash] = results++ return results++ except Exception:+ logger.exception(+ f"Failed to fetch results for query: {query[:50]}"+ )+ # Store None to indicate fetch failed+ self._fetch_results[query_hash] = None+ return None++ finally:+ # Signal completion to waiting threads+ fetch_event.set()++ # Clean up after a delay+ def cleanup():+ time.sleep(2) # Give waiting threads time to get results+ with self._fetch_locks_lock:+ self._fetch_locks.pop(query_hash, None)+ self._fetch_events.pop(query_hash, None)+ self._fetch_results.pop(query_hash, None)++ # Run cleanup in background+ threading.Thread(target=cleanup, daemon=True).start()+def invalidate(self, query: str, search_engine: str = "default") -> bool:"""Invalidate cached results for a specific query."""query_hash = self._get_query_hash(query, search_engine)diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pyindex 5088420e8d..868d7fe913 100644--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@ -218,13 +218,6 @@ def create_app():apply_middleware(app)logger.info("Middleware applied successfully")- # Initialize dogpile cache- logger.info("Initializing dogpile cache...")- from ..memory_cache.app_integration import setup_dogpile_cache-- setup_dogpile_cache(app)- logger.info("Dogpile cache initialized successfully")-# Register blueprintslogger.info("Registering blueprints...")register_blueprints(app)diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 5f0d5babe9..01ac49e742 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -1056,18 +1056,13 @@ def run_research_process(# Get the report content from database for better headline/topic generationreport_content = ""try:- from ...memory_cache.cached_services import (- CachedResearchService,+ research = (+ db_session.query(ResearchHistory)+ .filter_by(id=research_id)+ .first())-- cached_research = CachedResearchService(- db_session, username- )- report_data = cached_research.get_report(- research_id- )- if report_data:- report_content = report_data+ if research and research.report_content:+ report_content = research.report_contentlogger.info(f"Retrieved {len(report_content)} chars from database for headline generation")@@ -1243,22 +1238,38 @@ def run_research_process(f"Saved {sources_saved} sources for research {research_id}")- # Save report using cached service- from ...memory_cache.cached_services import CachedResearchService-+ # Save report to databasewith get_user_db_session(username) as db_session:- cached_research = CachedResearchService(db_session, username)-# Update metadatametadata = final_report["metadata"]metadata["iterations"] = results["iterations"]- # Save report to database and cache- success = cached_research.save_report(- research_id=research_id,- report_content=formatted_content,- metadata=metadata,- )+ # Save report to database+ try:+ research = (+ db_session.query(ResearchHistory)+ .filter_by(id=research_id)+ .first()+ )++ if not research:+ logger.error(f"Research {research_id} not found")+ success = False+ else:+ research.report_content = formatted_content+ if research.research_meta:+ research.research_meta.update(metadata)+ else:+ research.research_meta = metadata+ db_session.commit()+ success = True+ logger.info(+ f"Saved report for research {research_id} to database"+ )+ except Exception:+ logger.exception("Error saving report to database")+ db_session.rollback()+ success = Falseif not success:raise Exception("Failed to save research report")@@ -1326,18 +1337,13 @@ def run_research_process(# Get the report content from database for better headline/topic generationreport_content = ""try:- from ...memory_cache.cached_services import (- CachedResearchService,- )-- cached_research = CachedResearchService(- db_session, username- )- report_data = cached_research.get_report(- research_id+ research = (+ db_session.query(ResearchHistory)+ .filter_by(id=research_id)+ .first())- if report_data:- report_content = report_data+ if research and research.report_content:+ report_content = research.report_contentelse:logger.warning(f"No report content found in database for research_id: {research_id}"diff --git a/tests/test_search_cache_stampede.py b/tests/test_search_cache_stampede.pynew file mode 100644index 0000000000..1432ada7fc--- /dev/null+++ b/tests/test_search_cache_stampede.py@@ -0,0 +1,285 @@+"""+Test search cache stampede protection functionality.+"""++import concurrent.futures+import threading+import time+import unittest+from tempfile import TemporaryDirectory+from typing import List, Dict, Any++from src.local_deep_research.utilities.search_cache import SearchCache+++class TestSearchCacheStampede(unittest.TestCase):+ """Test that SearchCache properly prevents cache stampedes."""++ def setUp(self):+ """Set up test cache with temporary directory."""+ self.temp_dir = TemporaryDirectory()+ self.cache = SearchCache(+ cache_dir=self.temp_dir.name, max_memory_items=100, default_ttl=60+ )++ # Track API calls+ self.api_call_count = 0+ self.api_call_lock = threading.Lock()+ self.api_call_threads = []++ def tearDown(self):+ """Clean up temporary directory."""+ self.temp_dir.cleanup()++ def mock_api_call(self, query: str) -> List[Dict[str, Any]]:+ """Mock API call that simulates slow external search."""+ with self.api_call_lock:+ self.api_call_count += 1+ self.api_call_threads.append(threading.current_thread().name)++ # Simulate network latency+ time.sleep(0.1)++ # Return mock results+ return [+ {"title": f"Result 1 for {query}", "url": "http://example.com/1"},+ {"title": f"Result 2 for {query}", "url": "http://example.com/2"},+ ]++ def test_single_thread_caching(self):+ """Test basic caching works for a single thread."""+ query = "test query single"++ # First call - should miss cache and call API+ results = self.cache.get_or_fetch(+ query, lambda: self.mock_api_call(query)+ )++ self.assertEqual(self.api_call_count, 1)+ self.assertIsNotNone(results)+ self.assertEqual(len(results), 2)++ # Second call - should hit cache+ results2 = self.cache.get_or_fetch(+ query, lambda: self.mock_api_call(query)+ )++ self.assertEqual(self.api_call_count, 1) # No additional API call+ self.assertEqual(results, results2)++ def test_stampede_protection(self):+ """Test that multiple concurrent requests only trigger one API call."""+ query = "test query stampede"+ num_threads = 10+ results_list = []++ def fetch_with_cache(thread_id):+ """Function each thread will run."""+ results = self.cache.get_or_fetch(+ query, lambda: self.mock_api_call(query)+ )+ results_list.append((thread_id, results))+ return results++ # Launch multiple threads concurrently+ with concurrent.futures.ThreadPoolExecutor(+ max_workers=num_threads+ ) as executor:+ futures = [+ executor.submit(fetch_with_cache, i) for i in range(num_threads)+ ]+ concurrent.futures.wait(futures)++ # Check that only ONE API call was made despite multiple threads+ self.assertEqual(+ self.api_call_count,+ 1,+ f"Expected 1 API call but got {self.api_call_count}. "+ f"Threads that called API: {self.api_call_threads}",+ )++ # Check all threads got the same results+ self.assertEqual(len(results_list), num_threads)+ first_result = results_list[0][1]+ for thread_id, result in results_list:+ self.assertEqual(+ result,+ first_result,+ f"Thread {thread_id} got different results",+ )++ def test_different_queries_not_blocked(self):+ """Test that different queries can be fetched concurrently."""+ queries = [f"query_{i}" for i in range(5)]+ results_dict = {}++ def fetch_query(query):+ results = self.cache.get_or_fetch(+ query, lambda: self.mock_api_call(query)+ )+ results_dict[query] = results+ return results++ # Launch threads for different queries+ with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:+ futures = [executor.submit(fetch_query, query) for query in queries]+ concurrent.futures.wait(futures)++ # Each unique query should trigger exactly one API call+ self.assertEqual(+ self.api_call_count,+ 5,+ f"Expected 5 API calls for 5 different queries, got {self.api_call_count}",+ )++ # Verify each query got cached+ for query in queries:+ cached = self.cache.get(query)+ self.assertIsNotNone(cached)+ self.assertEqual(cached, results_dict[query])++ def test_expired_cache_refetch(self):+ """Test that expired cache entries trigger refetch with stampede protection."""+ query = "test expiring query"++ # First fetch with very short TTL+ self.cache.get_or_fetch(+ query,+ lambda: self.mock_api_call(query),+ ttl=1, # 1 second TTL+ )++ self.assertEqual(self.api_call_count, 1)++ # Wait for cache to expire+ time.sleep(1.5)++ # Multiple threads try to fetch expired entry+ num_threads = 5+ results_list = []++ def fetch_expired():+ return self.cache.get_or_fetch(+ query, lambda: self.mock_api_call(query)+ )++ with concurrent.futures.ThreadPoolExecutor(+ max_workers=num_threads+ ) as executor:+ futures = [+ executor.submit(fetch_expired) for _ in range(num_threads)+ ]+ for future in concurrent.futures.as_completed(futures):+ results_list.append(future.result())++ # Should have made exactly 2 API calls total (initial + refetch after expiry)+ self.assertEqual(+ self.api_call_count,+ 2,+ f"Expected 2 API calls (initial + refetch), got {self.api_call_count}",+ )++ # All threads should get the same refreshed results+ for results in results_list:+ self.assertEqual(results, results_list[0])++ def test_get_during_fetch(self):+ """Test that get() returns None while another thread is fetching."""+ query = "test get during fetch"+ fetch_started = threading.Event()+ fetch_complete = threading.Event()++ def slow_fetch():+ fetch_started.set()+ time.sleep(0.5) # Simulate slow API+ fetch_complete.set()+ return self.mock_api_call(query)++ def thread1_fetch():+ """First thread - initiates fetch."""+ return self.cache.get_or_fetch(query, slow_fetch)++ def thread2_get():+ """Second thread - checks cache during fetch."""+ fetch_started.wait() # Ensure fetch has started+ result = self.cache.get(query)+ return result++ def thread3_get_or_fetch():+ """Third thread - uses get_or_fetch during fetch."""+ fetch_started.wait() # Ensure fetch has started+ time.sleep(0.1) # Small delay+ result = self.cache.get_or_fetch(+ query, lambda: self.mock_api_call(query)+ )+ return result++ with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:+ future1 = executor.submit(thread1_fetch)+ future2 = executor.submit(thread2_get)+ future3 = executor.submit(thread3_get_or_fetch)++ # Thread 2 should return None (cache miss during fetch)+ result2 = future2.result()+ self.assertIsNone(result2, "get() should return None during fetch")++ # Thread 3 should wait and get results without calling API again+ result3 = future3.result()+ self.assertIsNotNone(+ result3, "get_or_fetch() should wait and get results"+ )++ # Thread 1 completes the fetch+ result1 = future1.result()+ self.assertIsNotNone(result1)+ self.assertEqual(result1, result3)++ # Only one API call should have been made+ self.assertEqual(self.api_call_count, 1)++ def test_fetch_error_handling(self):+ """Test that fetch errors don't break stampede protection."""+ query = "test error query"+ attempt_count = 0++ def failing_fetch():+ nonlocal attempt_count+ attempt_count += 1+ if attempt_count < 2:+ raise Exception("API error")+ return self.mock_api_call(query)++ # First attempt fails+ result1 = self.cache.get_or_fetch(query, failing_fetch)+ self.assertIsNone(result1)+ self.assertEqual(attempt_count, 1)++ # Second attempt succeeds+ result2 = self.cache.get_or_fetch(query, failing_fetch)+ self.assertIsNotNone(result2)+ self.assertEqual(attempt_count, 2)++ # Third attempt uses cache+ result3 = self.cache.get_or_fetch(query, failing_fetch)+ self.assertEqual(result2, result3)+ self.assertEqual(attempt_count, 2) # No additional attempt++ def test_cleanup_of_locks(self):+ """Test that locks are cleaned up after fetching."""+ query = "test cleanup"++ # Fetch and cache+ self.cache.get_or_fetch(query, lambda: self.mock_api_call(query))++ # Wait for cleanup thread to run (cleanup delay is 2 seconds)+ time.sleep(3)++ # Check that locks and events have been cleaned up+ query_hash = self.cache._get_query_hash(query)+ self.assertNotIn(query_hash, self.cache._fetch_locks)+ self.assertNotIn(query_hash, self.cache._fetch_events)+ self.assertNotIn(query_hash, self.cache._fetch_results)+++if __name__ == "__main__":+ unittest.main()