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.

refactor: Further simplify cache system

LearningCircuit4ce97b213e61
diff --git a/src/local_deep_research/memory_cache/cached_services.py b/src/local_deep_research/memory_cache/cached_services.py
index 95343d3804..85e1f3bb69 100644
--- a/src/local_deep_research/memory_cache/cached_services.py
+++ b/src/local_deep_research/memory_cache/cached_services.py
@@ -1,268 +1,14 @@
"""Cached service implementations using dogpile.cache.
-This module provides cached versions of common services like
-SettingsManager and search cache functionality.
+This module provides cached versions of search and API cache functionality.
"""
-from typing import Any, Dict, List, Optional, Union
+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
-from ..database.models import UserSettings
-
-
-class SettingsManager:
- """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:
diff --git a/src/local_deep_research/memory_cache/config.py b/src/local_deep_research/memory_cache/config.py
index 31cf52a4d2..e1460e4395 100644
--- a/src/local_deep_research/memory_cache/config.py
+++ b/src/local_deep_research/memory_cache/config.py
@@ -1,6 +1,6 @@
"""Dogpile cache configuration for SQLCipher-encrypted databases.
-This module provides a two-tier caching system optimized for per-user
+This module provides a simple in-memory caching system optimized for per-user
encrypted databases with SQLAlchemy and SQLCipher.
"""
@@ -10,7 +10,6 @@ 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
@@ -24,9 +23,7 @@ PROJECT_STATIC_DIR = get_data_directory()
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
+DEFAULT_CACHE_TTL = 3600 # 1 hour
CACHE_KEY_SECRET = os.environ.get("CACHE_KEY_SECRET", None)
if not CACHE_KEY_SECRET:
# Generate a cache key secret similar to Flask SECRET_KEY
@@ -85,80 +82,6 @@ def get_namespaced_key(user_id: str, namespace: str, key: str) -> str:
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()
@@ -173,7 +96,7 @@ class SingleTierCache:
self,
cache_region: Optional[CacheRegion] = None,
enable_metrics: bool = True,
- default_ttl: int = DEFAULT_WARM_CACHE_TTL,
+ default_ttl: int = DEFAULT_CACHE_TTL,
):
"""Initialize single-tier cache.
@@ -365,59 +288,12 @@ class SingleTierCache:
TwoTierCache = SingleTierCache
-def get_thread_local_cache(redis_url: Optional[str] = None) -> SingleTierCache:
+def get_thread_local_cache() -> SingleTierCache:
"""Get or create thread-local cache instance.
- Args:
- redis_url: Optional Redis URL override
-
Returns:
Thread-local SingleTierCache instance
"""
if not hasattr(thread_local, "cache"):
thread_local.cache = SingleTierCache()
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/invalidation.py b/src/local_deep_research/memory_cache/invalidation.py
index a257e79b35..f55235010e 100644
--- a/src/local_deep_research/memory_cache/invalidation.py
+++ b/src/local_deep_research/memory_cache/invalidation.py
@@ -12,8 +12,6 @@ from .config import get_thread_local_cache
from ..database.models import (
UserSettings,
APIKey,
- TokenUsage,
- SearchCall,
Cache,
)
@@ -189,28 +187,7 @@ def setup_cache_invalidation(session_factory) -> None:
],
)
- # 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",
- }
- ],
- )
+ # Metrics are no longer cached, so no invalidation needed
# Register Cache model invalidation (for legacy cache)
_invalidator.register_model(
@@ -251,7 +228,7 @@ def invalidate_all_user_caches(user_id: str) -> None:
Args:
user_id: User identifier
"""
- namespaces = ["settings", "api_keys", "metrics", "legacy_cache"]
+ namespaces = ["settings", "api_keys", "legacy_cache"]
cache = get_thread_local_cache()
for namespace in namespaces:
diff --git a/src/local_deep_research/memory_cache/warmup.py b/src/local_deep_research/memory_cache/warmup.py
index 53b1a3bebe..9549a90da0 100644
--- a/src/local_deep_research/memory_cache/warmup.py
+++ b/src/local_deep_research/memory_cache/warmup.py
@@ -6,12 +6,12 @@ as they change frequently and are better served directly from the database.
"""
import asyncio
-from typing import Dict, List, Optional, Any
+from typing import Dict, List, Optional
from concurrent.futures import ThreadPoolExecutor
from loguru import logger
-from .config import get_thread_local_cache, cache_user_data
+from .config import get_thread_local_cache
from ..database.models import UserSettings, APIKey
from ..database.session_context import get_user_db_session
@@ -295,47 +295,5 @@ def get_cache_warmer() -> CacheWarmer:
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
+# Note: The cached query functions were removed as they were not used anywhere.
+# Caching is now handled directly in the SettingsManager and other services.