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(search): close the collection-engine cache gaps - creation-path invalidation, read-store race, teardown eviction, pool-test engagement (#6893)

LearningCircuita566211a605e
diff --git a/changelog.d/6609.bugfix.md b/changelog.d/6609.bugfix.md
new file mode 100644
index 0000000000..95f8e55dab
--- /dev/null
+++ b/changelog.d/6609.bugfix.md
@@ -0,0 +1 @@
+Collections created outside the web routes — first library initialization, the default Notes collection, and Zotero sync imports — now appear immediately as collection search engines for new research runs instead of after up to 30 seconds of cache staleness, and a user's cached collection list is now cleared on logout, on password change, and when idle-connection cleanup closes their database.
diff --git a/src/local_deep_research/database/library_init.py b/src/local_deep_research/database/library_init.py
index 62b7da47e5..8f8dde3364 100644
--- a/src/local_deep_research/database/library_init.py
+++ b/src/local_deep_research/database/library_init.py
@@ -179,6 +179,17 @@ def ensure_default_library_collection(
session.add(library)
session.commit()
+ # The collection-engine cache may already hold this user's
+ # (empty) engine list from a search within the TTL; drop it so
+ # the next research sees the new collection as a tool (#6609).
+ # Lazy import: search_engines_config pulls in the search stack,
+ # which imports this package — module level would be circular.
+ from ..web_search_engines.search_engines_config import (
+ invalidate_collection_engines_cache,
+ )
+
+ invalidate_collection_engines_cache(username)
+
logger.info(f"Created default Library collection: {library_id}")
return library_id
@@ -232,6 +243,14 @@ def ensure_research_history_collection(
session.add(collection)
session.commit()
+ # Same cache-invalidation contract as the default Library above
+ # (#6609): a search within the TTL must not hide this collection.
+ from ..web_search_engines.search_engines_config import (
+ invalidate_collection_engines_cache,
+ )
+
+ invalidate_collection_engines_cache(username)
+
logger.info(f"Created Research History collection: {collection_id}")
return collection_id
diff --git a/src/local_deep_research/research_library/notes/services/note_service.py b/src/local_deep_research/research_library/notes/services/note_service.py
index b0ae36ff89..063247bd0e 100644
--- a/src/local_deep_research/research_library/notes/services/note_service.py
+++ b/src/local_deep_research/research_library/notes/services/note_service.py
@@ -607,6 +607,14 @@ class NoteService:
except Exception:
session.rollback()
raise
+ # The collection-engine cache may hold this user's pre-creation
+ # (empty) engine list from a search within the TTL; drop it so
+ # the next research offers the Notes collection as a tool (#6609).
+ from ....web_search_engines.search_engines_config import (
+ invalidate_collection_engines_cache,
+ )
+
+ invalidate_collection_engines_cache(self.username)
logger.info("Created default Notes collection: {}", collection_id)
return collection_id
diff --git a/src/local_deep_research/research_library/zotero/sync_service.py b/src/local_deep_research/research_library/zotero/sync_service.py
index 73f4404faa..c4dd64398e 100644
--- a/src/local_deep_research/research_library/zotero/sync_service.py
+++ b/src/local_deep_research/research_library/zotero/sync_service.py
@@ -600,7 +600,7 @@ class ZoteroSyncService:
default_collection_id: Optional[str] = None
try:
with get_user_db_session(self.username, self.password) as session:
- ldr_collection_id = self._ensure_ldr_collection(
+ ldr_collection_id, ldr_created = self._ensure_ldr_collection(
session, client, cfg, collection_key
)
state = self._get_or_create_state(
@@ -608,6 +608,15 @@ class ZoteroSyncService:
)
state.last_status = "syncing"
session.commit()
+ if ldr_created:
+ # Durable only now (the commit above). A search within
+ # the cache TTL must offer the fresh Zotero collection
+ # as a tool, not the pre-creation engine list (#6609).
+ from ...web_search_engines.search_engines_config import (
+ invalidate_collection_engines_cache,
+ )
+
+ invalidate_collection_engines_cache(self.username)
self._set_progress(
phase="checking",
@@ -1156,8 +1165,15 @@ class ZoteroSyncService:
client: ZoteroClient,
cfg: ZoteroConfig,
collection_key: str,
- ) -> str:
- """Find or create the LDR collection backing this Zotero collection."""
+ ) -> Tuple[str, bool]:
+ """Find or create the LDR collection backing this Zotero collection.
+
+ Returns ``(collection_id, created)``; callers must invalidate the
+ collection-engine cache only AFTER the transaction that makes a
+ newly created row durable commits — invalidating at flush time
+ would let a refill in the flush→commit window re-cache the
+ pre-creation engine list (#6609).
+ """
ck = collection_key or ""
state = (
session.query(ZoteroSyncState)
@@ -1175,7 +1191,7 @@ class ZoteroSyncService:
.first()
)
if existing:
- return existing.id
+ return existing.id, False
# Determine a friendly name.
if collection_key:
@@ -1199,7 +1215,7 @@ class ZoteroSyncService:
)
)
session.flush()
- return collection_id
+ return collection_id, True
def _get_or_create_state(
self,
diff --git a/src/local_deep_research/web/auth/connection_cleanup.py b/src/local_deep_research/web/auth/connection_cleanup.py
index 95906c85e6..c5f0c9bf12 100644
--- a/src/local_deep_research/web/auth/connection_cleanup.py
+++ b/src/local_deep_research/web/auth/connection_cleanup.py
@@ -107,6 +107,28 @@ def _pop_per_user_locks(username: str) -> None:
logger.warning(f"Failed to pop _faiss_write_locks for {username}")
+def _evict_collection_engines_cache(username: str) -> None:
+ """Best-effort drop of ``username``'s cached collection search engines.
+
+ The collection-engine cache in ``search_engines_config`` holds the user's
+ collection names/descriptions for up to its 30 s TTL (5 minutes under
+ stale-serve after a DB error). Like the lock entries above it is
+ per-user residue, so every teardown path calls this: logout, password
+ change, and the idle-connection sweep (#6609). Lazy-imported for the
+ same import-graph reason as ``_pop_per_user_locks``.
+ """
+ try:
+ from ...web_search_engines.search_engines_config import (
+ evict_collection_engines_cache,
+ )
+
+ evict_collection_engines_cache(username)
+ except Exception:
+ logger.warning(
+ f"Failed to evict cached collection engines for {username}"
+ )
+
+
def _disconnect_all_user_sockets(username: str) -> None:
"""Best-effort disconnect of ALL of ``username``'s live sockets.
@@ -219,6 +241,9 @@ def cleanup_idle_connections(session_manager, db_manager):
# Stable plain-lock registries keep their identities; tracked caches
# can evict idle entries. This remains independent of engine teardown.
_pop_per_user_locks(username)
+ # The user's cached collection engines are teardown residue too,
+ # dropped outside the try for the same reason (#6609).
+ _evict_collection_engines_cache(username)
if closed:
logger.info(f"Connection cleanup: closed {closed} idle connection(s)")
diff --git a/src/local_deep_research/web/routers/auth.py b/src/local_deep_research/web/routers/auth.py
index e2c8629723..d46fef307a 100644
--- a/src/local_deep_research/web/routers/auth.py
+++ b/src/local_deep_research/web/routers/auth.py
@@ -986,10 +986,22 @@ def logout(request: Request):
# done by the idle-connection sweeper; without this, those
# three module-level dicts accumulate one entry per username
# across the process lifetime.
- from ..auth.connection_cleanup import _pop_per_user_locks
+ from ..auth.connection_cleanup import (
+ _evict_collection_engines_cache,
+ _pop_per_user_locks,
+ )
_pop_per_user_locks(username)
+ # Same per-user residue as the lock dicts above, dropped on the
+ # same teardown paths (this one, password change, the idle
+ # sweeper): the user's cached collection names/descriptions
+ # (#6609). Best-effort: logout does not stop a running research
+ # (the DB-close step above defers to it), and that research can
+ # refill the entry afterwards. Such an entry then expires under
+ # the TTL like any other.
+ _evict_collection_engines_cache(username)
+
# Always wipe the cookie session so the browser is genuinely
# logged out even if earlier cleanup raised.
request.session.clear()
@@ -1222,10 +1234,15 @@ def change_password(
# an explicit close here is defensive — harmless if redundant.
db_manager.close_user_database(username)
- # 2a. Drop per-user lock-dict entries (matches logout path).
- from ..auth.connection_cleanup import _pop_per_user_locks
+ # 2a. Drop per-user lock-dict entries and the cached collection
+ # engines (matches logout path; every session ends below).
+ from ..auth.connection_cleanup import (
+ _evict_collection_engines_cache,
+ _pop_per_user_locks,
+ )
_pop_per_user_locks(username)
+ _evict_collection_engines_cache(username)
# 2b. Purge old backups (encrypted with old key) and create
# a fresh backup with the new key. Old-key backups are a
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 0eace085d7..82fbc689b2 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
@@ -25,6 +25,29 @@ _COLLECTION_CACHE_MAX_STALE = 300.0 # seconds (5 minutes stale age cap)
_COLLECTION_ENGINES_CACHE: LRUCache[str, tuple[float, Dict[str, Any]]] = (
LRUCache(maxsize=_COLLECTION_CACHE_MAXSIZE)
)
+# Write generation of _COLLECTION_ENGINES_CACHE: ONE process-wide counter,
+# advanced (under _COLLECTION_CACHE_LOCK) by every invalidation, per-user
+# or global, and by every eviction. A cache-miss reader captures it under
+# the same lock as its lookup and stores its DB snapshot only if it is
+# unchanged at store time. Any invalidation or eviction after the capture
+# aborts the store. Otherwise the reader would cache a pre-change snapshot
+# OVER the invalidation and resurrect stale engines for a full TTL (#6609).
+#
+# Never reused: the counter is only ever incremented, never reset or
+# removed, so a value a reader captured cannot recur. That is why there
+# is no per-user generation map. Its entries would have to be dropped
+# (to bound memory and leave no logout residue), and a dropped entry
+# reads back as a default an in-flight reader may already hold, so its
+# stale store would match again (ABA). The cost is that one user's
+# invalidation also aborts another user's in-flight store. That is a
+# skipped store, never stale data: that user's next read re-queries.
+_COLLECTION_CACHE_GENERATION = 0
+
+
+def _advance_collection_cache_generation() -> None:
+ """Abort every in-flight cache-miss store. Caller holds the lock."""
+ global _COLLECTION_CACHE_GENERATION
+ _COLLECTION_CACHE_GENERATION += 1
def invalidate_collection_engines_cache(
@@ -41,6 +64,33 @@ def invalidate_collection_engines_cache(
_COLLECTION_ENGINES_CACHE.pop(username, None)
else:
_COLLECTION_ENGINES_CACHE.clear()
+ # Advanced on both branches, so no miss in flight at this point
+ # can store, including one for a user with no cache entry (its
+ # first-ever read).
+ _advance_collection_cache_generation()
+
+
+def evict_collection_engines_cache(username: str) -> None:
+ """Drop ``username``'s cached collection engines at session teardown.
+
+ Called by every teardown path (logout, password change, idle-connection
+ sweeper): the entry holds the user's collection names/descriptions for
+ up to the 30 s TTL, or 5 minutes under stale-serve after a DB error.
+ The mechanics are those of a per-user invalidation. The entry is
+ removed (there is no other per-user state here) and the generation
+ advances, so a miss already in flight at teardown cannot store its
+ snapshot afterwards. Unlike the invalidation, a falsy ``username`` is a
+ no-op, never a global clear.
+
+ Best-effort: logout deliberately leaves a running research alive, and
+ that research can refill the entry through :func:`search_config`. Such
+ an entry then expires like any other (TTL, LRU).
+ """
+ if not username:
+ return
+ with _COLLECTION_CACHE_LOCK:
+ _COLLECTION_ENGINES_CACHE.pop(username, None)
+ _advance_collection_cache_generation()
def _get_setting(
@@ -259,6 +309,11 @@ def search_config(
now - cache_entry[0] < _COLLECTION_CACHE_TTL
):
cached_engines = cache_entry[1]
+ # Captured under the same lock as the lookup so a
+ # concurrent invalidation cannot slip between "miss"
+ # and "capture": any later invalidation or eviction
+ # advances it and aborts our store below.
+ generation = _COLLECTION_CACHE_GENERATION
if cached_engines is not None:
search_engines.update(copy.deepcopy(cached_engines))
@@ -326,12 +381,24 @@ def search_config(
}
with _COLLECTION_CACHE_LOCK:
- _COLLECTION_ENGINES_CACHE[
- collection_username
- ] = (
- now,
- copy.deepcopy(user_collection_engines),
- )
+ # Abort the store if an invalidation or
+ # eviction landed since our lookup: our
+ # snapshot may predate it, so caching it
+ # could resurrect a stale engine list for a
+ # full TTL (#6609).
+ if _COLLECTION_CACHE_GENERATION == generation:
+ _COLLECTION_ENGINES_CACHE[
+ collection_username
+ ] = (
+ now,
+ copy.deepcopy(user_collection_engines),
+ )
+ else:
+ logger.debug(
+ f"Skipped caching collection engines for "
+ f"{collection_username}: the cache was "
+ f"invalidated during refresh"
+ )
search_engines.update(
copy.deepcopy(user_collection_engines)
diff --git a/tests/database/test_library_init.py b/tests/database/test_library_init.py
index dfc225bbe0..3c0bcc1360 100644
--- a/tests/database/test_library_init.py
+++ b/tests/database/test_library_init.py
@@ -202,6 +202,41 @@ class TestEnsureDefaultLibraryCollection:
with pytest.raises(RuntimeError, match="Database error"):
ensure_default_library_collection("testuser")
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config.invalidate_collection_engines_cache"
+ )
+ @patch("local_deep_research.database.library_init.get_user_db_session")
+ def test_creation_invalidates_collection_engines_cache(
+ self, mock_get_session, mock_invalidate
+ ):
+ """Creating the collection must drop the user's cached engine list,
+ so a research started within the 30 s TTL offers it as a tool (#6609)."""
+ mock_session = MagicMock()
+ mock_get_session.return_value.__enter__.return_value = mock_session
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ ensure_default_library_collection("testuser", "testpass")
+
+ mock_invalidate.assert_called_once_with("testuser")
+
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config.invalidate_collection_engines_cache"
+ )
+ @patch("local_deep_research.database.library_init.get_user_db_session")
+ def test_existing_collection_does_not_invalidate(
+ self, mock_get_session, mock_invalidate
+ ):
+ """No creation, no cache churn."""
+ mock_session = MagicMock()
+ mock_get_session.return_value.__enter__.return_value = mock_session
+ mock_existing = MagicMock()
+ mock_existing.id = "existing-library-uuid"
+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_existing
+
+ ensure_default_library_collection("testuser", "testpass")
+
+ mock_invalidate.assert_not_called()
+
class TestEnsureResearchHistoryCollection:
"""Tests for ensure_research_history_collection function."""
@@ -247,6 +282,23 @@ class TestEnsureResearchHistoryCollection:
with pytest.raises(RuntimeError, match="Database error"):
ensure_research_history_collection("testuser")
+ @patch(
+ "local_deep_research.web_search_engines.search_engines_config.invalidate_collection_engines_cache"
+ )
+ @patch("local_deep_research.database.library_init.get_user_db_session")
+ def test_creation_invalidates_collection_engines_cache(
+ self, mock_get_session, mock_invalidate
+ ):
+ """Creating the collection must drop the user's cached engine list
+ (#6609) — same contract as the default Library collection."""
+ mock_session = MagicMock()
+ mock_get_session.return_value.__enter__.return_value = mock_session
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ ensure_research_history_collection("testuser", "testpass")
+
+ mock_invalidate.assert_called_once_with("testuser")
+
class TestInitializeLibraryForUser:
"""Tests for initialize_library_for_user function."""
diff --git a/tests/database/test_session_context.py b/tests/database/test_session_context.py
index 01a9fd8ee9..e12bcdbdba 100644
--- a/tests/database/test_session_context.py
+++ b/tests/database/test_session_context.py
@@ -741,57 +741,108 @@ class TestSessionContextRollbackOnExit:
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.
+ """Threads running queries through get_user_db_session do not
+ exhaust a small QueuePool because connections are returned when the
+ outermost scope ends — not pinned for the thread's lifetime.
+
+ Engages the production thread-local session machinery (the
+ engagement shape carried over from #6387's
+ test_user_db_session_release.py): ``db_manager`` is swapped for a
+ stand-in backed by a real QueuePool engine in BOTH
+ ``session_context`` and ``thread_local_session``, and nothing is
+ patched around ``get_metrics_session`` — the thread-local
+ manager's session reuse and scope-depth handling run for real.
+ The old shape built its own engine + SessionLocal and patched
+ get_metrics_session, so the machinery this docstring names was
+ never reached; with per-task cleanup_current_thread() it also
+ masked the release-at-exit guarantee entirely.
+
+ The barrier keeps every thread ALIVE after its ``with`` block
+ ends, so scope-exit is the only path that can return the
+ connection: 10 live threads hold sessions but the pool of 5 must
+ show zero checked-out connections.
"""
- import concurrent.futures
+ import threading
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import QueuePool
+ from local_deep_research.database import (
+ session_context,
+ thread_local_session,
+ )
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
+ max_overflow=2, # Max total 5 connections — half the threads
pool_timeout=3.0,
+ # The per-user QueuePool shares connections across worker
+ # threads; default SQLite (check_same_thread=True) rejects that.
+ connect_args={"check_same_thread": False},
)
- SessionLocal = sessionmaker(bind=engine)
- def worker_task(i):
+ class _FakeDBManager:
+ """Stand-in for encrypted_db.db_manager backed by a real
+ QueuePool engine — the two methods the session machinery
+ actually calls."""
+
+ def __init__(self, engine):
+ self._sessionmaker = sessionmaker(bind=engine)
+ self.has_encryption = False
+
+ def open_user_database(self, username, password):
+ return engine
+
+ def create_thread_safe_session_for_metrics(
+ self, username, password
+ ):
+ return self._sessionmaker()
+
+ fake_db = _FakeDBManager(engine)
+
+ n = 10 # live threads on a pool of max 5 connections
+ errors = []
+ barrier = threading.Barrier(n + 1)
+ release = threading.Event()
+
+ def worker(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()
+ except Exception as exc: # noqa: BLE001
+ errors.append(exc)
+ barrier.wait(timeout=30)
+ release.wait(timeout=30)
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
+ with (
+ patch.object(session_context, "db_manager", fake_db),
+ patch.object(thread_local_session, "db_manager", fake_db),
+ ):
+ threads = [
+ threading.Thread(target=worker, args=(i,), daemon=True)
+ for i in range(n)
+ ]
+ for t in threads:
+ t.start()
+ barrier.wait(timeout=30)
+ # Every block has ended but every thread still lives: the
+ # connections must already be back in the pool.
+ checked_out = engine.pool.checkedout()
+ release.set()
+ for t in threads:
+ t.join(timeout=30)
+ assert not errors, f"worker errors: {errors}"
+ assert checked_out == 0, (
+ f"connections still checked out after every scope ended: "
+ f"{checked_out} — the thread-local session is pinning its "
+ f"QueuePool connection past scope exit"
+ )
finally:
engine.dispose()
diff --git a/tests/research_library/test_note_service_contracts.py b/tests/research_library/test_note_service_contracts.py
index f73ae9479f..78d03dcd2b 100644
--- a/tests/research_library/test_note_service_contracts.py
+++ b/tests/research_library/test_note_service_contracts.py
@@ -1012,3 +1012,33 @@ def test_delete_note_removes_its_versions_annotations_and_links_only(db):
"Paper",
"Survivor",
]
+
+
+# ---------------------------------------------------------------------------
+# Default Notes collection creation and the search-engine cache (#6609)
+# ---------------------------------------------------------------------------
+
+
+def test_creating_default_notes_collection_invalidates_engine_cache(
+ db, monkeypatch
+):
+ """The first notes access creates the default Notes collection; that
+ creation must drop the user's cached collection-engine list so a
+ research started within the 30 s TTL offers it as a tool (#6609)."""
+ calls = []
+ monkeypatch.setattr(
+ "local_deep_research.web_search_engines.search_engines_config."
+ "invalidate_collection_engines_cache",
+ lambda username=None: calls.append(username),
+ )
+
+ alice = db.service(ALICE)
+ collection_id = alice.get_notes_collection_id()
+
+ assert collection_id is not None
+ assert calls == [ALICE]
+
+ # Second resolution finds the existing collection: no creation, no
+ # further cache churn.
+ assert alice.get_notes_collection_id() == collection_id
+ assert calls == [ALICE]
diff --git a/tests/research_library/zotero/test_sync_service.py b/tests/research_library/zotero/test_sync_service.py
index abf36a3703..1c95679cab 100644
--- a/tests/research_library/zotero/test_sync_service.py
+++ b/tests/research_library/zotero/test_sync_service.py
@@ -2972,7 +2972,9 @@ def test_manual_sync_reprocesses_previously_skipped_items(
# document by an earlier sync of THIS collection. The state row must
# exist too, or _sync_one would mint a fresh collection id and never
# see the map row.
- ldr_collection_id = svc._ensure_ldr_collection(db_session, client, cfg, "")
+ ldr_collection_id, _created = svc._ensure_ldr_collection(
+ db_session, client, cfg, ""
+ )
svc._get_or_create_state(db_session, cfg, "", ldr_collection_id)
db_session.add(
ZoteroItemMap(
@@ -3451,3 +3453,95 @@ def test_default_purge_spares_kept_docs_in_mixed_removal_sync(
default_purged.update(ids)
assert owned_doc in default_purged
assert foreign_id not in default_purged # kept doc stays searchable
+
+
+def test_sync_creating_ldr_collection_invalidates_engine_cache(
+ db_session, monkeypatch, tmp_path
+):
+ """A sync that CREATES the backing LDR collection must invalidate the
+ user's cached collection-engine list, and only once the row is durable,
+ so a research started within the 30 s TTL offers the fresh collection
+ as a tool (#6609). An existing collection must NOT churn the cache.
+
+ The ordering is pinned through an event log: the invalidation must
+ come after the commit that follows the creation. An invalidation
+ placed before that commit, or at flush time inside
+ ``_ensure_ldr_collection``, would let a refill in the flush→commit
+ window re-cache the pre-creation list, and fails here. The version
+ fetch raises, so the sync fails right after the creation commit.
+ """
+ import local_deep_research.research_library.zotero.sync_service as svc_mod
+ from local_deep_research.research_library.zotero.client import ZoteroError
+
+ source_type_id = str(uuid.uuid4())
+ db_session.add(
+ SourceType(id=source_type_id, name="zotero", display_name="Zotero")
+ )
+ db_session.commit()
+
+ @contextmanager
+ def fake_session(*_a, **_k):
+ yield db_session
+
+ monkeypatch.setattr(svc_mod, "get_user_db_session", fake_session)
+ monkeypatch.setattr(
+ svc_mod, "get_source_type_id", lambda *a, **k: source_type_id
+ )
+ events = []
+ real_commit = db_session.commit
+
+ def recording_commit():
+ real_commit()
+ events.append("commit")
+
+ monkeypatch.setattr(db_session, "commit", recording_commit)
+ monkeypatch.setattr(
+ "local_deep_research.web_search_engines.search_engines_config."
+ "invalidate_collection_engines_cache",
+ lambda username=None: events.append(("invalidate", username)),
+ )
+
+ def recording_service():
+ svc = ZoteroSyncService("cache_user", None)
+ monkeypatch.setattr(svc, "_library_root", lambda: str(tmp_path))
+ real_ensure = svc._ensure_ldr_collection
+
+ def recording_ensure(*args, **kwargs):
+ result = real_ensure(*args, **kwargs)
+ events.append("created" if result[1] else "found")
+ return result
+
+ monkeypatch.setattr(svc, "_ensure_ldr_collection", recording_ensure)
+ return svc
+
+ cfg = ZoteroConfig(
+ enabled=True,
+ api_key="zotero-api-key-abcdefghijklmnop",
+ library_id="1",
+ pdf_storage_mode="none",
+ )
+ client = MagicMock()
+ client.get_top_item_versions.side_effect = ZoteroError("rate limited")
+
+ stats = recording_service()._sync_one(client, cfg, "")
+ assert stats["status"] == "failed"
+ assert (
+ db_session.query(Collection).filter_by(collection_type="zotero").count()
+ == 1
+ )
+ invalidation = ("invalidate", "cache_user")
+ assert events.count(invalidation) == 1, events
+ created_at = events.index("created")
+ invalidated_at = events.index(invalidation)
+ # Durable-after-commit: a commit sits between the creation and the
+ # invalidation.
+ assert "commit" in events[created_at:invalidated_at], events
+
+ # A re-sync that finds the collection existing must not invalidate again.
+ events.clear()
+ client2 = MagicMock()
+ client2.get_top_item_versions.side_effect = ZoteroError("rate limited")
+ stats2 = recording_service()._sync_one(client2, cfg, "")
+ assert stats2["status"] == "failed"
+ assert "found" in events
+ assert invalidation not in events
diff --git a/tests/research_library/zotero/test_sync_service_edge_branches.py b/tests/research_library/zotero/test_sync_service_edge_branches.py
index 76c2e1091c..e21c656ad3 100644
--- a/tests/research_library/zotero/test_sync_service_edge_branches.py
+++ b/tests/research_library/zotero/test_sync_service_edge_branches.py
@@ -265,9 +265,10 @@ def test_collection_and_helper_failure_edges(
service = ZoteroSyncService("user")
client = mocker.MagicMock()
client.get_collection_name.return_value = None
- collection_id = service._ensure_ldr_collection(
+ collection_id, created = service._ensure_ldr_collection(
library_session, client, ZoteroConfig(library_id="7"), "KEY"
)
+ assert created is True
collection = (
library_session.query(Collection).filter_by(id=collection_id).one()
)
diff --git a/tests/web/auth/test_connection_cleanup.py b/tests/web/auth/test_connection_cleanup.py
index ced7bf3223..5bb38d13ff 100644
--- a/tests/web/auth/test_connection_cleanup.py
+++ b/tests/web/auth/test_connection_cleanup.py
@@ -462,6 +462,50 @@ class TestCleanupIdleConnections:
for cleanup in (clear_credentials, disconnect, pop_locks):
assert {call.args[0] for call in cleanup.call_args_list} == users
+ def test_sweep_evicts_idle_users_collection_engine_cache(self, sm, db):
+ """The sweep is the teardown path for most users, so it must drop
+ an idle user's cached collection engines (collection names and
+ descriptions) like logout does (#6609). It does so even when the DB
+ close raises, and leaves a still-protected user's entry alone."""
+ import time
+
+ from local_deep_research.web_search_engines import (
+ search_engines_config as sec,
+ )
+
+ idle = "test-sweep-evict-idle-zzz"
+ active = "test-sweep-evict-active-zzz"
+ db.get_connected_usernames.return_value = {idle, active}
+ db.close_user_database.side_effect = RuntimeError(
+ "simulated DB close failure"
+ )
+ with sec._COLLECTION_CACHE_LOCK:
+ for user in (idle, active):
+ sec._COLLECTION_ENGINES_CACHE[user] = (
+ time.monotonic(),
+ {"collection_x": {"display_name": "x (Collection)"}},
+ )
+ try:
+ sm.create_session(active)
+ with (
+ patch(
+ "local_deep_research.web.auth.connection_cleanup.get_usernames_with_active_research",
+ return_value=set(),
+ ),
+ patch(
+ "local_deep_research.scheduler.background.get_background_job_scheduler"
+ ),
+ ):
+ cleanup_idle_connections(sm, db)
+
+ with sec._COLLECTION_CACHE_LOCK:
+ assert idle not in sec._COLLECTION_ENGINES_CACHE
+ assert active in sec._COLLECTION_ENGINES_CACHE
+ finally:
+ with sec._COLLECTION_CACHE_LOCK:
+ for user in (idle, active):
+ sec._COLLECTION_ENGINES_CACHE.pop(user, None)
+
class TestPopPerUserLocks:
"""Tests for ``_pop_per_user_locks`` cache cleanup.
diff --git a/tests/web/test_auth_session_lifecycle.py b/tests/web/test_auth_session_lifecycle.py
index 8d92e3153e..fa01e24250 100644
--- a/tests/web/test_auth_session_lifecycle.py
+++ b/tests/web/test_auth_session_lifecycle.py
@@ -915,3 +915,70 @@ class TestRegistrationAutoLoginGetsTheShortServerDeadline:
"a registration auto-login session past "
"security.session_timeout_hours",
)
+
+
+class TestSessionTeardownEvictsCollectionEngineCache:
+ """Every session teardown path must evict the user's collection-engine
+ cache entry (#6609): logout and password change here, the idle sweeper
+ in ``tests/web/auth/test_connection_cleanup.py``.
+
+ The cache holds the user's collection names/descriptions for up to the
+ 30 s TTL (longer under stale-serve after a DB error); it is the same
+ per-user residue class as the lock dicts these paths already drop.
+ """
+
+ def test_logout_evicts_the_users_cache_entry(
+ self, registered_user, monkeypatch
+ ):
+ from local_deep_research.web_search_engines import (
+ search_engines_config as sec,
+ )
+
+ app, username = registered_user
+ client = _client(app)
+ assert _login(client, username).status_code == 302
+
+ evicted = []
+ monkeypatch.setattr(
+ sec, "evict_collection_engines_cache", lambda u: evicted.append(u)
+ )
+
+ assert _logout(client).status_code == 302
+
+ assert evicted == [username]
+
+ def test_password_change_evicts_the_users_cache_entry(
+ self, registered_user, monkeypatch
+ ):
+ """A successful password change ends every session of the user,
+ so it is a teardown path too."""
+ from local_deep_research.web_search_engines import (
+ search_engines_config as sec,
+ )
+
+ app, username = registered_user
+ client = _client(app)
+ assert _login(client, username).status_code == 302
+
+ evicted = []
+ monkeypatch.setattr(
+ sec, "evict_collection_engines_cache", lambda u: evicted.append(u)
+ )
+
+ new_password = "N3w-Lifecycle-Pass!" # noqa: S105
+ token = _csrf(client)
+ resp = client.post(
+ "/auth/change-password",
+ data={
+ "current_password": TEST_PASSWORD,
+ "new_password": new_password,
+ "confirm_password": new_password,
+ "csrf_token": token,
+ },
+ headers={"X-CSRFToken": token},
+ follow_redirects=False,
+ )
+ assert resp.status_code == 302, resp.text[:300]
+ assert resp.headers.get("location") == "/auth/login"
+
+ assert evicted == [username]
diff --git a/tests/web_search_engines/test_search_engines_config.py b/tests/web_search_engines/test_search_engines_config.py
index c88a548a30..1a4bcd5354 100644
--- a/tests/web_search_engines/test_search_engines_config.py
+++ b/tests/web_search_engines/test_search_engines_config.py
@@ -854,6 +854,204 @@ class TestCollectionEnginesCachingAndFallback:
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_invalidation_during_refresh_aborts_store(
+ self, mock_get_setting, mock_get_session
+ ):
+ """A cache-miss reader whose DB read straddles an invalidation must
+ not store its pre-change snapshot over that invalidation (#6609).
+
+ The creator's commit lands between the reader's DB read and its
+ cache store (simulated by invalidating inside the read itself).
+ The reader still returns fresh data for THIS call, but its
+ snapshot must not be cached: the next read re-queries instead of
+ being served a stale engine list for a full TTL.
+ """
+ from local_deep_research.web_search_engines.search_engines_config import (
+ invalidate_collection_engines_cache,
+ 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_race"
+ mock_collection.name = "Raced Collection"
+ mock_collection.description = None
+ mock_collection.is_public = False
+ mock_collection.agent_enabled = True
+
+ mock_session = MagicMock()
+
+ def read_that_triggers_invalidation():
+ # The invalidation lands AFTER the reader's DB read started
+ # but BEFORE the reader reaches its store.
+ invalidate_collection_engines_cache("racer")
+ return [mock_collection]
+
+ mock_session.query.return_value.all.side_effect = (
+ read_that_triggers_invalidation
+ )
+ mock_get_session.return_value.__enter__.return_value = mock_session
+
+ cfg1 = search_config(username="racer")
+ assert "collection_col_race" in cfg1
+
+ # The store must have aborted: the next read re-queries the DB
+ # rather than being served the invalidated snapshot.
+ cfg2 = search_config(username="racer")
+ assert mock_get_session.call_count == 2
+ assert "collection_col_race" in cfg2
+
+ @pytest.mark.parametrize(
+ ("before_read", "during_read"),
+ [
+ # A user never invalidated before: logout in another tab.
+ pytest.param([], ["evict"], id="never-invalidated-then-evicted"),
+ # Such a user again, hit by a global (no-arg) invalidation.
+ pytest.param(
+ [], ["invalidate_all"], id="never-invalidated-then-global"
+ ),
+ # ABA: the reader captured the generation after N earlier
+ # invalidations; a logout evicts, then N new invalidations.
+ pytest.param(["invalidate"], ["evict", "invalidate"], id="aba-n1"),
+ pytest.param(
+ ["invalidate"] * 3,
+ ["evict"] + ["invalidate"] * 3,
+ id="aba-n3",
+ ),
+ ],
+ )
+ @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_refresh_straddling_an_eviction_never_stores(
+ self, mock_get_setting, mock_get_session, before_read, during_read
+ ):
+ """An eviction or invalidation landing between a cache-miss
+ reader's lookup and its store must abort that store (#6609).
+
+ Pins the failure class of a generation that can repeat: the value
+ the reader captured must never come back. Eviction used to drop a
+ per-user counter that then read back as 0. A logout followed by N
+ new invalidations restored a captured N (ABA), and the captured 0
+ of a never-invalidated user did not change at all. Either way the
+ stale store landed: the snapshot was cached over the logout and
+ the new collections, and a research started within the TTL was
+ served the stale engine list.
+ """
+ import uuid
+
+ from local_deep_research.web_search_engines import (
+ search_engines_config as sec,
+ )
+
+ # Unique per case: no generation history from other tests.
+ username = f"straddle_{uuid.uuid4().hex[:8]}"
+ ops = {
+ "invalidate": lambda: sec.invalidate_collection_engines_cache(
+ username
+ ),
+ "invalidate_all": sec.invalidate_collection_engines_cache,
+ "evict": lambda: sec.evict_collection_engines_cache(username),
+ }
+
+ 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)
+ )
+
+ def collection(collection_id):
+ row = MagicMock()
+ row.id = collection_id
+ row.name = collection_id
+ row.description = None
+ row.is_public = False
+ row.agent_enabled = True
+ return row
+
+ reads = []
+
+ def read_collections():
+ reads.append("read")
+ if len(reads) == 1:
+ # Another tab acts between this miss's lookup and its
+ # store; the snapshot returned predates what it wrote.
+ for op in during_read:
+ ops[op]()
+ return [collection("col_old")]
+ return [collection("col_old"), collection("col_new")]
+
+ mock_session = MagicMock()
+ mock_session.query.return_value.all.side_effect = read_collections
+ mock_get_session.return_value.__enter__.return_value = mock_session
+
+ for op in before_read:
+ ops[op]()
+
+ sec.search_config(username=username)
+
+ with sec._COLLECTION_CACHE_LOCK:
+ assert username not in sec._COLLECTION_ENGINES_CACHE, (
+ "the straddling miss stored its pre-change snapshot"
+ )
+ cfg = sec.search_config(username=username)
+ assert len(reads) == 2 # re-queried, not served the stale snapshot
+ assert "collection_col_new" in cfg
+
+ def test_every_cache_write_advances_a_never_reused_generation(self):
+ """Every invalidation (per-user or global) and every eviction,
+ including one for a user with no state at all, moves the generation
+ strictly forward. A value a reader captured can therefore never
+ recur, which is the property the store-time check relies on."""
+ from local_deep_research.web_search_engines import (
+ search_engines_config as sec,
+ )
+
+ writes = [
+ lambda: sec.invalidate_collection_engines_cache("gen_user"),
+ lambda: sec.evict_collection_engines_cache("gen_user"),
+ lambda: sec.invalidate_collection_engines_cache("gen_user"),
+ sec.invalidate_collection_engines_cache,
+ lambda: sec.evict_collection_engines_cache("gen_never_seen"),
+ ]
+ seen = [sec._COLLECTION_CACHE_GENERATION]
+ for write in writes:
+ write()
+ seen.append(sec._COLLECTION_CACHE_GENERATION)
+
+ assert all(a < b for a, b in zip(seen, seen[1:])), seen
+
+ def test_evict_drops_only_that_users_entry(self):
+ """Eviction (session teardown) removes the user's cache entry and
+ leaves other users' entries alone. A falsy username is a no-op
+ rather than the global clear ``invalidate`` would perform."""
+ import time
+
+ from local_deep_research.web_search_engines import (
+ search_engines_config as sec,
+ )
+
+ with sec._COLLECTION_CACHE_LOCK:
+ sec._COLLECTION_ENGINES_CACHE["leaver"] = (time.monotonic(), {})
+ sec._COLLECTION_ENGINES_CACHE["stayer"] = (time.monotonic(), {})
+
+ sec.evict_collection_engines_cache("leaver")
+ sec.evict_collection_engines_cache("")
+
+ with sec._COLLECTION_CACHE_LOCK:
+ assert "leaver" not in sec._COLLECTION_ENGINES_CACHE
+ assert "stayer" in sec._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"