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(db): release queuepool connections on session exit and cache collection engines (#6485)

S6a4ad175f843
diff --git a/changelog.d/6485.bugfix.md b/changelog.d/6485.bugfix.md
new file mode 100644
index 0000000000..8d732dddad
--- /dev/null
+++ b/changelog.d/6485.bugfix.md
@@ -0,0 +1 @@
+Fixed database connection pool exhaustion hangs during deep research runs by releasing checked-out connections on session scope exit, and cached collection search engines with stale-on-error fallback to prevent collection tools from being dropped mid-research.
diff --git a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
index 11e761457a..ebadc1cdf1 100644
--- a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
@@ -1205,6 +1205,16 @@ def _make_web_search_tool(
return _scrub_tool_error(f"Search error: {exc}")
finally:
safe_close(engine, "web search engine")
+ try:
+ from local_deep_research.database.thread_local_session import (
+ cleanup_current_thread,
+ thread_session_manager,
+ )
+
+ if not thread_session_manager.in_scope():
+ cleanup_current_thread()
+ except Exception: # allow: silent-exception
+ pass
web_search.description = description
return web_search
@@ -1253,6 +1263,16 @@ def _make_specialized_search_tool(
return _scrub_tool_error(f"Search error ({engine_name}): {exc}")
finally:
safe_close(engine, f"{engine_name} search engine")
+ try:
+ from local_deep_research.database.thread_local_session import (
+ cleanup_current_thread,
+ thread_session_manager,
+ )
+
+ if not thread_session_manager.in_scope():
+ cleanup_current_thread()
+ except Exception: # allow: silent-exception
+ pass
# Override name and description after decoration
specialized_search.name = f"search_{engine_name}"
diff --git a/src/local_deep_research/database/session_context.py b/src/local_deep_research/database/session_context.py
index 32a7ec1b24..071004a1b9 100644
--- a/src/local_deep_research/database/session_context.py
+++ b/src/local_deep_research/database/session_context.py
@@ -11,6 +11,7 @@ from loguru import logger
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
+from ..security.log_sanitizer import scrub_error
from ..utilities.thread_context import get_search_context
from .encrypted_db import db_manager
from .thread_local_session import thread_session_manager
@@ -201,6 +202,21 @@ def get_user_db_session(
raise
finally:
thread_session_manager.exit_scope()
+ if not thread_session_manager.in_scope():
+ try:
+ # If a transaction was left open (e.g. from read queries autobeginning
+ # a transaction and checking out a connection from QueuePool, or uncommitted writes),
+ # roll back on outermost exit to return the checked-out connection to QueuePool
+ # and release SQLite SHARED read locks.
+ if (
+ hasattr(session, "in_transaction")
+ and session.in_transaction()
+ ):
+ safe_rollback(session, "get_user_db_session exit")
+ except Exception as exc:
+ logger.debug(
+ f"safe_rollback on get_user_db_session exit raised: {scrub_error(exc)}"
+ )
def with_user_database(func: Callable) -> Callable:
diff --git a/src/local_deep_research/research_library/deletion/services/collection_deletion.py b/src/local_deep_research/research_library/deletion/services/collection_deletion.py
index 63cd3f1afa..4fd3e5bc34 100644
--- a/src/local_deep_research/research_library/deletion/services/collection_deletion.py
+++ b/src/local_deep_research/research_library/deletion/services/collection_deletion.py
@@ -229,6 +229,12 @@ class CollectionDeletionService:
session.commit()
+ from ....web_search_engines.search_engines_config import (
+ invalidate_collection_engines_cache,
+ )
+
+ invalidate_collection_engines_cache(self.username)
+
result["deleted"] = True
logger.info(
f"Deleted collection {collection_id[:8]}... "
diff --git a/src/local_deep_research/web/routers/library_delete.py b/src/local_deep_research/web/routers/library_delete.py
index 87492066ac..de105650a5 100644
--- a/src/local_deep_research/web/routers/library_delete.py
+++ b/src/local_deep_research/web/routers/library_delete.py
@@ -286,6 +286,11 @@ def delete_collection(
)
if result.get("deleted"):
+ from ...web_search_engines.search_engines_config import (
+ invalidate_collection_engines_cache,
+ )
+
+ invalidate_collection_engines_cache(username)
return {"success": True, **result}
error = result.get("error", "Unknown error")
# 404 not found, 409 for a protected/system collection the service
diff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.py
index 8860de883c..e1a2b7a6c7 100644
--- a/src/local_deep_research/web/routers/rag.py
+++ b/src/local_deep_research/web/routers/rag.py
@@ -1980,13 +1980,21 @@ def _create_collection_sync(data, username):
db_session.add(collection)
db_session.commit()
+ from ...web_search_engines.search_engines_config import (
+ invalidate_collection_engines_cache,
+ )
+
+ invalidate_collection_engines_cache(username)
+
return {
"success": True,
"collection": {
"id": collection.id,
"name": collection.name,
"description": collection.description,
- "created_at": collection.created_at.isoformat(),
+ "created_at": collection.created_at.isoformat()
+ if collection.created_at
+ else None,
"collection_type": collection.collection_type,
"is_public": bool(collection.is_public),
"agent_enabled": _agent_enabled_default_on(collection),
@@ -2139,6 +2147,12 @@ def _update_collection_sync(data, collection_id, username):
db_session.commit()
+ from ...web_search_engines.search_engines_config import (
+ invalidate_collection_engines_cache,
+ )
+
+ invalidate_collection_engines_cache(username)
+
return {
"success": True,
"collection": {
diff --git a/src/local_deep_research/web_search_engines/search_engines_config.py b/src/local_deep_research/web_search_engines/search_engines_config.py
index fa583a0ac1..0eace085d7 100644
--- a/src/local_deep_research/web_search_engines/search_engines_config.py
+++ b/src/local_deep_research/web_search_engines/search_engines_config.py
@@ -3,7 +3,11 @@ Configuration file for search engines.
Loads search engine definitions from the user's configuration.
"""
+import copy
+import threading
+import time
from typing import Any, Dict, Optional
+from cachetools import LRUCache
from sqlalchemy.orm import Session
from ..security.secure_logging import logger
@@ -13,6 +17,31 @@ from ..security.log_sanitizer import scrub_error
from ..utilities.db_utils import get_settings_manager
from .search_engine_base import _is_api_key_placeholder
+_COLLECTION_CACHE_LOCK = threading.Lock()
+_COLLECTION_CACHE_MAXSIZE = 50
+_COLLECTION_CACHE_TTL = 30.0 # seconds
+_COLLECTION_CACHE_MAX_STALE = 300.0 # seconds (5 minutes stale age cap)
+# username -> (timestamp, {engine_id: engine_dict})
+_COLLECTION_ENGINES_CACHE: LRUCache[str, tuple[float, Dict[str, Any]]] = (
+ LRUCache(maxsize=_COLLECTION_CACHE_MAXSIZE)
+)
+
+
+def invalidate_collection_engines_cache(
+ username: Optional[str] = None,
+) -> None:
+ """Invalidate cached collection search engine configurations.
+
+ Args:
+ username: If provided, invalidate cache for this username only.
+ If None, clear the entire collection engines cache.
+ """
+ with _COLLECTION_CACHE_LOCK:
+ if username:
+ _COLLECTION_ENGINES_CACHE.pop(username, None)
+ else:
+ _COLLECTION_ENGINES_CACHE.clear()
+
def _get_setting(
key: str,
@@ -220,70 +249,134 @@ def search_config(
)
if collection_username:
- with get_user_db_session(collection_username) as session:
- collections = session.query(Collection).all()
-
- for collection in collections:
- engine_id = f"collection_{collection.id}"
- # Add suffix to distinguish from the all-collections search
- display_name = f"{collection.name} (Collection)"
- # Egress classification follows the per-collection
- # public/private flag (default private). A "public"
- # collection counts as a public engine (allowed under
- # PUBLIC_ONLY); a private one is local-only. NULL
- # (pre-migration rows) reads as private — the safe
- # default.
- collection_is_public = bool(
- getattr(collection, "is_public", False)
+ now = time.monotonic()
+ cached_engines = None
+ with _COLLECTION_CACHE_LOCK:
+ cache_entry = _COLLECTION_ENGINES_CACHE.get(
+ collection_username
+ )
+ if cache_entry and (
+ now - cache_entry[0] < _COLLECTION_CACHE_TTL
+ ):
+ cached_engines = cache_entry[1]
+
+ if cached_engines is not None:
+ search_engines.update(copy.deepcopy(cached_engines))
+ logger.debug(
+ f"Reused {len(cached_engines)} cached document collection engines for {collection_username}"
+ )
+ else:
+ try:
+ with get_user_db_session(
+ collection_username
+ ) as session:
+ collections = session.query(Collection).all()
+
+ user_collection_engines = {}
+ for collection in collections:
+ engine_id = f"collection_{collection.id}"
+ # Add suffix to distinguish from the all-collections search
+ display_name = f"{collection.name} (Collection)"
+ # Egress classification follows the per-collection
+ # public/private flag (default private). A "public"
+ # collection counts as a public engine (allowed under
+ # PUBLIC_ONLY); a private one is local-only. NULL
+ # (pre-migration rows) reads as private — the safe
+ # default.
+ collection_is_public = bool(
+ getattr(collection, "is_public", False)
+ )
+ # Usability flag (NOT egress): whether the LangGraph
+ # research agent offers this collection as a tool. NULL
+ # (pre-migration rows) reads as available (True). Uses
+ # the same `is not False` idiom as the rag_routes
+ # serializers so all call sites share one NULL→available
+ # default and can't drift.
+ collection_agent_enabled = (
+ getattr(collection, "agent_enabled", True)
+ is not False
+ )
+ user_collection_engines[engine_id] = {
+ "module_path": ".engines.search_engine_collection",
+ "class_name": "CollectionSearchEngine",
+ "requires_llm": True,
+ "is_local": True,
+ "is_public": collection_is_public,
+ "agent_enabled": collection_agent_enabled,
+ "display_name": display_name,
+ "default_params": {
+ "collection_id": collection.id,
+ "collection_name": collection.name,
+ },
+ "description": (
+ collection.description
+ if collection.description
+ else f"Search documents in {collection.name} collection only"
+ ),
+ "strengths": [
+ f"Searches only documents in {collection.name}",
+ "Focused semantic search within specific topic area",
+ "Returns documents from a curated collection",
+ ],
+ "weaknesses": [
+ "Limited to documents in this collection",
+ "Smaller result pool than full library search",
+ ],
+ "reliability": "High - searches a specific collection",
+ }
+
+ with _COLLECTION_CACHE_LOCK:
+ _COLLECTION_ENGINES_CACHE[
+ collection_username
+ ] = (
+ now,
+ copy.deepcopy(user_collection_engines),
+ )
+
+ search_engines.update(
+ copy.deepcopy(user_collection_engines)
+ )
+ logger.info(
+ f"Registered {len(user_collection_engines)} document collections as search engines"
+ )
+ except Exception as exc:
+ safe_msg = scrub_error(exc)
+ logger.warning(
+ f"Could not register document collections for {collection_username}: {safe_msg}"
)
- # Usability flag (NOT egress): whether the LangGraph
- # research agent offers this collection as a tool. NULL
- # (pre-migration rows) reads as available (True). Uses
- # the same `is not False` idiom as the rag_routes
- # serializers so all call sites share one NULL→available
- # default and can't drift.
- collection_agent_enabled = (
- getattr(collection, "agent_enabled", True)
- is not False
+ logger.debug(
+ f"Traceback for collection registration failure for {collection_username}",
+ exc_info=True,
)
- search_engines[engine_id] = {
- "module_path": ".engines.search_engine_collection",
- "class_name": "CollectionSearchEngine",
- "requires_llm": True,
- "is_local": True,
- "is_public": collection_is_public,
- "agent_enabled": collection_agent_enabled,
- "display_name": display_name,
- "default_params": {
- "collection_id": collection.id,
- "collection_name": collection.name,
- },
- "description": (
- collection.description
- if collection.description
- else f"Search documents in {collection.name} collection only"
- ),
- "strengths": [
- f"Searches only documents in {collection.name}",
- "Focused semantic search within specific topic area",
- "Returns documents from a curated collection",
- ],
- "weaknesses": [
- "Limited to documents in this collection",
- "Smaller result pool than full library search",
- ],
- "reliability": "High - searches a specific collection",
- }
-
- logger.info(
- f"Registered {len(collections)} document collections as search engines"
- )
+ with _COLLECTION_CACHE_LOCK:
+ stale_entry = _COLLECTION_ENGINES_CACHE.get(
+ collection_username
+ )
+ if stale_entry and (
+ now - stale_entry[0] <= _COLLECTION_CACHE_MAX_STALE
+ ):
+ search_engines.update(copy.deepcopy(stale_entry[1]))
+ logger.warning(
+ f"Using {len(stale_entry[1])} stale cached collection engines for {collection_username} after DB error"
+ )
+ elif stale_entry:
+ logger.warning(
+ f"Stale cached collection engines for {collection_username} expired "
+ f"(age {now - stale_entry[0]:.1f}s > {_COLLECTION_CACHE_MAX_STALE}s), skipping"
+ )
else:
logger.debug(
"No username available for collection registration"
)
- except Exception:
- logger.warning("Could not register document collections")
+ except Exception as exc:
+ safe_msg = scrub_error(exc)
+ logger.warning(
+ f"Could not register document collections: {safe_msg}"
+ )
+ logger.debug(
+ "Traceback for document collections registration failure",
+ exc_info=True,
+ )
return search_engines
diff --git a/tests/database/test_session_context.py b/tests/database/test_session_context.py
index 272fba35a7..01a9fd8ee9 100644
--- a/tests/database/test_session_context.py
+++ b/tests/database/test_session_context.py
@@ -544,3 +544,254 @@ class TestSafeRollback:
assert thread_session_manager._local.session is cached
finally:
thread_session_manager._local.session = None
+
+
+class TestSessionContextRollbackOnExit:
+ """Tests for automatic safe_rollback on outermost scope exit to prevent
+ QueuePool connection leaks.
+ """
+
+ def test_outermost_scope_rolls_back_if_in_transaction(self):
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+ from local_deep_research.database.thread_local_session import (
+ thread_session_manager,
+ )
+
+ mock_session = Mock()
+ mock_session.in_transaction.return_value = True
+
+ with patch(
+ "local_deep_research.database.session_context.db_manager"
+ ) as mock_db:
+ mock_db.has_encryption = False
+ with patch(
+ "local_deep_research.database.thread_local_session.get_metrics_session",
+ return_value=mock_session,
+ ):
+ with patch(
+ "local_deep_research.database.session_context.safe_rollback"
+ ) as mock_rollback:
+ with get_user_db_session(username="testuser"):
+ assert thread_session_manager.in_scope()
+ assert not thread_session_manager.in_scope()
+ mock_rollback.assert_called_once_with(
+ mock_session, "get_user_db_session exit"
+ )
+
+ def test_outermost_scope_skips_rollback_if_not_in_transaction(self):
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+
+ mock_session = Mock()
+ mock_session.in_transaction.return_value = False
+
+ with patch(
+ "local_deep_research.database.session_context.db_manager"
+ ) as mock_db:
+ mock_db.has_encryption = False
+ with patch(
+ "local_deep_research.database.thread_local_session.get_metrics_session",
+ return_value=mock_session,
+ ):
+ with patch(
+ "local_deep_research.database.session_context.safe_rollback"
+ ) as mock_rollback:
+ with get_user_db_session(username="testuser"):
+ pass
+ mock_rollback.assert_not_called()
+
+ def test_nested_scope_does_not_rollback_on_inner_exit(self):
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+ from local_deep_research.database.thread_local_session import (
+ thread_session_manager,
+ )
+
+ mock_session = Mock()
+ mock_session.in_transaction.return_value = True
+
+ with patch(
+ "local_deep_research.database.session_context.db_manager"
+ ) as mock_db:
+ mock_db.has_encryption = False
+ with patch(
+ "local_deep_research.database.thread_local_session.get_metrics_session",
+ return_value=mock_session,
+ ):
+ with patch(
+ "local_deep_research.database.session_context.safe_rollback"
+ ) as mock_rollback:
+ with get_user_db_session(username="testuser"):
+ assert (
+ getattr(
+ thread_session_manager._local, "scope_depth", 0
+ )
+ == 1
+ )
+ with get_user_db_session(username="testuser"):
+ assert (
+ getattr(
+ thread_session_manager._local,
+ "scope_depth",
+ 0,
+ )
+ == 2
+ )
+ # Inner exit: should NOT have rolled back yet
+ mock_rollback.assert_not_called()
+ assert thread_session_manager.in_scope()
+ # Outer exit: should roll back
+ mock_rollback.assert_called_once_with(
+ mock_session, "get_user_db_session exit"
+ )
+
+ def test_outermost_scope_swallows_in_transaction_missing_attribute(self):
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+
+ session_without_attr = object() # No in_transaction attribute
+
+ with patch(
+ "local_deep_research.database.session_context.db_manager"
+ ) as mock_db:
+ mock_db.has_encryption = False
+ with patch(
+ "local_deep_research.database.thread_local_session.get_metrics_session",
+ return_value=session_without_attr,
+ ):
+ with patch(
+ "local_deep_research.database.session_context.safe_rollback"
+ ) as mock_rollback:
+ with get_user_db_session(username="testuser"):
+ pass
+ mock_rollback.assert_not_called()
+
+ def test_outermost_scope_swallows_in_transaction_exception(self):
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+
+ mock_session = Mock()
+ mock_session.in_transaction.side_effect = RuntimeError("Broken session")
+
+ with patch(
+ "local_deep_research.database.session_context.db_manager"
+ ) as mock_db:
+ mock_db.has_encryption = False
+ with patch(
+ "local_deep_research.database.thread_local_session.get_metrics_session",
+ return_value=mock_session,
+ ):
+ # Must exit cleanly without re-raising RuntimeError
+ with get_user_db_session(username="testuser"):
+ pass
+
+ def test_real_engine_queuepool_connection_released_on_exit(self, tmp_path):
+ """End-to-end integration test with real SQLAlchemy engine & QueuePool.
+ Verifies that after querying SQLite in get_user_db_session, exiting the
+ context returns the checked-out connection to QueuePool (checkedout() == 0).
+ """
+ from sqlalchemy import create_engine, text
+ from sqlalchemy.orm import sessionmaker
+ from sqlalchemy.pool import QueuePool
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+ from local_deep_research.database.thread_local_session import (
+ cleanup_current_thread,
+ )
+
+ db_file = tmp_path / "test_pool.db"
+ engine = create_engine(
+ f"sqlite:///{db_file}",
+ poolclass=QueuePool,
+ pool_size=5,
+ max_overflow=5,
+ pool_timeout=5.0,
+ )
+ SessionLocal = sessionmaker(bind=engine)
+ real_session = SessionLocal()
+
+ try:
+ with patch(
+ "local_deep_research.database.session_context.db_manager"
+ ) as mock_db:
+ mock_db.has_encryption = False
+ with patch(
+ "local_deep_research.database.thread_local_session.get_metrics_session",
+ return_value=real_session,
+ ):
+ with get_user_db_session(username="real_user") as s:
+ s.execute(text("SELECT 1"))
+ # Connection is checked out from QueuePool
+ assert engine.pool.checkedout() == 1
+ assert s.in_transaction()
+
+ # On exit from get_user_db_session, connection must be returned
+ assert engine.pool.checkedout() == 0
+ assert not real_session.in_transaction()
+ finally:
+ real_session.close()
+ engine.dispose()
+ cleanup_current_thread()
+
+ def test_multi_thread_pool_exhaustion_prevented(self, tmp_path):
+ """Multiple threads running queries concurrently through get_user_db_session
+ do not exhaust a small QueuePool because connections are returned on exit.
+ """
+ import concurrent.futures
+ from sqlalchemy import create_engine, text
+ from sqlalchemy.orm import sessionmaker
+ from sqlalchemy.pool import QueuePool
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+ from local_deep_research.database.thread_local_session import (
+ cleanup_current_thread,
+ )
+
+ db_file = tmp_path / "test_threaded_pool.db"
+ engine = create_engine(
+ f"sqlite:///{db_file}",
+ poolclass=QueuePool,
+ pool_size=3,
+ max_overflow=2, # Max total 5 connections
+ pool_timeout=3.0,
+ )
+ SessionLocal = sessionmaker(bind=engine)
+
+ def worker_task(i):
+ try:
+ with get_user_db_session(username=f"user_{i}") as sess:
+ res = sess.execute(text("SELECT 1")).scalar()
+ assert res == 1
+ return True
+ finally:
+ cleanup_current_thread()
+
+ try:
+ with patch(
+ "local_deep_research.database.session_context.db_manager"
+ ) as mock_db:
+ mock_db.has_encryption = False
+ with patch(
+ "local_deep_research.database.thread_local_session.get_metrics_session",
+ side_effect=lambda *a, **kw: SessionLocal(),
+ ):
+ # Run 20 worker tasks across 10 threads on a pool of max 5 connections
+ with concurrent.futures.ThreadPoolExecutor(
+ max_workers=10
+ ) as executor:
+ futures = [
+ executor.submit(worker_task, i) for i in range(20)
+ ]
+ results = [f.result() for f in futures]
+ assert all(results)
+ assert engine.pool.checkedout() == 0
+ finally:
+ engine.dispose()
diff --git a/tests/database/test_session_context_rollback.py b/tests/database/test_session_context_rollback.py
index ffaa643850..e66b61e134 100644
--- a/tests/database/test_session_context_rollback.py
+++ b/tests/database/test_session_context_rollback.py
@@ -88,9 +88,9 @@ class TestGetUserDbSessionRollback:
real_session.close()
engine.dispose()
- def test_clean_exit_does_not_roll_back(self):
- """Normal (non-exception) exit must NOT roll back — intentional pending
- state is the caller's to commit; we only recover on error.
+ def test_clean_exit_rolls_back_open_transaction(self):
+ """Clean exit on the outermost scope rolls back any open transaction
+ to return checked-out connections to QueuePool and release read locks.
"""
from local_deep_research.database.session_context import (
get_user_db_session,
@@ -103,6 +103,22 @@ class TestGetUserDbSessionRollback:
with get_user_db_session(username="u", password="p"):
pass
+ mock_session.rollback.assert_called_once()
+
+ def test_clean_exit_without_transaction_does_not_roll_back(self):
+ """Clean exit does not roll back if no transaction is open."""
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+
+ with patch(f"{SC}.db_manager") as mock_db:
+ mock_db.has_encryption = False
+ mock_session = Mock()
+ mock_session.in_transaction.return_value = False
+ with patch(TLS, return_value=mock_session):
+ with get_user_db_session(username="u", password="p"):
+ pass
+
mock_session.rollback.assert_not_called()
def test_secondary_rollback_failure_does_not_mask_original_error(self):
@@ -122,4 +138,4 @@ class TestGetUserDbSessionRollback:
with get_user_db_session(username="u", password="p"):
raise ValueError("original")
- mock_session.rollback.assert_called_once()
+ assert mock_session.rollback.call_count == 2
diff --git a/tests/research_library/deletion/services/test_collection_deletion.py b/tests/research_library/deletion/services/test_collection_deletion.py
index 3a0a910204..6f729e09f8 100644
--- a/tests/research_library/deletion/services/test_collection_deletion.py
+++ b/tests/research_library/deletion/services/test_collection_deletion.py
@@ -95,6 +95,44 @@ class TestCollectionDeletionServiceDeleteCollection:
assert result["collection_id"] == "col-123"
assert result["chunks_deleted"] == 10
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config.invalidate_collection_engines_cache"
+ )
+ def test_deletes_collection_invalidates_cache(self, mock_invalidate):
+ """Should invalidate collection engines cache when collection is deleted."""
+ service = CollectionDeletionService(username="testuser")
+
+ with patch(
+ "local_deep_research.research_library.deletion.services.collection_deletion.get_user_db_session"
+ ) as mock_get_session:
+ mock_session = MagicMock()
+ mock_cm = MagicMock()
+ mock_cm.__enter__ = Mock(return_value=mock_session)
+ mock_cm.__exit__ = Mock(return_value=None)
+ mock_get_session.return_value = mock_cm
+
+ mock_collection = MagicMock()
+ mock_collection.id = "col-123"
+ mock_collection.name = "Test Collection"
+ mock_session.get.return_value = mock_collection
+
+ mock_session.query.return_value.filter_by.return_value.all.return_value = []
+ mock_session.query.return_value.filter_by.return_value.delete.return_value = 0
+
+ with patch(
+ "local_deep_research.research_library.deletion.services.collection_deletion.CascadeHelper"
+ ) as mock_helper:
+ mock_helper.delete_collection_chunks.return_value = 0
+ mock_helper.delete_rag_indices_for_collection.return_value = {
+ "deleted_indices": 0,
+ "index_paths": [],
+ }
+
+ result = service.delete_collection("col-123")
+
+ assert result["deleted"] is True
+ mock_invalidate.assert_called_once_with("testuser")
+
def test_deletes_orphaned_documents_by_default(self):
"""Should delete orphaned documents when enabled."""
service = CollectionDeletionService(username="testuser")
diff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.py
index b42ff2de9e..2bcd54552b 100644
--- a/tests/strategies/test_langgraph_agent_strategy.py
+++ b/tests/strategies/test_langgraph_agent_strategy.py
@@ -6654,3 +6654,188 @@ class TestSourcesBlockStaysCoherent:
assert strategy._heartbeat_message(2).startswith(
"Step 2 · 2 sources gathered · "
)
+
+
+# ---------------------------------------------------------------------------
+# Search Tool Thread Cleanup on Exit
+# ---------------------------------------------------------------------------
+
+
+class TestSearchToolThreadCleanup:
+ """Ensure search tools invoke cleanup_current_thread in their finally block."""
+
+ @patch(
+ "local_deep_research.database.thread_local_session.cleanup_current_thread"
+ )
+ @patch(
+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine"
+ )
+ def test_web_search_tool_cleans_up_on_success(
+ self, mock_factory, mock_cleanup
+ ):
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ _make_web_search_tool,
+ SearchResultsCollector,
+ )
+
+ engine_mock = MagicMock()
+ engine_mock.run.return_value = [
+ {"title": "t", "link": "http://x", "snippet": "s"}
+ ]
+ mock_factory.return_value = engine_mock
+
+ collector = SearchResultsCollector([])
+ tool = _make_web_search_tool("searxng", MagicMock(), {}, collector)
+ result = tool.invoke({"query": "test query"})
+
+ assert "t" in result
+ mock_cleanup.assert_called_once()
+
+ @patch(
+ "local_deep_research.database.thread_local_session.cleanup_current_thread"
+ )
+ @patch(
+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine"
+ )
+ def test_web_search_tool_cleans_up_on_error(
+ self, mock_factory, mock_cleanup
+ ):
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ _make_web_search_tool,
+ SearchResultsCollector,
+ )
+
+ engine_mock = MagicMock()
+ engine_mock.run.side_effect = RuntimeError("Engine exploded")
+ mock_factory.return_value = engine_mock
+
+ collector = SearchResultsCollector([])
+ tool = _make_web_search_tool("searxng", MagicMock(), {}, collector)
+ result = tool.invoke({"query": "test query"})
+
+ assert "Search error" in result
+ mock_cleanup.assert_called_once()
+
+ @patch(
+ "local_deep_research.database.thread_local_session.cleanup_current_thread"
+ )
+ @patch(
+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine"
+ )
+ def test_specialized_search_tool_cleans_up_on_success(
+ self, mock_factory, mock_cleanup
+ ):
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ _make_specialized_search_tool,
+ SearchResultsCollector,
+ )
+
+ engine_mock = MagicMock()
+ engine_mock.run.return_value = [
+ {"title": "t", "link": "http://x", "snippet": "s"}
+ ]
+ mock_factory.return_value = engine_mock
+
+ collector = SearchResultsCollector([])
+ tool = _make_specialized_search_tool(
+ "collection_1", "Search col 1", MagicMock(), {}, collector
+ )
+ result = tool.invoke({"query": "test query"})
+
+ assert "t" in result
+ mock_cleanup.assert_called_once()
+
+ @patch(
+ "local_deep_research.database.thread_local_session.cleanup_current_thread"
+ )
+ @patch(
+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine"
+ )
+ def test_specialized_search_tool_cleans_up_on_error(
+ self, mock_factory, mock_cleanup
+ ):
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ _make_specialized_search_tool,
+ SearchResultsCollector,
+ )
+
+ engine_mock = MagicMock()
+ engine_mock.run.side_effect = RuntimeError("Engine exploded")
+ mock_factory.return_value = engine_mock
+
+ collector = SearchResultsCollector([])
+ tool = _make_specialized_search_tool(
+ "collection_1", "Search col 1", MagicMock(), {}, collector
+ )
+ result = tool.invoke({"query": "test query"})
+
+ assert "Search error" in result
+ mock_cleanup.assert_called_once()
+
+ @patch(
+ "local_deep_research.database.thread_local_session.thread_session_manager.in_scope",
+ return_value=True,
+ )
+ @patch(
+ "local_deep_research.database.thread_local_session.cleanup_current_thread"
+ )
+ @patch(
+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine"
+ )
+ def test_web_search_tool_skips_cleanup_when_in_enclosing_session_scope(
+ self, mock_factory, mock_cleanup, mock_in_scope
+ ):
+ """If tool is invoked inside an enclosing get_user_db_session block on the same
+ thread, thread cleanup must NOT run so enclosing uncommitted work is preserved."""
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ _make_web_search_tool,
+ SearchResultsCollector,
+ )
+
+ engine_mock = MagicMock()
+ engine_mock.run.return_value = [
+ {"title": "t", "link": "http://x", "snippet": "s"}
+ ]
+ mock_factory.return_value = engine_mock
+
+ collector = SearchResultsCollector([])
+ tool = _make_web_search_tool("searxng", MagicMock(), {}, collector)
+ result = tool.invoke({"query": "test query"})
+
+ assert "t" in result
+ mock_cleanup.assert_not_called()
+
+ @patch(
+ "local_deep_research.database.thread_local_session.thread_session_manager.in_scope",
+ return_value=True,
+ )
+ @patch(
+ "local_deep_research.database.thread_local_session.cleanup_current_thread"
+ )
+ @patch(
+ "local_deep_research.web_search_engines.search_engine_factory.create_search_engine"
+ )
+ def test_specialized_search_tool_skips_cleanup_when_in_enclosing_session_scope(
+ self, mock_factory, mock_cleanup, mock_in_scope
+ ):
+ """If specialized search tool is invoked inside an enclosing session block,
+ thread cleanup must NOT run so enclosing uncommitted work is preserved."""
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ _make_specialized_search_tool,
+ SearchResultsCollector,
+ )
+
+ engine_mock = MagicMock()
+ engine_mock.run.return_value = [
+ {"title": "t", "link": "http://x", "snippet": "s"}
+ ]
+ mock_factory.return_value = engine_mock
+
+ collector = SearchResultsCollector([])
+ tool = _make_specialized_search_tool(
+ "collection_1", "Search col 1", MagicMock(), {}, collector
+ )
+ result = tool.invoke({"query": "test query"})
+
+ assert "t" in result
+ mock_cleanup.assert_not_called()
diff --git a/tests/web/routers/test_settings_routes_corrupted_coverage_port.py b/tests/web/routers/test_settings_routes_corrupted_coverage_port.py
index c731755715..680cbce105 100644
--- a/tests/web/routers/test_settings_routes_corrupted_coverage_port.py
+++ b/tests/web/routers/test_settings_routes_corrupted_coverage_port.py
@@ -479,8 +479,8 @@ class TestFixCorruptedSettingsDuplicatesAndDefaults:
(``web/routes/settings_routes.py:2733``). The branch delegates it to
``get_user_db_session`` (``database/session_context.py:191-201``), so
this test runs the REAL context manager with only
- ``get_metrics_session`` stubbed — asserting production rollback, not a
- rollback re-implemented in this file.
+ ``get_metrics_session`` stubbed — asserting production rollback on
+ both exception handling and scope exit.
"""
from local_deep_research.web.routers.settings import (
fix_corrupted_settings,
@@ -504,7 +504,7 @@ class TestFixCorruptedSettingsDuplicatesAndDefaults:
resp = handler(Mock(), username="testuser")
assert resp.status_code == 500
- mock_session.rollback.assert_called_once()
+ assert mock_session.rollback.call_count == 2
class TestSaveSettingsExceptionInLoop:
diff --git a/tests/web_search_engines/test_search_engines_config.py b/tests/web_search_engines/test_search_engines_config.py
index c8153428bd..c88a548a30 100644
--- a/tests/web_search_engines/test_search_engines_config.py
+++ b/tests/web_search_engines/test_search_engines_config.py
@@ -9,6 +9,7 @@ Tests the configuration loading and processing for search engines:
- local_search_engines() - local engine listing
"""
+import pytest
from unittest.mock import MagicMock, patch
from local_deep_research.web_search_engines.search_engines_config import (
@@ -720,3 +721,520 @@ class TestGetAvailableEngines:
)
assert "searxng" in result
assert "wikipedia" not in result
+
+
+class TestCollectionEnginesCachingAndFallback:
+ """Tests for collection search engines caching, invalidation, and stale fallback."""
+
+ def setup_method(self):
+ from local_deep_research.web_search_engines.search_engines_config import (
+ invalidate_collection_engines_cache,
+ )
+
+ invalidate_collection_engines_cache()
+
+ def teardown_method(self):
+ from local_deep_research.web_search_engines.search_engines_config import (
+ invalidate_collection_engines_cache,
+ )
+
+ invalidate_collection_engines_cache()
+
+ @patch("local_deep_research.database.session_context.get_user_db_session")
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_collection_engines_cached_across_calls(
+ self, mock_get_setting, mock_get_session
+ ):
+ from local_deep_research.web_search_engines.search_engines_config import (
+ search_config,
+ )
+
+ mock_get_setting.side_effect = lambda key, default=None, **kw: (
+ True
+ if "library.enabled" in key
+ else ({} if "search.engine.web" in key else default)
+ )
+
+ mock_collection = MagicMock()
+ mock_collection.id = "col1"
+ mock_collection.name = "History Collection"
+ mock_collection.description = "History papers"
+ mock_collection.is_public = True
+ mock_collection.agent_enabled = True
+
+ mock_session = MagicMock()
+ mock_session.query.return_value.all.return_value = [mock_collection]
+ mock_get_session.return_value.__enter__.return_value = mock_session
+
+ # Call 1: should query DB
+ cfg1 = search_config(username="test_researcher")
+ assert "collection_col1" in cfg1
+ assert (
+ cfg1["collection_col1"]["display_name"]
+ == "History Collection (Collection)"
+ )
+ assert mock_get_session.call_count == 1
+
+ # Call 2: within TTL, should reuse cache without querying DB
+ cfg2 = search_config(username="test_researcher")
+ assert "collection_col1" in cfg2
+ assert mock_get_session.call_count == 1 # Still 1!
+
+ @patch("local_deep_research.database.session_context.get_user_db_session")
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_invalidate_cache_single_user(
+ self, mock_get_setting, mock_get_session
+ ):
+ from local_deep_research.web_search_engines.search_engines_config import (
+ search_config,
+ invalidate_collection_engines_cache,
+ )
+
+ mock_get_setting.side_effect = lambda key, default=None, **kw: (
+ True
+ if "library.enabled" in key
+ else ({} if "search.engine.web" in key else default)
+ )
+
+ mock_session = MagicMock()
+ mock_session.query.return_value.all.return_value = []
+ mock_get_session.return_value.__enter__.return_value = mock_session
+
+ # Populate user1 and user2
+ search_config(username="user1")
+ search_config(username="user2")
+ assert mock_get_session.call_count == 2
+
+ # Invalidate user1 only
+ invalidate_collection_engines_cache(username="user1")
+
+ # user2 should still be cached
+ search_config(username="user2")
+ assert mock_get_session.call_count == 2
+
+ # user1 should re-query
+ search_config(username="user1")
+ assert mock_get_session.call_count == 3
+
+ @patch("local_deep_research.database.session_context.get_user_db_session")
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_invalidate_cache_all_users(
+ self, mock_get_setting, mock_get_session
+ ):
+ from local_deep_research.web_search_engines.search_engines_config import (
+ search_config,
+ invalidate_collection_engines_cache,
+ )
+
+ mock_get_setting.side_effect = lambda key, default=None, **kw: (
+ True
+ if "library.enabled" in key
+ else ({} if "search.engine.web" in key else default)
+ )
+
+ mock_session = MagicMock()
+ mock_session.query.return_value.all.return_value = []
+ mock_get_session.return_value.__enter__.return_value = mock_session
+
+ search_config(username="user1")
+ search_config(username="user2")
+ assert mock_get_session.call_count == 2
+
+ # Clear entire cache
+ invalidate_collection_engines_cache()
+
+ search_config(username="user1")
+ assert mock_get_session.call_count == 3
+ search_config(username="user2")
+ assert mock_get_session.call_count == 4
+
+ @patch("local_deep_research.database.session_context.get_user_db_session")
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_db_error_falls_back_to_stale_cache(
+ self, mock_get_setting, mock_get_session
+ ):
+ import time
+ from local_deep_research.web_search_engines.search_engines_config import (
+ search_config,
+ _COLLECTION_ENGINES_CACHE,
+ _COLLECTION_CACHE_LOCK,
+ )
+
+ mock_get_setting.side_effect = lambda key, default=None, **kw: (
+ True
+ if "library.enabled" in key
+ else ({} if "search.engine.web" in key else default)
+ )
+
+ mock_collection = MagicMock()
+ mock_collection.id = "col_stale"
+ mock_collection.name = "Stale Collection"
+ mock_collection.description = "Stale papers"
+ mock_collection.is_public = False
+ mock_collection.agent_enabled = True
+
+ mock_session = MagicMock()
+ mock_session.query.return_value.all.return_value = [mock_collection]
+ mock_get_session.return_value.__enter__.return_value = mock_session
+
+ # 1. Warm the cache
+ cfg1 = search_config(username="researcher_x")
+ assert "collection_col_stale" in cfg1
+
+ # 2. Simulate cache expiration by winding back the timestamp
+ with _COLLECTION_CACHE_LOCK:
+ old_data = _COLLECTION_ENGINES_CACHE["researcher_x"][1]
+ _COLLECTION_ENGINES_CACHE["researcher_x"] = (
+ time.monotonic() - 100.0,
+ old_data,
+ )
+
+ # 3. Simulate DB failure (e.g. QueuePool timeout)
+ mock_get_session.side_effect = TimeoutError(
+ "QueuePool connection timed out"
+ )
+
+ # 4. search_config should catch error and fall back to stale cache!
+ cfg2 = search_config(username="researcher_x")
+ assert "collection_col_stale" in cfg2
+ assert (
+ cfg2["collection_col_stale"]["display_name"]
+ == "Stale Collection (Collection)"
+ )
+
+ @patch("local_deep_research.database.session_context.get_user_db_session")
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_db_error_cold_cache_does_not_crash(
+ self, mock_get_setting, mock_get_session
+ ):
+ from local_deep_research.web_search_engines.search_engines_config import (
+ search_config,
+ )
+
+ mock_get_setting.side_effect = lambda key, default=None, **kw: (
+ True
+ if "library.enabled" in key
+ else ({} if "search.engine.web" in key else default)
+ )
+ mock_get_session.side_effect = RuntimeError("Database unreachable")
+
+ # Must not raise, returns other configured engines
+ cfg = search_config(username="cold_user")
+ assert isinstance(cfg, dict)
+ assert not any(k.startswith("collection_") for k in cfg)
+
+ @patch("local_deep_research.database.session_context.get_user_db_session")
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_copy_on_read_prevents_cache_corruption(
+ self, mock_get_setting, mock_get_session
+ ):
+ """Mutating a returned engine dict must not corrupt cached data for subsequent calls."""
+ from local_deep_research.web_search_engines.search_engines_config import (
+ search_config,
+ )
+
+ mock_get_setting.side_effect = lambda key, default=None, **kw: (
+ True
+ if "library.enabled" in key
+ else ({} if "search.engine.web" in key else default)
+ )
+
+ mock_collection = MagicMock()
+ mock_collection.id = "col_mutate"
+ mock_collection.name = "Original Name"
+ mock_collection.description = "Original Description"
+ mock_collection.is_public = False
+ mock_collection.agent_enabled = True
+
+ mock_session = MagicMock()
+ mock_session.query.return_value.all.return_value = [mock_collection]
+ mock_get_session.return_value.__enter__.return_value = mock_session
+
+ # First read
+ cfg1 = search_config(username="user_mut")
+ assert (
+ cfg1["collection_col_mutate"]["display_name"]
+ == "Original Name (Collection)"
+ )
+
+ # Mutate returned dictionary and nested default_params
+ cfg1["collection_col_mutate"]["display_name"] = "Corrupted Name"
+ cfg1["collection_col_mutate"]["default_params"]["collection_name"] = (
+ "Corrupted Name"
+ )
+
+ # Second read from cache must remain pristine
+ cfg2 = search_config(username="user_mut")
+ assert (
+ cfg2["collection_col_mutate"]["display_name"]
+ == "Original Name (Collection)"
+ )
+ assert (
+ cfg2["collection_col_mutate"]["default_params"]["collection_name"]
+ == "Original Name"
+ )
+
+ @patch("local_deep_research.database.session_context.get_user_db_session")
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_stale_cache_age_cap_rejects_expired_stale_entries(
+ self, mock_get_setting, mock_get_session
+ ):
+ """Stale cached engines older than _COLLECTION_CACHE_MAX_STALE must not be served."""
+ import time
+ from local_deep_research.web_search_engines.search_engines_config import (
+ search_config,
+ _COLLECTION_ENGINES_CACHE,
+ _COLLECTION_CACHE_LOCK,
+ _COLLECTION_CACHE_MAX_STALE,
+ )
+
+ mock_get_setting.side_effect = lambda key, default=None, **kw: (
+ True
+ if "library.enabled" in key
+ else ({} if "search.engine.web" in key else default)
+ )
+
+ mock_collection = MagicMock()
+ mock_collection.id = "col_expired_stale"
+ mock_collection.name = "Old Stale Collection"
+ mock_collection.description = "Old stale papers"
+ mock_collection.is_public = False
+ mock_collection.agent_enabled = True
+
+ mock_session = MagicMock()
+ mock_session.query.return_value.all.return_value = [mock_collection]
+ mock_get_session.return_value.__enter__.return_value = mock_session
+
+ # 1. Warm cache
+ cfg1 = search_config(username="user_stale_expired")
+ assert "collection_col_expired_stale" in cfg1
+
+ # 2. Wind back cache timestamp beyond _COLLECTION_CACHE_MAX_STALE
+ with _COLLECTION_CACHE_LOCK:
+ old_data = _COLLECTION_ENGINES_CACHE["user_stale_expired"][1]
+ _COLLECTION_ENGINES_CACHE["user_stale_expired"] = (
+ time.monotonic() - (_COLLECTION_CACHE_MAX_STALE + 10.0),
+ old_data,
+ )
+
+ # 3. Simulate DB failure
+ mock_get_session.side_effect = TimeoutError(
+ "Database connection timed out"
+ )
+
+ # 4. Outage re-queries DB, fails, and stale cache is expired -> must NOT serve stale collection
+ cfg2 = search_config(username="user_stale_expired")
+ assert "collection_col_expired_stale" not in cfg2
+
+ @patch("local_deep_research.database.session_context.get_user_db_session")
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_unbounded_growth_bounded_by_lru_cache(
+ self, mock_get_setting, mock_get_session
+ ):
+ """Cache must be bounded by LRU eviction when users exceed _COLLECTION_CACHE_MAXSIZE."""
+ from local_deep_research.web_search_engines.search_engines_config import (
+ search_config,
+ _COLLECTION_ENGINES_CACHE,
+ _COLLECTION_CACHE_LOCK,
+ _COLLECTION_CACHE_MAXSIZE,
+ )
+
+ mock_get_setting.side_effect = lambda key, default=None, **kw: (
+ True
+ if "library.enabled" in key
+ else ({} if "search.engine.web" in key else default)
+ )
+
+ mock_session = MagicMock()
+ mock_session.query.return_value.all.return_value = []
+ mock_get_session.return_value.__enter__.return_value = mock_session
+
+ # Fill cache up to maxsize + 5 users
+ total_users = _COLLECTION_CACHE_MAXSIZE + 5
+ for i in range(total_users):
+ search_config(username=f"user_{i}")
+
+ with _COLLECTION_CACHE_LOCK:
+ assert len(_COLLECTION_ENGINES_CACHE) <= _COLLECTION_CACHE_MAXSIZE
+ # Earliest users (e.g. user_0) must have been evicted by LRU
+ assert "user_0" not in _COLLECTION_ENGINES_CACHE
+ assert f"user_{total_users - 1}" in _COLLECTION_ENGINES_CACHE
+
+ @patch("local_deep_research.database.session_context.get_user_db_session")
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config._get_setting"
+ )
+ def test_flip_is_public_cache_expiry_and_runtime_containment(
+ self, mock_get_setting, mock_get_session
+ ):
+ """Flip is_public True->False: before cache expiry, listing still shows engine
+ while runtime search() fails closed at the DB backstop; once expired, engine
+ is dropped from list_eligible_engine_configs and runtime search() still fails closed."""
+ from local_deep_research.security.egress.policy import (
+ EgressContext,
+ EgressScope,
+ PolicyDeniedError,
+ )
+ from local_deep_research.web_search_engines.search_engines_config import (
+ list_eligible_engine_configs,
+ invalidate_collection_engines_cache,
+ )
+ from local_deep_research.web_search_engines.engines.search_engine_collection import (
+ CollectionSearchEngine,
+ )
+
+ mock_get_setting.side_effect = lambda key, default=None, **kw: (
+ True
+ if "library.enabled" in key
+ else ({} if "search.engine.web" in key else default)
+ )
+
+ mock_collection = MagicMock()
+ mock_collection.id = "col_egress"
+ mock_collection.name = "Public Research"
+ mock_collection.description = "Open access docs"
+ mock_collection.is_public = True
+ mock_collection.agent_enabled = True
+ mock_collection.embedding_model = "test-embed"
+ mock_collection.embedding_model_type = None
+
+ mock_session = MagicMock()
+ mock_session.query.return_value.all.return_value = [mock_collection]
+ mock_session.query.return_value.filter.return_value.first.return_value = mock_collection
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_collection
+ mock_get_session.return_value.__enter__.return_value = mock_session
+
+ snapshot = {
+ "_username": "sec_user",
+ "policy.egress_scope": {"value": "public_only"},
+ "search.tool": {"value": "wikipedia"},
+ }
+ egress_ctx = EgressContext(
+ scope=EgressScope.PUBLIC_ONLY,
+ primary_engine="wikipedia",
+ require_local_llm=False,
+ require_local_embeddings=False,
+ username="sec_user",
+ )
+
+ # 1. Initially is_public is True: collection is listed as eligible under PUBLIC_ONLY
+ eligible_configs = list_eligible_engine_configs(
+ settings_snapshot=snapshot, egress_context=egress_ctx
+ )
+ assert "collection_col_egress" in eligible_configs
+
+ # 2. In DB, flip collection visibility to private: is_public = False
+ mock_collection.is_public = False
+
+ # 3. Runtime egress backstop: CollectionSearchEngine.search() executes fresh DB check
+ # and fails closed immediately with PolicyDeniedError (even while cache is still warm)
+ engine = CollectionSearchEngine(
+ collection_id="col_egress",
+ collection_name="Public Research",
+ settings_snapshot=snapshot,
+ )
+ with pytest.raises(PolicyDeniedError):
+ engine.search("query")
+
+ # 4. Expire/invalidate collection cache
+ invalidate_collection_engines_cache("sec_user")
+
+ # 5. After cache expiration: list_eligible_engine_configs re-reads DB and drops the engine
+ updated_configs = list_eligible_engine_configs(
+ settings_snapshot=snapshot, egress_context=egress_ctx
+ )
+ assert "collection_col_egress" not in updated_configs
+
+ # 6. Runtime backstop continues to fail closed
+ with pytest.raises(PolicyDeniedError):
+ engine.search("query")
+
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config.invalidate_collection_engines_cache"
+ )
+ @patch("local_deep_research.database.session_context.get_user_db_session")
+ def test_create_and_update_routes_invalidate_cache(
+ self, mock_get_session, mock_invalidate
+ ):
+ """Creating and updating collections in rag routes must invalidate collection engines cache."""
+ from local_deep_research.web.routers.rag import (
+ _create_collection_sync,
+ _update_collection_sync,
+ )
+
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+ mock_get_session.return_value.__enter__.return_value = mock_session
+
+ # Create collection
+ create_res = _create_collection_sync(
+ {"name": "New Collection", "description": "Desc"},
+ username="user_routes",
+ )
+ assert create_res["success"] is True
+ mock_invalidate.assert_called_with("user_routes")
+
+ mock_invalidate.reset_mock()
+
+ # Update collection
+ existing_col = MagicMock()
+ existing_col.id = "col_up"
+ existing_col.name = "Old Name"
+ existing_col.description = "Old Desc"
+ existing_col.created_at = None
+ existing_col.collection_type = "user_uploads"
+ existing_col.is_public = False
+ existing_col.agent_enabled = True
+ mock_session.query.return_value.filter_by.return_value.first.return_value = existing_col
+ mock_session.query.return_value.filter.return_value.first.return_value = None
+
+ update_res = _update_collection_sync(
+ {"is_public": True},
+ collection_id="col_up",
+ username="user_routes",
+ )
+ assert update_res["success"] is True
+ mock_invalidate.assert_called_with("user_routes")
+
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config.invalidate_collection_engines_cache"
+ )
+ @patch(
+ "local_deep_research.web.routers.library_delete.CollectionDeletionService"
+ )
+ def test_delete_route_invalidates_cache(
+ self, mock_service_cls, mock_invalidate
+ ):
+ """Deleting a collection via the delete route must invalidate collection engines cache."""
+ from local_deep_research.web.routers.library_delete import (
+ delete_collection,
+ )
+
+ mock_service = MagicMock()
+ mock_service.delete_collection.return_value = {"deleted": True}
+ mock_service_cls.return_value = mock_service
+
+ mock_request = MagicMock()
+ res = delete_collection(
+ request=mock_request,
+ collection_id="col_del",
+ username="user_del",
+ )
+ assert res["success"] is True
+ mock_invalidate.assert_called_with("user_del")