~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: add thread-safe locking to embedding model initialization (#2183)
LearningCircuitc1b86f6d3e4c
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_local.py b/src/local_deep_research/web_search_engines/engines/search_engine_local.pyindex 67413bd833..9f3d503a26 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_local.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_local.py@@ -1,6 +1,7 @@import hashlibimport jsonimport os+import threadingimport timeimport uuidfrom concurrent.futures import ProcessPoolExecutor@@ -142,8 +143,9 @@ class LocalEmbeddingManager:# Create cache directory if it doesn't existself.cache_dir.mkdir(parents=True, exist_ok=True)- # Initialize the embedding model+ # Initialize the embedding model (with lock for thread-safe lazy init)self._embeddings = None+ self._embedding_lock = threading.Lock()# Initialize the text splitterself.text_splitter = RecursiveCharacterTextSplitter(@@ -185,10 +187,16 @@ class LocalEmbeddingManager:Lazily initialize embeddings when first accessed.This allows the LocalEmbeddingManager to be created withoutimmediately loading models, which is helpful when no local search is performed.++ Uses double-checked locking to ensure thread-safe initialization.+ Concurrent SentenceTransformer model loading causes meta tensor errors+ in PyTorch when multiple threads call model.to(device) simultaneously."""if self._embeddings is None:- logger.info("Initializing embeddings on first use")- self._embeddings = self._initialize_embeddings()+ with self._embedding_lock:+ if self._embeddings is None:+ logger.info("Initializing embeddings on first use")+ self._embeddings = self._initialize_embeddings()return self._embeddingsdef _initialize_embeddings(self):diff --git a/tests/web_search_engines/test_local_embedding_manager.py b/tests/web_search_engines/test_local_embedding_manager.pyindex 5ebb340be8..e5ff7efeed 100644--- a/tests/web_search_engines/test_local_embedding_manager.py+++ b/tests/web_search_engines/test_local_embedding_manager.py@@ -1,14 +1,16 @@"""-Tests for LocalEmbeddingManager cache directory handling.+Tests for LocalEmbeddingManager cache directory handling and thread safety.These tests verify that the cache directory is properly resolved-to an absolute path using the application's configured cache directory.+to an absolute path using the application's configured cache directory,+and that embedding initialization is thread-safe."""import osimport tempfile+import threadingfrom pathlib import Path-from unittest.mock import patch+from unittest.mock import MagicMock, patchclass TestLocalEmbeddingManagerCacheDir:@@ -129,6 +131,76 @@ class TestLocalSearchEngineCacheDir:).startswith(".cache")+class TestEmbeddingThreadSafety:+ """Tests that embedding initialization is thread-safe."""++ def test_concurrent_embedding_access_initializes_once(self):+ """Multiple threads accessing .embeddings should only init once."""+ with tempfile.TemporaryDirectory() as temp_dir:+ temp_path = Path(temp_dir)++ with (+ patch(+ "local_deep_research.web_search_engines.engines.search_engine_local.get_cache_directory",+ return_value=temp_path,+ ),+ patch(+ "local_deep_research.web_search_engines.engines.search_engine_local.LocalEmbeddingManager._load_indexed_folders",+ return_value={},+ ),+ ):+ from local_deep_research.web_search_engines.engines.search_engine_local import (+ LocalEmbeddingManager,+ )++ manager = LocalEmbeddingManager(+ embedding_model="test-model",+ )++ # Track how many times _initialize_embeddings is called+ init_count = 0+ init_lock = threading.Lock()+ mock_embeddings = MagicMock()++ def counting_init():+ nonlocal init_count+ with init_lock:+ init_count += 1+ # Simulate slow initialization to widen race window+ import time++ time.sleep(0.1)+ return mock_embeddings++ manager._initialize_embeddings = counting_init++ # Access embeddings from multiple threads concurrently+ results = []+ errors = []++ def access_embeddings():+ try:+ emb = manager.embeddings+ results.append(emb)+ except Exception as e:+ errors.append(e)++ threads = [+ threading.Thread(target=access_embeddings) for _ in range(4)+ ]+ for t in threads:+ t.start()+ for t in threads:+ t.join()++ assert not errors, f"Threads raised errors: {errors}"+ assert init_count == 1, (+ f"_initialize_embeddings called {init_count} times, expected 1"+ )+ # All threads should get the same instance+ assert all(r is mock_embeddings for r in results)++class TestGetCacheDirectory:"""Tests for get_cache_directory function."""