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(research): carry username in run snapshot so the agent can use document collections (#4746)

LearningCircuitbc7a8d3acf68
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index 5cd9c56ce3..c0fa519c89 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -1,4 +1,4 @@
-# src/local_deep_research/search_system/search_system.py
+# src/local_deep_research/search_system.py
from typing import Any, Callable, Dict
from langchain_core.language_models import BaseChatModel
@@ -18,6 +18,38 @@ from .web_search_engines.search_engine_base import BaseSearchEngine
from .constants import DEFAULT_SEARCH_TOOL
+def _ensure_snapshot_username(settings_snapshot, username):
+ """Ensure the run's settings snapshot carries the username under the
+ ``_username`` key that snapshot-driven consumers look it up by.
+
+ The LangGraph agent re-instantiates the search engine *per tool call*
+ from this snapshot (``_make_web_search_tool`` -> ``create_search_engine``),
+ and registering a user's document collections needs the username
+ (``get_user_db_session``), which collection registration reads only from
+ ``settings_snapshot["_username"]``. The snapshot is built without it (the
+ user lives under ``system.user``), so without this a collection/library
+ primary fails inside the agent with "Unknown search engine 'collection_…'".
+
+ Injected here in ``AdvancedSearchSystem.__init__`` — the narrowest common
+ consumer of the strategy-running paths — so the web run and the
+ programmatic API are repaired in one place. (No-ops when ``username`` is
+ absent, e.g. benchmarks/news, which don't use per-user collections anyway.)
+ Mirrors the convention ``get_search()`` already applies to its own local
+ snapshot copy.
+
+ Returns the snapshot unchanged when there is no username, it is not a dict,
+ or ``_username`` is already set (never overwrites an explicit value);
+ otherwise a shallow copy with ``_username`` added (no mutation).
+ """
+ if (
+ username
+ and isinstance(settings_snapshot, dict)
+ and not settings_snapshot.get("_username")
+ ):
+ return {**settings_snapshot, "_username": username}
+ return settings_snapshot
+
+
class AdvancedSearchSystem:
"""
Advanced search system that coordinates different search strategies.
@@ -91,8 +123,13 @@ class AdvancedSearchSystem:
self.model = llm
self.search = search
- # Store settings snapshot
- self.settings_snapshot = settings_snapshot or {}
+ # Store settings snapshot. Inject the username under "_username" so
+ # snapshot-driven consumers (notably the LangGraph agent's per-call
+ # search-engine creation, which must register the user's document
+ # collections) can find it. See _ensure_snapshot_username.
+ self.settings_snapshot = _ensure_snapshot_username(
+ settings_snapshot or {}, username
+ )
# Store programmatic mode
self.programmatic_mode = programmatic_mode
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 7a752f1bc6..bc4df9b0bc 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -880,6 +880,12 @@ def run_research_process(research_id, query, mode, **kwargs):
settings_snapshot = kwargs.get(
"settings_snapshot", {}
) # Complete settings snapshot
+ # NOTE: the "_username" injection that lets the agent register the
+ # user's document collections is done downstream in
+ # AdvancedSearchSystem.__init__ (the narrowest common consumer of the
+ # strategy-running paths — web run and the programmatic API), not here.
+ # Run-start egress (below) doesn't need it: it passes username
+ # explicitly. See _ensure_snapshot_username in search_system.py.
# Log settings snapshot to debug
from ...settings.logger import log_settings
diff --git a/tests/core/test_search_system_username_injection.py b/tests/core/test_search_system_username_injection.py
new file mode 100644
index 0000000000..8c02357dae
--- /dev/null
+++ b/tests/core/test_search_system_username_injection.py
@@ -0,0 +1,93 @@
+"""Tests for the run-snapshot username injection in AdvancedSearchSystem.
+
+The LangGraph agent re-instantiates the search engine *per tool call* from the
+run's ``settings_snapshot``; registering a user's document collections needs
+the username, which collection registration reads only from
+``settings_snapshot["_username"]``. ``AdvancedSearchSystem.__init__`` injects it
+— it is the single consumer of every strategy-running path (web run,
+programmatic API, benchmarks) — so a collection/library primary works for all
+of them. Regression: a collection primary previously failed inside the agent
+with "Unknown search engine 'collection_…'".
+"""
+
+from unittest.mock import Mock, patch
+
+from local_deep_research.search_system import (
+ AdvancedSearchSystem,
+ _ensure_snapshot_username,
+)
+
+
+class TestEnsureSnapshotUsername:
+ """Unit contract of the injection helper."""
+
+ def test_injects_username_when_missing(self):
+ snap = {"search.tool": "collection_abc"}
+ result = _ensure_snapshot_username(snap, "alice")
+ assert result["_username"] == "alice"
+ # search.tool (and everything else) is preserved.
+ assert result["search.tool"] == "collection_abc"
+
+ def test_does_not_mutate_caller_dict(self):
+ snap = {"search.tool": "collection_abc"}
+ result = _ensure_snapshot_username(snap, "alice")
+ assert "_username" not in snap # original untouched
+ assert result is not snap
+
+ def test_preserves_existing_username(self):
+ snap = {"_username": "already", "search.tool": "x"}
+ result = _ensure_snapshot_username(snap, "alice")
+ # An explicit value is never overwritten, and no copy is made.
+ assert result is snap
+ assert result["_username"] == "already"
+
+ def test_noop_when_username_none(self):
+ snap = {"search.tool": "x"}
+ result = _ensure_snapshot_username(snap, None)
+ assert result is snap
+ assert "_username" not in result
+
+ def test_noop_when_username_empty_string(self):
+ snap = {"search.tool": "x"}
+ result = _ensure_snapshot_username(snap, "")
+ assert result is snap
+ assert "_username" not in result
+
+ def test_noop_when_snapshot_not_dict(self):
+ # Defensive: a non-dict snapshot is returned unchanged, never crashes.
+ assert _ensure_snapshot_username(None, "alice") is None
+
+
+class TestAdvancedSearchSystemInjectsUsername:
+ """Locks the call site: constructing the system with a username must put it
+ into the snapshot the strategy (and its per-call engine creation) reads.
+ ``create_strategy`` is patched so the assertion is about the injection, not
+ strategy construction details.
+ """
+
+ def test_init_injects_username_into_snapshot(self):
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy",
+ return_value=Mock(),
+ ):
+ system = AdvancedSearchSystem(
+ llm=Mock(),
+ search=Mock(),
+ settings_snapshot={"search.tool": "collection_abc"},
+ username="alice",
+ )
+ assert system.settings_snapshot["_username"] == "alice"
+ # The configured primary is preserved alongside the injected username.
+ assert system.settings_snapshot["search.tool"] == "collection_abc"
+
+ def test_init_without_username_leaves_snapshot_clean(self):
+ with patch(
+ "local_deep_research.search_system_factory.create_strategy",
+ return_value=Mock(),
+ ):
+ system = AdvancedSearchSystem(
+ llm=Mock(),
+ search=Mock(),
+ settings_snapshot={"search.tool": "searxng"},
+ )
+ assert "_username" not in system.settings_snapshot