Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(embeddings): reuse local model weights across searches (#7263)

LearningCircuit9fa613229553
diff --git a/changelog.d/7263.bugfix.md b/changelog.d/7263.bugfix.md
new file mode 100644
index 0000000000..c99fb30203
--- /dev/null
+++ b/changelog.d/7263.bugfix.md
@@ -0,0 +1 @@
+Reuse one resident Sentence Transformers embedding model across searches and indexing operations instead of repeatedly loading its weights; embedding calls on that model run one at a time. Detect changes to linked model artifacts, including replacements while a model loads: an existing embedding client that must reload the model then raises an error instead of silently using different weights, and a new client loads the replacement. Only one model stays resident, so work that alternates between embedding configurations, such as collections indexed with different models, reloads the model from local files at every switch. Collect model reference cycles when switching configurations, and release the idle cache during shutdown without delaying other cleanup behind busy inference. Each caller keeps its own closeable handle and provider admission checks; query text, documents, credentials and embedding results are not shared or cached.
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 4cc28cc2a3..0d9b80224d 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -208,7 +208,7 @@ They are not available in the Web UI because they are needed to start the applic
| `policy.trusted_inference_providers` | `LDR_POLICY_TRUSTED_INFERENCE_PROVIDERS` | ``[]`` | EXPERIMENTAL. LLM/embeddings providers you explicitly trust to receive sensitive content — listing one treats it as a 'contained' inference sink even though it is off-machine (e.g. a zero-retention enterprise Anthropic endpoint). Relaxes the two-axis egress classification; use only for providers you have vetted. | LLM |
| `policy.trusted_search_engines` | `LDR_POLICY_TRUSTED_SEARCH_ENGINES` | ``[]`` | EXPERIMENTAL. Search engines whose endpoint you explicitly trust — listing one (e.g. a self-hosted Elasticsearch/Paperless on a public hostname) treats it as 'contained' rather than an exposing sink. Relaxes the two-axis egress classification; use only for endpoints you control. | SEARCH |
| `rag.indexing_batch_size` | `LDR_RAG_INDEXING_BATCH_SIZE` | `15` | Maximum number of documents grouped into a single SSE progress batch on /api/rag/index-all. Documents within a batch are processed in parallel via rag.indexing_max_parallel_docs. Higher values reduce SSE overhead but increase the unit of cancellation. | APP |
-| `rag.indexing_max_parallel_docs` | `LDR_RAG_INDEXING_MAX_PARALLEL_DOCS` | `4` | Maximum number of documents indexed concurrently within a single indexing job (per-user). One job holds up to this many workers; each worker calls the existing per-document path so the FAISS write lock still serializes the disk-merge step. Lower if your embedding backend (e.g. local CPU sentence-transformers) is throughput-bound and concurrent calls contend; raise to e.g. 8-16 for sentence-transformers on GPU, or HTTP embedding providers (OpenAI-compatible, vLLM, Ollama with OLLAMA_NUM_PARALLEL>1). Default 4 keeps RAM modest for collections with many large documents. | APP |
+| `rag.indexing_max_parallel_docs` | `LDR_RAG_INDEXING_MAX_PARALLEL_DOCS` | `4` | Maximum number of documents indexed concurrently within a single indexing job (per-user). One job holds up to this many workers; each worker calls the existing per-document path so the FAISS write lock still serializes the disk-merge step. Lower if your embedding backend is throughput-bound and concurrent calls contend; local sentence-transformers run one embedding call at a time per process, so raise to e.g. 8-16 mainly for HTTP embedding providers (OpenAI-compatible, vLLM, Ollama with OLLAMA_NUM_PARALLEL>1). Default 4 keeps RAM modest for collections with many large documents. | APP |
| `rate_limiting.decay_per_day` | `LDR_RATE_LIMITING_DECAY_PER_DAY` | `0.95` | How much to trust old rate limit data as it ages (0.5-0.99). At 0.95, data retains 95% reliability per day. Lower values discard old data faster, forcing the system to re-learn optimal wait times. | APP |
| `rate_limiting.enabled` | `LDR_RATE_LIMITING_ENABLED` | `true` | Enable adaptive rate limiting that learns optimal wait times for each search engine to avoid hitting API rate limits. When disabled, requests are sent with minimal delay (0.1s), which may trigger rate limit errors from some APIs. | APP |
| `rate_limiting.exploration_rate` | `LDR_RATE_LIMITING_EXPLORATION_RATE` | `0.1` | Fraction of requests that test shorter wait times to check if the API allows faster access (0.0-1.0). Higher values adapt faster to relaxed limits but risk more rate limit errors. | APP |
diff --git a/docs/developing/resource-cleanup.md b/docs/developing/resource-cleanup.md
index 9f2fca0e85..42e4c67cab 100644
--- a/docs/developing/resource-cleanup.md
+++ b/docs/developing/resource-cleanup.md
@@ -324,10 +324,12 @@ here is the full ledger:
the generator and never close it, **but** `LibraryRAGService.close()`
only sets references to `None` — it releases no FDs. FAISS uses
`pickle.load()` (not mmap); OllamaEmbeddings holds no FDs per the
- item above; the SentenceTransformer model+tokenizer mmaps are
- process-wide singletons. What gets delayed is ~50–200 MB of
- embedding-model RAM until GC. A memory-pressure question, not the
- eventpoll FD class this Wave addressed.
+ item above. The historical audit's claim that SentenceTransformer
+ models were process-wide singletons was incorrect: each provider
+ construction loaded a separate model. Their reference cycles could
+ retain substantial embedding-model RAM until full garbage collection.
+ The shared local embedding model described below addresses that
+ memory ownership separately from this audit's file-descriptor findings.
- **Residual `pidfd` accumulation via Playwright fallback** —
identified in a Round-8 follow-up after the eventpoll fix landed.
Live `/proc` on the prerelease container showed ~29 pidfds steady
@@ -957,6 +959,79 @@ reference this section first.
survive. Add `changelog.d/<id>.feature.md`.
---
+## Shared local embedding model
+
+`SentenceTransformersProvider` returns a separate, closeable `Embeddings`
+handle for each caller. Handles share one resident backend per process, keyed
+by the model, revision, device, loader and encoding options, cache directory
+and local file metadata. They retain no weights themselves. User settings, credentials,
+documents and returned vectors are not cached. Provider admission still runs
+before every new handle is created, including when the model is already warm.
+
+Embedding calls on the resident model run **one at a time**. Tokenization and
+some forward passes mutate model and tokenizer state even in evaluation mode,
+so admitted calls take turns on the one model; synchronous and asynchronous
+callers wait for the same turn. No second copy of the model or its weights is
+created. Creating a handle for the warm model does not wait for a running
+call.
+
+Construction and inference use an exclusive/shared access gate. Model loading,
+configuration changes and cleanup wait for all admitted inference calls,
+including calls still waiting for their turn. Waiting writers take priority
+over new readers. This also prevents Transformers'
+temporary process-wide dtype/initialization changes during construction from
+affecting inference. Changing configurations releases the old model and
+collects its reference cycles before loading another model.
+An old handle can reload its configuration using local files only. If
+those files changed after the handle was created, including during the reload,
+it raises and discards that model instead of silently using different weights.
+A first load whose files change while it runs, such as an authorized download
+or repair, is repeated once from local files. That model is kept only if the
+files stay unchanged while it loads; otherwise creating the handle raises.
+Callers should create a new handle after changing a
+model installation. Artifact tracking follows module directory links, with
+cycle detection, as well as individual file links.
+
+The gate is held for a whole constructor call, including any download inside
+it. A policy-authorized first download or repair of an embedding model still
+runs inside its constructor, so it blocks other local embedding calls until it
+finishes. The `sentence` text splitter is separate: it builds its own
+`SentenceTransformer` for tokenization outside this cache and gate, so the
+gate does not cover its construction or downloads.
+
+Closing a handle does not evict the warm model or invalidate other callers.
+`clear_sentence_transformer_cache()` releases the resident model. App shutdown
+and the process-exit hook use `wait=False`: they clear an idle cache but do not
+wait behind a long-running inference call. The app makes this nonblocking lock
+attempt directly so a saturated thread pool cannot delay log flushing and
+database cleanup; cleanup failures also leave those later steps reachable.
+Clearing an idle model collects its reference cycles on the shutdown thread.
+The operating system reclaims a busy model at process exit. Full garbage
+collection occurs on eviction or cache clearing, not on every search. Native
+allocators can retain freed pages; the operating system's RSS need not fall
+immediately by the full size of the model.
+
+This bounds resident weights and simultaneous embedding calls, not total
+process RAM. The active call needs one inference workspace; larger batches
+and longer texts still cost more memory. Vector indexes and separate sentence
+text splitters have additional memory costs. Each server worker has its own cache.
+Serial calls do not change Torch/BLAS thread settings:
+one call can still use several CPU threads. No request thread-count
+or CPU-affinity setting is a RAM limit.
+
+The cache holds exactly one model per worker, so alternating configurations
+reload it. Creating a handle for a different configuration evicts the resident
+model and loads the new one; an older handle's next call then evicts that
+model and reloads its own. Examples are two collections indexed with different
+embedding models, users with different embedding model or device settings, and
+the embedding test (`/api/rag/test-embedding`) with a model other than the one
+in use. Each switch costs a full garbage collection and a full load of the
+other model from local files, reading and building all of its weights. No
+other local embedding call in that worker runs during the switch. Work that
+alternates between two configurations call by call therefore pays a model load
+on every call. Keeping several models resident would avoid the reloads but
+cost each extra model's RAM; this cache keeps one.
+
## Glossary
- **`_owns_llm`** — instance flag set in `__init__` to `True` when the
diff --git a/src/local_deep_research/defaults/research_library/library_settings.json b/src/local_deep_research/defaults/research_library/library_settings.json
index a37856e390..6547794c80 100644
--- a/src/local_deep_research/defaults/research_library/library_settings.json
+++ b/src/local_deep_research/defaults/research_library/library_settings.json
@@ -73,7 +73,7 @@
},
"rag.indexing_max_parallel_docs": {
"category": "research_library",
- "description": "Maximum number of documents indexed concurrently within a single indexing job (per-user). One job holds up to this many workers; each worker calls the existing per-document path so the FAISS write lock still serializes the disk-merge step. Lower if your embedding backend (e.g. local CPU sentence-transformers) is throughput-bound and concurrent calls contend; raise to e.g. 8-16 for sentence-transformers on GPU, or HTTP embedding providers (OpenAI-compatible, vLLM, Ollama with OLLAMA_NUM_PARALLEL>1). Default 4 keeps RAM modest for collections with many large documents.",
+ "description": "Maximum number of documents indexed concurrently within a single indexing job (per-user). One job holds up to this many workers; each worker calls the existing per-document path so the FAISS write lock still serializes the disk-merge step. Lower if your embedding backend is throughput-bound and concurrent calls contend; local sentence-transformers run one embedding call at a time per process, so raise to e.g. 8-16 mainly for HTTP embedding providers (OpenAI-compatible, vLLM, Ollama with OLLAMA_NUM_PARALLEL>1). Default 4 keeps RAM modest for collections with many large documents.",
"editable": true,
"max_value": 16,
"min_value": 1,
diff --git a/src/local_deep_research/embeddings/model_cache.py b/src/local_deep_research/embeddings/model_cache.py
new file mode 100644
index 0000000000..32276b6f2d
--- /dev/null
+++ b/src/local_deep_research/embeddings/model_cache.py
@@ -0,0 +1,331 @@
+"""One resident local embedding backend; callers own weight-free handles.
+
+The cache contains model weights/tokenizer only, never user settings, documents,
+query results, or authorization decisions. Provider admission runs before this
+module is called. Inference is serial: one call at a time uses the resident
+model, and model replacement waits until every admitted call finishes.
+"""
+
+from __future__ import annotations
+
+import atexit
+from copy import deepcopy
+import gc
+import hashlib
+from pathlib import Path
+import re
+from stat import S_ISDIR
+from threading import Lock, local
+from typing import Any, Callable, TypeVar
+
+from langchain_core.embeddings import Embeddings
+
+from .model_loading import MODEL_LOAD_LOCK, load_sentence_transformer
+from ..security.secure_logging import logger
+
+_Result = TypeVar("_Result")
+_Factory = Callable[..., Embeddings]
+_CacheKey = tuple[tuple[_Factory, Any], str]
+
+
+def _freeze(value: Any) -> Any:
+ if isinstance(value, dict):
+ return tuple(
+ sorted((key, _freeze(item)) for key, item in value.items())
+ )
+ if isinstance(value, (list, tuple)):
+ return tuple(_freeze(item) for item in value)
+ return value
+
+
+def _artifact_stamp(kwargs: dict) -> str:
+ """Notice local replacements and floating Hub ref changes without I/O
+ of model contents or contacting the network.
+
+ Hub snapshots consist of links to immutable blobs. Stat follows those links
+ so an operator replacing a blob also changes the key. Local module directory
+ links are followed too, visiting each directory once to stop cycles. A handle
+ cannot reload changed files after eviction and silently use different weights.
+ """
+ name = kwargs["model_name"]
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Provider admission confines absolute model paths to the app models directory; the stamp only stats and lists entries
+ path = Path(name)
+ references = []
+ if path.is_absolute():
+ roots = [path]
+ else:
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Operator model cache root; admitted repository ids have slashes replaced and revisions are catalog or cached commit ids
+ cache = Path(kwargs["cache_folder"])
+ repositories = [name]
+ if "/" not in name:
+ repositories.append(f"sentence-transformers/{name}")
+ roots = []
+ revision = kwargs.get("model_kwargs", {}).get("revision")
+ for repository in repositories:
+ cached_repo = cache / ("models--" + repository.replace("/", "--"))
+ snapshot = revision
+ if not revision or not re.fullmatch(r"[0-9a-f]{40}", revision):
+ reference = cached_repo / "refs" / (revision or "main")
+ references.append(reference)
+ try:
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Reads refs/main of an admitted repository inside the operator model cache; repository ids have slashes replaced and provider revisions are commit ids
+ snapshot = reference.read_text(encoding="ascii").strip()
+ except FileNotFoundError:
+ snapshot = None
+ if snapshot and re.fullmatch(r"[0-9a-f]{40}", snapshot):
+ roots.append(cached_repo / "snapshots" / snapshot)
+ # Do not scan all snapshots/blobs or .no_exist markers: warming an
+ # unrelated revision must not invalidate handles pinned to old bytes.
+ roots.extend(references)
+ digest = hashlib.sha256()
+ for root in roots:
+ # Missing files are part of the identity too (initial download/repair).
+ digest.update(str(root).encode())
+ paths = [root]
+ seen_directories = set()
+ while paths:
+ path = paths.pop()
+ try:
+ stat = path.stat()
+ except FileNotFoundError:
+ continue
+ digest.update(str(path).encode())
+ digest.update(
+ repr(
+ (
+ stat.st_dev,
+ stat.st_ino,
+ stat.st_size,
+ stat.st_mtime_ns,
+ stat.st_ctime_ns,
+ )
+ ).encode()
+ )
+ if S_ISDIR(stat.st_mode):
+ # rglob does not descend into directory symlinks. Stamp the
+ # target and its files, while preventing alias/cycle expansion.
+ directory = (stat.st_dev, stat.st_ino)
+ if directory in seen_directories:
+ continue
+ seen_directories.add(directory)
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Lists an admitted model root and its linked module directories only to stat entries; no file contents are read or written
+ paths.extend(sorted(path.iterdir(), reverse=True))
+ return digest.hexdigest()
+
+
+class _ModelCache:
+ def __init__(self) -> None:
+ self.key: _CacheKey | None = None
+ self.backend: Embeddings | None = None
+ # Tokenization and forward passes mutate model and tokenizer state,
+ # so admitted calls take turns on the one resident backend.
+ self._inference = Lock()
+ self._inference_state = local()
+
+ def _clear_locked(self) -> None:
+ had_model = self.backend is not None
+ self.backend = None
+ self.key = None
+ if had_model:
+ # SentenceTransformer -> model_card_data -> SentenceTransformer
+ # is a strong cycle. Dropping the wrapper alone retains hundreds
+ # of MiB until a generation-2 collection eventually happens.
+ gc.collect()
+
+ def clear(self, *, wait: bool = True) -> bool:
+ if MODEL_LOAD_LOCK.acquire(blocking=wait):
+ try:
+ self._clear_locked()
+ return True
+ finally:
+ MODEL_LOAD_LOCK.release()
+ return False
+
+ def prepare(
+ self, factory: _Factory, kwargs: dict[str, Any]
+ ) -> SharedSentenceTransformerEmbeddings:
+ # A warm handle for an identical configuration is created without
+ # waiting for active calls; its own calls then wait for their turn.
+ with MODEL_LOAD_LOCK.inference():
+ options, identity = self._options(factory, kwargs)
+ key = (identity, _artifact_stamp(kwargs))
+ if self.key == key:
+ return SharedSentenceTransformerEmbeddings(
+ self, factory, options, key
+ )
+ with MODEL_LOAD_LOCK:
+ return self._prepare_locked(factory, kwargs)
+
+ @staticmethod
+ def _options(factory: _Factory, kwargs: dict[str, Any]):
+ local_options = deepcopy(kwargs)
+ local_options.setdefault("model_kwargs", {})["local_files_only"] = True
+ return local_options, (factory, _freeze(local_options))
+
+ def _load_locked(self, factory: _Factory, kwargs: dict[str, Any]) -> None:
+ self.backend = load_sentence_transformer(factory, **kwargs)
+
+ def _prepare_locked(
+ self, factory: _Factory, kwargs: dict[str, Any]
+ ) -> SharedSentenceTransformerEmbeddings:
+ options = deepcopy(kwargs)
+ # Network permission is checked by the provider on EVERY request.
+ # It is not a property of the resident weights. After initial
+ # construction, an evicted handle may only reload local files.
+ local_options, identity = self._options(factory, options)
+ stamp = _artifact_stamp(options)
+ key = (identity, stamp)
+ if self.key != key:
+ self._clear_locked()
+ logger.info("Loading resident local embedding model")
+ try:
+ self._load_locked(factory, options)
+ loaded = _artifact_stamp(options)
+ if loaded != stamp:
+ # An authorized download/repair, or a replacement, changed
+ # the files while the constructor read them, so neither
+ # stamp need describe the loaded bytes. Load once more
+ # from local files and keep it only if they stay intact.
+ self._clear_locked()
+ logger.info(
+ "Reloading local embedding model after its files changed"
+ )
+ self._load_locked(factory, local_options)
+ stamp, loaded = loaded, _artifact_stamp(options)
+ except BaseException:
+ self._clear_locked()
+ raise
+ if loaded != stamp:
+ self._clear_locked()
+ raise ValueError(
+ "Local embedding model files changed; create a new embedding client"
+ )
+ key = (identity, stamp)
+ self.key = key
+ return SharedSentenceTransformerEmbeddings(
+ self, factory, local_options, key
+ )
+
+ def embed(
+ self,
+ handle: SharedSentenceTransformerEmbeddings,
+ operation: Callable[[Embeddings], _Result],
+ ) -> _Result:
+ while True:
+ with MODEL_LOAD_LOCK.inference():
+ if handle._closed:
+ raise RuntimeError("Embedding client is closed")
+ if self.key == handle._key:
+ return self._run_serially(handle, operation)
+ # Never upgrade shared access in place: another reader may also
+ # need a different model. Recheck after obtaining exclusive access.
+ with MODEL_LOAD_LOCK:
+ self._reload_locked(handle)
+
+ def _reload_locked(
+ self, handle: SharedSentenceTransformerEmbeddings
+ ) -> None:
+ if handle._closed:
+ raise RuntimeError("Embedding client is closed")
+ if self.key != handle._key:
+ if _artifact_stamp(handle._kwargs) != handle._key[1]:
+ raise ValueError(
+ "Local embedding model files changed; create a new embedding client"
+ )
+ self._clear_locked()
+ logger.info("Reloading evicted local embedding model")
+ try:
+ self._load_locked(handle._factory, handle._kwargs)
+ # An operator or another process can replace artifacts while
+ # the constructor reads them. Never give an old handle the
+ # resulting weights under its original configuration identity.
+ stamp = _artifact_stamp(handle._kwargs)
+ except BaseException:
+ self._clear_locked()
+ raise
+ if stamp != handle._key[1]:
+ self._clear_locked()
+ raise ValueError(
+ "Local embedding model files changed; create a new embedding client"
+ )
+ self.key = handle._key
+
+ def _run_serially(
+ self,
+ handle: SharedSentenceTransformerEmbeddings,
+ operation: Callable[[Embeddings], _Result],
+ ) -> _Result:
+ # The caller holds shared access, so no writer can replace the backend
+ # while this call waits for its turn or runs. The returned vectors are
+ # ordinary lists; no caller keeps a model reference that could defeat
+ # eviction or the one-model cap.
+ backend = self.backend
+ if backend is None:
+ raise RuntimeError("Local embedding model was not initialized")
+ if getattr(self._inference_state, "active", False):
+ # The inference lock is not reentrant; waiting would deadlock.
+ raise RuntimeError(
+ "Recursive local embedding inference is not supported"
+ )
+ with self._inference:
+ try:
+ self._inference_state.active = True
+ if handle._closed:
+ raise RuntimeError("Embedding client is closed")
+ return operation(backend)
+ finally:
+ self._inference_state.active = False
+
+
+class SharedSentenceTransformerEmbeddings(Embeddings):
+ """Per-caller lifecycle/configuration, with no ownership of model weights."""
+
+ def __init__(
+ self,
+ cache: _ModelCache,
+ factory: _Factory,
+ kwargs: dict[str, Any],
+ key: _CacheKey,
+ ) -> None:
+ self._cache = cache
+ self._factory = factory
+ self._kwargs = kwargs
+ self._key = key
+ self._closed = False
+
+ def embed_documents(self, texts: list[str]) -> list[list[float]]:
+ return self._cache.embed(
+ self, lambda backend: backend.embed_documents(texts)
+ )
+
+ def embed_query(self, text: str) -> list[float]:
+ return self._cache.embed(
+ self, lambda backend: backend.embed_query(text)
+ )
+
+ def close(self) -> None:
+ # Closing one search must not invalidate another search's handle.
+ # Already-started inference may finish; future calls are refused.
+ self._closed = True
+
+
+_MODEL_CACHE = _ModelCache()
+
+
+def shared_sentence_transformer_embeddings(
+ factory: Callable[..., Embeddings], **kwargs: Any
+) -> Embeddings:
+ """Prepare a checked provider configuration and return a lightweight handle."""
+ return _MODEL_CACHE.prepare(factory, kwargs)
+
+
+def clear_sentence_transformer_cache(*, wait: bool = True) -> bool:
+ """Release weights, returning False if shutdown finds inference busy.
+
+ Shutdown must not wait indefinitely for a daemon research worker. In that
+ case the process exit reclaims its active model along with the worker.
+ """
+ return _MODEL_CACHE.clear(wait=wait)
+
+
+atexit.register(clear_sentence_transformer_cache, wait=False)
diff --git a/src/local_deep_research/embeddings/model_loading.py b/src/local_deep_research/embeddings/model_loading.py
new file mode 100644
index 0000000000..4c4f75e71f
--- /dev/null
+++ b/src/local_deep_research/embeddings/model_loading.py
@@ -0,0 +1,107 @@
+"""Keep model loading exclusive while allowing resident-model inference."""
+
+from contextlib import contextmanager
+from threading import Condition, RLock, get_ident
+from typing import Any, Callable, TypeVar
+
+_Model = TypeVar("_Model")
+
+
+class ModelAccessLock:
+ """Reentrant writer lock with shared inference access.
+
+ Shared holders create handles for the warm model and run admitted
+ embedding calls; the model cache lets those calls use the model one at a
+ time. Writers take priority over new readers, so configuration changes and
+ cleanup cannot starve behind a stream of inference requests. The cache's
+ model constructors also use this gate: Transformers temporarily changes
+ process-wide dtype and initialization state, which must not overlap
+ resident inference.
+ """
+
+ def __init__(self) -> None:
+ self._condition = Condition(RLock())
+ self._writer: int | None = None
+ self._depth = 0
+ self._readers: dict[int, int] = {}
+ self._waiting_writers = 0
+
+ def acquire(self, blocking: bool = True) -> bool:
+ if not self._condition.acquire(blocking=blocking):
+ return False
+ try:
+ owner = get_ident()
+ if self._writer == owner:
+ self._depth += 1
+ return True
+ if not blocking and (self._writer is not None or self._readers):
+ return False
+ if owner in self._readers:
+ raise RuntimeError(
+ "Cannot load or clear a model during inference"
+ )
+ self._waiting_writers += 1
+ try:
+ while self._writer is not None or self._readers:
+ self._condition.wait()
+ self._writer = owner
+ self._depth = 1
+ return True
+ finally:
+ self._waiting_writers -= 1
+ self._condition.notify_all()
+ finally:
+ self._condition.release()
+
+ def release(self) -> None:
+ with self._condition:
+ if self._writer != get_ident():
+ raise RuntimeError(
+ "Model loading lock is not owned by this thread"
+ )
+ self._depth -= 1
+ if not self._depth:
+ self._writer = None
+ self._condition.notify_all()
+
+ def __enter__(self):
+ self.acquire()
+ return self
+
+ def __exit__(self, *_exc):
+ self.release()
+
+ @contextmanager
+ def inference(self):
+ owner = get_ident()
+ with self._condition:
+ while self._writer != owner and (
+ self._writer is not None
+ or (self._waiting_writers and owner not in self._readers)
+ ):
+ self._condition.wait()
+ self._readers[owner] = self._readers.get(owner, 0) + 1
+ try:
+ yield
+ finally:
+ with self._condition:
+ self._readers[owner] -= 1
+ if not self._readers[owner]:
+ del self._readers[owner]
+ self._condition.notify_all()
+
+
+MODEL_LOAD_LOCK = ModelAccessLock()
+
+
+def load_sentence_transformer(
+ factory: Callable[..., _Model], **kwargs: Any
+) -> _Model:
+ """Keep Transformers' dtype and initialization helpers out of races.
+
+ The gate is held for the whole constructor call and blocks every local
+ embedding call, so a constructor that downloads holds it for the whole
+ download.
+ """
+ with MODEL_LOAD_LOCK:
+ return factory(**kwargs)
diff --git a/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py b/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py
index 5da6e306b9..b66fbb3ecb 100644
--- a/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py
+++ b/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py
@@ -9,6 +9,7 @@ from langchain_core.embeddings import Embeddings
from ....security.secure_logging import logger
from ....config.thread_settings import get_setting_from_snapshot
+from ...model_cache import shared_sentence_transformer_embeddings
from ...sentence_transformer_models import (
DEFAULT_SENTENCE_TRANSFORMER_MODEL,
SENTENCE_TRANSFORMER_MODELS,
@@ -47,7 +48,7 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
**kwargs,
) -> Embeddings:
"""
- Create Sentence Transformers embeddings instance.
+ Create a Sentence Transformers embeddings handle.
Args:
model: Model name (defaults to Alibaba-NLP/gte-modernbert-base)
@@ -55,7 +56,8 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
**kwargs: Additional parameters (device, etc.)
Returns:
- SentenceTransformerEmbeddings instance
+ A closeable handle to the process-wide resident model; it holds
+ no weights itself.
"""
from langchain_community.embeddings import (
SentenceTransformerEmbeddings,
@@ -79,7 +81,7 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
)
logger.info(
- f"Creating SentenceTransformerEmbeddings with model={model}, device={device}"
+ f"Preparing local embeddings with model={model}, device={device}"
)
# Constructing a cache-missing model is itself an egress action. It is
@@ -148,7 +150,8 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
)
cache_dir = cls._model_cache_directory()
if local_model_path is not None:
- return SentenceTransformerEmbeddings(
+ return shared_sentence_transformer_embeddings(
+ SentenceTransformerEmbeddings,
model_name=str(local_model_path),
cache_folder=cache_dir,
model_kwargs={
@@ -175,7 +178,8 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
"in local-only mode (not in catalog but already cached)",
model,
)
- return SentenceTransformerEmbeddings(
+ return shared_sentence_transformer_embeddings(
+ SentenceTransformerEmbeddings,
model_name=model,
cache_folder=cache_dir,
model_kwargs={
@@ -268,7 +272,8 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
)
try:
- return SentenceTransformerEmbeddings(
+ return shared_sentence_transformer_embeddings(
+ SentenceTransformerEmbeddings,
model_name=resolved_model,
cache_folder=cache_dir,
model_kwargs=model_kwargs,
@@ -304,7 +309,8 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
raise
repair_kwargs = dict(model_kwargs)
repair_kwargs.pop("local_files_only")
- return SentenceTransformerEmbeddings(
+ return shared_sentence_transformer_embeddings(
+ SentenceTransformerEmbeddings,
model_name=resolved_model,
cache_folder=cache_dir,
model_kwargs=repair_kwargs,
diff --git a/src/local_deep_research/utilities/llm_utils.py b/src/local_deep_research/utilities/llm_utils.py
index ede31f0270..668fa0d2e9 100644
--- a/src/local_deep_research/utilities/llm_utils.py
+++ b/src/local_deep_research/utilities/llm_utils.py
@@ -115,9 +115,11 @@ def _close_base_llm(llm):
init by a Pydantic ``@model_validator(mode="after")``. ``ChatAnthropic``
and ``ChatOpenAI`` use ``@lru_cache``'d shared httpx clients that must
NOT be closed; the ``ollama``-module check below short-circuits cleanly
- for them. Same skip applies to local providers like
- ``HuggingFaceEmbeddings`` / ``SentenceTransformerEmbeddings`` (no
- per-instance httpx client at all).
+ for them. Raw ``HuggingFaceEmbeddings`` /
+ ``SentenceTransformerEmbeddings`` instances are skipped the same way (no
+ per-instance httpx client at all). The Sentence Transformers provider
+ returns a shared-model handle with its own ``close()``, which the
+ delegation below calls; it closes only that handle, not the shared model.
Each Ollama class owns both ``_client`` (sync ``ollama.Client`` wrapping
``httpx.Client``) and ``_async_client`` (async ``ollama.AsyncClient``
diff --git a/src/local_deep_research/web/fastapi_app.py b/src/local_deep_research/web/fastapi_app.py
index cb9c47201d..b4f4fb840f 100644
--- a/src/local_deep_research/web/fastapi_app.py
+++ b/src/local_deep_research/web/fastapi_app.py
@@ -559,6 +559,16 @@ async def lifespan(app: FastAPI):
except Exception:
logger.debug("Error stopping queue processor")
+ try:
+ from ..embeddings.model_cache import clear_sentence_transformer_cache
+
+ # This lock attempt never waits for inference. Queueing it on the
+ # default executor would still wait when inference occupies that pool,
+ # delaying log/database cleanup. Traffic has drained at this point.
+ clear_sentence_transformer_cache(wait=False)
+ except Exception:
+ logger.debug("Error clearing embedding model cache during shutdown")
+
# Flush pending DB log writes BEFORE closing databases; `database_sink`
# swallows errors silently, so anything flushed after close is just
# dropped.
diff --git a/src/local_deep_research/web_search_engines/engines/local_embedding_manager.py b/src/local_deep_research/web_search_engines/engines/local_embedding_manager.py
index 4067476ba1..ee8a5295af 100644
--- a/src/local_deep_research/web_search_engines/engines/local_embedding_manager.py
+++ b/src/local_deep_research/web_search_engines/engines/local_embedding_manager.py
@@ -63,9 +63,9 @@ class LocalEmbeddingManager:
``OllamaEmbeddings`` eagerly constructs both clients in its Pydantic
``@model_validator(mode="after")``, so dropping the Python reference
alone leaks ~2 FDs per instance — see the migration regression note
- in docs/developing/resource-cleanup.md. Non-Ollama providers
- (sentence_transformers, OpenAI's lru_cache'd shared client) are
- no-ops via the module-prefix check inside ``_close_base_llm``.
+ in docs/developing/resource-cleanup.md. Sentence Transformers closes
+ this manager's lightweight handle; the shared weights stay available
+ for the next search. OpenAI's shared HTTP client remains open.
"""
if self._closed:
return
diff --git a/tests/embeddings/conftest.py b/tests/embeddings/conftest.py
index 0cb885deec..2ff756ad7b 100644
--- a/tests/embeddings/conftest.py
+++ b/tests/embeddings/conftest.py
@@ -6,6 +6,17 @@ import pytest
from unittest.mock import Mock
[email protected](autouse=True)
+def clear_local_model_cache():
+ from local_deep_research.embeddings.model_cache import (
+ clear_sentence_transformer_cache,
+ )
+
+ clear_sentence_transformer_cache()
+ yield
+ clear_sentence_transformer_cache()
+
+
@pytest.fixture
def mock_settings_snapshot():
"""Create a mock settings snapshot for testing."""
diff --git a/tests/embeddings/test_model_cache.py b/tests/embeddings/test_model_cache.py
new file mode 100644
index 0000000000..7ec961dcb3
--- /dev/null
+++ b/tests/embeddings/test_model_cache.py
@@ -0,0 +1,690 @@
+"""Memory ownership and concurrent use of the resident embedding backend."""
+
+from concurrent.futures import ThreadPoolExecutor
+import gc
+from pathlib import Path
+from threading import Barrier, Event
+from types import SimpleNamespace
+import weakref
+
+import pytest
+
+from local_deep_research.embeddings import model_cache
+from local_deep_research.embeddings.model_cache import (
+ clear_sentence_transformer_cache,
+ shared_sentence_transformer_embeddings,
+)
+
+
+class CyclicBackend:
+ def __init__(self, model_name, **kwargs):
+ self.name = model_name
+ self.cycle = self
+
+ def embed_query(self, text):
+ return [float(len(text))]
+
+ def embed_documents(self, texts):
+ return [self.embed_query(text) for text in texts]
+
+
+def models(tmp_path):
+ refs = []
+ calls = []
+
+ def factory(**kwargs):
+ calls.append(kwargs)
+ backend = CyclicBackend(**kwargs)
+ refs.append(weakref.ref(backend))
+ return backend
+
+ def create(name="synthetic/model", **options):
+ return shared_sentence_transformer_embeddings(
+ factory,
+ model_name=name,
+ cache_folder=str(tmp_path),
+ model_kwargs=options,
+ )
+
+ return create, calls, refs
+
+
+def test_finished_searches_reuse_weights_and_do_not_share_results(models):
+ create, calls, refs = models
+ for i in range(12):
+ client = create(device="cpu", revision="one")
+ result = client.embed_query("query" + "x" * i)
+ assert result == [float(5 + i)]
+ result[0] = -1 # A caller cannot poison a subsequent result.
+ client.close()
+ assert len(calls) == 1
+ assert sum(ref() is not None for ref in refs) == 1
+
+
+def test_handles_do_not_pin_evicted_models_or_their_cycles(models):
+ create, calls, refs = models
+ was_enabled = gc.isenabled()
+ gc.disable() # Prove eviction does not depend on automatic collection.
+ try:
+ first = create("synthetic/first")
+ second = create("synthetic/second")
+ assert refs[0]() is None
+ assert refs[1]() is not None
+ assert first.embed_query("reloaded") == [8.0]
+ assert refs[1]() is None
+ assert refs[2]() is not None
+ assert len(calls) == 3
+ assert calls[-1]["model_kwargs"]["local_files_only"] is True
+ clear_sentence_transformer_cache()
+ assert all(ref() is None for ref in refs)
+ # Both lightweight handles still exist, but neither owns weights.
+ assert not first._closed and not second._closed
+ finally:
+ if was_enabled:
+ gc.enable()
+
+
+ "first,second",
+ [
+ ({"device": "cpu"}, {"device": "cuda"}),
+ ({"revision": "one"}, {"revision": "two"}),
+ (
+ {"model_kwargs": {"torch_dtype": "float16"}},
+ {"model_kwargs": {"torch_dtype": "float32"}},
+ ),
+ ],
+)
+def test_model_options_are_part_of_the_identity(models, first, second):
+ create, calls, refs = models
+ a = create(**first)
+ b = create(**second)
+ assert len(calls) == 2
+ assert refs[0]() is None
+ assert a is not b
+
+
+def test_close_is_per_handle_and_idempotent(models):
+ create, calls, refs = models
+ a, b = create(), create()
+ a.close()
+ a.close()
+ with pytest.raises(RuntimeError, match="closed"):
+ a.embed_query("closed")
+ assert b.embed_documents(["a", "bb"]) == [[1.0], [2.0]]
+ assert len(calls) == 1 and refs[0]() is not None
+
+
+def test_simultaneous_first_users_load_one_model(models):
+ create, calls, _ = models
+ barrier = Barrier(6)
+
+ def search(i):
+ barrier.wait(timeout=10)
+ client = create()
+ try:
+ return client.embed_query("x" * i)
+ finally:
+ client.close()
+
+ with ThreadPoolExecutor(max_workers=6) as executor:
+ results = list(executor.map(search, range(6)))
+ assert results == [[float(i)] for i in range(6)]
+ assert len(calls) == 1
+
+
+def test_eviction_waits_for_inference(tmp_path):
+ entered, release, requested = Event(), Event(), Event()
+ refs = []
+
+ class BlockingBackend(CyclicBackend):
+ def embed_query(self, text):
+ entered.set()
+ assert release.wait(timeout=10)
+ assert refs[0]() is self
+ return super().embed_query(text)
+
+ def factory(**kwargs):
+ backend = BlockingBackend(**kwargs)
+ refs.append(weakref.ref(backend))
+ return backend
+
+ def create(name):
+ return shared_sentence_transformer_embeddings(
+ factory,
+ model_name=name,
+ cache_folder=str(tmp_path),
+ model_kwargs={},
+ )
+
+ def replace():
+ requested.set()
+ return create("synthetic/second")
+
+ first = create("synthetic/first")
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ inference = executor.submit(first.embed_query, "busy")
+ assert entered.wait(timeout=10)
+ replacement = executor.submit(replace)
+ assert requested.wait(timeout=10)
+ try:
+ assert clear_sentence_transformer_cache(wait=False) is False
+ assert not replacement.done()
+ assert len(refs) == 1
+ finally:
+ release.set()
+ assert inference.result(timeout=10) == [4.0]
+ replacement.result(timeout=10)
+ assert refs[0]() is None and refs[1]() is not None
+
+
+def test_failed_load_is_retryable_and_never_poisoned(tmp_path):
+ attempts = []
+
+ def factory(**kwargs):
+ attempts.append(kwargs)
+ if len(attempts) == 1:
+ raise OSError("synthetic missing weights")
+ return CyclicBackend(**kwargs)
+
+ kwargs = dict(
+ model_name="synthetic/model",
+ cache_folder=str(tmp_path),
+ model_kwargs={},
+ )
+ with pytest.raises(OSError):
+ shared_sentence_transformer_embeddings(factory, **kwargs)
+ client = shared_sentence_transformer_embeddings(factory, **kwargs)
+ assert client.embed_query("retry") == [5.0]
+ assert len(attempts) == 2
+
+
+def test_encoding_options_are_part_of_the_configuration(tmp_path):
+ calls = []
+
+ def factory(**kwargs):
+ calls.append(kwargs)
+ return CyclicBackend(**kwargs)
+
+ def create(**encode_kwargs):
+ return shared_sentence_transformer_embeddings(
+ factory,
+ model_name="synthetic/model",
+ cache_folder=str(tmp_path),
+ encode_kwargs=encode_kwargs,
+ )
+
+ create(normalize_embeddings=True, prompt="query: ")
+ create(prompt="query: ", normalize_embeddings=True)
+ assert len(calls) == 1
+ create(normalize_embeddings=False, prompt="query: ")
+ create(normalize_embeddings=False, prompt="document: ")
+ assert len(calls) == 3
+
+
+def test_recursive_serial_backend_fails_instead_of_waiting_for_its_own_slot(
+ tmp_path,
+):
+ class RecursiveBackend(CyclicBackend):
+ def embed_query(self, text):
+ if text == "recursive":
+ return client.embed_query("inner")
+ return super().embed_query(text)
+
+ client = shared_sentence_transformer_embeddings(
+ RecursiveBackend,
+ model_name="synthetic/model",
+ cache_folder=str(tmp_path),
+ )
+ with pytest.raises(RuntimeError, match="Recursive local embedding"):
+ client.embed_query("recursive")
+ assert client.embed_query("recovered") == [9.0]
+
+
+def test_local_replacement_invalidates_cache_and_old_handles(models, tmp_path):
+ create, calls, refs = models
+ model_dir = tmp_path / "local-model"
+ model_dir.mkdir()
+ weight = model_dir / "model.safetensors"
+ weight.write_bytes(b"synthetic-v1")
+ old = create(str(model_dir))
+ # A same-path replacement has a different file identity, even if size and
+ # timestamps have low resolution on the platform running this test.
+ replacement = model_dir / "replacement"
+ replacement.write_bytes(b"synthetic-v2-longer")
+ replacement.replace(weight)
+ new = create(str(model_dir))
+ assert len(calls) == 2 and refs[0]() is None
+ assert new.embed_query("new") == [3.0]
+ with pytest.raises(ValueError, match="files changed"):
+ old.embed_query("old")
+ assert len(calls) == 2
+
+
+class ArtifactBackend(CyclicBackend):
+ def __init__(self, value, **kwargs):
+ super().__init__(**kwargs)
+ self.value = value
+
+ def embed_query(self, _text):
+ return [self.value]
+
+
+def _model_artifacts(tmp_path, layout):
+ """Synthetic weights "1"; each replacement toggles them between 1 and 2.
+
+ ``local`` rewrites a file in an explicit model directory. ``hub_ref``
+ moves a Hub cache's floating ``refs/main`` between two snapshots.
+
+ Neither change may depend on the clock. The artifact stamp sees an
+ in-place rewrite through size and timestamps only, and a rewrite
+ microseconds after the previous write can keep the same timestamps on
+ coarse filesystems. So the ``local`` rewrite also changes the size. The
+ ``hub_ref`` move changes the stamped snapshot path itself.
+ """
+ cache_dir = tmp_path / "hub"
+ if layout == "local":
+ model = tmp_path / "local-model"
+ model.mkdir()
+ weights = model / "model.safetensors"
+ weights.write_text("1")
+
+ def current_weights():
+ return float(weights.read_text())
+
+ def replace_weights():
+ weights.write_text("2.0" if current_weights() == 1.0 else "1")
+
+ return str(model), cache_dir, current_weights, replace_weights
+
+ repository = cache_dir / "models--synthetic--model"
+ for revision, value in (("a" * 40, "1"), ("b" * 40, "2")):
+ snapshot = repository / "snapshots" / revision
+ snapshot.mkdir(parents=True)
+ (snapshot / "model.safetensors").write_text(value)
+ (repository / "refs").mkdir()
+ reference = repository / "refs/main"
+ reference.write_text("a" * 40)
+
+ def current_weights():
+ return float(
+ (
+ repository
+ / "snapshots"
+ / reference.read_text()
+ / "model.safetensors"
+ ).read_text()
+ )
+
+ def replace_weights():
+ reference.write_text("b" * 40 if current_weights() == 1.0 else "a" * 40)
+
+ return "synthetic/model", cache_dir, current_weights, replace_weights
+
+
+def coarse_clock(monkeypatch):
+ """Hide file timestamps from the artifact stamp, as one tick would.
+
+ Tests using ``_model_artifacts`` then pass or fail the same way on every
+ filesystem, however fine its timestamps.
+ """
+
+ class CoarseClockPath(type(Path())):
+ def stat(self, *, follow_symlinks=True):
+ real = super().stat(follow_symlinks=follow_symlinks)
+ return SimpleNamespace(
+ st_mode=real.st_mode,
+ st_dev=real.st_dev,
+ st_ino=real.st_ino,
+ st_size=real.st_size,
+ st_mtime_ns=0,
+ st_ctime_ns=0,
+ )
+
+ monkeypatch.setattr(model_cache, "Path", CoarseClockPath)
+
+
[email protected]("coarse_clock")
[email protected]("layout", ["local", "hub_ref"])
[email protected]("replace_during_load", [False, True])
+def test_evicted_reload_rechecks_artifacts_after_loading(
+ tmp_path, layout, replace_during_load
+):
+ """An old handle must never adopt weights replaced during its reload."""
+ model_name, cache_dir, current_weights, replace_weights = _model_artifacts(
+ tmp_path, layout
+ )
+ calls = []
+ refs = []
+ replacing = False
+
+ def factory(**kwargs):
+ calls.append(kwargs)
+ if kwargs["model_name"] == model_name:
+ if replacing:
+ # Runs after pre-load validation, before the loader reads the
+ # artifacts. No timing sleeps or model download are needed.
+ replace_weights()
+ value = current_weights()
+ else:
+ value = 9.0
+ backend = ArtifactBackend(value, **kwargs)
+ refs.append(weakref.ref(backend))
+ return backend
+
+ def create(name):
+ return shared_sentence_transformer_embeddings(
+ factory, model_name=name, cache_folder=str(cache_dir)
+ )
+
+ old = create(model_name)
+ assert old.embed_query("original") == [1.0]
+ assert create("synthetic/other").embed_query("other") == [9.0]
+ replacing = replace_during_load
+ if replace_during_load:
+ with pytest.raises(ValueError, match="files changed"):
+ old.embed_query("must not use different weights")
+ assert refs[-1]() is None # Failed reload releases its model cycle.
+ replacing = False
+ fresh = create(model_name)
+ assert fresh.embed_query("new handle") == [2.0]
+ with pytest.raises(ValueError, match="files changed"):
+ old.embed_query("old handle stays invalid")
+ assert fresh.embed_query("still usable") == [2.0]
+ assert len(calls) == 4
+ else:
+ assert old.embed_query("unchanged weights") == [1.0]
+ assert len(calls) == 3
+ assert calls[2]["model_kwargs"]["local_files_only"] is True
+
+
[email protected]("coarse_clock")
[email protected]("layout", ["local", "hub_ref"])
[email protected]("replaced", ["before_read", "after_read"])
+def test_first_load_rechecks_artifacts_after_loading(
+ tmp_path, layout, replaced
+):
+ """A first load must not adopt a key describing bytes it did not load.
+
+ A download or repair populates files before the constructor reads them;
+ an operator replacement can also land after the read. Either way the
+ handle must use the bytes now on disk, before and after an eviction.
+ """
+ model_name, cache_dir, current_weights, replace_weights = _model_artifacts(
+ tmp_path, layout
+ )
+ calls = []
+ replacing = True
+
+ def factory(**kwargs):
+ nonlocal replacing
+ calls.append(kwargs)
+ if kwargs["model_name"] != model_name:
+ return ArtifactBackend(9.0, **kwargs)
+ if replacing and replaced == "before_read":
+ replace_weights()
+ value = current_weights()
+ if replacing and replaced == "after_read":
+ replace_weights()
+ replacing = False
+ return ArtifactBackend(value, **kwargs)
+
+ def create(name):
+ return shared_sentence_transformer_embeddings(
+ factory, model_name=name, cache_folder=str(cache_dir)
+ )
+
+ client = create(model_name)
+ assert client.embed_query("first call") == [2.0]
+ assert create("synthetic/other").embed_query("other") == [9.0]
+ assert client.embed_query("same handle after reload") == [2.0]
+ # The changed first load is retried once from local files, never by
+ # another download, and the reloaded handle keeps that key.
+ assert len(calls) == 4
+ assert calls[1]["model_name"] == model_name
+ assert calls[1]["model_kwargs"]["local_files_only"] is True
+
+
[email protected]("coarse_clock")
[email protected]("layout", ["local", "hub_ref"])
+def test_first_load_gives_up_when_files_keep_changing(tmp_path, layout):
+ model_name, cache_dir, current_weights, replace_weights = _model_artifacts(
+ tmp_path, layout
+ )
+ calls = []
+ refs = []
+ changing = True
+
+ def factory(**kwargs):
+ calls.append(kwargs)
+ if changing:
+ replace_weights()
+ backend = ArtifactBackend(current_weights(), **kwargs)
+ refs.append(weakref.ref(backend))
+ return backend
+
+ def create():
+ return shared_sentence_transformer_embeddings(
+ factory, model_name=model_name, cache_folder=str(cache_dir)
+ )
+
+ with pytest.raises(ValueError, match="files changed"):
+ create()
+ assert len(calls) == 2 # One bounded retry, never a loop.
+ assert all(ref() is None for ref in refs) # Neither model stays resident.
+ changing = False
+ assert create().embed_query("stable files") == [current_weights()]
+ assert len(calls) == 3
+
+
+def _model_symlink(link, target, *, directory=False):
+ try:
+ link.symlink_to(target, target_is_directory=directory)
+ except (OSError, NotImplementedError): # pragma: no cover - platform
+ pytest.skip("symlinks not supported on this platform")
+
+
[email protected]("layout", ["directory", "file_link", "directory_link"])
+def test_evicted_handle_rejects_changed_linked_artifacts(
+ models, tmp_path, layout
+):
+ create, calls, _ = models
+ model = tmp_path / "local-model"
+ backing = tmp_path / "shared-module"
+ model.mkdir()
+ backing.mkdir()
+ module = model / "0_Transformer"
+ weight = backing / "model.safetensors"
+ weight.write_bytes(b"original")
+ if layout == "directory_link":
+ _model_symlink(module, backing, directory=True)
+ else:
+ module.mkdir()
+ if layout == "file_link":
+ _model_symlink(module / weight.name, weight)
+ else:
+ weight = module / weight.name
+ weight.write_bytes(b"original")
+
+ old = create(str(model))
+ assert create(str(model)).embed_query("warm") == [4.0]
+ assert len(calls) == 1
+ create("synthetic/other") # Evict without closing the first handle.
+ weight.write_bytes(b"replacement weights")
+ with pytest.raises(ValueError, match="files changed"):
+ old.embed_query("must not reload changed weights")
+ assert len(calls) == 2
+ assert create(str(model)).embed_query("new") == [3.0]
+ assert len(calls) == 3
+
+
[email protected]("cycle", [False, True])
+def test_shared_directory_links_are_stamped_without_following_cycles(
+ models, tmp_path, cycle
+):
+ create, calls, _ = models
+ model = tmp_path / "local-model"
+ backing = tmp_path / "shared-module"
+ model.mkdir()
+ backing.mkdir()
+ _model_symlink(model / "first", backing, directory=True)
+ _model_symlink(model / "second", backing, directory=True)
+ if cycle:
+ _model_symlink(backing / "parent", model, directory=True)
+ weight = backing / "model.safetensors"
+ weight.write_bytes(b"original")
+ old = create(str(model))
+ create(str(model))
+ assert len(calls) == 1
+ weight.write_bytes(b"replacement weights")
+ create(str(model))
+ assert len(calls) == 2
+ with pytest.raises(ValueError, match="files changed"):
+ old.embed_query("old")
+
+
+def test_retargeting_a_module_directory_invalidates_old_handles(
+ models, tmp_path
+):
+ create, calls, _ = models
+ model = tmp_path / "local-model"
+ model.mkdir()
+ for name in ("original", "replacement"):
+ backing = tmp_path / name
+ backing.mkdir()
+ (backing / "model.safetensors").write_text(name)
+ module = model / "0_Transformer"
+ _model_symlink(module, tmp_path / "original", directory=True)
+ old = create(str(model))
+ module.unlink()
+ _model_symlink(module, tmp_path / "replacement", directory=True)
+ create(str(model))
+ assert len(calls) == 2
+ with pytest.raises(ValueError, match="files changed"):
+ old.embed_query("old")
+
+
+def test_caller_mutation_cannot_change_evicted_reload(models):
+ create, calls, _ = models
+ options = {"torch_dtype": "original"}
+ first = create(model_kwargs=options)
+ options["torch_dtype"] = "modified"
+ create("synthetic/other")
+ first.embed_query("reload")
+ assert calls[-1]["model_kwargs"]["model_kwargs"] == {
+ "torch_dtype": "original"
+ }
+
+
+def test_pinned_model_ignores_other_hub_revisions(models, tmp_path):
+ create, calls, _ = models
+ cache = tmp_path / "models--synthetic--model"
+ revision = "a" * 40
+ original = cache / "snapshots" / revision
+ original.mkdir(parents=True)
+ (original / "config.json").write_text("original")
+ first = create(revision=revision)
+ other = cache / "snapshots" / ("b" * 40)
+ other.mkdir()
+ (other / "config.json").write_text("other revision")
+ (cache / "refs").mkdir()
+ (cache / "refs/main").write_text("b" * 40)
+ second = create(revision=revision)
+ assert first.embed_query("one") == second.embed_query("two") == [3.0]
+ assert len(calls) == 1
+
+
+def test_floating_ref_update_invalidates_old_handle(models, tmp_path):
+ create, calls, _ = models
+ cache = tmp_path / "models--synthetic--model"
+ (cache / "refs").mkdir(parents=True)
+ reference = cache / "refs/main"
+ reference.write_text("a" * 40)
+ first = create()
+ reference.write_text("b" * 40)
+ create()
+ assert len(calls) == 2
+ with pytest.raises(ValueError, match="files changed"):
+ first.embed_query("cannot change weights silently")
+
+
+async def test_async_embeddings_use_the_same_resident_model(models):
+ create, calls, _ = models
+ client = create()
+ assert await client.aembed_query("async") == [5.0]
+ assert await client.aembed_documents(["x", "yy"]) == [[1.0], [2.0]]
+ assert len(calls) == 1
+
+
+def test_real_managers_reuse_backend_across_users_without_retaining_settings(
+ monkeypatch, tmp_path
+):
+ from langchain_community import embeddings
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider as Provider,
+ )
+ from local_deep_research.web_search_engines.engines.local_embedding_manager import (
+ LocalEmbeddingManager,
+ )
+
+ calls = []
+
+ def factory(**kwargs):
+ calls.append(kwargs)
+ return CyclicBackend(**kwargs)
+
+ monkeypatch.setattr(embeddings, "SentenceTransformerEmbeddings", factory)
+ monkeypatch.setattr(
+ Provider, "_model_cache_directory", lambda: str(tmp_path)
+ )
+ monkeypatch.setattr(
+ Provider, "_is_model_cached_locally", lambda *a, **kw: True
+ )
+ for username in ("synthetic-alice", "synthetic-bob", "synthetic-alice"):
+ with LocalEmbeddingManager(
+ settings_snapshot={
+ "_username": username,
+ "policy.egress_scope": "public_only",
+ "search.tool": "arxiv",
+ }
+ ) as manager:
+ handle = manager.embeddings
+ assert handle.embed_query(username) == [float(len(username))]
+ with pytest.raises(RuntimeError, match="closed"):
+ handle.embed_query("after close")
+ assert len(calls) == 1
+ assert "_username" not in repr(calls)
+ assert "synthetic-alice" not in repr(vars(handle))
+
+
+def test_warm_weights_do_not_bypass_provider_admission(monkeypatch, tmp_path):
+ from langchain_community import embeddings
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider as Provider,
+ )
+ from local_deep_research.security.egress.policy import PolicyDeniedError
+
+ calls = []
+
+ def factory(**kwargs):
+ calls.append(kwargs)
+ return CyclicBackend(**kwargs)
+
+ monkeypatch.setattr(embeddings, "SentenceTransformerEmbeddings", factory)
+ monkeypatch.setattr(
+ Provider, "_model_cache_directory", lambda: str(tmp_path)
+ )
+ monkeypatch.setattr(
+ Provider, "_is_model_cached_locally", lambda *a, **kw: True
+ )
+ Provider.create_embeddings(settings_snapshot={}).embed_query("warm")
+ monkeypatch.setattr(
+ Provider, "_is_model_cached_locally", lambda *a, **kw: False
+ )
+ with pytest.raises(PolicyDeniedError):
+ Provider.create_embeddings(settings_snapshot={})
+ assert len(calls) == 1
diff --git a/tests/embeddings/test_model_cache_serial.py b/tests/embeddings/test_model_cache_serial.py
new file mode 100644
index 0000000000..4fcdd83e1a
--- /dev/null
+++ b/tests/embeddings/test_model_cache_serial.py
@@ -0,0 +1,407 @@
+"""Exercise real, tiny offline models: one resident model, serial inference."""
+
+import asyncio
+from concurrent.futures import ThreadPoolExecutor
+import gc
+from threading import Event, Lock
+import weakref
+
+import pytest
+
+from local_deep_research.embeddings import model_cache
+from local_deep_research.embeddings.model_loading import (
+ MODEL_LOAD_LOCK,
+ load_sentence_transformer,
+)
+
+
[email protected](scope="module", params=["bert", "modernbert"])
+def tiny_model_path(request, tmp_path_factory):
+ """Random weights and a six-word tokenizer; never download a real model."""
+ import torch
+ from tokenizers import Tokenizer, models, pre_tokenizers
+ from transformers import (
+ BertConfig,
+ BertModel,
+ ModernBertConfig,
+ ModernBertModel,
+ PreTrainedTokenizerFast,
+ )
+
+ path = tmp_path_factory.mktemp(request.param)
+ tokenizer = Tokenizer(
+ models.WordLevel(
+ {"[PAD]": 0, "[UNK]": 1, "a": 2, "b": 3, "c": 4, "d": 5},
+ unk_token="[UNK]",
+ )
+ )
+ tokenizer.pre_tokenizer = pre_tokenizers.Whitespace()
+ PreTrainedTokenizerFast(
+ tokenizer_object=tokenizer,
+ pad_token="[PAD]",
+ unk_token="[UNK]",
+ model_max_length=64,
+ ).save_pretrained(path)
+ options = dict(
+ vocab_size=6,
+ hidden_size=16,
+ intermediate_size=32,
+ num_hidden_layers=2,
+ num_attention_heads=2,
+ max_position_embeddings=64,
+ pad_token_id=0,
+ )
+ if request.param == "bert":
+ model = BertModel(BertConfig(**options))
+ else:
+ model = ModernBertModel(
+ ModernBertConfig(
+ **options,
+ local_attention=8,
+ global_attn_every_n_layers=2,
+ cls_token_id=2,
+ sep_token_id=3,
+ )
+ )
+ model.save_pretrained(path)
+ del model
+ old_threads = torch.get_num_threads()
+ torch.set_num_threads(1)
+ try:
+ yield str(path)
+ finally:
+ torch.set_num_threads(old_threads)
+
+
+def real_backend(tiny_model_path, monkeypatch):
+ from langchain_community.embeddings.huggingface import HuggingFaceEmbeddings
+
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ monkeypatch.setenv("TRANSFORMERS_OFFLINE", "1")
+ return HuggingFaceEmbeddings(
+ model_name=tiny_model_path,
+ model_kwargs={
+ "device": "cpu",
+ "local_files_only": True,
+ "model_kwargs": {"attn_implementation": "eager"},
+ },
+ encode_kwargs={"normalize_embeddings": True},
+ )
+
+
+class _ObservedLock:
+ """Delegate to the cache's inference lock; report calls taking a turn.
+
+ ``waiting`` is set once ``after`` calls have asked for a turn, before the
+ last of them blocks on the real lock.
+ """
+
+ def __init__(self, lock, waiting, after=1):
+ self._lock = lock
+ self._waiting = waiting
+ self._after = after
+ self._count = Lock()
+ self.waits = 0
+
+ def __enter__(self):
+ with self._count:
+ self.waits += 1
+ if self.waits >= self._after:
+ self._waiting.set()
+ return self._lock.__enter__()
+
+ def __exit__(self, *exc):
+ return self._lock.__exit__(*exc)
+
+
+def test_calls_take_turns_on_one_model_and_block_loaders_and_cleanup(
+ real_backend, tiny_model_path, monkeypatch
+):
+ client = model_cache.shared_sentence_transformer_embeddings(
+ lambda **_: real_backend, model_name=tiny_model_path
+ )
+ transformer_type = type(real_backend.client[0].auto_model)
+ forward = transformer_type.forward
+ entered, release, loader_requested, loaded = (Event() for _ in range(4))
+ mutex = Lock()
+ active = peak = 0
+ modules = set()
+
+ def blocking_forward(self, *args, **kwargs):
+ nonlocal active, peak
+ with mutex:
+ active += 1
+ peak = max(peak, active)
+ modules.add(id(self))
+ entered.set()
+ try:
+ assert release.wait(timeout=10)
+ return forward(self, *args, **kwargs)
+ finally:
+ with mutex:
+ active -= 1
+
+ def load_other():
+ loader_requested.set()
+ return load_sentence_transformer(lambda: loaded.set())
+
+ monkeypatch.setattr(transformer_type, "forward", blocking_forward)
+ with ThreadPoolExecutor(max_workers=4) as executor:
+ futures = [executor.submit(client.embed_query, "a b") for _ in range(3)]
+ try:
+ assert entered.wait(timeout=10)
+ loading = executor.submit(load_other)
+ assert loader_requested.wait(timeout=10)
+ assert (
+ model_cache.clear_sentence_transformer_cache(wait=False)
+ is False
+ )
+ assert not loaded.is_set()
+ assert peak == 1
+ finally:
+ release.set()
+ for future in futures:
+ assert len(future.result(timeout=15)) == 16
+ loading.result(timeout=15)
+ assert peak == 1
+ # Every call used the one resident model; no copy was made for a call.
+ assert modules == {id(real_backend.client[0].auto_model)}
+ assert loaded.is_set()
+
+
+async def test_async_calls_take_turns_on_the_resident_model(
+ real_backend, tiny_model_path, monkeypatch
+):
+ client = model_cache.shared_sentence_transformer_embeddings(
+ lambda **_: real_backend, model_name=tiny_model_path
+ )
+ transformer_type = type(real_backend.client[0].auto_model)
+ forward = transformer_type.forward
+ cache = model_cache._MODEL_CACHE
+ both_waiting = Event()
+ observed = _ObservedLock(cache._inference, both_waiting, after=2)
+ monkeypatch.setattr(cache, "_inference", observed)
+ mutex = Lock()
+ active = peak = 0
+
+ def blocking_forward(self, *args, **kwargs):
+ nonlocal active, peak
+ with mutex:
+ active += 1
+ peak = max(peak, active)
+ try:
+ # Hold the model until the other call waits for its turn.
+ assert both_waiting.wait(timeout=10)
+ return forward(self, *args, **kwargs)
+ finally:
+ with mutex:
+ active -= 1
+
+ monkeypatch.setattr(transformer_type, "forward", blocking_forward)
+ results = await asyncio.wait_for(
+ asyncio.gather(
+ client.aembed_query("a"), client.aembed_documents(["b c"])
+ ),
+ timeout=15,
+ )
+ assert len(results[0]) == len(results[1][0]) == 16
+ assert observed.waits == 2
+ assert peak == 1
+
+
+def test_warm_handle_is_created_while_busy_and_closes_while_queued(
+ real_backend, tiny_model_path, monkeypatch
+):
+ loads = []
+
+ def factory(**_kwargs):
+ loads.append(True)
+ return real_backend
+
+ def create():
+ return model_cache.shared_sentence_transformer_embeddings(
+ factory, model_name=tiny_model_path
+ )
+
+ client = create()
+ entered, release, queued = Event(), Event(), Event()
+ transformer_type = type(real_backend.client[0].auto_model)
+ forward = transformer_type.forward
+ lock = Lock()
+ forwards = 0
+
+ def blocking_forward(self, *args, **kwargs):
+ nonlocal forwards
+ with lock:
+ forwards += 1
+ entered.set()
+ assert release.wait(timeout=10)
+ return forward(self, *args, **kwargs)
+
+ monkeypatch.setattr(transformer_type, "forward", blocking_forward)
+ cache = model_cache._MODEL_CACHE
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ first = executor.submit(client.embed_query, "a")
+ try:
+ assert entered.wait(timeout=10)
+ # Shared access: creating a warm handle needs no turn on the model.
+ late = executor.submit(create).result(timeout=5)
+ assert len(loads) == 1
+ monkeypatch.setattr(
+ cache, "_inference", _ObservedLock(cache._inference, queued)
+ )
+ third = executor.submit(late.embed_query, "c")
+ assert queued.wait(timeout=5)
+ late.close()
+ finally:
+ release.set()
+ assert len(first.result(timeout=10)) == 16
+ with pytest.raises(RuntimeError, match="closed"):
+ third.result(timeout=10)
+ assert forwards == 1
+ assert len(client.embed_query("d")) == 16
+
+
+def test_configuration_change_waits_for_active_and_queued_calls(
+ real_backend, tiny_model_path, monkeypatch
+):
+ loads = []
+
+ def factory(**kwargs):
+ loads.append(kwargs["encode_kwargs"])
+ return real_backend
+
+ def create(normalize):
+ return model_cache.shared_sentence_transformer_embeddings(
+ factory,
+ model_name=tiny_model_path,
+ encode_kwargs={"normalize_embeddings": normalize},
+ )
+
+ client = create(True)
+ (
+ entered_first,
+ entered_second,
+ release_first,
+ release_second,
+ queued,
+ requested,
+ ) = (Event() for _ in range(6))
+ transformer_type = type(real_backend.client[0].auto_model)
+ forward = transformer_type.forward
+ lock = Lock()
+ forwards = 0
+
+ def blocking_forward(self, *args, **kwargs):
+ nonlocal forwards
+ with lock:
+ index = forwards
+ forwards += 1
+ (entered_first if index == 0 else entered_second).set()
+ assert (release_first if index == 0 else release_second).wait(
+ timeout=10
+ )
+ return forward(self, *args, **kwargs)
+
+ def switch():
+ requested.set()
+ return create(False)
+
+ monkeypatch.setattr(transformer_type, "forward", blocking_forward)
+ cache = model_cache._MODEL_CACHE
+ with ThreadPoolExecutor(max_workers=3) as executor:
+ first = executor.submit(client.embed_query, "a")
+ try:
+ assert entered_first.wait(timeout=10)
+ monkeypatch.setattr(
+ cache, "_inference", _ObservedLock(cache._inference, queued)
+ )
+ second = executor.submit(client.embed_query, "b c")
+ # Admitted before the switch, so the switch must wait for it too.
+ assert queued.wait(timeout=5)
+ switching = executor.submit(switch)
+ assert requested.wait(timeout=5)
+ release_first.set()
+ assert len(first.result(timeout=10)) == 16
+ # The queued call takes its turn on the old model; the switch waits.
+ assert entered_second.wait(timeout=10)
+ assert not switching.done()
+ assert len(loads) == 1
+ assert cache.key == client._key
+ finally:
+ release_first.set()
+ release_second.set()
+ assert len(second.result(timeout=10)) == 16
+ switching.result(timeout=10)
+ assert loads == [
+ {"normalize_embeddings": True},
+ {"normalize_embeddings": False},
+ ]
+
+
+def test_failed_forward_releases_inference_turn_and_gate(
+ real_backend, tiny_model_path, monkeypatch
+):
+ client = model_cache.shared_sentence_transformer_embeddings(
+ lambda **_: real_backend, model_name=tiny_model_path
+ )
+ transformer_type = type(real_backend.client[0].auto_model)
+ forward = transformer_type.forward
+
+ def fail(self, *args, **kwargs):
+ raise RuntimeError("synthetic inference failure")
+
+ monkeypatch.setattr(transformer_type, "forward", fail)
+ for _ in range(3):
+ with pytest.raises(RuntimeError, match="synthetic inference failure"):
+ client.embed_query("a")
+ monkeypatch.setattr(transformer_type, "forward", forward)
+ assert len(client.embed_query("b")) == 16
+ assert model_cache.clear_sentence_transformer_cache(wait=False) is True
+
+
+def test_cache_clear_collects_the_real_model_cycle_with_live_handles(
+ tiny_model_path, monkeypatch
+):
+ from langchain_community.embeddings.huggingface import HuggingFaceEmbeddings
+
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ monkeypatch.setenv("TRANSFORMERS_OFFLINE", "1")
+ # As with provider handles, the cache is the model's only owner.
+ client = model_cache.shared_sentence_transformer_embeddings(
+ HuggingFaceEmbeddings,
+ model_name=tiny_model_path,
+ model_kwargs={
+ "device": "cpu",
+ "model_kwargs": {"attn_implementation": "eager"},
+ },
+ )
+ assert len(client.embed_query("a")) == 16
+ model = weakref.ref(model_cache._MODEL_CACHE.backend.client)
+ # SentenceTransformer -> model_card_data -> SentenceTransformer.
+ assert model().model_card_data.model is model()
+ was_enabled = gc.isenabled()
+ gc.disable()
+ try:
+ assert model_cache.clear_sentence_transformer_cache(wait=False)
+ assert model() is None
+ assert not client._closed
+ finally:
+ if was_enabled:
+ gc.enable()
+
+
+def test_reader_gate_rejects_unsafe_upgrade_and_remains_usable():
+ with MODEL_LOAD_LOCK.inference():
+ assert MODEL_LOAD_LOCK.acquire(blocking=False) is False
+ with pytest.raises(RuntimeError, match="during inference"):
+ load_sentence_transformer(lambda: None)
+ with MODEL_LOAD_LOCK.inference():
+ pass
+ with MODEL_LOAD_LOCK:
+ with MODEL_LOAD_LOCK:
+ with MODEL_LOAD_LOCK.inference():
+ pass
+ assert model_cache.clear_sentence_transformer_cache(wait=False)
diff --git a/tests/embeddings/test_sentence_transformer_model_catalog.py b/tests/embeddings/test_sentence_transformer_model_catalog.py
index 0d7d41fb4e..0be51d6b57 100644
--- a/tests/embeddings/test_sentence_transformer_model_catalog.py
+++ b/tests/embeddings/test_sentence_transformer_model_catalog.py
@@ -110,7 +110,9 @@ def test_public_curated_legacy_model_can_download_without_repinning(
},
)
- assert result is stub
+ from langchain_core.embeddings import Embeddings
+
+ assert isinstance(result, Embeddings)
kwargs = embedding_cls.call_args.kwargs
assert kwargs["model_name"] == "all-MiniLM-L6-v2"
assert kwargs["model_kwargs"] == {
@@ -532,7 +534,8 @@ def test_partial_cache_repair_stays_on_the_same_revision(
metadata_file = snapshot / filename
metadata_file.parent.mkdir(parents=True, exist_ok=True)
metadata_file.write_text("{}")
- loaded = object()
+ loaded = MagicMock()
+ loaded.embed_query.return_value = [0.5, 0.25]
with (
patch(
"huggingface_hub.try_to_load_from_cache",
@@ -547,16 +550,15 @@ def test_partial_cache_repair_stays_on_the_same_revision(
side_effect=[OSError("missing weights"), loaded],
) as constructor,
):
- assert (
- Provider.create_embeddings(
- model=model,
- settings_snapshot={
- "policy.egress_scope": "public_only",
- "search.tool": "arxiv",
- },
- )
- is loaded
+ result = Provider.create_embeddings(
+ model=model,
+ settings_snapshot={
+ "policy.egress_scope": "public_only",
+ "search.tool": "arxiv",
+ },
)
+ assert result.embed_query("repaired") == [0.5, 0.25]
+ loaded.embed_query.assert_called_once_with("repaired")
assert constructor.call_count == 2
first, second = [call.kwargs for call in constructor.call_args_list]
assert first["model_kwargs"]["local_files_only"] is True
diff --git a/tests/embeddings/test_sentence_transformers.py b/tests/embeddings/test_sentence_transformers.py
index 71202d3641..e134412043 100644
--- a/tests/embeddings/test_sentence_transformers.py
+++ b/tests/embeddings/test_sentence_transformers.py
@@ -154,7 +154,11 @@ class TestSentenceTransformersProviderCreateEmbeddings:
settings_snapshot=PUBLIC_SETTINGS
)
- assert result is mock_embeddings
+ mock_embeddings.embed_query.return_value = [0.25, 0.5]
+ assert result.embed_query("synthetic query") == [0.25, 0.5]
+ mock_embeddings.embed_query.assert_called_once_with(
+ "synthetic query"
+ )
mock_class.assert_called_once()
call_kwargs = mock_class.call_args[1]
# Default model should be used
diff --git a/tests/security/test_egress_policy.py b/tests/security/test_egress_policy.py
index 4acd261c93..d55a67a2b1 100644
--- a/tests/security/test_egress_policy.py
+++ b/tests/security/test_egress_policy.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from unittest.mock import patch
+from unittest.mock import Mock, patch
import pytest
from huggingface_hub import _CACHED_NO_EXIST
@@ -2511,7 +2511,8 @@ def test_create_embeddings_admits_cached_legacy_catalog_model_under_require_loca
return "/fake/path/config.json"
return None
- stub = object()
+ stub = Mock()
+ stub.embed_query.return_value = [0.25, 0.5]
# Empty snapshot: resolve_run_primary_engine raises (no primary), so
# create_embeddings fails closed to require_local=True and the gate
# actually runs — no need to synthesise a PRIVATE_ONLY scope.
@@ -2528,7 +2529,8 @@ def test_create_embeddings_admits_cached_legacy_catalog_model_under_require_loca
device="cpu",
)
- assert result is stub
+ assert result.embed_query("admitted") == [0.25, 0.5]
+ stub.embed_query.assert_called_once_with("admitted")
# Admitted, and forced offline for defence in depth.
assert mock_st.call_args.kwargs["model_kwargs"]["local_files_only"] is True
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index 88f5baef7c..2cf3578992 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -2438,7 +2438,7 @@
},
"rag.indexing_max_parallel_docs": {
"category": "research_library",
- "description": "Maximum number of documents indexed concurrently within a single indexing job (per-user). One job holds up to this many workers; each worker calls the existing per-document path so the FAISS write lock still serializes the disk-merge step. Lower if your embedding backend (e.g. local CPU sentence-transformers) is throughput-bound and concurrent calls contend; raise to e.g. 8-16 for sentence-transformers on GPU, or HTTP embedding providers (OpenAI-compatible, vLLM, Ollama with OLLAMA_NUM_PARALLEL>1). Default 4 keeps RAM modest for collections with many large documents.",
+ "description": "Maximum number of documents indexed concurrently within a single indexing job (per-user). One job holds up to this many workers; each worker calls the existing per-document path so the FAISS write lock still serializes the disk-merge step. Lower if your embedding backend is throughput-bound and concurrent calls contend; local sentence-transformers run one embedding call at a time per process, so raise to e.g. 8-16 mainly for HTTP embedding providers (OpenAI-compatible, vLLM, Ollama with OLLAMA_NUM_PARALLEL>1). Default 4 keeps RAM modest for collections with many large documents.",
"editable": true,
"max_value": 16,
"min_value": 1,
diff --git a/tests/web/test_lifespan_boot.py b/tests/web/test_lifespan_boot.py
index 3038ad3156..42458ea63f 100644
--- a/tests/web/test_lifespan_boot.py
+++ b/tests/web/test_lifespan_boot.py
@@ -20,15 +20,27 @@ would leave the ``asyncio.Lock`` bound to a dead loop. Do not turn this into a
reusable fixture, and do not add a second lifespan-entering test to the file.
"""
+import weakref
+
import pytest
from fastapi.testclient import TestClient
@pytest.mark.lifespan
-def test_app_boots_serves_and_shuts_down_cleanly():
+def test_app_boots_serves_and_shuts_down_cleanly(tmp_path):
"""Enter lifespan, prove the app is live, then exit cleanly."""
from local_deep_research.web.fastapi_app import app
from local_deep_research.web.services import socketio_asgi
+ from local_deep_research.embeddings.model_cache import (
+ shared_sentence_transformer_embeddings,
+ )
+
+ model_refs = []
+
+ class CyclicModel:
+ def __init__(self, **kwargs):
+ self.cycle = self
+ model_refs.append(weakref.ref(self))
# Deliberately NOT asserting that _main_loop is None here. Some fixtures
# elsewhere in the suite enter lifespan (leaving a closed loop behind), so
@@ -62,7 +74,17 @@ def test_app_boots_serves_and_shuts_down_cleanly():
f"app booted but health returned {resp.status_code}: "
f"{resp.text[:200]}"
)
+ shared_sentence_transformer_embeddings(
+ CyclicModel,
+ model_name="synthetic/shutdown",
+ cache_folder=str(tmp_path),
+ model_kwargs={},
+ )
+ assert model_refs[0]() is not None
# Exiting the context manager ran shutdown. Reaching here at all means it
# completed rather than hanging — the failure mode that would otherwise
# only show up as a killed container.
+ assert model_refs[0]() is None, (
+ "Shutdown retained the resident embedding model"
+ )
diff --git a/tests/web/test_lifespan_startup_shutdown.py b/tests/web/test_lifespan_startup_shutdown.py
index 774a85a970..4234cb2e4f 100644
--- a/tests/web/test_lifespan_startup_shutdown.py
+++ b/tests/web/test_lifespan_startup_shutdown.py
@@ -110,6 +110,7 @@ import json
import os
import sys
import threading
+from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from stat import S_IMODE
@@ -135,6 +136,7 @@ def snapshot():
from fastapi.testclient import TestClient
from local_deep_research.database.encrypted_db import db_manager
+from local_deep_research.embeddings import model_cache
from local_deep_research.utilities import log_utils
from local_deep_research.web import fastapi_app
from local_deep_research.web.auth import connection_cleanup
@@ -167,6 +169,34 @@ _real_start_cleanup = connection_cleanup.start_connection_cleanup_scheduler
_real_qp_start = queue_processor.start
_real_qp_stop = queue_processor.stop
_real_close_all = db_manager.close_all_databases
+embedding_entered = threading.Event()
+embedding_release = threading.Event()
+
+
+if MODE == "embedding-busy":
+ class BlockingBackend:
+ def __init__(self, **kwargs):
+ pass
+
+ def embed_query(self, text):
+ embedding_entered.set()
+ if not embedding_release.wait(timeout=60):
+ raise RuntimeError("Embedding shutdown probe timed out")
+ return [1.0]
+
+ embedding_handle = model_cache.shared_sentence_transformer_embeddings(
+ BlockingBackend,
+ model_name="synthetic/shutdown",
+ cache_folder=str(OUT.parent),
+ model_kwargs={},
+ )
+
+if MODE == "embedding-cache-error":
+ def _broken_cache_clear(**kwargs):
+ record("embedding_cache.clear_failed")
+ raise RuntimeError("simulated cache cleanup failure")
+
+ model_cache.clear_sentence_transformer_cache = _broken_cache_clear
def _set_main_loop(loop):
@@ -225,7 +255,14 @@ def _qp_stop(*args, **kwargs):
def _close_all(*args, **kwargs):
record("close_all_databases")
- return _real_close_all(*args, **kwargs)
+ try:
+ return _real_close_all(*args, **kwargs)
+ finally:
+ if MODE == "embedding-busy":
+ result["closed_databases_before_inference_finished"] = (
+ not embedding_release.is_set()
+ )
+ embedding_release.set()
socketio_asgi.set_main_loop = _set_main_loop
@@ -289,6 +326,27 @@ with TestClient(fastapi_app.app) as client:
result["legacy_report_after_startup"] = legacy_report.read_text(
encoding="utf-8"
)
+ if MODE == "embedding-busy":
+ import asyncio
+
+ def _limit_executor():
+ asyncio.get_running_loop().set_default_executor(
+ ThreadPoolExecutor(max_workers=1)
+ )
+
+ client.portal.call(_limit_executor)
+ # Release only after database cleanup, with a watchdog to let a
+ # broken implementation finish and report the ordering failure.
+ watchdog = threading.Timer(20, embedding_release.set)
+ watchdog.start()
+ client.portal.start_task_soon(
+ embedding_handle.aembed_query, "held during shutdown"
+ )
+ assert embedding_entered.wait(timeout=10)
+
+if MODE == "embedding-busy":
+ watchdog.cancel()
+ watchdog.join(timeout=2)
# Immediately after __exit__, then again after giving anything still alive a
# bounded join. The join absorbs the exit race of a thread that WAS signalled
@@ -385,6 +443,22 @@ def _matching(snapshot: list[dict], needle: str) -> list[dict]:
return [entry for entry in snapshot if needle in entry["name"]]
+def test_busy_embedding_cache_does_not_delay_database_cleanup(tmp_path):
+ boot = _run_boot_probe("embedding-busy", tmp_path)
+ assert boot["closed_databases_before_inference_finished"], (
+ "Lifespan queued cache cleanup behind busy inference, delaying "
+ "log flushing and database cleanup until the watchdog released it"
+ )
+ assert "flush_log_queue" in _events(boot)
+
+
+def test_embedding_cache_failure_does_not_skip_database_cleanup(tmp_path):
+ boot = _run_boot_probe("embedding-cache-error", tmp_path)
+ events = _events(boot)
+ assert "embedding_cache.clear_failed" in events
+ assert events.index("flush_log_queue") < events.index("close_all_databases")
+
+
# ---------------------------------------------------------------------------
# 1. Startup ran, completely, in the documented order.
# ---------------------------------------------------------------------------