~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(security): scope search-engine and LLM registries per user (#5539)
LearningCircuit02b7746fc92b
diff --git a/changelog.d/+per-user-search-llm-registries.security.md b/changelog.d/+per-user-search-llm-registries.security.mdnew file mode 100644index 0000000000..b74c91ad5a--- /dev/null+++ b/changelog.d/+per-user-search-llm-registries.security.md@@ -0,0 +1,24 @@+Programmatically registered search retrievers and custom LLMs are now+scoped to the user who registered them. Built-in providers and engines+remain shared for everyone, but one user's registration can no longer+shadow another user's provider/engine resolution or appear in another+user's engine list.++The run's user is now threaded through every LLM-resolution seam that+had been relying on the settings snapshot alone. When a user's primary+search source is their own private (local-only) retriever, the local-only+inference policy is now enforced for the model/provider override path of a+research run, for domain classification, and for the news scheduler's+post-run headline/topic generation — closing paths where those calls could+otherwise fall back to a cloud LLM for a private-corpus run.++As a safety net, when ADAPTIVE egress cannot classify a run's primary engine+in any visible namespace it still resolves to the permissive (cloud-capable)+scope, but now emits a policy-audit warning naming the primary and reporting+whether a username was threaded — so a future missed username thread surfaces+in the logs instead of failing open silently.++Note for programmatic/SDK callers: registering a `None` retriever or LLM+(via `register` / `register_multiple`) now raises `ValueError` instead of+being silently stored, and `register_multiple` is atomic — a batch+containing any `None` value registers none of its entries.diff --git a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.pyindex d035db9167..2212b1ea13 100644--- a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py+++ b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py@@ -349,12 +349,17 @@ class JournalReputationFilter(BaseFilter):PolicyDeniedError,context_from_snapshot,)+ from ...search_system import username_from_snapshotprimary_raw = unwrap_setting(snapshot.get("search.tool", DEFAULT_SEARCH_TOOL))+ # Thread username so a per-user private retriever primary+ # resolves PRIVATE_ONLY and the public journal fetch is skipped.ctx = context_from_snapshot(- snapshot, primary_raw or DEFAULT_SEARCH_TOOL+ snapshot,+ primary_raw or DEFAULT_SEARCH_TOOL,+ username=username_from_snapshot(snapshot),)return ctx.scope in (EgressScope.PRIVATE_ONLY, EgressScope.STRICT)except PolicyDeniedError: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.pyindex fe843702e9..47aa0d80be 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@@ -513,7 +513,12 @@ def _load_specialized_engine_tools(try:if config.get("is_retriever"):try:- meta = retriever_registry.get_metadata(name)+ meta = retriever_registry.get_metadata(+ name,+ username=getattr(+ egress_context, "username", None+ ),+ )except AttributeError:meta = Nonedecision = evaluate_retriever(@@ -1441,7 +1446,19 @@ class LangGraphAgentStrategy(BaseSearchStrategy):# then degrades to unfiltered (the factory PEP still enforces) —# research_service has already failed the run closed by that point.primary = resolve_run_primary_engine(self.settings_snapshot)- return context_from_snapshot(self.settings_snapshot, primary)+ # Thread the run's username so ADAPTIVE can classify a per-user+ # private retriever primary (registered under the user's+ # namespace) as PRIVATE_ONLY, and so the resulting+ # ``egress_context.username`` is populated for the per-user+ # retriever-metadata reads in _load_specialized_engine_tools.+ from ...search_system import username_from_snapshot++ username = username_from_snapshot(+ self.settings_snapshot+ ) or getattr(self, "_username", None)+ return context_from_snapshot(+ self.settings_snapshot, primary, username=username+ )except PolicyDeniedError:# Corrupted/invalid policy.egress_scope — re-raise so the# caller fails closed instead of silently running unfiltered.@@ -1465,10 +1482,12 @@ class LangGraphAgentStrategy(BaseSearchStrategy):username = Noneif self.settings_snapshot:# The snapshot carries the username under the ``_username`` key- # injected by ``AdvancedSearchSystem._ensure_snapshot_username``;+ # injected by ``AdvancedSearchSystem.ensure_snapshot_username``;# the strategy also checks ``self._username`` attribute as a fallback# for non-snapshot callers (tests, programmatic API).- username = self.settings_snapshot.get("_username")+ from ...search_system import username_from_snapshot++ username = username_from_snapshot(self.settings_snapshot)if not username:username = getattr(self, "_username", None)if not username:@@ -1532,8 +1551,17 @@ class LangGraphAgentStrategy(BaseSearchStrategy):)primary_source_type = PrimarySourceType.RETRIEVER+ # Scope the lookup to this run's user so a per-user+ # retriever's classification resolves (falls back to the+ # shared namespace when no username is available).+ from ...search_system import username_from_snapshot++ _md_username = username_from_snapshot(+ self.settings_snapshot+ ) or getattr(self, "_username", None)retriever_metadata = retriever_registry.get_metadata(- self._search_engine_name+ self._search_engine_name,+ username=_md_username,)retriever_is_local = (retriever_metadata.get("is_local")diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.pyindex 2c42cc18ce..b1f6cdc6ac 100644--- a/src/local_deep_research/api/research_functions.py+++ b/src/local_deep_research/api/research_functions.py@@ -81,7 +81,7 @@ def _init_search_system(if retrievers:from ..web_search_engines.retriever_registry import retriever_registry- retriever_registry.register_multiple(retrievers)+ retriever_registry.register_multiple(retrievers, username=username)logger.info(f"Registered {len(retrievers)} retrievers: {list(retrievers.keys())}")@@ -91,7 +91,7 @@ def _init_search_system(from ..llm import register_llmfor name, llm_instance in llms.items():- register_llm(name, llm_instance)+ register_llm(name, llm_instance, username=username)logger.info(f"Registered {len(llms)} LLMs: {list(llms.keys())}")# Use settings_snapshot from parameter, or fall back to kwargs@@ -107,6 +107,7 @@ def _init_search_system(research_id=research_id,research_context=research_context,settings_snapshot=settings_snapshot,+ username=username,)# Set the search engine if specified or get from settings@@ -272,7 +273,7 @@ def quick_summary(if retrievers:from ..web_search_engines.retriever_registry import retriever_registry- retriever_registry.register_multiple(retrievers)+ retriever_registry.register_multiple(retrievers, username=username)logger.info(f"Registered {len(retrievers)} retrievers: {list(retrievers.keys())}")@@ -282,7 +283,7 @@ def quick_summary(from ..llm import register_llmfor name, llm_instance in llms.items():- register_llm(name, llm_instance)+ register_llm(name, llm_instance, username=username)logger.info(f"Registered {len(llms)} LLMs: {list(llms.keys())}")search_context = {@@ -438,7 +439,7 @@ def generate_report(if retrievers:from ..web_search_engines.retriever_registry import retriever_registry- retriever_registry.register_multiple(retrievers)+ retriever_registry.register_multiple(retrievers, username=username)logger.info(f"Registered {len(retrievers)} retrievers: {list(retrievers.keys())}")@@ -448,7 +449,7 @@ def generate_report(from ..llm import register_llmfor name, llm_instance in llms.items():- register_llm(name, llm_instance)+ register_llm(name, llm_instance, username=username)logger.info(f"Registered {len(llms)} LLMs: {list(llms.keys())}")import uuid@@ -555,7 +556,7 @@ def detailed_research(if retrievers:from ..web_search_engines.retriever_registry import retriever_registry- retriever_registry.register_multiple(retrievers)+ retriever_registry.register_multiple(retrievers, username=username)logger.info(f"Registered {len(retrievers)} retrievers: {list(retrievers.keys())}")@@ -565,7 +566,7 @@ def detailed_research(from ..llm import register_llmfor name, llm_instance in llms.items():- register_llm(name, llm_instance)+ register_llm(name, llm_instance, username=username)logger.info(f"Registered {len(llms)} LLMs: {list(llms.keys())}")search_context = {@@ -664,9 +665,13 @@ def analyze_documents(llm = Nonesearch = Nonetry:- # Get language model with custom temperature+ # Get language model with custom temperature. Pass username so a+ # per-user registered LLM (and per-user egress classification)+ # resolves for this caller.llm = get_llm(- temperature=temperature, settings_snapshot=settings_snapshot+ temperature=temperature,+ settings_snapshot=settings_snapshot,+ username=username,)# Get search engine for the specified collectiondiff --git a/src/local_deep_research/chat/routes.py b/src/local_deep_research/chat/routes.pyindex 2f4694fc58..25df5e2185 100644--- a/src/local_deep_research/chat/routes.py+++ b/src/local_deep_research/chat/routes.py@@ -99,9 +99,18 @@ def _load_settings(username):next research, not be served from a stale cache."""with get_user_db_session(username) as db:- return SettingsManager(db_session=db).get_all_settings(+ snapshot = SettingsManager(db_session=db).get_all_settings(bypass_cache=True)+ # Inject the username so snapshot-driven consumers (get_llm, and ADAPTIVE+ # egress-scope resolution for a per-user retriever primary) can resolve it.+ # Without it, chat follow-up summarization builds get_llm() with+ # username=None -> a private-retriever primary is invisible -> scope falls+ # open to BOTH and a cloud LLM summarizes private-corpus turns. Mirrors+ # AdvancedSearchSystem.ensure_snapshot_username.+ from ..search_system import ensure_snapshot_username++ return ensure_snapshot_username(snapshot, username)def _parse_int_param(diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.pyindex 9a70c88a21..757a8f3302 100644--- a/src/local_deep_research/config/llm_config.py+++ b/src/local_deep_research/config/llm_config.py@@ -59,6 +59,7 @@ def get_llm(research_id=None,research_context=None,settings_snapshot=None,+ username=None,):"""Get LLM instance based on model name and provider.@@ -72,11 +73,23 @@ def get_llm(the ``llm.openai_endpoint.url`` setting.research_id: Optional research ID for token trackingresearch_context: Optional research context for enhanced token tracking+ username: Requesting user, used to resolve per-user registered LLMs.+ When omitted, falls back to the ``_username`` in the settings+ snapshot; ``None`` resolves shared/built-in providers only.Returns:A LangChain LLM instance with automatic think-tag removal"""+ # Resolve the effective username for per-user registry lookups. An+ # explicit argument wins; otherwise fall back to the ``_username`` the+ # settings snapshot carries. None resolves the shared namespace (which+ # holds the auto-discovered built-in providers) only.+ if username is None:+ from ..search_system import username_from_snapshot++ username = username_from_snapshot(settings_snapshot)+# Use database values for parameters if not providedif model_name is None:model_name = get_setting_from_snapshot(@@ -154,7 +167,10 @@ def get_llm(require_local_embeddings=True,)decision = evaluate_llm_endpoint(- provider, ctx, settings_snapshot=settings_snapshot+ provider,+ ctx,+ settings_snapshot=settings_snapshot,+ username=username,)if not decision.allowed:logger.bind(policy_audit=True).warning(@@ -167,7 +183,7 @@ def get_llm(# reason evaluate_llm_endpoint allows them: no endpoint to# classify, operator-injected, audit-hook backstopped.elif provider not in _LOCAL_DEFAULT_LLM_PROVIDERS and not (- _is_user_registered_llm(provider)+ _is_user_registered_llm(provider, username=username)):logger.bind(policy_audit=True).warning("LLM constructed without policy snapshot; refusing "@@ -190,7 +206,15 @@ def get_llm(# primary_engine raises on a missing/invalid primary, which we# treat as a hard stop here.primary_engine = resolve_run_primary_engine(settings_snapshot)- ctx = context_from_snapshot(settings_snapshot, primary_engine)+ # Pass username so a per-user private retriever set as the+ # run's primary is classified against the caller's own+ # namespace. Without it ADAPTIVE can't see the retriever+ # (shared namespace only), resolves to the permissive BOTH,+ # leaves require_local_llm False, and admits a cloud LLM for a+ # run over the user's private corpus (fail-open).+ ctx = context_from_snapshot(+ settings_snapshot, primary_engine, username=username+ )except ValueError as exc:# No configured primary, or an invalid policy config. Fail# closed: previously a missing primary silently fell back to@@ -209,7 +233,10 @@ def get_llm(if ctx is not None and ctx.require_local_llm:decision = evaluate_llm_endpoint(- provider, ctx, settings_snapshot=settings_snapshot+ provider,+ ctx,+ settings_snapshot=settings_snapshot,+ username=username,)if not decision.allowed:logger.bind(policy_audit=True).warning(@@ -219,10 +246,12 @@ def get_llm()raise PolicyDeniedError(decision, target=provider)- # Check if this is a registered custom LLM first- if provider and is_llm_registered(provider):+ # Check if this is a registered custom LLM first. Resolve against the+ # caller's own namespace before the shared/built-in providers so one+ # user's registration can't shadow a built-in for anyone else.+ if provider and is_llm_registered(provider, username=username):logger.info(f"Using registered custom LLM: {provider}")- custom_llm = get_llm_from_registry(provider)+ custom_llm = get_llm_from_registry(provider, username=username)# Check if it's a callable (factory function) or a BaseChatModel instanceif callable(custom_llm) and not isinstance(custom_llm, BaseChatModel):diff --git a/src/local_deep_research/config/search_config.py b/src/local_deep_research/config/search_config.pyindex bee191b569..6d327244f4 100644--- a/src/local_deep_research/config/search_config.py+++ b/src/local_deep_research/config/search_config.py@@ -54,8 +54,13 @@ def get_search(f"Creating search engine with tool: {tool} (type: {type(tool)})")- # Get LLM instance (use provided or get fresh one)- llm = llm_instance or get_llm(settings_snapshot=settings_snapshot)+ # Get LLM instance (use provided or get fresh one). Pass username+ # explicitly: this runs BEFORE ``_username`` is injected into the+ # snapshot below, so without it a per-user registered LLM (and per-user+ # egress classification) would be invisible to this fresh get_llm.+ llm = llm_instance or get_llm(+ settings_snapshot=settings_snapshot, username=username+ )# Ensure username is in settings_snapshot for search engines that need it (e.g., library)if username and settings_snapshot is not None:diff --git a/src/local_deep_research/domain_classifier/classifier.py b/src/local_deep_research/domain_classifier/classifier.pyindex 1b6263c7a8..e05477fe5c 100644--- a/src/local_deep_research/domain_classifier/classifier.py+++ b/src/local_deep_research/domain_classifier/classifier.py@@ -99,7 +99,15 @@ class DomainClassifier:def _get_llm(self):"""Get or initialize LLM instance."""if self.llm is None:- self.llm = get_llm(settings_snapshot=self.settings_snapshot)+ # Thread the user so the LLM PEP enforces local-only policy: the+ # route builds settings_snapshot with a bare SettingsManager (no+ # `_username`), and classification prompts carry the user's own+ # resource titles, which must not fail open to a cloud LLM when+ # the user's default engine is a private retriever.+ self.llm = get_llm(+ settings_snapshot=self.settings_snapshot,+ username=self.username,+ )return self.llmdef close(self) -> None:diff --git a/src/local_deep_research/embeddings/embeddings_config.py b/src/local_deep_research/embeddings/embeddings_config.pyindex 540555eeb2..7264a75b56 100644--- a/src/local_deep_research/embeddings/embeddings_config.py+++ b/src/local_deep_research/embeddings/embeddings_config.py@@ -203,6 +203,7 @@ def get_embeddings(evaluate_embeddings,resolve_run_primary_engine,)+ from ..search_system import username_from_snapshottry:# Single source of truth for the primary (was: search.tool +@@ -211,7 +212,17 @@ def get_embeddings(# stayed False -> the corpus could ship to a cloud embedder for a# private run). A missing/invalid primary now raises -> fail closed.primary = resolve_run_primary_engine(settings_snapshot)- ctx = context_from_snapshot(settings_snapshot, primary)+ # Thread the run's username (carried in the snapshot) so a+ # per-user private retriever primary resolves to PRIVATE_ONLY,+ # which forces require_local_embeddings=True. Without it the+ # per-user retriever is invisible (shared namespace only),+ # ADAPTIVE falls back to BOTH, and the corpus could reach a+ # cloud embedder (fail-open).+ ctx = context_from_snapshot(+ settings_snapshot,+ primary,+ username=username_from_snapshot(settings_snapshot),+ )except PolicyDeniedError:raiseexcept ValueError as exc:diff --git a/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py b/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.pyindex 2c828f3bef..b254bde508 100644--- a/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py+++ b/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py@@ -138,13 +138,16 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):context_from_snapshot,resolve_run_primary_engine,)+ from ....search_system import username_from_snapshot# Single source of truth for the primary (was: search.tool +# searxng fallback, a fail-OPEN that could permit a remote model# download for a primary-less private run)._primary = resolve_run_primary_engine(settings_snapshot)require_local = context_from_snapshot(- settings_snapshot, _primary+ settings_snapshot,+ _primary,+ username=username_from_snapshot(settings_snapshot),).require_local_embeddingsexcept ValueError:# No usable primary / invalid scope: fail CLOSED to local-onlydiff --git a/src/local_deep_research/llm/llm_registry.py b/src/local_deep_research/llm/llm_registry.pyindex 13dfea04da..50e939360b 100644--- a/src/local_deep_research/llm/llm_registry.py+++ b/src/local_deep_research/llm/llm_registry.py@@ -1,7 +1,14 @@"""Registry for custom LangChain LLMs.-This module provides a global registry for registering and managing custom LangChain+This module provides a registry for registering and managing custom LangChainLLMs that can be used with Local Deep Research.++Entries are keyed per user. Built-in providers (auto-discovered at import via+``discover_providers()``) and SDK/MCP/benchmark registrations that carry no+username live in a shared namespace and resolve for everyone. A registration+made with a ``username`` lives in that user's namespace and is resolved for+that user first, so one user's custom LLM can neither shadow a built-in+provider for anyone else nor leak into another user's registry listing."""import threading@@ -10,95 +17,172 @@ from typing import Callable, Dict, Optional, Unionfrom langchain.chat_models.base import BaseChatModelfrom loguru import logger+# Sentinel key for the shared/global namespace (see module docstring).+_SHARED_NAMESPACE: Optional[str] = None++_LLMType = Union[BaseChatModel, Callable[..., BaseChatModel]]+class LLMRegistry:- """Thread-safe registry for custom LangChain LLMs."""+ """Thread-safe, per-user registry for custom LangChain LLMs."""def __init__(self):- self._llms: Dict[- str, Union[BaseChatModel, Callable[..., BaseChatModel]]- ] = {}+ # {namespace: {normalized_name: llm}}. ``namespace`` is a username+ # or ``_SHARED_NAMESPACE`` for shared/global entries (built-ins ++ # username-less registrations).+ self._llms: Dict[Optional[str], Dict[str, _LLMType]] = {}self._lock = threading.Lock()+ @staticmethod+ def _ns(username: Optional[str]) -> Optional[str]:+ """Normalize a username to a namespace key.++ A falsy username maps to the shared namespace, so legacy/global+ callers keep a single shared namespace and never crash for want of+ a username.+ """+ return username or _SHARED_NAMESPACE+def register(- self, name: str, llm: Union[BaseChatModel, Callable[..., BaseChatModel]]+ self,+ name: str,+ llm: _LLMType,+ username: Optional[str] = None,) -> None:"""Register a custom LLM.Args:name: Unique name for the LLM (case-insensitive)llm: Either a BaseChatModel instance or a factory function that returns one+ username: Owner of the registration. When omitted the entry is+ stored in the shared namespace (visible to all callers).++ Raises:+ ValueError: ``llm`` is None. A stored ``None`` would silently+ miss in ``get()``'s ``found is not None`` check and fall+ through to the shared namespace, letting a misregistered+ entry resolve to an unrelated (possibly built-in) provider."""+ if llm is None:+ raise ValueError(f"Cannot register LLM '{name}': value is None")+ ns = self._ns(username)with self._lock:# Normalize name to lowercase for case-insensitive storagenormalized_name = name.lower()- if normalized_name in self._llms:+ bucket = self._llms.setdefault(ns, {})+ if normalized_name in bucket:logger.warning(f"Overwriting existing LLM: {name}")- self._llms[normalized_name] = llm+ bucket[normalized_name] = llmlogger.info(f"Registered custom LLM: {name} (normalized: {normalized_name})")# Completes the CRUD API surface for the registry.# Used in tests to verify cleanup behavior.- def unregister(self, name: str) -> None:+ def unregister(self, name: str, username: Optional[str] = None) -> None:"""Unregister a custom LLM.Args:name: Name of the LLM to unregister (case-insensitive)+ username: Owner namespace to remove from (None = shared)"""+ ns = self._ns(username)with self._lock:normalized_name = name.lower()- if normalized_name in self._llms:- del self._llms[normalized_name]+ bucket = self._llms.get(ns)+ if bucket and normalized_name in bucket:+ del bucket[normalized_name]logger.info(f"Unregistered custom LLM: {name}")def get(- self, name: str- ) -> Optional[Union[BaseChatModel, Callable[..., BaseChatModel]]]:+ self, name: str, username: Optional[str] = None+ ) -> Optional[_LLMType]:"""Get a registered LLM.+ Resolution order: the caller's own namespace, then the shared+ namespace (which holds built-in providers). A user's registration+ never resolves for another user.+Args:name: Name of the LLM to retrieve (case-insensitive)+ username: Requesting user (None resolves the shared namespace only)Returns:The LLM instance/factory or None if not found"""+ ns = self._ns(username)with self._lock:normalized_name = name.lower()- return self._llms.get(normalized_name)+ if ns is not _SHARED_NAMESPACE:+ found = self._llms.get(ns, {}).get(normalized_name)+ if found is not None:+ return found+ return self._llms.get(_SHARED_NAMESPACE, {}).get(normalized_name)- def is_registered(self, name: str) -> bool:- """Check if an LLM is registered.+ def is_registered(self, name: str, username: Optional[str] = None) -> bool:+ """Check if an LLM is registered and resolvable for the caller.Args:name: Name to check (case-insensitive)+ username: Requesting user (None resolves the shared namespace only)Returns:True if registered, False otherwise"""- with self._lock:- normalized_name = name.lower()- return normalized_name in self._llms+ return self.get(name, username=username) is not None# Used in test assertions to verify registry state;# part of public API for plugin authors.- def list_registered(self) -> list[str]:- """Get list of all registered LLM names.+ def list_registered(self, username: Optional[str] = None) -> list[str]:+ """Get list of LLM names visible to the caller.++ Returns the caller's own registrations plus shared ones (built-in+ providers); never another user's names.++ Order is DETERMINISTIC: the caller's own entries first (insertion+ order), then shared entries not shadowed by an own-namespace name.+ This mirrors ``get()``'s own-namespace-first resolution (a same-named+ own entry shadows the shared built-in, so it is listed once, under+ own) and replaces the previous ``set``-union, whose ``list(set(...))``+ order was nondeterministic run to run.++ Args:+ username: Requesting user (None lists the shared namespace only)Returns:List of registered LLM names"""+ ns = self._ns(username)with self._lock:- return list(self._llms.keys())+ shared = self._llms.get(_SHARED_NAMESPACE, {})+ if ns is _SHARED_NAMESPACE:+ return list(shared.keys())+ own = self._llms.get(ns, {})+ return list(own.keys()) + [+ name for name in shared if name not in own+ ]# Used in 7+ test files' autouse fixtures for test isolation# (64+ tests depend on this to reset global state between runs).- def clear(self) -> None:- """Clear all registered LLMs."""+ def clear(self, username: Optional[str] = None) -> None:+ """Clear registered LLMs.++ With no ``username`` every namespace is cleared — including the+ shared built-in providers — matching the historic reset behavior+ the test-isolation fixtures depend on. With a ``username`` only+ that user's namespace is cleared.+ """+ # TODO: hook clear(username=<deleted user>) into a user-deletion+ # flow so a removed user's registered LLMs are evicted from this+ # in-process registry. No user-deletion hook exists yet, so+ # eviction-on-deletion is out of scope here; this is the seam.with self._lock:- self._llms.clear()- logger.info("Cleared all registered custom LLMs")+ if username is None:+ self._llms.clear()+ logger.info("Cleared all registered custom LLMs")+ else:+ self._llms.pop(self._ns(username), None)+ logger.info("Cleared registered custom LLMs for one user")# Global registry instance@@ -107,61 +191,71 @@ _llm_registry = LLMRegistry()# Public API functionsdef register_llm(- name: str, llm: Union[BaseChatModel, Callable[..., BaseChatModel]]+ name: str,+ llm: _LLMType,+ username: Optional[str] = None,) -> None:- """Register a custom LLM in the global registry.+ """Register a custom LLM in the registry.Args:name: Unique name for the LLMllm: Either a BaseChatModel instance or a factory function+ username: Owner of the registration (None = shared namespace)"""- _llm_registry.register(name, llm)+ _llm_registry.register(name, llm, username=username)-def unregister_llm(name: str) -> None:- """Unregister a custom LLM from the global registry.+def unregister_llm(name: str, username: Optional[str] = None) -> None:+ """Unregister a custom LLM from the registry.Args:name: Name of the LLM to unregister+ username: Owner namespace to remove from (None = shared)"""- _llm_registry.unregister(name)+ _llm_registry.unregister(name, username=username)def get_llm_from_registry(name: str,-) -> Optional[Union[BaseChatModel, Callable[..., BaseChatModel]]]:- """Get a registered LLM from the global registry.+ username: Optional[str] = None,+) -> Optional[_LLMType]:+ """Get a registered LLM from the registry.Args:name: Name of the LLM to retrieve+ username: Requesting user (None resolves the shared namespace only)Returns:The LLM instance/factory or None if not found"""- return _llm_registry.get(name)+ return _llm_registry.get(name, username=username)-def is_llm_registered(name: str) -> bool:- """Check if an LLM is registered in the global registry.+def is_llm_registered(name: str, username: Optional[str] = None) -> bool:+ """Check if an LLM is registered in the registry.Args:name: Name to check+ username: Requesting user (None resolves the shared namespace only)Returns:True if registered, False otherwise"""- return _llm_registry.is_registered(name)+ return _llm_registry.is_registered(name, username=username)-def list_registered_llms() -> list[str]:- """Get list of all registered LLM names.+def list_registered_llms(username: Optional[str] = None) -> list[str]:+ """Get list of registered LLM names visible to the caller.++ Args:+ username: Requesting user (None lists the shared namespace only)Returns:List of registered LLM names"""- return _llm_registry.list_registered()+ return _llm_registry.list_registered(username=username)-def clear_llm_registry() -> None:- """Clear all registered LLMs from the global registry."""- _llm_registry.clear()+def clear_llm_registry(username: Optional[str] = None) -> None:+ """Clear registered LLMs (all namespaces when no username is given)."""+ _llm_registry.clear(username=username)diff --git a/src/local_deep_research/notifications/manager.py b/src/local_deep_research/notifications/manager.pyindex 753d785df6..b07a201629 100644--- a/src/local_deep_research/notifications/manager.py+++ b/src/local_deep_research/notifications/manager.py@@ -419,12 +419,16 @@ class NotificationManager:)return service_urls+ from ..search_system import username_from_snapshot+primary_raw = unwrap_setting(snapshot.get("search.tool", DEFAULT_SEARCH_TOOL))try:ctx = context_from_snapshot(- snapshot, primary_raw or DEFAULT_SEARCH_TOOL+ snapshot,+ primary_raw or DEFAULT_SEARCH_TOOL,+ username=username_from_snapshot(snapshot),)except (PolicyDeniedError, ValueError) as exc:# Snapshot present but policy cannot be evaluated. Thediff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.pyindex 52757976d9..19b6a839d7 100644--- a/src/local_deep_research/research_library/routes/rag_routes.py+++ b/src/local_deep_research/research_library/routes/rag_routes.py@@ -678,6 +678,7 @@ def get_available_models():from ...config.thread_settings import (get_setting_from_snapshot,)+ from ...search_system import username_from_snapshotprimary = (get_setting_from_snapshot(@@ -687,7 +688,15 @@ def get_available_models():)or DEFAULT_SEARCH_TOOL)- ctx = context_from_snapshot(settings_snapshot, primary)+ # Thread username so a per-user private retriever primary+ # resolves PRIVATE_ONLY (forcing local embeddings) and this+ # route can't probe a remote embedder for that user.+ ctx = context_from_snapshot(+ settings_snapshot,+ primary,+ username=username_from_snapshot(settings_snapshot)+ or session.get("username"),+ )if not ctx.require_local_embeddings:return Truedecision = evaluate_embeddings(diff --git a/src/local_deep_research/scheduler/background.py b/src/local_deep_research/scheduler/background.pyindex f6a009b62b..0535eaaaea 100644--- a/src/local_deep_research/scheduler/background.py+++ b/src/local_deep_research/scheduler/background.py@@ -2214,6 +2214,17 @@ class BackgroundJobScheduler:# Get user settings to store in metadatasettings_manager = SettingsManager(db)settings_snapshot = settings_manager.get_settings_snapshot()+ # Scope the snapshot to this subscription's owner so the+ # post-hoc headline/topic LLM calls resolve a per-user+ # provider and honor local-only policy. get_settings_snapshot+ # omits `_username`; without it the news findings (which can+ # come from a private-retriever run) could fail open to a+ # cloud LLM.+ from ..search_system import ensure_snapshot_username++ settings_snapshot = ensure_snapshot_username(+ settings_snapshot, username+ )# Get the report content - check both 'report' and 'summary' fieldsreport_content = serializable_result.get(diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.pyindex c0fa519c89..013bd0241a 100644--- a/src/local_deep_research/search_system.py+++ b/src/local_deep_research/search_system.py@@ -18,7 +18,7 @@ from .web_search_engines.search_engine_base import BaseSearchEnginefrom .constants import DEFAULT_SEARCH_TOOL-def _ensure_snapshot_username(settings_snapshot, username):+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.@@ -50,6 +50,22 @@ def _ensure_snapshot_username(settings_snapshot, username):return settings_snapshot+def username_from_snapshot(settings_snapshot):+ """Return the run owner's username carried in a settings snapshot.++ Centralizes the ``settings_snapshot.get("_username")`` read (the mirror of+ :func:`ensure_snapshot_username`'s write) behind a single ``isinstance``+ guard so every consumer treats a missing / non-dict snapshot identically —+ returning ``None`` rather than raising or applying an inconsistent guard.+ ``None`` resolves the shared/built-in namespace in the per-user registries.+ """+ return (+ settings_snapshot.get("_username")+ if isinstance(settings_snapshot, dict)+ else None+ )++class AdvancedSearchSystem:"""Advanced search system that coordinates different search strategies.@@ -126,8 +142,8 @@ class AdvancedSearchSystem:# 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(+ # collections) can find it. See ensure_snapshot_username.+ self.settings_snapshot = ensure_snapshot_username(settings_snapshot or {}, username)diff --git a/src/local_deep_research/security/egress/policy.py b/src/local_deep_research/security/egress/policy.pyindex 7cdc6fd7a9..cc0bf36705 100644--- a/src/local_deep_research/security/egress/policy.py+++ b/src/local_deep_research/security/egress/policy.py@@ -16,9 +16,11 @@ Vocabulary borrowed from XACML / zero-trust:from __future__ import annotations+import hashlibimport jsonimport socketimport threading+from collections import OrderedDictfrom concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutfrom dataclasses import dataclass, fieldfrom enum import Enum@@ -27,6 +29,7 @@ from urllib.parse import unquote, urlsplitfrom loguru import logger+from ..log_sanitizer import sanitize_for_logfrom ..network_utils import is_private_ipfrom ...utilities.type_utils import unwrap_setting@@ -819,7 +822,9 @@ _LOCAL_DEFAULT_EMBEDDING_PROVIDERS = frozenset()-def _is_user_registered_llm(provider: str) -> bool:+def _is_user_registered_llm(+ provider: str, username: Optional[str] = None+) -> bool:"""True when ``provider`` is a user-registered in-process LLM.The programmatic API (``quick_summary(llms={"mock": ...})``) and plugins@@ -844,7 +849,7 @@ def _is_user_registered_llm(provider: str) -> bool:from ...llm.providers import discover_providersfrom ...llm.providers.base import normalize_provider- if not provider or not is_llm_registered(provider):+ if not provider or not is_llm_registered(provider, username=username):return Falsediscovered = {normalize_provider(key) for key in discover_providers()}return normalize_provider(provider) not in discovered@@ -860,11 +865,18 @@ def evaluate_llm_endpoint(ctx: EgressContext,*,settings_snapshot: dict,+ username: Optional[str] = None,) -> Decision:"""Decide whether an LLM provider may be instantiated.Only meaningful when ``ctx.require_local_llm`` is True; otherwise allow.++ ``username`` scopes the user-registered-LLM exemption to the caller's own+ namespace so a per-user in-process LLM is recognized. It defaults to the+ context's username when the caller does not pass one explicitly."""+ if username is None:+ username = getattr(ctx, "username", None)if settings_snapshot is None:return Decision(False, "no_snapshot")try:@@ -878,7 +890,7 @@ def evaluate_llm_endpoint(# User-registered in-process LLMs (programmatic API / plugins) have# no endpoint to classify; allow them — the audit hook still# backstops stray sockets under PRIVATE_ONLY/STRICT.- if _is_user_registered_llm(provider):+ if _is_user_registered_llm(provider, username=username):return Decision(True, "user_registered_llm")# Providers with a configurable URL: classify the URL.@@ -1303,6 +1315,106 @@ def _retriever_is_local(return is_local if isinstance(is_local, bool) else None+# Bounded, thread-safe, PER-USER dedup for the ADAPTIVE fail-open WARNING+# emitted below. ``context_from_snapshot`` runs at every research-run start+# AND at every per-URL fetch-gate check (``BaseSearchEngine.+# _build_full_search_egress_context``, called once per fetched URL), so an+# unclassifiable primary would otherwise emit one identical WARNING per+# fetched URL -- potentially hundreds per run. We remember, PER USER, which+# (sanitized) primary engines have already warned, so a genuinely new+# (user, primary) combination still logs once while repeats are silent.+#+# The dedup MUST be keyed on the actual user identity (a stable hash of the+# username, ``None`` bucket for an unauthenticated / un-threaded run) -- NOT+# merely on "was a username present". Keying on presence alone means a+# genuine fail-open for user B on a primary name already logged for user A is+# silently swallowed: the audit signal for B never fires. Keying on identity+# keeps each user's fail-opens independently detectable.+#+# ``primary_engine`` is user-controlled (``search.tool``), so the dedup state+# is bounded in BOTH dimensions -- mirroring the capped ``warned: set`` dedup+# in ``web/services/socket_service.py::_install_origin_rejection_logging``:+# * each user's bucket caps the distinct primaries it remembers+# (``_ADAPTIVE_FAILOPEN_WARN_CAP_PER_USER``); once full it stops+# warning/recording, exactly as the old single global set did -- but now+# that ceiling is reached PER USER, so it only ever silences the ONE user+# who flooded it, and+# * the set of tracked users is a bounded LRU+# (``_ADAPTIVE_FAILOPEN_MAX_USERS``); the least-recently-seen user's whole+# bucket is evicted beyond the cap (which can only ever re-enable a+# warning, never suppress one).+# A single authenticated user flooding distinct junk primaries therefore only+# ever exhausts THEIR OWN bucket -- it can never suppress the fail-open audit+# warnings of any other user (the bug a single global set had: 512 junk+# primaries from one user permanently silenced everyone). Total memory is+# capped at MAX_USERS * WARN_CAP_PER_USER short strings.+_ADAPTIVE_FAILOPEN_WARNED: "OrderedDict[Optional[str], OrderedDict[str, None]]" = OrderedDict()+_ADAPTIVE_FAILOPEN_LOCK = threading.Lock()+# Max distinct (sanitized) primaries remembered per user; once a user's bucket+# is full we stop warning/recording for that user (memory-safe, and preserves+# the original anti-log-amplification behavior) -- but PER USER, so it never+# touches another user's audit budget.+_ADAPTIVE_FAILOPEN_WARN_CAP_PER_USER = 128+# Max distinct users tracked at once; the least-recently-seen user's whole+# bucket is LRU-evicted beyond this, keeping total memory bounded.+_ADAPTIVE_FAILOPEN_MAX_USERS = 256+++def _adaptive_failopen_user_key(username: Optional[str]) -> Optional[str]:+ """Stable, bounded-length bucket key for the per-user fail-open dedup.++ ``None`` (unauthenticated / un-threaded run) is its own bucket. A present+ username is hashed rather than stored raw: it bounds the key length+ regardless of the username, and avoids retaining plaintext identities in+ this long-lived process-global audit structure (the warning itself only+ ever emits ``username_present``, never the name).+ """+ if username is None:+ return None+ return hashlib.sha256(username.encode("utf-8")).hexdigest()[:16]+++def _should_warn_adaptive_failopen(+ sanitized_primary: str, username: Optional[str]+) -> bool:+ """True the first time this ``(user, sanitized_primary)`` pair is seen.++ Dedup is PER USER: the bucket key is a stable hash of ``username``+ (``None`` for an unauthenticated run), so a genuine fail-open for one user+ is never swallowed by an already-logged fail-open for a DIFFERENT user on+ the same primary name. Returns False for a repeat of an already-recorded+ pair, and for any NEW primary once *this* user's bucket is full (bounded,+ and only that user is affected). The set of tracked users is a bounded LRU+ -- see the ``_ADAPTIVE_FAILOPEN_WARNED`` docstring above for the+ memory-safety and cross-user-isolation rationale.+ """+ user_key = _adaptive_failopen_user_key(username)+ with _ADAPTIVE_FAILOPEN_LOCK:+ bucket = _ADAPTIVE_FAILOPEN_WARNED.get(user_key)+ if bucket is None:+ # First fail-open for this user. Enforce the users-tracked cap by+ # LRU-evicting the least-recently-seen user before inserting.+ if len(_ADAPTIVE_FAILOPEN_WARNED) >= _ADAPTIVE_FAILOPEN_MAX_USERS:+ _ADAPTIVE_FAILOPEN_WARNED.popitem(last=False)+ bucket = OrderedDict()+ _ADAPTIVE_FAILOPEN_WARNED[user_key] = bucket+ else:+ # Seen this user before -> mark most-recently-used so an active+ # user is never the one evicted by the users cap.+ _ADAPTIVE_FAILOPEN_WARNED.move_to_end(user_key)++ if sanitized_primary in bucket:+ return False+ # This user's per-user budget is full: stop warning AND recording, so+ # one user's junk-primary flood can neither grow memory nor amplify+ # logs. Bounded and scoped to this ONE user's bucket -- every other+ # user keeps their full audit budget.+ if len(bucket) >= _ADAPTIVE_FAILOPEN_WARN_CAP_PER_USER:+ return False+ bucket[sanitized_primary] = None+ return True++def _resolve_adaptive_scope(primary_engine: str,settings_snapshot: dict,@@ -1366,6 +1478,53 @@ def _resolve_adaptive_scope(if retriever_local is False:return EgressScope.PUBLIC_ONLY+ # SECURITY (detectable fail-open): the primary could not be classified+ # in ANY namespace visible here — it is not a static engine, not a+ # collection, and not a retriever resolvable for ``username``. ADAPTIVE+ # therefore resolves to the PERMISSIVE ``BOTH`` (cloud-capable) scope.+ #+ # The benign cause is a genuinely-unregistered / typo'd / removed+ # meta-engine primary. The DANGEROUS cause is a per-user PRIVATE+ # retriever that is invisible here because ``username=`` was not+ # threaded into this resolution (or the snapshot lacked ``_username``):+ # the retriever would classify as local (=> PRIVATE_ONLY, forcing local+ # inference) if its owner's namespace were consulted, but under the+ # wrong/absent username it disappears and the run silently fails open+ # to cloud-capable BOTH.+ #+ # We do NOT fail closed here: reaching this branch means classify_engine+ # returned (None, None), i.e. a *legitimately-public* primary can never+ # land here (a public engine classifies is_public=True => PUBLIC_ONLY+ # above). But we still cannot cleanly separate "benign unregistered+ # primary" from "invisible per-user retriever" without peeking across+ # other users' registry namespaces (breaking the isolation this PR+ # establishes, and misfiring PRIVATE_ONLY onto a legitimate+ # unregistered public primary that merely shares a name). Since the+ # distinction isn't clean, per the security-hardening guidance we keep+ # the non-breaking permissive behavior and make it DETECTABLE instead:+ # a missed ``username=`` threading now shows up as this WARNING rather+ # than silently permissive egress.+ # primary_engine is user-controlled (search.tool): scrub it before+ # interpolating into the log line so embedded newlines/control chars+ # can't forge additional log entries (log injection). Dedup on the+ # SANITIZED value too, per _should_warn_adaptive_failopen above, so+ # this fires at most once per unique (user, primary) pair in the+ # process rather than once per call. The dedup keys on the ACTUAL+ # username (hashed), not merely "was one present", so a genuine+ # fail-open for one user is never swallowed by another user's.+ safe_primary = sanitize_for_log(primary_engine)+ if _should_warn_adaptive_failopen(safe_primary, username):+ logger.bind(policy_audit=True).warning(+ f"ADAPTIVE egress fail-open: primary engine "+ f"'{safe_primary}' could not be classified in any visible "+ f"namespace (static engine, collection, or retriever visible to "+ f"this user); resolving PERMISSIVELY to BOTH (cloud-capable). If "+ f"'{safe_primary}' is a per-user PRIVATE retriever this is a "+ f"fail-open — verify username= is threaded into egress "+ f"resolution (username_present={username is not None})."+ )+ return EgressScope.BOTH+return EgressScope.BOTHdiff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 31042c57bc..28a78b00fc 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -907,7 +907,7 @@ def run_research_process(research_id, query, mode, **kwargs):# 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.+ # explicitly. See ensure_snapshot_username in search_system.py.# Log settings snapshot to debugfrom ...settings.logger import log_settings@@ -1375,6 +1375,14 @@ def run_research_process(research_id, query, mode, **kwargs):settings_snapshot=shared_research_context.get("settings_snapshot"),+ # Thread the run's user so the LLM PEP can resolve a+ # per-user registered provider and enforce local-only+ # policy. The shared_research_context snapshot is captured+ # before AdvancedSearchSystem injects `_username`, so+ # without this the whole overridden run (question gen,+ # summaries, final report) could fail open to a cloud LLM+ # for a user whose primary is a private retriever.+ username=username,)logger.info(@@ -2080,6 +2088,23 @@ def run_research_process(research_id, query, mode, **kwargs):from ...news.utils.topic_generator import (generate_topics,)+ from ...search_system import (+ ensure_snapshot_username,+ )++ # Scope the snapshot to this run's owner so+ # the LLM PEP resolves a per-user provider+ # and honors local-only policy, mirroring+ # the scheduler's _store_research_result fix+ # (background.py). Without it, headline/topic+ # generation silently no-ops for cloud-+ # provider users here (fails closed, not a+ # security hole, but inconsistent).+ headline_topic_snapshot = (+ ensure_snapshot_username(+ settings_snapshot, username+ )+ )# Get the report content from database for better headline/topic generationreport_content = ""@@ -2108,7 +2133,9 @@ def run_research_process(research_id, query, mode, **kwargs):f"Generating headline for query: {query[:100]}")headline = generate_headline(- query, report_content+ query,+ report_content,+ settings_snapshot=headline_topic_snapshot,)metadata["generated_headline"] = headline@@ -2121,6 +2148,7 @@ def run_research_process(research_id, query, mode, **kwargs):findings=report_content,category=metadata.get("category", "News"),max_topics=6,+ settings_snapshot=headline_topic_snapshot,)metadata["generated_topics"] = topics@@ -2383,6 +2411,18 @@ def run_research_process(research_id, query, mode, **kwargs):from ...news.utils.topic_generator import (generate_topics, # type: ignore[no-redef])+ from ...search_system import (+ ensure_snapshot_username,+ )++ # Scope the snapshot to this run's owner so the LLM+ # PEP resolves a per-user provider and honors+ # local-only policy. Mirrors the quick-summary+ # branch above and the scheduler's+ # _store_research_result fix (background.py).+ headline_topic_snapshot = ensure_snapshot_username(+ settings_snapshot, username+ )# Get the report content from database for better headline/topic generationreport_content = ""@@ -2404,7 +2444,11 @@ def run_research_process(research_id, query, mode, **kwargs):)# Generate headline- headline = generate_headline(query, report_content)+ headline = generate_headline(+ query,+ report_content,+ settings_snapshot=headline_topic_snapshot,+ )metadata["generated_headline"] = headline# Generate topics@@ -2413,6 +2457,7 @@ def run_research_process(research_id, query, mode, **kwargs):findings=report_content,category=metadata.get("category", "News"),max_topics=6,+ settings_snapshot=headline_topic_snapshot,)metadata["generated_topics"] = topicsdiff --git a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.pyindex fb108e5015..312eebaf00 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py@@ -53,6 +53,7 @@ class ElasticsearchSearchEngine(BaseSearchEngine):context_from_snapshot,)from ...config.thread_settings import get_setting_from_snapshot+ from ...search_system import username_from_snapshotsnapshot = settings_snapshot or {}primary = (@@ -63,7 +64,9 @@ class ElasticsearchSearchEngine(BaseSearchEngine):)or DEFAULT_SEARCH_TOOL)- ctx = context_from_snapshot(snapshot, primary)+ ctx = context_from_snapshot(+ snapshot, primary, username=username_from_snapshot(snapshot)+ )return ctx.scope in (EgressScope.PRIVATE_ONLY,EgressScope.STRICT,diff --git a/src/local_deep_research/web_search_engines/retriever_registry.py b/src/local_deep_research/web_search_engines/retriever_registry.pyindex bc443cb679..36e59b20de 100644--- a/src/local_deep_research/web_search_engines/retriever_registry.py+++ b/src/local_deep_research/web_search_engines/retriever_registry.py@@ -8,6 +8,13 @@ from typing import Dict, Optionalfrom langchain_core.retrievers import BaseRetrieverfrom ..security.secure_logging import logger+# Sentinel key for the shared/global namespace. Retrievers registered+# without a username (SDK, MCP, benchmarks, legacy internal callers) live+# here and remain visible to everyone, preserving the historic single-+# namespace behavior. Per-user registrations live under their username so+# one user can neither shadow nor see another user's retrievers.+_SHARED_NAMESPACE: Optional[str] = None+class RetrieverRegistry:"""@@ -15,22 +22,41 @@ class RetrieverRegistry:This allows users to register retrievers programmatically and use themas search engines within LDR.++ Entries are keyed per user: a registration made with a ``username`` is+ stored in that user's namespace, and a registration made without one+ goes to a shared namespace. Reads resolve the caller's own namespace+ first and fall back to the shared namespace, so a user's registration+ can never shadow or leak into another user's engine list."""def __init__(self):- self._retrievers: Dict[str, BaseRetriever] = {}- # Parallel map of name -> classification metadata, e.g.+ # {namespace: {name: retriever}}. ``namespace`` is a username or+ # ``_SHARED_NAMESPACE`` for shared/global entries.+ self._retrievers: Dict[Optional[str], Dict[str, BaseRetriever]] = {}+ # Parallel {namespace: {name: metadata}} map, e.g.# {"is_local": True}. Kept separate from _retrievers so get()# keeps returning the bare retriever object (callers + tests# depend on `get() is retriever`).- self._metadata: Dict[str, dict] = {}+ self._metadata: Dict[Optional[str], Dict[str, dict]] = {}self._lock = Lock()+ @staticmethod+ def _ns(username: Optional[str]) -> Optional[str]:+ """Normalize a username to a namespace key.++ A falsy username (``None`` / empty string) maps to the shared+ namespace so legacy/global callers keep a single shared namespace+ and never crash for want of a username.+ """+ return username or _SHARED_NAMESPACE+def register(self,name: str,retriever: BaseRetriever,is_local: bool = True,+ username: Optional[str] = None,) -> None:"""Register a retriever with a given name.@@ -44,10 +70,23 @@ class RetrieverRegistry:registered retrievers are almost always private corpora;the egress policy uses this to decide whether theretriever may run under PUBLIC_ONLY / PRIVATE_ONLY scopes.+ username: Owner of the registration. When omitted the entry is+ stored in the shared namespace (visible to all callers).++ Raises:+ ValueError: ``retriever`` is None. A stored ``None`` would+ silently miss in ``get()``'s ``found is not None`` check and+ fall through to the shared namespace, letting a+ misregistered entry resolve to an unrelated retriever."""+ if retriever is None:+ raise ValueError(+ f"Cannot register retriever '{name}': value is None"+ )+ ns = self._ns(username)with self._lock:- self._retrievers[name] = retriever- self._metadata[name] = {"is_local": is_local}+ self._retrievers.setdefault(ns, {})[name] = retriever+ self._metadata.setdefault(ns, {})[name] = {"is_local": is_local}logger.info(f"Registered retriever '{name}' of type {type(retriever).__name__} "f"(is_local={is_local})"@@ -57,6 +96,7 @@ class RetrieverRegistry:self,retrievers: Dict[str, "BaseRetriever | dict"],is_local: bool = True,+ username: Optional[str] = None,) -> None:"""Register multiple retrievers at once.@@ -76,83 +116,149 @@ class RetrieverRegistry:retriever MUST use the dict shape with``is_local=False`` or they will egress underPRIVATE_ONLY (silent classification lie).+ username: Owner of the registrations. When omitted the+ entries are stored in the shared namespace.++ Raises:+ ValueError: an entry resolves to a None retriever (bare shape+ ``{name: None}`` or dict shape with a missing/None+ ``"retriever"`` key). A stored ``None`` would silently miss+ in ``get()``'s ``found is not None`` check and fall through+ to the shared namespace — see ``register``'s docstring."""+ ns = self._ns(username)+ # Two-pass so the batch is atomic: validate every entry (resolving+ # its retriever + is_local) BEFORE mutating any state, so a None+ # value raises without leaving a partially-registered batch behind.+ validated = []+ for name, entry in retrievers.items():+ if isinstance(entry, dict):+ retriever = entry.get("retriever")+ entry_is_local = bool(entry.get("is_local", is_local))+ else:+ retriever = entry+ entry_is_local = is_local+ if retriever is None:+ raise ValueError(+ f"Cannot register retriever '{name}': value is None"+ )+ validated.append((name, retriever, entry_is_local))with self._lock:- for name, entry in retrievers.items():- if isinstance(entry, dict):- retriever = entry.get("retriever")- entry_is_local = bool(entry.get("is_local", is_local))- else:- retriever = entry- entry_is_local = is_local- if retriever is None:- logger.warning(- f"Retriever entry '{name}' has no retriever — skipped"- )- continue- self._retrievers[name] = retriever- self._metadata[name] = {"is_local": entry_is_local}+ bucket = self._retrievers.setdefault(ns, {})+ meta_bucket = self._metadata.setdefault(ns, {})+ for name, retriever, entry_is_local in validated:+ bucket[name] = retriever+ meta_bucket[name] = {"is_local": entry_is_local}logger.info(f"Registered retriever '{name}' of type {type(retriever).__name__} "f"(is_local={entry_is_local})")- def get(self, name: str) -> Optional[BaseRetriever]:+ def get(+ self, name: str, username: Optional[str] = None+ ) -> Optional[BaseRetriever]:"""Get a registered retriever by name.+ Resolution order: the caller's own namespace, then the shared+ namespace. A user's registration never resolves for another user.+Args:name: Name of the retriever+ username: Requesting user (None resolves the shared namespace only)Returns:The retriever if found, None otherwise"""+ ns = self._ns(username)with self._lock:- return self._retrievers.get(name)+ if ns is not _SHARED_NAMESPACE:+ found = self._retrievers.get(ns, {}).get(name)+ if found is not None:+ return found+ return self._retrievers.get(_SHARED_NAMESPACE, {}).get(name)- def unregister(self, name: str) -> None:+ def unregister(self, name: str, username: Optional[str] = None) -> None:"""- Remove a registered retriever.+ Remove a registered retriever from the given user's namespace.Args:name: Name of the retriever to remove+ username: Owner namespace to remove from (None = shared)"""+ ns = self._ns(username)with self._lock:- if name in self._retrievers:- del self._retrievers[name]- self._metadata.pop(name, None)+ bucket = self._retrievers.get(ns)+ if bucket and name in bucket:+ del bucket[name]+ self._metadata.get(ns, {}).pop(name, None)logger.info(f"Unregistered retriever '{name}'")- def clear(self) -> None:- """Clear all registered retrievers."""+ def clear(self, username: Optional[str] = None) -> None:+ """Clear registered retrievers.++ With no ``username`` every namespace is cleared (used by test+ isolation fixtures to reset all global state). With a ``username``+ only that user's namespace is cleared.+ """+ # TODO: hook clear(username=<deleted user>) into a user-deletion+ # flow so a removed user's registered retrievers are evicted from+ # this in-process registry. No user-deletion hook exists yet, so+ # eviction-on-deletion is out of scope here; this is the seam.with self._lock:- count = len(self._retrievers)- self._retrievers.clear()- self._metadata.clear()+ if username is None:+ count = sum(len(bucket) for bucket in self._retrievers.values())+ self._retrievers.clear()+ self._metadata.clear()+ else:+ ns = self._ns(username)+ count = len(self._retrievers.get(ns, {}))+ self._retrievers.pop(ns, None)+ self._metadata.pop(ns, None)logger.info(f"Cleared {count} registered retrievers")- def is_registered(self, name: str) -> bool:+ def is_registered(self, name: str, username: Optional[str] = None) -> bool:"""- Check if a retriever is registered.+ Check if a retriever is registered and resolvable for the caller.Args:name: Name of the retriever+ username: Requesting user (None resolves the shared namespace only)Returns:True if registered, False otherwise"""- with self._lock:- return name in self._retrievers+ return self.get(name, username=username) is not None- def list_registered(self) -> list[str]:+ def list_registered(self, username: Optional[str] = None) -> list[str]:"""- Get list of all registered retriever names.+ Get list of retriever names visible to the caller.++ Returns the caller's own registrations plus shared ones; never+ another user's names.++ Order is DETERMINISTIC: the caller's own entries first (insertion+ order), then shared entries not shadowed by an own-namespace name.+ This mirrors ``get()``'s own-namespace-first resolution (a same-named+ own entry shadows the shared one, so it is listed once, under own) and+ replaces the previous ``set``-union, whose ``list(set(...))`` order was+ nondeterministic run to run.++ Args:+ username: Requesting user (None lists the shared namespace only)Returns:List of retriever names"""+ ns = self._ns(username)with self._lock:- return list(self._retrievers.keys())+ shared = self._retrievers.get(_SHARED_NAMESPACE, {})+ if ns is _SHARED_NAMESPACE:+ return list(shared.keys())+ own = self._retrievers.get(ns, {})+ return list(own.keys()) + [+ name for name in shared if name not in own+ ]def get_metadata(self, name: str, username: Optional[str] = None@@ -168,14 +274,22 @@ class RetrieverRegistry:The egress policy's ``evaluate_retriever`` consults this hook todecide whether a retriever may run under the active scope.- ``username`` is accepted so future per-user retriever isolation- can plug in without changing the call sites.+ ``username`` scopes the lookup the same way ``get`` does: the+ caller's own namespace first, then the shared namespace, so a+ user's classification is never read for another user."""+ ns = self._ns(username)with self._lock:- if name not in self._retrievers:- return None- # Copy so callers can't mutate the stored classification.- return dict(self._metadata.get(name, {}))+ if ns is not _SHARED_NAMESPACE and name in self._retrievers.get(+ ns, {}+ ):+ # Copy so callers can't mutate the stored classification.+ return dict(self._metadata.get(ns, {}).get(name, {}))+ if name in self._retrievers.get(_SHARED_NAMESPACE, {}):+ return dict(+ self._metadata.get(_SHARED_NAMESPACE, {}).get(name, {})+ )+ return None# Global registry instancediff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.pyindex 4a43612a98..63f8cf4ba3 100644--- a/src/local_deep_research/web_search_engines/search_engine_base.py+++ b/src/local_deep_research/web_search_engines/search_engine_base.py@@ -584,6 +584,7 @@ class BaseSearchEngine(ABC):context_from_snapshot,evaluate_engine,)+ from ..search_system import username_from_snapshotprimary = unwrap_setting(self.settings_snapshot.get("search.tool", self._engine_name)@@ -591,7 +592,7 @@ class BaseSearchEngine(ABC):ctx = context_from_snapshot(self.settings_snapshot,primary or self._engine_name,- username=self.settings_snapshot.get("_username"),+ username=username_from_snapshot(self.settings_snapshot),)decision = evaluate_engine(self._engine_name,@@ -1175,12 +1176,20 @@ class BaseSearchEngine(ABC):)return None+ from ..search_system import username_from_snapshot+primary_raw = unwrap_setting(self.settings_snapshot.get("search.tool", DEFAULT_SEARCH_TOOL))try:+ # Thread username so a per-user private retriever primary+ # resolves PRIVATE_ONLY here too; otherwise the per-URL fetch+ # gate would fall back to BOTH and allow public hosts under a+ # run whose posture is private.return context_from_snapshot(- self.settings_snapshot, primary_raw or DEFAULT_SEARCH_TOOL+ self.settings_snapshot,+ primary_raw or DEFAULT_SEARCH_TOOL,+ username=username_from_snapshot(self.settings_snapshot),)except (PolicyDeniedError, ValueError) as exc:safe_msg = self._scrub_error(exc)diff --git a/src/local_deep_research/web_search_engines/search_engine_factory.py b/src/local_deep_research/web_search_engines/search_engine_factory.pyindex 2517c061ab..f9ca929e9c 100644--- a/src/local_deep_research/web_search_engines/search_engine_factory.py+++ b/src/local_deep_research/web_search_engines/search_engine_factory.py@@ -35,13 +35,23 @@ def create_search_engine(f"create_search_engine called with engine_name={engine_name} (type: {type(engine_name)})")+ # Resolve the effective username for per-user registry lookups. Callers+ # that thread it explicitly win; otherwise fall back to the ``_username``+ # carried in the settings snapshot (injected by search_config.get_search /+ # AdvancedSearchSystem). None resolves the shared namespace only.+ if username is None:+ from ..search_system import username_from_snapshot++ username = username_from_snapshot(settings_snapshot)+# Egress policy PEP runs AFTER retriever-registry + config lookup, so# registered retrievers don't go through engine-name classification.# The actual call site is right before engine instantiation, further# down.- # Check if this is a registered retriever first- retriever = retriever_registry.get(engine_name)+ # Check if this is a registered retriever first (the caller's own+ # retrievers resolve before shared/global ones).+ retriever = retriever_registry.get(engine_name, username=username)if retriever:# Egress policy: gate the retriever against the active scope.# Retrievers are classified at registration (is_local, defaultdiff --git a/src/local_deep_research/web_search_engines/search_engines_config.py b/src/local_deep_research/web_search_engines/search_engines_config.pyindex 7f00d48caa..fa583a0ac1 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@@ -105,7 +105,10 @@ def search_config(Returns the search engine configuration loaded from the database or settings snapshot.Args:- username: Username for backward compatibility (deprecated)+ username: Username used to scope the per-user retriever listing+ (own registrations plus shared ones) so one user's retrievers+ never leak into another user's engine list. Falls back to the+ ``_username`` carried in ``settings_snapshot`` when omitted.db_session: Database session for direct access (preferred for web routes)settings_snapshot: Settings snapshot for thread context (preferred for background threads)@@ -140,10 +143,17 @@ def search_config(entry.full_search_class)- # Add registered retrievers as available search engines+ # Add registered retrievers as available search engines. Scope the+ # listing to the requesting user (their own registrations plus shared+ # ones) so one user's retriever names/metadata never leak into another+ # user's engine list. Prefer an explicit username, else the ``_username``+ # carried in the snapshot; None lists shared retrievers only.+ from ..search_system import username_from_snapshot++ effective_username = username or username_from_snapshot(settings_snapshot)from .retriever_registry import retriever_registry- for name in retriever_registry.list_registered():+ for name in retriever_registry.list_registered(username=effective_username):search_engines[name] = {"module_path": ".engines.search_engine_retriever","class_name": "RetrieverSearchEngine",@@ -200,10 +210,11 @@ def search_config(try:from ..database.models.library import Collectionfrom ..database.session_context import get_user_db_session+ from ..search_system import username_from_snapshot# Get username from settings_snapshot if availablecollection_username = (- settings_snapshot.get("_username")+ username_from_snapshot(settings_snapshot)if settings_snapshotelse username)@@ -383,7 +394,10 @@ def list_eligible_engine_configs(try:from .retriever_registry import retriever_registry- meta = retriever_registry.get_metadata(name)+ meta = retriever_registry.get_metadata(+ name,+ username=getattr(egress_context, "username", None),+ )except Exception:meta = Nonedecision = evaluate_retriever(diff --git a/tests/api/test_research_api.py b/tests/api/test_research_api.pyindex 1a3dca9c84..375b21563b 100644--- a/tests/api/test_research_api.py+++ b/tests/api/test_research_api.py@@ -214,7 +214,9 @@ class TestInitSearchSystem:retrievers = {"custom": MagicMock()}_init_search_system(retrievers=retrievers)- mock_registry.register_multiple.assert_called_once_with(retrievers)+ mock_registry.register_multiple.assert_called_once_with(+ retrievers, username=None+ )@patch("local_deep_research.api.research_functions.get_llm")@patch("local_deep_research.api.research_functions.AdvancedSearchSystem")@@ -236,7 +238,9 @@ class TestInitSearchSystem:llms = {"custom_llm": custom_llm}_init_search_system(llms=llms)- mock_register_llm.assert_called_once_with("custom_llm", custom_llm)+ mock_register_llm.assert_called_once_with(+ "custom_llm", custom_llm, username=None+ )class TestQuickSummary:@@ -326,7 +330,9 @@ class TestQuickSummary:quick_summary("Query", retrievers=retrievers)# Retrievers are registered with the registry, not passed to _init_search_system- mock_registry.register_multiple.assert_called_once_with(retrievers)+ mock_registry.register_multiple.assert_called_once_with(+ retrievers, username=None+ )@patch("local_deep_research.api.research_functions._init_search_system")def test_quick_summary_with_research_id(self, mock_init_system):diff --git a/tests/api/test_research_functions.py b/tests/api/test_research_functions.pyindex cd83963157..1054d7f6e2 100644--- a/tests/api/test_research_functions.py+++ b/tests/api/test_research_functions.py@@ -130,8 +130,9 @@ class TestInitSearchSystem:) as mock_registry,):_init_search_system(retrievers={"custom": retriever})+ # Registrations are scoped to the calling user (None here).mock_registry.register_multiple.assert_called_once_with(- {"custom": retriever}+ {"custom": retriever}, username=None)def test_registers_llms(self, mock_get_llm, mock_get_search):@@ -144,7 +145,10 @@ class TestInitSearchSystem:patch("local_deep_research.llm.register_llm") as mock_register,):_init_search_system(llms={"custom_llm": custom_llm})- mock_register.assert_called_once_with("custom_llm", custom_llm)+ # Registrations are scoped to the calling user (None here).+ mock_register.assert_called_once_with(+ "custom_llm", custom_llm, username=None+ )def test_uses_settings_snapshot(self, mock_get_llm, mock_get_search, sample_settings_snapshotdiff --git a/tests/chat/test_chat_settings_integration.py b/tests/chat/test_chat_settings_integration.pyindex f3585294ce..96c191121e 100644--- a/tests/chat/test_chat_settings_integration.py+++ b/tests/chat/test_chat_settings_integration.py@@ -39,7 +39,12 @@ class TestLoadSettingsHelper:mock_manager_cls.assert_called_once_with(db_session=mock_db)mock_manager.get_all_settings.assert_called_once_with(bypass_cache=True)- assert snapshot == {"llm.provider": {"value": "ollama"}}+ # _load_settings injects the username so snapshot-driven consumers+ # (get_llm, egress-scope resolution) resolve it — see the fail-open fix.+ assert snapshot == {+ "llm.provider": {"value": "ollama"},+ "_username": "alice",+ }def test_load_settings_returns_independent_snapshot_per_call(self):"""Each ``_load_settings`` call returns the dict from thediff --git a/tests/core/test_search_system_username_injection.py b/tests/core/test_search_system_username_injection.pyindex 8c02357dae..bcf2ea41b1 100644--- a/tests/core/test_search_system_username_injection.py+++ b/tests/core/test_search_system_username_injection.py@@ -14,7 +14,8 @@ from unittest.mock import Mock, patchfrom local_deep_research.search_system import (AdvancedSearchSystem,- _ensure_snapshot_username,+ ensure_snapshot_username,+ username_from_snapshot,)@@ -23,39 +24,60 @@ class TestEnsureSnapshotUsername:def test_injects_username_when_missing(self):snap = {"search.tool": "collection_abc"}- result = _ensure_snapshot_username(snap, "alice")+ 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")+ result = ensure_snapshot_username(snap, "alice")assert "_username" not in snap # original untouchedassert result is not snapdef test_preserves_existing_username(self):snap = {"_username": "already", "search.tool": "x"}- result = _ensure_snapshot_username(snap, "alice")+ result = ensure_snapshot_username(snap, "alice")# An explicit value is never overwritten, and no copy is made.assert result is snapassert result["_username"] == "already"def test_noop_when_username_none(self):snap = {"search.tool": "x"}- result = _ensure_snapshot_username(snap, None)+ result = ensure_snapshot_username(snap, None)assert result is snapassert "_username" not in resultdef test_noop_when_username_empty_string(self):snap = {"search.tool": "x"}- result = _ensure_snapshot_username(snap, "")+ result = ensure_snapshot_username(snap, "")assert result is snapassert "_username" not in resultdef 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+ assert ensure_snapshot_username(None, "alice") is None+++class TestUsernameFromSnapshot:+ """Unit contract of the centralized reader (mirror of the writer above)."""++ def test_reads_injected_username(self):+ assert username_from_snapshot({"_username": "alice"}) == "alice"++ def test_returns_none_when_key_absent(self):+ assert username_from_snapshot({"search.tool": "x"}) is None++ def test_returns_none_for_non_dict(self):+ # The isinstance guard must hold uniformly: None and other non-dicts+ # never raise, they read as "no username" (shared namespace).+ assert username_from_snapshot(None) is None+ assert username_from_snapshot("not-a-dict") is None+ assert username_from_snapshot(42) is None++ def test_roundtrips_with_ensure_snapshot_username(self):+ snap = ensure_snapshot_username({"search.tool": "x"}, "bob")+ assert username_from_snapshot(snap) == "bob"class TestAdvancedSearchSystemInjectsUsername:diff --git a/tests/domain_classifier/test_classifier.py b/tests/domain_classifier/test_classifier.pyindex 38fb731657..87be2f7c89 100644--- a/tests/domain_classifier/test_classifier.py+++ b/tests/domain_classifier/test_classifier.py@@ -93,7 +93,12 @@ class TestGetLlm:assert result is mock_llmdef test_passes_settings_snapshot(self):- """Should pass settings snapshot to get_llm."""+ """Should pass settings snapshot AND the owning username to get_llm.++ The username scopes the LLM PEP to this user so a classify request+ built from a bare (``_username``-less) route snapshot still forces+ local-only when the user's primary is a private retriever.+ """snapshot = {"key": "value"}classifier = DomainClassifier(username="testuser", settings_snapshot=snapshot@@ -104,7 +109,9 @@ class TestGetLlm:) as mock_get:classifier._get_llm()- mock_get.assert_called_once_with(settings_snapshot=snapshot)+ mock_get.assert_called_once_with(+ settings_snapshot=snapshot, username="testuser"+ )class TestBuildClassificationPrompt:diff --git a/tests/security/test_egress_adaptive_resolution_followup.py b/tests/security/test_egress_adaptive_resolution_followup.pyindex 5aa36114e2..eec8b99c4f 100644--- a/tests/security/test_egress_adaptive_resolution_followup.py+++ b/tests/security/test_egress_adaptive_resolution_followup.py@@ -20,9 +20,11 @@ These cover gaps not already exercised byfrom __future__ import annotations+from contextlib import contextmanagerfrom unittest.mock import MagicMock, patchimport pytest+from loguru import loggerfrom local_deep_research.security.egress.policy import (EgressScope,@@ -35,6 +37,30 @@ from local_deep_research.web_search_engines.retriever_registry import ()+@contextmanager+def _capture_policy_warnings():+ """Capture WARNING-level loguru records emitted by the package.++ The package disables its own loguru namespace in ``__init__`` (so audit+ warnings don't spam host apps); enable it here and add a sink so the+ fail-open warning actually reaches us. Restore both in ``finally``.+ """+ records: list[dict] = []+ logger.enable("local_deep_research")+ sink_id = logger.add(lambda m: records.append(m.record), level="WARNING")+ try:+ yield records+ finally:+ logger.remove(sink_id)+ logger.disable("local_deep_research")+++# Distinctive phrase carried by the ADAPTIVE unclassifiable-primary fail-open+# warning in ``_resolve_adaptive_scope`` — pinned so the tests below key off+# the exact security signal, not incidental log lines.+_FAILOPEN_PHRASE = "could not be classified"++def _adaptive_snapshot(tool: str, **extra) -> dict:"""Nested-value snapshot selecting ADAPTIVE scope with the given tool."""snap = {@@ -199,6 +225,360 @@ def test_resolve_adaptive_unknown_primary_falls_back_to_both():assert ctx.require_local_embeddings is False+# ---------------------------------------------------------------------------+# ADAPTIVE: the unclassifiable-primary fail-open must be DETECTABLE (a WARNING+# names the primary + whether a username was present) so a missed ``username=``+# threading surfaces in logs instead of resolving silently to permissive BOTH.+# ---------------------------------------------------------------------------+++def test_resolve_adaptive_unclassifiable_primary_emits_failopen_warning():+ """An unclassifiable primary (not a static engine, collection, or a+ retriever visible for this user) resolves to the permissive BOTH AND emits+ a policy-audit WARNING naming the primary and reporting username presence.+ """+ name = "_adaptive_followup_failopen_unknown_primary"+ assert retriever_registry.get_metadata(name) is None+ with _capture_policy_warnings() as records:+ scope = _resolve_adaptive_scope(+ name, {}, username=None, local_hostnames=()+ )+ assert scope == EgressScope.BOTH+ failopen = [+ r+ for r in records+ if r["extra"].get("policy_audit") and _FAILOPEN_PHRASE in r["message"]+ ]+ assert failopen, (+ "expected a policy-audit fail-open WARNING for the unclassifiable "+ f"primary; got {[r['message'] for r in records]}"+ )+ msg = failopen[0]["message"]+ # Diagnostic context: the primary name and the username-present flag must+ # both ride on the message so a triager can spot a missed username thread.+ assert name in msg+ assert "username_present=False" in msg+++def test_resolve_adaptive_unclassifiable_primary_reports_username_present():+ """When a username IS threaded but the primary is still unclassifiable, the+ warning reports ``username_present=True`` (so the diagnosis distinguishes a+ missed-thread from a genuinely-unregistered primary)."""+ name = "_adaptive_followup_failopen_with_username"+ assert retriever_registry.get_metadata(name, username="alice") is None+ with _capture_policy_warnings() as records:+ scope = _resolve_adaptive_scope(+ name, {}, username="alice", local_hostnames=()+ )+ assert scope == EgressScope.BOTH+ failopen = [+ r+ for r in records+ if r["extra"].get("policy_audit") and _FAILOPEN_PHRASE in r["message"]+ ]+ assert failopen+ assert "username_present=True" in failopen[0]["message"]+++def test_resolve_adaptive_classified_public_primary_does_not_warn():+ """A normally-classified PUBLIC primary resolves to PUBLIC_ONLY and must NOT+ emit the unclassifiable fail-open warning (a public engine never lands in+ the None/None branch)."""+ with _capture_policy_warnings() as records:+ scope = _resolve_adaptive_scope(+ "arxiv", {}, username=None, local_hostnames=()+ )+ assert scope == EgressScope.PUBLIC_ONLY+ assert not [r for r in records if _FAILOPEN_PHRASE in r["message"]]+++def test_resolve_adaptive_classified_private_retriever_does_not_warn():+ """A registered LOCAL retriever primary resolves to PRIVATE_ONLY via the+ registry path and must NOT emit the fail-open warning (it IS classified)."""+ name = "_adaptive_followup_classified_local_kb"+ retriever_registry.register(name, MagicMock(), is_local=True)+ try:+ with _capture_policy_warnings() as records:+ scope = _resolve_adaptive_scope(+ name, {}, username=None, local_hostnames=()+ )+ assert scope == EgressScope.PRIVATE_ONLY+ assert not [r for r in records if _FAILOPEN_PHRASE in r["message"]]+ finally:+ retriever_registry.unregister(name)+++# ---------------------------------------------------------------------------+# The fail-open warning must be DEDUPED (log-spam guard): context_from_snapshot+# fires on every research-run start AND on every per-URL fetch-gate check+# (BaseSearchEngine._build_full_search_egress_context is called once per+# fetched URL), so an unclassifiable primary would otherwise emit one+# identical WARNING per fetched URL. It must fire at most once per unique+# (primary, username-presence) pair in the process, and must scrub a+# log-injection payload embedded in the (user-controlled) primary name.+# ---------------------------------------------------------------------------+++def test_resolve_adaptive_unclassifiable_primary_warning_deduped_on_repeat():+ """Calling _resolve_adaptive_scope repeatedly with the SAME unclassifiable+ primary + username combo must emit the fail-open WARNING only ONCE, not+ once per call — this is the log-spam fix for the per-URL fetch gate."""+ name = "_adaptive_followup_dedup_repeat_primary"+ assert retriever_registry.get_metadata(name) is None+ with _capture_policy_warnings() as records:+ for _ in range(5):+ scope = _resolve_adaptive_scope(+ name, {}, username=None, local_hostnames=()+ )+ assert scope == EgressScope.BOTH+ failopen = [+ r+ for r in records+ if r["extra"].get("policy_audit") and _FAILOPEN_PHRASE in r["message"]+ ]+ assert len(failopen) == 1, (+ f"expected exactly one deduped fail-open WARNING across 5 identical "+ f"calls, got {len(failopen)}: {[r['message'] for r in failopen]}"+ )+++def test_resolve_adaptive_unclassifiable_primary_warning_not_deduped_across_distinct_keys():+ """A different primary — or the same primary with a different+ username-presence — is a NEW dedup key and must still warn."""+ name_a = "_adaptive_followup_dedup_distinct_a"+ name_b = "_adaptive_followup_dedup_distinct_b"+ assert retriever_registry.get_metadata(name_a) is None+ assert retriever_registry.get_metadata(name_b, username="carol") is None+ with _capture_policy_warnings() as records:+ _resolve_adaptive_scope(name_a, {}, username=None, local_hostnames=())+ # Same name, but WITH a username -> distinct key -> warns again.+ _resolve_adaptive_scope(+ name_a, {}, username="carol", local_hostnames=()+ )+ # A different primary name -> distinct key -> warns again.+ _resolve_adaptive_scope(+ name_b, {}, username="carol", local_hostnames=()+ )+ failopen = [+ r+ for r in records+ if r["extra"].get("policy_audit") and _FAILOPEN_PHRASE in r["message"]+ ]+ assert len(failopen) == 3+++def test_resolve_adaptive_primary_engine_newline_scrubbed_in_warning():+ """A ``primary_engine`` value containing a newline (log-injection payload+ forging a fake subsequent log line) must be scrubbed before it reaches+ the emitted log record — the raw newline must not appear in the message."""+ injected = (+ "_adaptive_followup_injected_primary\n"+ "FAKE LOG LINE: policy_audit=True level=CRITICAL forged-entry"+ )+ assert retriever_registry.get_metadata(injected) is None+ with _capture_policy_warnings() as records:+ scope = _resolve_adaptive_scope(+ injected, {}, username=None, local_hostnames=()+ )+ assert scope == EgressScope.BOTH+ failopen = [+ r+ for r in records+ if r["extra"].get("policy_audit") and _FAILOPEN_PHRASE in r["message"]+ ]+ assert failopen, "expected the fail-open warning to fire for this key"+ msg = failopen[0]["message"]+ # The raw newline must be gone (control chars stripped by the sanitizer).+ assert "\n" not in msg+ # The forged "log line" text must not appear verbatim either — stripping+ # the newline alone already breaks the injection, but assert the intent+ # explicitly: the sanitized primary is still identifiable in the message.+ assert "_adaptive_followup_injected_primary" in msg+++@contextmanager+def _fresh_failopen_state():+ """Swap the module's per-user fail-open dedup state for empty structures.++ Restores the originals on exit so tests don't leak dedup state into each+ other (the structure is a process-global).+ """+ import threading as _threading+ from collections import OrderedDict as _OrderedDict++ from local_deep_research.security.egress import policy as policy_module++ with (+ patch.object(+ policy_module, "_ADAPTIVE_FAILOPEN_WARNED", _OrderedDict()+ ),+ patch.object(+ policy_module, "_ADAPTIVE_FAILOPEN_LOCK", _threading.Lock()+ ),+ ):+ yield policy_module+++def test_should_warn_adaptive_failopen_per_user_cap_is_bounded():+ """Each user's bucket is capped: once full, new primaries for THAT user are+ neither recorded nor warned (memory-safe, anti-log-amplification), since+ ``primary_engine`` is user-controlled. The cap is PER USER, so it never+ touches another user's audit budget."""+ with _fresh_failopen_state() as policy_module:+ with patch.object(+ policy_module, "_ADAPTIVE_FAILOPEN_WARN_CAP_PER_USER", 2+ ):+ assert (+ policy_module._should_warn_adaptive_failopen("k1", "alice")+ is True+ )+ assert (+ policy_module._should_warn_adaptive_failopen("k2", "alice")+ is True+ )+ # alice's bucket (cap 2) is full: a brand-new primary is refused+ # and NOT recorded.+ assert (+ policy_module._should_warn_adaptive_failopen("k3", "alice")+ is False+ )+ alice_key = policy_module._adaptive_failopen_user_key("alice")+ assert len(policy_module._ADAPTIVE_FAILOPEN_WARNED[alice_key]) == 2+ assert (+ "k3" not in policy_module._ADAPTIVE_FAILOPEN_WARNED[alice_key]+ )+ # A repeat of an already-recorded pair still reports False+ # (already warned), distinct from the cap-exhausted case.+ assert (+ policy_module._should_warn_adaptive_failopen("k1", "alice")+ is False+ )+ # A DIFFERENT user is unaffected by alice exhausting her bucket:+ # bob still warns on the very same primary names.+ assert (+ policy_module._should_warn_adaptive_failopen("k1", "bob")+ is True+ )+ assert (+ policy_module._should_warn_adaptive_failopen("k3", "bob")+ is True+ )+++def test_should_warn_adaptive_failopen_one_user_cannot_suppress_another():+ """The core audit-control fix: user B's genuine fail-open on a primary+ name ALREADY logged for user A must still warn (identity is in the key),+ and B flooding their own bucket to the cap must NOT silence A."""+ with _fresh_failopen_state() as policy_module:+ with patch.object(+ policy_module, "_ADAPTIVE_FAILOPEN_WARN_CAP_PER_USER", 4+ ):+ shared_primary = "some_private_kb"+ # User A logs the fail-open for the shared primary name.+ assert (+ policy_module._should_warn_adaptive_failopen(+ shared_primary, "alice"+ )+ is True+ )+ # User B floods their OWN bucket full with junk primaries (the+ # old global-set attack). This must not consume A's budget.+ for i in range(10):+ policy_module._should_warn_adaptive_failopen(f"junk-{i}", "bob")+ # B's genuine fail-open on the SAME primary A already logged still+ # warns -- it is a distinct (user, primary) pair. Under the old+ # presence-only key this was silently deduped.+ assert (+ policy_module._should_warn_adaptive_failopen(+ shared_primary, "bob"+ )+ is False # bob's bucket already full of junk -> suppressed+ )+ # ...but a THIRD user, carol, whose bucket is untouched, still+ # warns on the shared primary: no cross-user suppression.+ assert (+ policy_module._should_warn_adaptive_failopen(+ shared_primary, "carol"+ )+ is True+ )+ # And A can still warn on a brand-new primary of their own -- B's+ # flood never touched A's bucket.+ assert (+ policy_module._should_warn_adaptive_failopen(+ "another_primary", "alice"+ )+ is True+ )+++def test_should_warn_adaptive_failopen_users_dimension_is_bounded_lru():+ """The set of tracked users is a bounded LRU: beyond the users cap the+ least-recently-seen user's whole bucket is evicted, keeping total memory+ bounded. Eviction can only ever re-enable a warning, never suppress one."""+ with _fresh_failopen_state() as policy_module:+ with patch.object(policy_module, "_ADAPTIVE_FAILOPEN_MAX_USERS", 2):+ assert (+ policy_module._should_warn_adaptive_failopen("p", "u1") is True+ )+ assert (+ policy_module._should_warn_adaptive_failopen("p", "u2") is True+ )+ # Third distinct user -> evicts the least-recently-seen (u1).+ assert (+ policy_module._should_warn_adaptive_failopen("p", "u3") is True+ )+ assert len(policy_module._ADAPTIVE_FAILOPEN_WARNED) == 2+ u1_key = policy_module._adaptive_failopen_user_key("u1")+ assert u1_key not in policy_module._ADAPTIVE_FAILOPEN_WARNED+ # u1 was evicted, so u1's fail-open is now re-warnable (never+ # suppressed by eviction).+ assert (+ policy_module._should_warn_adaptive_failopen("p", "u1") is True+ )+++def test_should_warn_adaptive_failopen_none_username_is_own_bucket():+ """An un-threaded run (username=None) is its own bucket, distinct from any+ authenticated user's -- a present-vs-absent username stays a distinct key,+ preserving the original dedup granularity."""+ with _fresh_failopen_state() as policy_module:+ assert policy_module._should_warn_adaptive_failopen("p", None) is True+ # Same primary WITH a username -> distinct bucket -> warns again.+ assert policy_module._should_warn_adaptive_failopen("p", "dave") is True+ # Repeat of the None-bucket pair is deduped.+ assert policy_module._should_warn_adaptive_failopen("p", None) is False+++def test_should_warn_adaptive_failopen_is_thread_safe():+ """Concurrent calls with the same (user, primary) pair must record it+ exactly once: only one of many racing threads "wins" and returns True."""+ import threading as _threading++ with _fresh_failopen_state() as policy_module:++ def _hammer(results):+ for _ in range(200):+ results.append(+ policy_module._should_warn_adaptive_failopen(+ "_adaptive_followup_thread_key", "threaduser"+ )+ )++ all_results: list = []+ threads = [+ _threading.Thread(target=_hammer, args=(all_results,))+ for _ in range(8)+ ]+ for t in threads:+ t.start()+ for t in threads:+ t.join()+ # Exactly one of the 1600 concurrent calls should have "won" and+ # returned True (the rest see the pair already recorded).+ assert all_results.count(True) == 1++# ---------------------------------------------------------------------------# PRIVATE_ONLY coupling vs STRICT non-coupling# ---------------------------------------------------------------------------diff --git a/tests/security/test_registry_user_isolation.py b/tests/security/test_registry_user_isolation.pynew file mode 100644index 0000000000..c3db2ad0ec--- /dev/null+++ b/tests/security/test_registry_user_isolation.py@@ -0,0 +1,382 @@+"""Cross-user isolation of the retriever and LLM registries.++These are integration-level checks over the seams that previously let a+process-global registration made by one user shadow built-ins or leak into+another user's engine/provider resolution:++* ``search_engines_config.search_config`` must only surface the requesting+ user's retrievers (plus shared ones), never another user's names.+* ``config.llm_config.get_llm`` must resolve a per-user registered LLM only+ for its owner.+* The egress helper ``_is_user_registered_llm`` must scope its+ user-registered-LLM exemption to the owning user.+"""++from unittest.mock import MagicMock, patch++import pytest+from langchain_core.language_models import BaseChatModel+from langchain_core.messages import AIMessage+from langchain_core.outputs import ChatGeneration, ChatResult+++class _MockLLM(BaseChatModel):+ """Minimal in-process LLM used as a user-registered provider."""++ name: str = "mock"++ def _generate(self, messages, **kwargs):+ message = AIMessage(content=f"mock:{self.name}")+ return ChatResult(generations=[ChatGeneration(message=message)])++ @property+ def _llm_type(self):+ return "mock"+++def _p(value, ui="text"):+ return {"value": value, "ui_element": ui}+++def _snapshot(username):+ """A minimal snapshot: public primary engine, offline-friendly."""++ return {+ "search.tool": _p("searxng"),+ "search.engine.web": {},+ "search.engine.library.enabled": _p(False, "checkbox"),+ "llm.model": _p("test-model"),+ "llm.temperature": _p(0.7, "number"),+ "rate_limiting.llm_enabled": _p(False, "checkbox"),+ "_username": username,+ }+++def _private_primary_snapshot(username, primary):+ """Snapshot whose PRIMARY engine is a per-user private retriever, under+ the DEFAULT ADAPTIVE egress scope. ADAPTIVE must classify the primary as+ private and resolve PRIVATE_ONLY.+ """++ return {+ # The run's primary IS the private retriever (not a public engine).+ "search.tool": _p(primary),+ # Default protective scope (adaptive follows the primary).+ "policy.egress_scope": _p("adaptive"),+ "search.engine.web": {},+ "search.engine.library.enabled": _p(False, "checkbox"),+ "llm.model": _p("gpt-4o-mini"),+ "llm.temperature": _p(0.7, "number"),+ "rate_limiting.llm_enabled": _p(False, "checkbox"),+ "_username": username,+ }+++class TestRetrieverConfigLeak:+ """search_config must not leak one user's retrievers to another."""++ def test_engine_list_scoped_to_requesting_user(self):+ from local_deep_research.web_search_engines.retriever_registry import (+ retriever_registry,+ )+ from local_deep_research.web_search_engines.search_engines_config import (+ search_config,+ )++ try:+ retriever_registry.register(+ "sec_alice_ret", MagicMock(), username="sec_alice"+ )+ retriever_registry.register(+ "sec_bob_ret", MagicMock(), username="sec_bob"+ )+ retriever_registry.register("sec_shared_ret", MagicMock())++ bob_engines = search_config(settings_snapshot=_snapshot("sec_bob"))+ # Bob sees his own + the shared retriever, never Alice's.+ assert "sec_bob_ret" in bob_engines+ assert "sec_shared_ret" in bob_engines+ assert "sec_alice_ret" not in bob_engines++ alice_engines = search_config(+ settings_snapshot=_snapshot("sec_alice")+ )+ assert "sec_alice_ret" in alice_engines+ assert "sec_shared_ret" in alice_engines+ assert "sec_bob_ret" not in alice_engines+ finally:+ retriever_registry.clear(username="sec_alice")+ retriever_registry.clear(username="sec_bob")+ retriever_registry.unregister("sec_shared_ret")+++class TestGetLlmUserScoping:+ """get_llm resolves a per-user registered LLM only for its owner."""++ def test_registered_llm_invisible_to_other_user(self):+ from local_deep_research.llm import register_llm, unregister_llm+ from local_deep_research.config.llm_config import get_llm++ alice_llm = _MockLLM(name="alice")+ try:+ register_llm("sec_userllm", alice_llm, username="sec_alice")++ # Owner resolves her own LLM (wrapper patched to return as-is).+ with patch(+ "local_deep_research.config.llm_config."+ "wrap_llm_without_think_tags",+ side_effect=lambda llm, **kw: llm,+ ):+ resolved = get_llm(+ provider="sec_userllm",+ username="sec_alice",+ settings_snapshot=_snapshot("sec_alice"),+ )+ assert resolved is alice_llm++ # A different user does not see it: the name is not a valid+ # provider for Bob, so resolution fails closed.+ with pytest.raises(ValueError, match="Invalid provider"):+ get_llm(+ provider="sec_userllm",+ username="sec_bob",+ settings_snapshot=_snapshot("sec_bob"),+ )+ finally:+ unregister_llm("sec_userllm", username="sec_alice")++ def test_username_derived_from_snapshot(self):+ """When no explicit username is passed, get_llm uses the snapshot."""+ from local_deep_research.llm import register_llm, unregister_llm+ from local_deep_research.config.llm_config import get_llm++ alice_llm = _MockLLM(name="alice")+ try:+ register_llm("sec_snapllm", alice_llm, username="sec_alice")+ with patch(+ "local_deep_research.config.llm_config."+ "wrap_llm_without_think_tags",+ side_effect=lambda llm, **kw: llm,+ ):+ resolved = get_llm(+ provider="sec_snapllm",+ settings_snapshot=_snapshot("sec_alice"),+ )+ assert resolved is alice_llm+ finally:+ unregister_llm("sec_snapllm", username="sec_alice")+++class TestEgressUserRegisteredLlmScoping:+ """The egress exemption for user-registered LLMs is per-user."""++ def test_is_user_registered_llm_scoped(self):+ from local_deep_research.llm import register_llm, unregister_llm+ from local_deep_research.security.egress.policy import (+ _is_user_registered_llm,+ )++ try:+ register_llm("sec_egressllm", _MockLLM(), username="sec_alice")+ assert _is_user_registered_llm(+ "sec_egressllm", username="sec_alice"+ )+ # Not registered for Bob -> not exempt on his behalf.+ assert not _is_user_registered_llm(+ "sec_egressllm", username="sec_bob"+ )+ # And not visible in the shared namespace.+ assert not _is_user_registered_llm("sec_egressllm")+ finally:+ unregister_llm("sec_egressllm", username="sec_alice")+++class TestAdaptivePrivateRetrieverPrimaryNoCloudLeak:+ """Regression: a per-user PRIVATE retriever as the run's primary under+ ADAPTIVE must resolve PRIVATE_ONLY and block a cloud LLM/embedder.++ Per-user registry keying made ``get_metadata`` username-sensitive; if a+ scope-resolution call site omits ``username`` the retriever is invisible+ (shared namespace only), ADAPTIVE falls back to the permissive BOTH,+ ``require_local_*`` stays False, and a cloud model runs over the private+ corpus. This asserts the seam threads username so that fail-open is shut.+ """++ RET = "sec_private_kb"+ USER = "sec_alice"++ def _register_private_retriever(self):+ from local_deep_research.web_search_engines.retriever_registry import (+ retriever_registry,+ )++ retriever_registry.register(+ self.RET, MagicMock(), is_local=True, username=self.USER+ )+ return retriever_registry++ def test_adaptive_resolves_private_only_with_username(self):+ from local_deep_research.security.egress.policy import (+ EgressScope,+ context_from_snapshot,+ )++ reg = self._register_private_retriever()+ try:+ snap = _private_primary_snapshot(self.USER, self.RET)++ # With the owner's username, ADAPTIVE sees the private retriever+ # primary and resolves PRIVATE_ONLY -> local inference forced.+ ctx = context_from_snapshot(snap, self.RET, username=self.USER)+ assert ctx.scope == EgressScope.PRIVATE_ONLY+ assert ctx.require_local_llm is True+ assert ctx.require_local_embeddings is True++ # Witness the fail-open the fix closes: WITHOUT the username the+ # retriever is invisible (shared namespace only), so ADAPTIVE+ # falls back to the permissive BOTH and drops the local-only+ # requirement. This is exactly why every scope-resolution call+ # site must thread username.+ leaked = context_from_snapshot(snap, self.RET, username=None)+ assert leaked.scope != EgressScope.PRIVATE_ONLY+ assert leaked.require_local_llm is False+ finally:+ reg.clear(username=self.USER)++ def test_get_llm_refuses_cloud_under_private_retriever_primary(self):+ from local_deep_research.security.egress.policy import (+ PolicyDeniedError,+ )+ from local_deep_research.config.llm_config import get_llm++ reg = self._register_private_retriever()+ try:+ snap = _private_primary_snapshot(self.USER, self.RET)+ # username is derived from the snapshot's _username; a cloud LLM+ # (openai) must be refused for this private-corpus run.+ with pytest.raises(PolicyDeniedError):+ get_llm(provider="openai", settings_snapshot=snap)+ finally:+ reg.clear(username=self.USER)++ def test_get_embeddings_refuses_cloud_under_private_retriever_primary(+ self,+ ):+ from local_deep_research.security.egress.policy import (+ PolicyDeniedError,+ )+ from local_deep_research.embeddings.embeddings_config import (+ get_embeddings,+ )++ reg = self._register_private_retriever()+ try:+ snap = _private_primary_snapshot(self.USER, self.RET)+ # The private retriever primary forces require_local_embeddings;+ # a cloud embedder (openai) must be refused before instantiation.+ with pytest.raises(PolicyDeniedError):+ get_embeddings(provider="openai", settings_snapshot=snap)+ finally:+ reg.clear(username=self.USER)+++def _cloud_private_primary_snapshot_without_username(primary):+ """A private-retriever-primary snapshot that names a CLOUD llm.provider+ but omits ``_username`` — modelling the bare snapshots that call sites+ like the metrics/domain-classify route and the news scheduler build+ directly from ``SettingsManager`` (no ``_username`` injected). The call+ site must supply the username itself (explicit arg or by scoping the+ snapshot) or the private retriever is invisible and a cloud LLM fires.+ """++ return {+ "search.tool": _p(primary),+ "policy.egress_scope": _p("adaptive"),+ "search.engine.web": {},+ "search.engine.library.enabled": _p(False, "checkbox"),+ "llm.provider": _p("openai"),+ "llm.model": _p("gpt-4o-mini"),+ "llm.temperature": _p(0.7, "number"),+ "rate_limiting.llm_enabled": _p(False, "checkbox"),+ # NB: no "_username" key — the snapshot alone cannot scope the run.+ }+++class TestFailOpenCallSitesThreadUsername:+ """Regression for the three call sites that reached ``get_llm`` with a+ ``_username``-less snapshot and no explicit ``username=``.++ Each fed user content (resource titles, news findings, or a whole+ research run) to an LLM whose provider could resolve to cloud even+ though the user's primary was a private retriever, because the private+ retriever is only visible in the user's own registry namespace. The fix+ threads the user at each seam.+ """++ RET = "sec_failopen_kb"+ USER = "sec_alice"++ def _register_private_retriever(self):+ from local_deep_research.web_search_engines.retriever_registry import (+ retriever_registry,+ )++ retriever_registry.register(+ self.RET, MagicMock(), is_local=True, username=self.USER+ )+ return retriever_registry++ def test_domain_classifier_threads_username(self):+ """``DomainClassifier._get_llm`` must pass ``username=self.username``+ so the classify route's bare snapshot still forces local-only."""+ from local_deep_research.security.egress.policy import (+ PolicyDeniedError,+ )+ from local_deep_research.domain_classifier.classifier import (+ DomainClassifier,+ )++ reg = self._register_private_retriever()+ try:+ snap = _cloud_private_primary_snapshot_without_username(self.RET)+ classifier = DomainClassifier(+ username=self.USER, settings_snapshot=snap+ )+ with pytest.raises(PolicyDeniedError):+ classifier._get_llm()+ finally:+ reg.clear(username=self.USER)++ def test_scheduler_style_snapshot_scoping_blocks_cloud(self):+ """The news scheduler builds a bare snapshot and now scopes it with+ ``ensure_snapshot_username`` before the headline/topic LLM calls.+ Prove that scoping is what closes the fail-open: the bare snapshot+ resolves a cloud LLM, the scoped one is refused."""+ from local_deep_research.security.egress.policy import (+ PolicyDeniedError,+ )+ from local_deep_research.config.llm_config import get_llm+ from local_deep_research.search_system import (+ ensure_snapshot_username,+ )++ reg = self._register_private_retriever()+ try:+ bare = _cloud_private_primary_snapshot_without_username(self.RET)++ # Witness the fail-open: without a username the private retriever+ # is invisible, ADAPTIVE stays permissive, and the egress PEP does+ # NOT block the cloud provider. (Instantiation still fails for an+ # unrelated reason — no API key in the test snapshot — but that is+ # not the policy stopping it.)+ with pytest.raises(Exception) as bare_exc:+ get_llm(settings_snapshot=bare)+ assert not isinstance(bare_exc.value, PolicyDeniedError)++ # The scheduler fix scopes the snapshot to its owner; the egress+ # PEP now refuses the cloud LLM for the private-corpus run.+ scoped = ensure_snapshot_username(bare, self.USER)+ with pytest.raises(PolicyDeniedError):+ get_llm(settings_snapshot=scoped)+ finally:+ reg.clear(username=self.USER)diff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.pyindex d33a5d921f..07b2d96de4 100644--- a/tests/strategies/test_langgraph_agent_strategy.py+++ b/tests/strategies/test_langgraph_agent_strategy.py@@ -858,6 +858,19 @@ class TestPrimaryWebSearchClassification:# When the lead builds its tools and delegates one subtopic.with (search_config_patch as search_config_mock,+ # Isolate the primary-classification lookup under test from the+ # egress-context lookup. _build_egress_context ->+ # context_from_snapshot -> _resolve_adaptive_scope now also reads+ # retriever_registry.get_metadata(primary, username=...) for+ # ADAPTIVE scope, which would otherwise add a second, unrelated+ # get_metadata call to the assertion below. A non-None sentinel+ # keeps the `elif policy_ctx is not None` classify_engine branch+ # live (policy_ctx is only consumed here by patched builders).+ patch.object(+ mod.LangGraphAgentStrategy,+ "_build_egress_context",+ return_value=MagicMock(),+ ),patch.object(mod,"format_primary_search_description",@@ -939,7 +952,10 @@ class TestPrimaryWebSearchClassification:assert [metadata_call.argsfor metadata_call in get_metadata.call_args_list- if not metadata_call.kwargs+ # get_metadata is now called with a per-user ``username=`` kwarg;+ # ignore that kwarg so the primary-classification lookup is still+ # matched (get_metadata only takes ``name`` + ``username``).+ if not (set(metadata_call.kwargs) - {"username"})] == expected_primary_metadata_calls@@ -1113,7 +1129,7 @@ class TestBuildLibraryResolver:return LangGraphAgentStrategy(**defaults)def test_returns_resolver_when_username_present_in_snapshot(self):- """The username injected by ``_ensure_snapshot_username`` (via the+ """The username injected by ``ensure_snapshot_username`` (via the``_username`` snapshot key) drives the resolver build. The webrun calls this; programmatic mode without a username does not."""from local_deep_research.advanced_search_system.tools.fetch import (diff --git a/tests/test_llm/test_llm_registry.py b/tests/test_llm/test_llm_registry.pyindex dcfe46d5cd..347b1b28a9 100644--- a/tests/test_llm/test_llm_registry.py+++ b/tests/test_llm/test_llm_registry.py@@ -113,6 +113,19 @@ def test_multiple_llms():assert get_llm_from_registry("model2") is llm2+def test_list_registered_order_is_deterministic():+ """Shared-namespace listing preserves registration order and is stable+ across repeated calls (the old set-union made this nondeterministic)."""+ for name in ("gamma", "alpha", "delta", "beta"):+ register_llm(name, MockLLM(name=name))++ first = list_registered_llms()+ # Insertion order, NOT alphabetical.+ assert first == ["gamma", "alpha", "delta", "beta"]+ # Deterministic across repeated calls.+ assert list_registered_llms() == first++def test_overwrite_existing():"""Test overwriting an existing LLM."""llm1 = MockLLM(name="original")@@ -190,6 +203,27 @@ def test_thread_safety():assert len(results) == 6 # 3 register + 3 read threads+def test_register_none_llm_raises_value_error():+ """Registering None must raise, not silently store it.++ A stored None would miss the ``found is not None`` check in ``get()``+ and fall through to the shared namespace, so a caller's misregistered+ None could resolve to an unrelated (possibly built-in) provider instead+ of failing loudly.+ """+ with pytest.raises(ValueError):+ register_llm("broken_model", None)+ assert not is_llm_registered("broken_model")+ assert get_llm_from_registry("broken_model") is None+++def test_register_none_llm_raises_for_user_namespace():+ """The None guard applies to per-user registrations too."""+ with pytest.raises(ValueError):+ register_llm("broken_model", None, username="alice")+ assert not is_llm_registered("broken_model", username="alice")++def test_get_nonexistent():"""Test getting a non-existent LLM."""assert get_llm_from_registry("does_not_exist") is None@@ -201,3 +235,106 @@ def test_empty_registry():assert list_registered_llms() == []assert not is_llm_registered("any_model")assert get_llm_from_registry("any_model") is None+++class TestPerUserIsolation:+ """Per-user scoping: one user's LLM must not leak to another."""++ def test_user_llm_not_visible_to_other_user(self):+ """User A's registration is invisible to User B."""+ llm_a = MockLLM(name="alice-llm")+ register_llm("mymodel", llm_a, username="alice")++ assert get_llm_from_registry("mymodel", username="alice") is llm_a+ assert is_llm_registered("mymodel", username="alice")+ assert "mymodel" in list_registered_llms(username="alice")++ assert get_llm_from_registry("mymodel", username="bob") is None+ assert not is_llm_registered("mymodel", username="bob")+ assert "mymodel" not in list_registered_llms(username="bob")++ def test_shared_llm_visible_to_all_users(self):+ """A username-less (shared) registration resolves for everyone."""+ shared = MockLLM(name="shared")+ register_llm("shared_model", shared) # no username -> shared++ assert get_llm_from_registry("shared_model", username="alice") is shared+ assert get_llm_from_registry("shared_model", username="bob") is shared+ assert get_llm_from_registry("shared_model") is shared++ def test_user_shadows_shared_only_for_that_user(self):+ """Alice overriding a shared/built-in name only changes Alice.++ Emulates a user registering a name that matches a built-in provider+ (e.g. ``ollama``): it must not change any other user's resolution of+ that name, and the shared entry must still resolve for everyone else.+ """+ builtin = MockLLM(name="builtin-ollama")+ alice_ollama = MockLLM(name="alice-ollama")++ register_llm("ollama", builtin) # shared (stands in for a built-in)+ register_llm("ollama", alice_ollama, username="alice")++ assert get_llm_from_registry("ollama", username="alice") is alice_ollama+ # Bob (and anyone else) still resolves the shared/built-in one.+ assert get_llm_from_registry("ollama", username="bob") is builtin+ assert get_llm_from_registry("ollama") is builtin+ assert is_llm_registered("ollama", username="bob")++ def test_list_registered_excludes_other_users(self):+ """list_registered returns own + shared, never another user's."""+ register_llm("shared_model", MockLLM())+ register_llm("alice_model", MockLLM(), username="alice")+ register_llm("bob_model", MockLLM(), username="bob")++ alice_list = list_registered_llms(username="alice")+ assert sorted(alice_list) == ["alice_model", "shared_model"]+ assert "bob_model" not in alice_list++ assert list_registered_llms() == ["shared_model"]++ def test_list_registered_own_before_shared_no_duplicate(self):+ """Own-namespace entries first (insertion order), then shared entries+ not shadowed by an own name; a name in both namespaces appears once,+ under the own namespace (mirroring get() resolution)."""+ register_llm("shared1", MockLLM())+ register_llm("dup", MockLLM()) # shared+ register_llm("own1", MockLLM(), username="alice")+ register_llm("dup", MockLLM(), username="alice") # shadows shared++ result = list_registered_llms(username="alice")+ assert result == ["own1", "dup", "shared1"]+ assert result.count("dup") == 1++ def test_case_insensitive_within_namespace(self):+ """Names stay case-insensitive inside a user namespace."""+ llm = MockLLM()+ register_llm("MyModel", llm, username="alice")++ assert get_llm_from_registry("mymodel", username="alice") is llm+ assert is_llm_registered("MYMODEL", username="alice")+ assert not is_llm_registered("mymodel", username="bob")++ def test_clear_user_leaves_shared_and_other_users(self):+ """clear(username) removes only that user's namespace."""+ register_llm("shared_model", MockLLM())+ register_llm("alice_model", MockLLM(), username="alice")+ register_llm("bob_model", MockLLM(), username="bob")++ clear_llm_registry(username="alice")++ assert not is_llm_registered("alice_model", username="alice")+ assert is_llm_registered("shared_model", username="bob")+ assert is_llm_registered("bob_model", username="bob")++ def test_unregister_scoped_to_user(self):+ """unregister only touches the given user's namespace."""+ shared = MockLLM(name="shared")+ register_llm("model", shared)+ register_llm("model", MockLLM(name="alice"), username="alice")++ unregister_llm("model", username="alice")++ # Shared survives and is what Alice now resolves.+ assert get_llm_from_registry("model", username="alice") is shared+ assert get_llm_from_registry("model") is shareddiff --git a/tests/web/services/test_research_service_coverage.py b/tests/web/services/test_research_service_coverage.pyindex 3c81461b23..2a4ac44d04 100644--- a/tests/web/services/test_research_service_coverage.py+++ b/tests/web/services/test_research_service_coverage.py@@ -6,7 +6,7 @@ and helper functions."""import threading-from contextlib import contextmanager+from contextlib import contextmanager, ExitStackfrom datetime import datetime, UTCfrom pathlib import Pathfrom types import SimpleNamespace@@ -955,11 +955,11 @@ class TestRunResearchProcessQuickMode:patch("local_deep_research.news.utils.headline_generator.generate_headline",return_value="Breaking: Test",- ),+ ) as mock_headline,patch("local_deep_research.news.utils.topic_generator.generate_topics",return_value=["topic1", "topic2"],- ),+ ) as mock_topics,):raw_fn = _get_raw_run_research_process()raw_fn(@@ -973,6 +973,18 @@ class TestRunResearchProcessQuickMode:)assert research.status == "completed"+ # Headline/topic generation must receive a settings_snapshot scoped+ # to the run's owner (mirrors the scheduler's+ # _store_research_result fix) so the LLM PEP resolves a per-user+ # provider instead of silently no-oping for cloud-provider users.+ headline_snapshot = mock_headline.call_args.kwargs["settings_snapshot"]+ assert headline_snapshot["_username"] == "alice"+ assert headline_snapshot["search.tool"] == "searxng"++ topics_snapshot = mock_topics.call_args.kwargs["settings_snapshot"]+ assert topics_snapshot["_username"] == "alice"+ assert topics_snapshot["search.tool"] == "searxng"+class TestRunResearchProcessNoOutputDir:"""Regression: run_research_process must not create an empty@@ -1191,6 +1203,176 @@ class TestRunResearchProcessDetailedMode:== "# Full Report")+ def test_detailed_mode_news_search_generates_headlines(self):+ """Detailed-mode news search metadata should trigger headline/topic+ generation with a settings_snapshot scoped to the run's owner,+ mirroring the quick-mode path+ (test_quick_mode_news_search_generates_headlines) and the+ scheduler's _store_research_result fix (background.py). Without the+ scoped snapshot, the LLM PEP silently no-ops for cloud-provider+ users instead of resolving a per-user provider.+ """+ mock_session = MagicMock()+ research = _make_research_mock(+ research_meta={"is_news_search": True, "category": "Tech"}+ )+ research.report_content = "some report"+ mock_session.query.return_value.filter_by.return_value.first.return_value = research++ mock_system = MagicMock()+ mock_search_system = MagicMock()+ mock_search_system.all_links_of_system = [+ {"url": "http://a.com", "title": "A"}+ ]+ results = {+ "findings": [{"content": "news data"}],+ "formatted_findings": "# Report",+ "iterations": 2,+ "search_system": mock_search_system,+ }+ mock_system.analyze_topic.return_value = results++ mock_formatter = MagicMock()+ mock_formatter.format_document_split.return_value = (+ "# Full Report",+ [{"url": "u"}],+ False,+ )++ mock_report_gen = MagicMock()+ mock_report_gen.generate_report.return_value = {+ "content": "# Full Report",+ "metadata": {"sections": 3},+ }++ mock_storage = MagicMock()+ mock_storage.save_report.return_value = True++ mock_sources_service = MagicMock()+ mock_sources_service.save_research_sources.return_value = 1+ mock_qp = MagicMock()++ # Uses ExitStack rather than a single parenthesized `with` tuple:+ # this test needs two more patches (generate_headline,+ # generate_topics) than test_detailed_mode_success, which pushes a+ # literal nested `with (...)` past CPython's "too many statically+ # nested blocks" compile limit.+ with ExitStack() as stack:+ stack.enter_context(+ patch(+ "local_deep_research.web.routes.globals.is_termination_requested",+ return_value=False,+ )+ )+ stack.enter_context(+ patch(+ "local_deep_research.web.routes.globals.is_research_active",+ return_value=True,+ )+ )+ stack.enter_context(+ patch(+ "local_deep_research.web.routes.globals.update_progress_and_check_active",+ return_value=(50, True),+ )+ )+ stack.enter_context(+ patch(f"{RS}.get_llm", return_value=MagicMock())+ )+ stack.enter_context(+ patch(f"{RS}.get_search", return_value=MagicMock())+ )+ stack.enter_context(+ patch(f"{RS}.AdvancedSearchSystem", return_value=mock_system)+ )+ stack.enter_context(+ patch(+ f"{RS}.get_citation_formatter", return_value=mock_formatter+ )+ )+ stack.enter_context(+ patch(+ f"{RS}.get_user_db_session",+ side_effect=_fake_session_ctx(mock_session),+ )+ )+ stack.enter_context(patch(f"{RS}.cleanup_research_resources"))+ stack.enter_context(patch(f"{RS}.SocketIOService"))+ stack.enter_context(patch(f"{RS}.set_search_context"))+ stack.enter_context(+ patch(f"{RS}.calculate_duration", return_value=20.0)+ )+ stack.enter_context(+ patch(+ f"{RS}.IntegratedReportGenerator",+ return_value=mock_report_gen,+ )+ )+ stack.enter_context(+ patch(+ "local_deep_research.storage.get_report_storage",+ return_value=mock_storage,+ )+ )+ stack.enter_context(+ patch(+ f"{RS}.extract_links_from_search_results",+ return_value=[],+ )+ )+ stack.enter_context(+ patch(+ "local_deep_research.web.services.research_sources_service.ResearchSourcesService",+ return_value=mock_sources_service,+ )+ )+ stack.enter_context(+ patch(+ "local_deep_research.web.queue.processor_v2.queue_processor",+ mock_qp,+ )+ )+ stack.enter_context(+ patch("local_deep_research.settings.logger.log_settings")+ )+ stack.enter_context(+ patch(+ "local_deep_research.config.thread_settings.set_settings_context"+ )+ )+ mock_headline = stack.enter_context(+ patch(+ "local_deep_research.news.utils.headline_generator.generate_headline",+ return_value="Breaking: Test",+ )+ )+ mock_topics = stack.enter_context(+ patch(+ "local_deep_research.news.utils.topic_generator.generate_topics",+ return_value=["topic1", "topic2"],+ )+ )++ raw_fn = _get_raw_run_research_process()+ raw_fn(+ "r1",+ "query",+ "detailed",+ username="alice",+ settings_snapshot={"search.tool": "searxng"},+ model="m",+ search_engine="s",+ )+ assert research.status == "completed"++ headline_snapshot = mock_headline.call_args.kwargs["settings_snapshot"]+ assert headline_snapshot["_username"] == "alice"+ assert headline_snapshot["search.tool"] == "searxng"++ topics_snapshot = mock_topics.call_args.kwargs["settings_snapshot"]+ assert topics_snapshot["_username"] == "alice"+ assert topics_snapshot["search.tool"] == "searxng"+def test_detailed_mode_writes_file_backup_when_enabled(self):"""Detailed completion writes the on-disk file backup when thereport.enable_file_backup setting is on.diff --git a/tests/web_search_engines/test_retriever_registry.py b/tests/web_search_engines/test_retriever_registry.pyindex bca2a0884a..ccf011bd45 100644--- a/tests/web_search_engines/test_retriever_registry.py+++ b/tests/web_search_engines/test_retriever_registry.py@@ -11,6 +11,8 @@ Tests cover:from unittest.mock import Mock+import pytest+class TestRetrieverRegistryInit:"""Tests for RetrieverRegistry initialization."""@@ -68,6 +70,39 @@ class TestRegister:assert registry.get("test") is mock_retriever2+ def test_register_none_raises_value_error(self):+ """Registering None must raise, not silently store it.++ A stored None would miss the ``found is not None`` check in+ ``get()`` and fall through to the shared namespace, so a caller's+ misregistered None could resolve to an unrelated retriever instead+ of failing loudly.+ """+ from local_deep_research.web_search_engines.retriever_registry import (+ RetrieverRegistry,+ )++ registry = RetrieverRegistry()++ with pytest.raises(ValueError):+ registry.register("broken", None)++ assert not registry.is_registered("broken")+ assert registry.get("broken") is None++ def test_register_none_raises_for_user_namespace(self):+ """The None guard applies to per-user registrations too."""+ from local_deep_research.web_search_engines.retriever_registry import (+ RetrieverRegistry,+ )++ registry = RetrieverRegistry()++ with pytest.raises(ValueError):+ registry.register("broken", None, username="alice")++ assert not registry.is_registered("broken", username="alice")+class TestRegisterMultiple:"""Tests for register_multiple method."""@@ -101,6 +136,37 @@ class TestRegisterMultiple:assert registry.list_registered() == []+ def test_register_multiple_bare_none_raises_value_error(self):+ """A bare-shape entry that resolves to None must raise, not be+ silently skipped — a stored/omitted None entry could otherwise+ confuse resolution the same way an accepted None value would."""+ from local_deep_research.web_search_engines.retriever_registry import (+ RetrieverRegistry,+ )++ registry = RetrieverRegistry()+ mock_retriever = Mock()++ with pytest.raises(ValueError):+ registry.register_multiple({"good": mock_retriever, "broken": None})++ # Atomic all-or-nothing: the valid "good" entry must NOT have been+ # registered — the batch is validated in full before any mutation,+ # so a bad entry leaves no partial state behind.+ assert not registry.is_registered("good")+ assert registry.get("good") is None++ def test_register_multiple_dict_shape_missing_retriever_raises(self):+ """A dict-shape entry with no ``"retriever"`` key also raises."""+ from local_deep_research.web_search_engines.retriever_registry import (+ RetrieverRegistry,+ )++ registry = RetrieverRegistry()++ with pytest.raises(ValueError):+ registry.register_multiple({"broken": {"is_local": False}})+class TestGet:"""Tests for get method."""@@ -245,6 +311,44 @@ class TestListRegistered:assert sorted(result) == ["test1", "test2"]+ def test_list_registered_order_is_deterministic(self):+ """Order is stable and insertion-preserving: shared-namespace entries+ come back in registration order, and repeated calls return the exact+ same list (the old set-union made this nondeterministic run to run)."""+ from local_deep_research.web_search_engines.retriever_registry import (+ RetrieverRegistry,+ )++ registry = RetrieverRegistry()+ for name in ("gamma", "alpha", "delta", "beta"):+ registry.register(name, Mock())++ first = registry.list_registered()+ # Insertion order, NOT alphabetical.+ assert first == ["gamma", "alpha", "delta", "beta"]+ # Deterministic across repeated calls.+ assert registry.list_registered() == first++ def test_list_registered_own_before_shared_no_duplicate(self):+ """Own-namespace entries are listed first (insertion order), then+ shared entries not shadowed by an own name; a name in both namespaces+ appears once, under the own namespace (mirroring get() resolution)."""+ from local_deep_research.web_search_engines.retriever_registry import (+ RetrieverRegistry,+ )++ registry = RetrieverRegistry()+ registry.register("shared1", Mock())+ registry.register("dup", Mock()) # shared+ registry.register("own1", Mock(), username="alice")+ registry.register("dup", Mock(), username="alice") # shadows shared++ result = registry.list_registered(username="alice")+ # Own first (own1, dup), then shared-not-shadowed (shared1). "dup"+ # appears exactly once.+ assert result == ["own1", "dup", "shared1"]+ assert result.count("dup") == 1+class TestGlobalRegistry:"""Tests for global registry instance."""@@ -259,6 +363,133 @@ class TestGlobalRegistry:assert isinstance(retriever_registry, RetrieverRegistry)+class TestPerUserIsolation:+ """Per-user scoping: one user's retriever must not leak to another."""++ def _registry(self):+ from local_deep_research.web_search_engines.retriever_registry import (+ RetrieverRegistry,+ )++ return RetrieverRegistry()++ def test_user_retriever_not_visible_to_other_user(self):+ """User A's registration is invisible to User B (get + list)."""+ registry = self._registry()+ ret_a = Mock()++ registry.register("private_kb", ret_a, username="alice")++ # Alice sees her own retriever.+ assert registry.get("private_kb", username="alice") is ret_a+ assert "private_kb" in registry.list_registered(username="alice")++ # Bob does not — get returns None, list omits it.+ assert registry.get("private_kb", username="bob") is None+ assert "private_kb" not in registry.list_registered(username="bob")+ assert not registry.is_registered("private_kb", username="bob")++ def test_shared_retriever_visible_to_all_users(self):+ """A username-less (shared) registration resolves for everyone."""+ registry = self._registry()+ shared = Mock()++ registry.register("shared_kb", shared) # no username -> shared++ assert registry.get("shared_kb", username="alice") is shared+ assert registry.get("shared_kb", username="bob") is shared+ assert registry.get("shared_kb") is shared+ assert "shared_kb" in registry.list_registered(username="bob")++ def test_user_registration_shadows_only_for_that_user(self):+ """Alice overriding a shared name only changes Alice's resolution."""+ registry = self._registry()+ shared = Mock()+ alice_override = Mock()++ registry.register("kb", shared) # shared+ registry.register("kb", alice_override, username="alice")++ assert registry.get("kb", username="alice") is alice_override+ # Bob and the shared namespace still see the shared retriever.+ assert registry.get("kb", username="bob") is shared+ assert registry.get("kb") is shared++ def test_list_registered_excludes_other_users(self):+ """list_registered returns own + shared, never another user's."""+ registry = self._registry()+ registry.register("shared_kb", Mock())+ registry.register("alice_kb", Mock(), username="alice")+ registry.register("bob_kb", Mock(), username="bob")++ alice_list = registry.list_registered(username="alice")+ assert sorted(alice_list) == ["alice_kb", "shared_kb"]+ assert "bob_kb" not in alice_list++ # username-less listing sees shared only.+ assert registry.list_registered() == ["shared_kb"]++ def test_get_metadata_scoped_per_user(self):+ """Metadata resolves per user (own first, then shared)."""+ registry = self._registry()+ registry.register("kb", Mock(), is_local=False, username="alice")+ registry.register("kb", Mock(), is_local=True) # shared++ assert registry.get_metadata("kb", username="alice") == {+ "is_local": False+ }+ # Bob has no "kb" of his own -> falls back to the shared entry.+ assert registry.get_metadata("kb", username="bob") == {"is_local": True}++ def test_register_multiple_scoped_per_user(self):+ """register_multiple honors the username namespace."""+ registry = self._registry()+ registry.register_multiple(+ {"r1": Mock(), "r2": Mock()}, username="alice"+ )++ assert registry.is_registered("r1", username="alice")+ assert not registry.is_registered("r1", username="bob")+ assert registry.list_registered(username="bob") == []++ def test_clear_user_leaves_shared_and_other_users(self):+ """clear(username) removes only that user's namespace."""+ registry = self._registry()+ registry.register("shared_kb", Mock())+ registry.register("alice_kb", Mock(), username="alice")+ registry.register("bob_kb", Mock(), username="bob")++ registry.clear(username="alice")++ assert not registry.is_registered("alice_kb", username="alice")+ # Shared and Bob survive.+ assert registry.is_registered("shared_kb", username="bob")+ assert registry.is_registered("bob_kb", username="bob")++ def test_clear_all_wipes_every_namespace(self):+ """clear() with no username wipes all namespaces (test isolation)."""+ registry = self._registry()+ registry.register("shared_kb", Mock())+ registry.register("alice_kb", Mock(), username="alice")++ registry.clear()++ assert registry.list_registered() == []+ assert registry.list_registered(username="alice") == []++ def test_unregister_scoped_to_user(self):+ """unregister only touches the given user's namespace."""+ registry = self._registry()+ shared = Mock()+ registry.register("kb", shared)+ registry.register("kb", Mock(), username="alice")++ registry.unregister("kb", username="alice")++ assert registry.get("kb", username="alice") is shared # shared remains+ assert registry.get("kb") is shared++class TestThreadSafety:"""Tests for thread safety."""diff --git a/tests/web_search_engines/test_search_engine_factory_deep_coverage.py b/tests/web_search_engines/test_search_engine_factory_deep_coverage.pyindex f131ac76af..f7e5a97da0 100644--- a/tests/web_search_engines/test_search_engine_factory_deep_coverage.py+++ b/tests/web_search_engines/test_search_engine_factory_deep_coverage.py@@ -116,7 +116,7 @@ class TestRegisteredRetrieverPath:assert result is not Nonefinally:# cleanup- retriever_registry._retrievers.pop("__test_retriever__", None)+ retriever_registry.unregister("__test_retriever__")# ---------------------------------------------------------------------------