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: Rename cache module to memory_cache to avoid gitignore conflicts

LearningCircuit8e4b85fdd0c9
diff --git a/src/local_deep_research/memory_cache/__init__.py b/src/local_deep_research/memory_cache/__init__.py
new file mode 100644
index 0000000000..4627a4b2b4
--- /dev/null
+++ b/src/local_deep_research/memory_cache/__init__.py
@@ -0,0 +1 @@
+"""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.py
new file mode 100644
index 0000000000..bb2cc4fde4
--- /dev/null
+++ b/src/local_deep_research/memory_cache/app_integration.py
@@ -0,0 +1,38 @@
+"""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(" Hot cache: Memory-based, TTL=5 minutes")
+ logger.info(" Warm cache: Redis-based, TTL=1 hour")
+ logger.info(" Namespaces: settings, api_keys, metrics, search_results")
+ logger.info(" Security: HMAC-SHA256 key hashing enabled")
diff --git a/src/local_deep_research/memory_cache/cached_services.py b/src/local_deep_research/memory_cache/cached_services.py
new file mode 100644
index 0000000000..d174ce5257
--- /dev/null
+++ b/src/local_deep_research/memory_cache/cached_services.py
@@ -0,0 +1,536 @@
+"""Cached service implementations using dogpile.cache.
+
+This module provides cached versions of common services like
+SettingsManager and search cache functionality.
+"""
+
+from typing import Any, Dict, List, Optional, Union
+from dogpile.cache.api import NO_VALUE
+from loguru import logger
+from sqlalchemy.orm import Session
+
+from .config import get_thread_local_cache
+from ..database.models import UserSettings
+
+
+class CachedSettingsManager:
+ """Settings manager with dogpile cache integration."""
+
+ def __init__(self, session: Session, user_id: str):
+ """Initialize cached settings manager.
+
+ Args:
+ session: SQLAlchemy session
+ user_id: User identifier
+ """
+ self.session = session
+ self.user_id = str(user_id)
+ self.cache = get_thread_local_cache()
+
+ def get_setting(
+ self, key: str, default: Any = None, use_cache: bool = True
+ ) -> Any:
+ """Get setting value with caching.
+
+ Args:
+ key: Setting key
+ default: Default value if not found
+ use_cache: Whether to use cache
+
+ Returns:
+ Setting value or default
+ """
+ if not use_cache:
+ return self._get_from_db(key, default)
+
+ # Try cache first
+ value = self.cache.get(self.user_id, "settings", key)
+ if value is not NO_VALUE:
+ return value
+
+ # Get from database
+ value = self._get_from_db(key, default)
+
+ # Cache it
+ self.cache.set(
+ self.user_id,
+ "settings",
+ key,
+ value,
+ expiration_time=3600, # 1 hour
+ )
+
+ return value
+
+ def set_setting(self, key: str, value: Any) -> None:
+ """Set setting value and update cache.
+
+ Args:
+ key: Setting key
+ value: Setting value
+ """
+ # Update database
+ self._set_in_db(key, value)
+
+ # Update cache
+ self.cache.set(
+ self.user_id, "settings", key, value, expiration_time=3600
+ )
+
+ # Also invalidate the 'all' cache
+ self.cache.invalidate(self.user_id, "settings")
+
+ def get_all_settings(self, use_cache: bool = True) -> Dict[str, Any]:
+ """Get all settings as dictionary.
+
+ Args:
+ use_cache: Whether to use cache
+
+ Returns:
+ Dictionary of all settings
+ """
+ if not use_cache:
+ return self._get_all_from_db()
+
+ # Try cache first
+ all_settings = self.cache.get(self.user_id, "settings", "all")
+ if all_settings is not NO_VALUE:
+ return all_settings
+
+ # Get from database
+ all_settings = self._get_all_from_db()
+
+ # Cache it
+ self.cache.set(
+ self.user_id, "settings", "all", all_settings, expiration_time=3600
+ )
+
+ return all_settings
+
+ def _get_from_db(self, key: str, default: Any = None) -> Any:
+ """Get setting from database.
+
+ Args:
+ key: Setting key
+ default: Default value
+
+ Returns:
+ Setting value or default
+ """
+ from ..database.models import UserSettings
+
+ try:
+ setting = (
+ self.session.query(UserSettings).filter_by(key=key).first()
+ )
+
+ return setting.value if setting else default
+
+ except Exception as e:
+ logger.error(f"Error getting setting {key}: {e}")
+ return default
+
+ def _set_in_db(self, key: str, value: Any) -> None:
+ """Set setting in database.
+
+ Args:
+ key: Setting key
+ value: Setting value
+ """
+ from ..database.models import UserSettings
+
+ try:
+ setting = (
+ self.session.query(UserSettings).filter_by(key=key).first()
+ )
+
+ if setting:
+ setting.value = value
+ else:
+ setting = UserSettings(key=key, value=value)
+ self.session.add(setting)
+
+ self.session.commit()
+
+ except Exception as e:
+ logger.error(f"Error setting {key}={value}: {e}")
+ self.session.rollback()
+ raise
+
+ def _get_all_from_db(self) -> Dict[str, Any]:
+ """Get all settings from database.
+
+ Returns:
+ Dictionary of all settings
+ """
+ from ..database.models import UserSettings
+
+ try:
+ settings = self.session.query(UserSettings).all()
+
+ return {s.key: s.value for s in settings}
+
+ except Exception as e:
+ logger.error(f"Error getting all settings: {e}")
+ return {}
+
+ def load_from_defaults_file(
+ self, commit: bool = True, **kwargs: Any
+ ) -> None:
+ """Import settings from the defaults settings file.
+
+ Args:
+ commit: Whether to commit changes to database
+ **kwargs: Additional arguments (unused)
+ """
+ import importlib.resources as pkg_resources
+ import json
+ from local_deep_research import defaults
+
+ try:
+ # Load default settings
+ default_settings_json = pkg_resources.read_text(
+ defaults, "default_settings.json"
+ )
+ default_settings = json.loads(default_settings_json)
+
+ # Import each default setting
+ for key, setting_data in default_settings.items():
+ # Check if setting already exists (bypass cache to avoid invalidation loop)
+ existing = self._get_from_db(key)
+ if existing is None:
+ # Only set the value, not the full setting metadata
+ value = setting_data.get("value")
+ if value is not None:
+ # Directly update database without cache invalidation
+ self._set_in_db(key, value)
+
+ if commit:
+ self.session.commit()
+
+ # Invalidate cache once after all settings are loaded
+ self.cache.invalidate(self.user_id, "settings")
+
+ logger.info(f"Loaded {len(default_settings)} default settings")
+
+ except Exception as e:
+ logger.error(f"Error loading default settings: {e}")
+ if self.session:
+ self.session.rollback()
+
+ def create_or_update_setting(
+ self, setting: Union[Dict[str, Any], Any], commit: bool = True
+ ) -> Optional[UserSettings]:
+ """Create or update a setting.
+
+ Args:
+ setting: Setting dictionary or object with key and value
+ commit: Whether to commit the change
+
+ Returns:
+ Setting object if successful, None otherwise
+ """
+ try:
+ # Extract key and value
+ if isinstance(setting, dict):
+ key = setting.get("key")
+ value = setting.get("value")
+ else:
+ key = getattr(setting, "key", None)
+ value = getattr(setting, "value", None)
+
+ if not key:
+ logger.error("No key provided for setting")
+ return None
+
+ # Update the setting
+ self.set_setting(key, value)
+
+ if commit:
+ self.session.commit()
+
+ # Invalidate cache for this key
+ self.cache.invalidate(self.user_id, "settings")
+
+ # Get the updated setting to return
+ db_setting = (
+ self.session.query(UserSettings).filter_by(key=key).first()
+ )
+ return db_setting
+
+ except Exception as e:
+ logger.error(f"Error creating/updating setting: {e}")
+ if self.session:
+ self.session.rollback()
+ return None
+
+
+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 as e:
+ logger.error(f"Error saving research report: {e}")
+ 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 as e:
+ logger.error(f"Error getting research report: {e}")
+ 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.py
new file mode 100644
index 0000000000..5509d42f3d
--- /dev/null
+++ b/src/local_deep_research/memory_cache/config.py
@@ -0,0 +1,434 @@
+"""Dogpile cache configuration for SQLCipher-encrypted databases.
+
+This module provides a two-tier caching system optimized for per-user
+encrypted databases with SQLAlchemy and SQLCipher.
+"""
+
+import hashlib
+import hmac
+import os
+import threading
+from typing import Any, Dict, Optional, Union
+
+import msgpack
+from dogpile.cache import CacheRegion, make_region
+from dogpile.cache.api import NO_VALUE
+from loguru import logger
+
+from ..config.paths import get_data_directory
+
+# Get project static directory
+PROJECT_STATIC_DIR = get_data_directory()
+
+# Thread-local storage for cache regions (matches session pattern)
+thread_local = threading.local()
+
+# Cache configuration constants
+DEFAULT_HOT_CACHE_SIZE = 1000 # In-memory entries
+DEFAULT_HOT_CACHE_TTL = 300 # 5 minutes
+DEFAULT_WARM_CACHE_TTL = 3600 # 1 hour
+CACHE_KEY_SECRET = os.environ.get(
+ "CACHE_KEY_SECRET", "default-secret-change-in-production"
+)
+
+
+def secure_cache_key(user_id: str, key_parts: list) -> str:
+ """Generate secure cache key using HMAC-SHA256.
+
+ Args:
+ user_id: User identifier
+ key_parts: List of key components
+
+ Returns:
+ Secure hash of the cache key
+ """
+ key_material = f"{user_id}:{':'.join(str(p) for p in key_parts)}"
+ return hmac.new(
+ CACHE_KEY_SECRET.encode(), key_material.encode(), hashlib.sha256
+ ).hexdigest()[:32]
+
+
+def get_namespaced_key(user_id: str, namespace: str, key: str) -> str:
+ """Create namespaced cache key with security.
+
+ Args:
+ user_id: User identifier
+ namespace: Cache namespace (e.g., 'settings', 'metrics')
+ key: Specific cache key
+
+ Returns:
+ Namespaced and secured cache key
+ """
+ secure_id = secure_cache_key(user_id, [namespace, key])
+ return f"ldr:{user_id}:{namespace}:{secure_id}"
+
+
+class MsgpackSerializer:
+ """Custom msgpack serializer for dogpile.cache."""
+
+ @staticmethod
+ def dumps(obj: Any) -> bytes:
+ """Serialize object to msgpack bytes."""
+ try:
+ return msgpack.packb(obj, use_bin_type=True)
+ except Exception as e:
+ logger.error(f"Msgpack serialization failed: {e}")
+ raise
+
+ @staticmethod
+ def loads(data: bytes) -> Any:
+ """Deserialize msgpack bytes to object."""
+ try:
+ return msgpack.unpackb(data, raw=False)
+ except Exception as e:
+ logger.error(f"Msgpack deserialization failed: {e}")
+ raise
+
+
+def create_hot_cache_region(size: int = DEFAULT_HOT_CACHE_SIZE) -> CacheRegion:
+ """Create in-memory cache region for frequently accessed data.
+
+ Args:
+ size: Maximum number of cached items
+
+ Returns:
+ Configured in-memory cache region
+ """
+ region = make_region()
+ region.configure(
+ "dogpile.cache.memory_pickle",
+ expiration_time=DEFAULT_HOT_CACHE_TTL,
+ arguments={
+ "cache_dict": {},
+ "max_size": size,
+ },
+ )
+ return region
+
+
+def create_warm_cache_region(
+ redis_url: Optional[str] = None,
+ expiration_time: int = DEFAULT_WARM_CACHE_TTL,
+) -> CacheRegion:
+ """Create memory-backed cache region for warm data.
+
+ Since we don't want persistence between restarts, we'll use
+ memory cache for both hot and warm tiers.
+
+ Args:
+ redis_url: Redis connection URL (ignored)
+ expiration_time: Default cache TTL in seconds
+
+ Returns:
+ Configured memory cache region
+ """
+ # Use memory cache instead of Redis for no persistence
+ region = make_region()
+ region.configure(
+ "dogpile.cache.memory",
+ expiration_time=expiration_time,
+ arguments={
+ "cache_dict": {},
+ "max_size": 10000, # Larger size for warm cache
+ },
+ )
+
+ logger.info("Using memory-only cache (no persistence between restarts)")
+ return region
+
+
+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 TwoTierCache:
+ """Two-tier caching system with hot (memory) and warm (Redis) layers."""
+
+ def __init__(
+ self,
+ hot_region: Optional[CacheRegion] = None,
+ warm_region: Optional[CacheRegion] = None,
+ enable_metrics: bool = True,
+ ):
+ """Initialize two-tier cache.
+
+ Args:
+ hot_region: In-memory cache region
+ warm_region: Redis cache region
+ enable_metrics: Whether to track cache metrics
+ """
+ self.hot = hot_region or create_hot_cache_region()
+ self.warm = warm_region or create_warm_cache_region()
+ self.enable_metrics = enable_metrics
+
+ # Metrics tracking
+ self.metrics = {"hot_hits": 0, "warm_hits": 0, "misses": 0, "errors": 0}
+
+ def get(self, user_id: str, namespace: str, key: str) -> Any:
+ """Get value from cache with two-tier lookup.
+
+ 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 hot cache first
+ try:
+ value = self.hot.get(cache_key)
+ if value is not NO_VALUE:
+ if self.enable_metrics:
+ self.metrics["hot_hits"] += 1
+ return value
+ except Exception as e:
+ logger.warning(f"Hot cache error: {e}")
+ if self.enable_metrics:
+ self.metrics["errors"] += 1
+
+ # Try warm cache
+ try:
+ value = self.warm.get(cache_key)
+ if value is not NO_VALUE:
+ if self.enable_metrics:
+ self.metrics["warm_hits"] += 1
+ # Promote to hot cache
+ try:
+ self.hot.set(cache_key, value)
+ except Exception:
+ pass # Non-critical
+ return value
+ except Exception as e:
+ logger.warning(f"Warm 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 both cache tiers.
+
+ Args:
+ user_id: User identifier
+ namespace: Cache namespace
+ key: Cache key
+ value: Value to cache
+ expiration_time: Optional TTL override (ignored - uses region TTL)
+ """
+ cache_key = get_namespaced_key(user_id, namespace, key)
+
+ # Set in both tiers (expiration is configured at region level)
+ try:
+ self.hot.set(cache_key, value)
+ except Exception as e:
+ logger.warning(f"Failed to set hot cache: {e}")
+
+ try:
+ # Note: expiration_time is ignored - it's set at region level
+ self.warm.set(cache_key, value)
+ except Exception as e:
+ logger.warning(f"Failed to set warm cache: {e}")
+
+ 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 hot cache
+ try:
+ # Access the underlying cache dict for memory backend
+ if hasattr(self.hot.backend, "_cache"):
+ cache_dict = self.hot.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 hot cache"
+ )
+ except Exception as e:
+ logger.warning(f"Failed to invalidate hot cache pattern: {e}")
+
+ # Invalidate in warm cache
+ try:
+ # Access the underlying cache dict for memory backend
+ if hasattr(self.warm.backend, "_cache"):
+ cache_dict = self.warm.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 warm cache"
+ )
+ except Exception as e:
+ logger.warning(f"Failed to invalidate warm cache pattern: {e}")
+
+ def get_metrics(self) -> Dict[str, Union[int, float]]:
+ """Get cache performance metrics.
+
+ Returns:
+ Dictionary of cache metrics
+ """
+ total_hits = self.metrics["hot_hits"] + self.metrics["warm_hits"]
+ total_requests = total_hits + self.metrics["misses"]
+
+ return {
+ **self.metrics,
+ "total_hits": total_hits,
+ "total_requests": total_requests,
+ "hit_rate": total_hits / total_requests
+ if total_requests > 0
+ else 0,
+ "hot_hit_rate": self.metrics["hot_hits"] / total_requests
+ if total_requests > 0
+ else 0,
+ }
+
+
+def get_thread_local_cache(redis_url: Optional[str] = None) -> TwoTierCache:
+ """Get or create thread-local cache instance.
+
+ Args:
+ redis_url: Optional Redis URL override
+
+ Returns:
+ Thread-local TwoTierCache instance
+ """
+ if not hasattr(thread_local, "cache"):
+ thread_local.cache = TwoTierCache(
+ warm_region=create_warm_cache_region(redis_url)
+ )
+ return thread_local.cache
+
+
+# Decorators for common caching patterns
+def cache_user_data(
+ namespace: str,
+ expiration_time: Optional[int] = None,
+ key_generator: Optional[callable] = None,
+):
+ """Decorator for caching user-specific data.
+
+ Args:
+ namespace: Cache namespace
+ expiration_time: Optional TTL override
+ key_generator: Optional function to generate cache key
+ """
+
+ def decorator(func):
+ def wrapper(self, user_id: str, *args, **kwargs):
+ # Generate cache key
+ if key_generator:
+ key = key_generator(*args, **kwargs)
+ else:
+ # Simple key from function name and args
+ key = f"{func.__name__}:{':'.join(str(a) for a in args)}"
+
+ # Get cache
+ cache = get_thread_local_cache()
+
+ # Try cache first
+ value = cache.get(user_id, namespace, key)
+ if value is not NO_VALUE:
+ return value
+
+ # Compute value
+ value = func(self, user_id, *args, **kwargs)
+
+ # Cache it
+ cache.set(user_id, namespace, key, value, expiration_time)
+
+ return value
+
+ return wrapper
+
+ return decorator
diff --git a/src/local_deep_research/memory_cache/flask_integration.py b/src/local_deep_research/memory_cache/flask_integration.py
new file mode 100644
index 0000000000..2af6be11d0
--- /dev/null
+++ b/src/local_deep_research/memory_cache/flask_integration.py
@@ -0,0 +1,247 @@
+"""Flask integration for dogpile.cache.
+
+This module provides Flask-specific integration for the caching system,
+including app initialization, request hooks, and login handlers.
+"""
+
+import asyncio
+import os
+from flask import Flask, g, current_app
+from flask_login import user_loaded_from_request
+from loguru import logger
+from dogpile.cache.api import NO_VALUE
+
+from .config import (
+ TwoTierCache,
+ create_hot_cache_region,
+ create_warm_cache_region,
+)
+from .warmup import get_cache_warmer
+
+
+def init_cache(app: Flask) -> None:
+ """Initialize caching for Flask application.
+
+ Args:
+ app: Flask application instance
+ """
+ # Get cache configuration from app config or environment
+ redis_url = app.config.get("CACHE_REDIS_URL", os.environ.get("REDIS_URL"))
+ enable_cache = app.config.get("ENABLE_CACHE", True)
+
+ if not enable_cache:
+ logger.warning("Cache is disabled via configuration")
+ app.cache_regions = {"hot": None, "warm": None}
+ app.cache = None
+ return
+
+ # Create cache regions at app level
+ try:
+ hot_region = create_hot_cache_region()
+ warm_region = create_warm_cache_region(redis_url)
+
+ app.cache_regions = {"hot": hot_region, "warm": warm_region}
+
+ # Create two-tier cache
+ app.cache = TwoTierCache(
+ hot_region=hot_region, warm_region=warm_region, enable_metrics=True
+ )
+
+ logger.info("Cache initialized successfully")
+
+ except Exception as e:
+ logger.error(f"Failed to initialize cache: {e}")
+ # Fall back to null cache
+ app.cache_regions = {"hot": None, "warm": None}
+ app.cache = None
+
+ # Cache invalidation setup will be done per-user session
+ # since we use per-user encrypted databases
+ logger.info("Cache invalidation will be configured per-user session")
+
+ # Warm startup caches
+ if app.cache:
+ _warm_startup_caches(app)
+
+ # Register request handlers
+ _register_request_handlers(app)
+
+ # Register login handlers
+ _register_login_handlers(app)
+
+
+def _warm_startup_caches(app: Flask) -> None:
+ """Warm shared caches at startup.
+
+ Args:
+ app: Flask application
+ """
+ warmer = get_cache_warmer()
+
+ # Run async warming in background
+ try:
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+ results = loop.run_until_complete(warmer.warm_startup_caches())
+ logger.info(f"Startup cache warming results: {results}")
+ except Exception as e:
+ logger.error(f"Failed to warm startup caches: {e}")
+
+
+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 _register_login_handlers(app: Flask) -> None:
+ """Register login-related cache handlers.
+
+ Args:
+ app: Flask application
+ """
+
+ # Use Flask-Login's signal
+ @user_loaded_from_request.connect_via(app)
+ def on_user_loaded(sender, user):
+ """Warm user cache on login."""
+ if not current_app.cache:
+ return
+
+ try:
+ warmer = get_cache_warmer()
+ # Non-blocking cache warming - run in background thread
+ import threading
+
+ def warm_cache():
+ try:
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+ loop.run_until_complete(
+ warmer.warm_user_cache_async(
+ str(user.id),
+ cache_types=["settings", "api_keys", "metrics"],
+ )
+ )
+ except Exception as e:
+ logger.error(f"Cache warming error: {e}")
+
+ thread = threading.Thread(target=warm_cache)
+ thread.daemon = True
+ thread.start()
+ logger.debug(f"Initiated cache warming for user {user.id}")
+ except Exception as e:
+ logger.error(f"Failed to warm cache for user {user.id}: {e}")
+
+
+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 decorator
diff --git a/src/local_deep_research/memory_cache/invalidation.py b/src/local_deep_research/memory_cache/invalidation.py
new file mode 100644
index 0000000000..a257e79b35
--- /dev/null
+++ b/src/local_deep_research/memory_cache/invalidation.py
@@ -0,0 +1,260 @@
+"""Cache invalidation strategies for dogpile.cache.
+
+This module implements event-driven and hybrid invalidation patterns
+for maintaining cache consistency with SQLAlchemy models.
+"""
+
+from typing import Dict, List, Optional, Set, Type
+from sqlalchemy import event
+from loguru import logger
+
+from .config import get_thread_local_cache
+from ..database.models import (
+ UserSettings,
+ APIKey,
+ TokenUsage,
+ SearchCall,
+ Cache,
+)
+
+
+class CacheInvalidator:
+ """Handles cache invalidation for SQLAlchemy models."""
+
+ def __init__(self):
+ """Initialize cache invalidator."""
+ self.invalidation_rules: Dict[Type, List[Dict]] = {}
+ self.registered_models: Set[Type] = set()
+
+ def register_model(
+ self, model_class: Type, invalidation_patterns: List[Dict]
+ ) -> None:
+ """Register invalidation patterns for a model.
+
+ Args:
+ model_class: SQLAlchemy model class
+ invalidation_patterns: List of invalidation rules
+ """
+ self.invalidation_rules[model_class] = invalidation_patterns
+ self.registered_models.add(model_class)
+ logger.debug(
+ f"Registered invalidation rules for {model_class.__name__}"
+ )
+
+ def setup_listeners(self, session_factory) -> None:
+ """Set up SQLAlchemy event listeners.
+
+ Args:
+ session_factory: SQLAlchemy session factory
+ """
+ # Listen for after_commit to ensure transaction success
+ event.listen(session_factory, "after_commit", self._after_commit)
+ event.listen(
+ session_factory, "after_soft_rollback", self._after_rollback
+ )
+
+ # Listen for model-specific events
+ for model_class in self.registered_models:
+ event.listen(model_class, "after_update", self._after_update)
+ event.listen(model_class, "after_delete", self._after_delete)
+ event.listen(model_class, "after_insert", self._after_insert)
+
+ def _after_commit(self, session) -> None:
+ """Handle cache invalidation after successful commit.
+
+ Args:
+ session: SQLAlchemy session
+ """
+ cache = get_thread_local_cache()
+
+ # Process all dirty objects
+ for obj in session.identity_map.all_states():
+ if obj.modified or obj.deleted:
+ model_class = type(obj.obj())
+ if model_class in self.invalidation_rules:
+ self._invalidate_for_object(cache, obj.obj(), model_class)
+
+ def _invalidate_for_object(self, cache, obj, model_class) -> None:
+ """Invalidate cache entries for a specific object.
+
+ Args:
+ cache: TwoTierCache instance
+ obj: Model instance
+ model_class: Model class
+ """
+ rules = self.invalidation_rules.get(model_class, [])
+
+ for rule in rules:
+ try:
+ namespace = rule["namespace"]
+
+ # Get user_id for the object
+ user_id = self._get_user_id(
+ obj, rule.get("user_id_attr", "user_id")
+ )
+ if not user_id:
+ continue
+
+ # Invalidate based on pattern
+ if "key_pattern" in rule:
+ # Pattern provided but we invalidate entire namespace
+ _ = rule["key_pattern"].format(**obj.__dict__)
+ cache.invalidate(user_id, namespace)
+ elif "key_function" in rule:
+ # Key function is provided but we invalidate entire namespace
+ _ = rule["key_function"](obj)
+ cache.invalidate(user_id, namespace)
+ else:
+ # Invalidate entire namespace
+ cache.invalidate(user_id, namespace)
+
+ logger.debug(
+ f"Invalidated cache for {model_class.__name__} "
+ f"user_id={user_id} namespace={namespace}"
+ )
+
+ except Exception as e:
+ logger.error(f"Error invalidating cache: {e}")
+
+ def _get_user_id(self, obj, user_id_attr: str) -> Optional[str]:
+ """Extract user_id from object.
+
+ Args:
+ obj: Model instance
+ user_id_attr: Attribute name for user_id
+
+ Returns:
+ User ID or None
+ """
+ try:
+ return str(getattr(obj, user_id_attr))
+ except AttributeError:
+ return None
+
+ def _after_update(self, mapper, connection, target) -> None:
+ """Mark object as modified for later invalidation."""
+ # The actual invalidation happens in after_commit
+ pass
+
+ def _after_delete(self, mapper, connection, target) -> None:
+ """Mark object as deleted for later invalidation."""
+ pass
+
+ def _after_insert(self, mapper, connection, target) -> None:
+ """Handle cache invalidation for new objects."""
+ # Some caches may need invalidation on insert
+ pass
+
+ def _after_rollback(self, session, previous_transaction) -> None:
+ """Clean up after rollback - no invalidation needed."""
+ logger.debug("Transaction rolled back - no cache invalidation")
+
+
+# Global invalidator instance
+_invalidator = CacheInvalidator()
+
+
+def setup_cache_invalidation(session_factory) -> None:
+ """Set up cache invalidation rules for all models.
+
+ Args:
+ session_factory: SQLAlchemy session factory
+ """
+ # Register UserSettings invalidation
+ _invalidator.register_model(
+ UserSettings,
+ [
+ {
+ "namespace": "settings",
+ "user_id_attr": "user_id",
+ "key_pattern": "{key}", # Invalidate specific setting
+ },
+ {
+ "namespace": "settings",
+ "user_id_attr": "user_id",
+ "key_function": lambda obj: "all", # Also invalidate bulk cache
+ },
+ ],
+ )
+
+ # Register APIKey invalidation
+ _invalidator.register_model(
+ APIKey,
+ [
+ {
+ "namespace": "api_keys",
+ "user_id_attr": "user_id",
+ "key_pattern": "{provider}",
+ }
+ ],
+ )
+
+ # Register TokenUsage invalidation (metrics)
+ _invalidator.register_model(
+ TokenUsage,
+ [
+ {
+ "namespace": "metrics",
+ "user_id_attr": "user_id",
+ # Invalidate all metrics on new usage
+ }
+ ],
+ )
+
+ # Register SearchCall invalidation
+ _invalidator.register_model(
+ SearchCall,
+ [
+ {
+ "namespace": "metrics",
+ "user_id_attr": "user_id",
+ }
+ ],
+ )
+
+ # Register Cache model invalidation (for legacy cache)
+ _invalidator.register_model(
+ Cache,
+ [
+ {
+ "namespace": "legacy_cache",
+ "user_id_attr": "user_id",
+ }
+ ],
+ )
+
+ # Set up event listeners
+ _invalidator.setup_listeners(session_factory)
+
+ logger.info("Cache invalidation rules configured")
+
+
+def invalidate_user_cache(
+ user_id: str, namespace: Optional[str] = None
+) -> None:
+ """Manually invalidate cache for a user.
+
+ Args:
+ user_id: User identifier
+ namespace: Optional namespace to invalidate
+ """
+ cache = get_thread_local_cache()
+ cache.invalidate(user_id, namespace)
+ logger.info(
+ f"Manually invalidated cache for user {user_id} namespace={namespace}"
+ )
+
+
+def invalidate_all_user_caches(user_id: str) -> None:
+ """Invalidate all caches for a user.
+
+ Args:
+ user_id: User identifier
+ """
+ namespaces = ["settings", "api_keys", "metrics", "legacy_cache"]
+ cache = get_thread_local_cache()
+
+ for namespace in namespaces:
+ cache.invalidate(user_id, namespace)
+
+ logger.info(f"Invalidated all caches for user {user_id}")
diff --git a/src/local_deep_research/memory_cache/warmup.py b/src/local_deep_research/memory_cache/warmup.py
new file mode 100644
index 0000000000..28f54802dc
--- /dev/null
+++ b/src/local_deep_research/memory_cache/warmup.py
@@ -0,0 +1,385 @@
+"""Cache warming strategies for settings and metrics.
+
+This module implements non-blocking cache warming for user login
+and application startup scenarios.
+"""
+
+import asyncio
+from typing import Dict, List, Optional, Any
+from concurrent.futures import ThreadPoolExecutor
+
+from loguru import logger
+
+from .config import get_thread_local_cache, cache_user_data
+from ..database.models import UserSettings, APIKey, TokenUsage, SearchCall
+from ..database.session_context import get_user_db_session
+
+
+class CacheWarmer:
+ """Handles cache warming for various data types."""
+
+ def __init__(self, executor: Optional[ThreadPoolExecutor] = None):
+ """Initialize cache warmer.
+
+ Args:
+ executor: Thread pool executor for background tasks
+ """
+ self.executor = executor or ThreadPoolExecutor(max_workers=2)
+ self.cache = get_thread_local_cache()
+
+ async def warm_startup_caches(self) -> Dict[str, bool]:
+ """Warm shared caches at application startup.
+
+ Returns:
+ Dictionary of cache warming results
+ """
+ results = {}
+
+ try:
+ # Warm system configurations
+ await self._warm_system_configs()
+ results["system_configs"] = True
+ except Exception as e:
+ logger.error(f"Failed to warm system configs: {e}")
+ results["system_configs"] = False
+
+ try:
+ # Warm default settings
+ await self._warm_default_settings()
+ results["default_settings"] = True
+ except Exception as e:
+ logger.error(f"Failed to warm default settings: {e}")
+ results["default_settings"] = False
+
+ return results
+
+ async def warm_user_cache_async(
+ self, user_id: str, cache_types: Optional[List[str]] = None
+ ) -> None:
+ """Warm user-specific caches without blocking.
+
+ Args:
+ user_id: User identifier
+ cache_types: Optional list of cache types to warm
+ """
+ if cache_types is None:
+ cache_types = ["settings", "api_keys", "metrics"]
+
+ # Create background task
+ loop = asyncio.get_event_loop()
+ loop.run_in_executor(
+ self.executor, self._warm_user_cache_sync, user_id, cache_types
+ )
+
+ def _warm_user_cache_sync(
+ self, user_id: str, cache_types: List[str]
+ ) -> None:
+ """Synchronous cache warming for background execution.
+
+ Args:
+ user_id: User identifier
+ cache_types: List of cache types to warm
+ """
+ try:
+ with get_user_db_session(user_id) as session:
+ if "settings" in cache_types:
+ self._warm_user_settings(session, user_id)
+
+ if "api_keys" in cache_types:
+ self._warm_user_api_keys(session, user_id)
+
+ if "metrics" in cache_types:
+ self._warm_user_metrics(session, user_id)
+
+ except Exception as e:
+ logger.error(f"Cache warming failed for user {user_id}: {e}")
+
+ def _warm_user_settings(self, session, user_id: str) -> None:
+ """Warm all user settings."""
+ try:
+ # Fetch all settings for user (no user_id needed - it's a per-user database)
+ settings = session.query(UserSettings).all()
+
+ # Cache individual settings
+ for setting in settings:
+ self.cache.set(
+ user_id,
+ "settings",
+ setting.key,
+ setting.value,
+ expiration_time=3600, # 1 hour
+ )
+
+ # Cache as dictionary for bulk access
+ settings_dict = {s.key: s.value for s in settings}
+ self.cache.set(
+ user_id, "settings", "all", settings_dict, expiration_time=3600
+ )
+
+ logger.debug(f"Warmed {len(settings)} settings for user {user_id}")
+
+ except Exception as e:
+ logger.error(f"Failed to warm settings for user {user_id}: {e}")
+
+ def _warm_user_api_keys(self, session, user_id: str) -> None:
+ """Warm user API keys."""
+ try:
+ # Fetch all API keys for user (no user_id needed - it's a per-user database)
+ api_keys = session.query(APIKey).all()
+
+ # Cache API keys by provider
+ for key in api_keys:
+ self.cache.set(
+ user_id,
+ "api_keys",
+ key.provider,
+ {
+ "id": key.id,
+ "encrypted_key": key.encrypted_key,
+ "is_active": key.is_active,
+ },
+ expiration_time=3600,
+ )
+
+ logger.debug(f"Warmed {len(api_keys)} API keys for user {user_id}")
+
+ except Exception as e:
+ logger.error(f"Failed to warm API keys for user {user_id}: {e}")
+
+ def _warm_user_metrics(self, session, user_id: str) -> None:
+ """Warm user metrics aggregations."""
+ try:
+ # Warm recent token usage (no user_id filter needed)
+ recent_usage = (
+ session.query(TokenUsage.model_name, TokenUsage.total_tokens)
+ .order_by(TokenUsage.created_at.desc())
+ .limit(100)
+ .all()
+ )
+
+ self.cache.set(
+ user_id,
+ "metrics",
+ "recent_token_usage",
+ recent_usage,
+ expiration_time=300, # 5 minutes
+ )
+
+ # Warm search metrics (no user_id filter needed)
+ search_metrics = (
+ session.query(SearchCall.search_engine, SearchCall.success)
+ .order_by(SearchCall.created_at.desc())
+ .limit(100)
+ .all()
+ )
+
+ self.cache.set(
+ user_id,
+ "metrics",
+ "recent_searches",
+ search_metrics,
+ expiration_time=300,
+ )
+
+ logger.debug(f"Warmed metrics for user {user_id}")
+
+ except Exception as e:
+ logger.error(f"Failed to warm metrics for user {user_id}: {e}")
+
+ async def _warm_system_configs(self) -> None:
+ """Warm system-wide configurations."""
+ # This would warm shared configurations
+ # Implementation depends on your system config storage
+ pass
+
+ async def _warm_default_settings(self) -> None:
+ """Warm default settings from JSON."""
+ # This would load and cache default settings
+ # Implementation depends on your default settings location
+ pass
+
+
+class ProgressiveCacheWarmer(CacheWarmer):
+ """Progressive cache warming with priority-based loading."""
+
+ def __init__(
+ self,
+ executor: Optional[ThreadPoolExecutor] = None,
+ batch_size: int = 10,
+ ):
+ """Initialize progressive cache warmer.
+
+ Args:
+ executor: Thread pool executor
+ batch_size: Number of items to warm per batch
+ """
+ super().__init__(executor)
+ self.batch_size = batch_size
+
+ async def warm_user_cache_progressive(
+ self, user_id: str, priority_order: Optional[List[str]] = None
+ ) -> None:
+ """Progressively warm caches with yielding.
+
+ Args:
+ user_id: User identifier
+ priority_order: Priority order for cache warming
+ """
+ if priority_order is None:
+ priority_order = [
+ "settings:frequently_used",
+ "api_keys:active",
+ "metrics:summary",
+ "settings:all",
+ "metrics:detailed",
+ ]
+
+ for cache_type in priority_order:
+ try:
+ await self._warm_cache_type(user_id, cache_type)
+ # Yield control between batches
+ await asyncio.sleep(0.1)
+ except Exception as e:
+ logger.warning(f"Failed to warm {cache_type}: {e}")
+
+ async def _warm_cache_type(self, user_id: str, cache_type: str) -> None:
+ """Warm specific cache type."""
+ namespace, subtype = cache_type.split(":", 1)
+
+ if namespace == "settings" and subtype == "frequently_used":
+ # Warm only frequently accessed settings
+ frequent_keys = [
+ "theme",
+ "language",
+ "default_model",
+ "max_results",
+ ]
+ await self._warm_specific_settings(user_id, frequent_keys)
+ elif namespace == "api_keys" and subtype == "active":
+ # Warm only active API keys
+ await self._warm_active_api_keys(user_id)
+ # Add more cache type handlers as needed
+
+ async def _warm_specific_settings(
+ self, user_id: str, setting_keys: List[str]
+ ) -> None:
+ """Warm specific settings by key."""
+ loop = asyncio.get_event_loop()
+ await loop.run_in_executor(
+ self.executor, self._warm_settings_batch, user_id, setting_keys
+ )
+
+ def _warm_settings_batch(
+ self, user_id: str, setting_keys: List[str]
+ ) -> None:
+ """Warm a batch of settings."""
+ try:
+ with get_user_db_session(user_id) as session:
+ settings = (
+ session.query(UserSettings)
+ .filter(UserSettings.key.in_(setting_keys))
+ .all()
+ )
+
+ for setting in settings:
+ self.cache.set(
+ user_id,
+ "settings",
+ setting.key,
+ setting.value,
+ expiration_time=3600,
+ )
+ except Exception as e:
+ logger.error(f"Failed to warm settings batch: {e}")
+
+ async def _warm_active_api_keys(self, user_id: str) -> None:
+ """Warm only active API keys."""
+ loop = asyncio.get_event_loop()
+ await loop.run_in_executor(
+ self.executor, self._warm_active_keys_sync, user_id
+ )
+
+ def _warm_active_keys_sync(self, user_id: str) -> None:
+ """Synchronously warm active API keys."""
+ try:
+ with get_user_db_session(user_id) as session:
+ active_keys = (
+ session.query(APIKey).filter_by(is_active=True).all()
+ )
+
+ for key in active_keys:
+ self.cache.set(
+ user_id,
+ "api_keys",
+ key.provider,
+ {
+ "id": key.id,
+ "encrypted_key": key.encrypted_key,
+ "is_active": True,
+ },
+ expiration_time=3600,
+ )
+ except Exception as e:
+ logger.error(f"Failed to warm active API keys: {e}")
+
+
+# Singleton warmer instance
+_warmer_instance = None
+
+
+def get_cache_warmer() -> CacheWarmer:
+ """Get singleton cache warmer instance.
+
+ Returns:
+ CacheWarmer instance
+ """
+ global _warmer_instance
+ if _warmer_instance is None:
+ _warmer_instance = ProgressiveCacheWarmer()
+ return _warmer_instance
+
+
+# Decorators for cached queries
+@cache_user_data("settings", expiration_time=3600)
+def get_cached_setting(self, user_id: str, key: str) -> Optional[str]:
+ """Get cached user setting.
+
+ Args:
+ user_id: User identifier
+ key: Setting key
+
+ Returns:
+ Setting value or None
+ """
+ with get_user_db_session(user_id) as session:
+ setting = session.query(UserSettings).filter_by(key=key).first()
+ return setting.value if setting else None
+
+
+@cache_user_data("api_keys", expiration_time=3600)
+def get_cached_api_key(
+ self, user_id: str, provider: str
+) -> Optional[Dict[str, Any]]:
+ """Get cached API key for provider.
+
+ Args:
+ user_id: User identifier
+ provider: API provider name
+
+ Returns:
+ API key information or None
+ """
+ with get_user_db_session(user_id) as session:
+ api_key = (
+ session.query(APIKey)
+ .filter_by(provider=provider, is_active=True)
+ .first()
+ )
+
+ if api_key:
+ return {
+ "id": api_key.id,
+ "encrypted_key": api_key.encrypted_key,
+ "is_active": api_key.is_active,
+ }
+ return None
diff --git a/src/local_deep_research/storage/database.py b/src/local_deep_research/storage/database.py
index f431202690..1e552f456b 100644
--- a/src/local_deep_research/storage/database.py
+++ b/src/local_deep_research/storage/database.py
@@ -6,7 +6,7 @@ from sqlalchemy.orm import Session
from .base import ReportStorage
from ..database.models import ResearchHistory
-from ..cache.cached_services import CachedResearchService
+from ..memory_cache.cached_services import CachedResearchService
class DatabaseReportStorage(ReportStorage):
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index a26ed73e6e..2a79dc4dc3 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -121,7 +121,7 @@ def create_app():
apply_middleware(app)
# Initialize dogpile cache
- from ..cache.app_integration import setup_dogpile_cache
+ from ..memory_cache.app_integration import setup_dogpile_cache
setup_dogpile_cache(app)