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: Remove unused memory_cache settings functionality (issue #595) (#625)

LearningCircuit889ee92a80f7
diff --git a/src/local_deep_research/memory_cache/app_integration.py b/src/local_deep_research/memory_cache/app_integration.py
index d5945da34f..24b10a4ad4 100644
--- a/src/local_deep_research/memory_cache/app_integration.py
+++ b/src/local_deep_research/memory_cache/app_integration.py
@@ -33,4 +33,4 @@ def setup_dogpile_cache(app: Flask) -> None:
if app.cache:
logger.info("Cache configuration:")
logger.info(" Simple in-memory cache (1 hour TTL)")
- logger.info(" Namespaces: settings, api_keys, search_results")
+ logger.info(" Used for search results and API response caching")
diff --git a/src/local_deep_research/memory_cache/flask_integration.py b/src/local_deep_research/memory_cache/flask_integration.py
index 856fab379c..23b20171fa 100644
--- a/src/local_deep_research/memory_cache/flask_integration.py
+++ b/src/local_deep_research/memory_cache/flask_integration.py
@@ -4,9 +4,7 @@ This module provides Flask-specific integration for the caching system,
including app initialization, request hooks, and login handlers.
"""
-import asyncio
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
@@ -14,7 +12,6 @@ from .config import (
SingleTierCache,
TwoTierCache, # Alias for compatibility
)
-from .warmup import get_cache_warmer
def init_cache(app: Flask) -> None:
@@ -43,38 +40,13 @@ def init_cache(app: Flask) -> None:
# Fall back to null cache
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)
+ # 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)
- # 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:
- logger.exception("Failed to warm startup caches")
-
def _register_request_handlers(app: Flask) -> None:
"""Register request-level cache handlers.
@@ -103,49 +75,6 @@ def _register_request_handlers(app: Flask) -> None:
)
-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",
- ], # Removed metrics
- )
- )
- except Exception:
- logger.exception("Cache warming error")
-
- thread = threading.Thread(target=warm_cache)
- thread.daemon = True
- thread.start()
- logger.debug(f"Initiated cache warming for user {user.id}")
- except Exception:
- logger.exception(f"Failed to warm cache for user {user.id}")
-
-
def get_cache() -> TwoTierCache:
"""Get cache instance from Flask context.
diff --git a/src/local_deep_research/memory_cache/invalidation.py b/src/local_deep_research/memory_cache/invalidation.py
deleted file mode 100644
index 63920de5f9..0000000000
--- a/src/local_deep_research/memory_cache/invalidation.py
+++ /dev/null
@@ -1,237 +0,0 @@
-"""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,
- 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:
- logger.exception("Error invalidating cache")
-
- 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}",
- }
- ],
- )
-
- # Metrics are no longer cached, so no invalidation needed
-
- # 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", "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
deleted file mode 100644
index 84ced77264..0000000000
--- a/src/local_deep_research/memory_cache/warmup.py
+++ /dev/null
@@ -1,299 +0,0 @@
-"""Cache warming strategies for settings and API keys.
-
-This module implements non-blocking cache warming for user login
-and application startup scenarios. Metrics are intentionally not cached
-as they change frequently and are better served directly from the database.
-"""
-
-import asyncio
-from typing import Dict, List, Optional
-from concurrent.futures import ThreadPoolExecutor
-
-from loguru import logger
-
-from .config import get_thread_local_cache
-from ..database.models import UserSettings, APIKey
-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:
- logger.exception("Failed to warm system configs")
- results["system_configs"] = False
-
- try:
- # Warm default settings
- await self._warm_default_settings()
- results["default_settings"] = True
- except Exception:
- logger.exception("Failed to warm default settings")
- 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"]
-
- # 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)
-
- except Exception:
- logger.exception(f"Cache warming failed for user: {user_id}")
-
- 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:
- logger.exception("Failed to warm settings for user")
-
- 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:
- logger.exception("Failed to warm API keys for user")
-
- 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",
- "settings:all",
- ]
-
- 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:
- logger.exception("Failed to warm settings batch")
-
- 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:
- logger.exception("Failed to warm active API keys")
-
-
-# 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
-
-
-# Note: The cached query functions were removed as they were not used anywhere.
-# Caching is now handled directly in the SettingsManager and other services.