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.

Curated embedding default with egress-gated download (#5244)

LearningCircuite83ea8b229f0
diff --git a/Dockerfile b/Dockerfile
index 01e6ac38d2..f1c040b116 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -138,7 +138,6 @@ RUN for i in 1 2 3; do \
# See .grype.yaml (CVE-2026-6653).
RUN /install/.venv/bin/python -c "from lxml import etree; v = etree.LIBXML_VERSION; assert v >= (2, 11, 0), f'lxml is linked against vulnerable libxml2 {v} (the CVE-2026-6653 fix is in 2.11.0); expected a wheel-bundled libxml2'; print(f'lxml uses libxml2 {v} (>= 2.11.0 CVE-2026-6653 fix) OK')"
-
####
# Container for running tests.
####
@@ -393,6 +392,11 @@ RUN HOME=/home/ldruser setpriv --reuid=ldruser --regid=ldruser --init-groups --
# makes the VOLUME actually load-bearing for bare `docker run -v ...`
# invocations too.
ENV LDR_DATA_DIR=/data
+# Optional Hugging Face model artifacts use the persistent /data volume. Scope
+# this override to the Hub artifact cache rather than HF_HOME (which also moves
+# credentials and unrelated state). The entrypoint forbids implicit use of any
+# ambient Hugging Face token; provider loads additionally pass token=False.
+ENV HF_HUB_CACHE=/data/cache/huggingface/hub
VOLUME /app/.config/local_deep_research
VOLUME /data
diff --git a/changelog.d/5244.feature.md b/changelog.d/5244.feature.md
new file mode 100644
index 0000000000..060813964e
--- /dev/null
+++ b/changelog.d/5244.feature.md
@@ -0,0 +1,12 @@
+The pinned GTE ModernBERT embedding model is now the default for new local
+search indexes. Curated Sentence Transformers models can be downloaded under
+a public-capable egress scope and reused offline; interrupted cached downloads
+can be repaired at the same revision when policy permits. Existing cached
+non-catalog models and confined local models remain available offline when
+compatible with safetensors weights and disabled remote code; a confined local
+model directory that resolves inside the models directory still wins over a
+curated model of the same name, and that substitution is written to the policy
+audit log (a symlink pointing outside the models directory is ignored and the
+curated Hub model is used). Ambiguous existing
+cache revisions are refused instead of downloading newer model bytes. The
+embedding settings test uses fixed server-owned text and explains policy denials.
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 1f068e6cd1..43e15af9e7 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -165,7 +165,7 @@ They are not available in the Web UI because they are needed to start the applic
| `local_search_chunk_overlap` | `LDR_LOCAL_SEARCH_CHUNK_OVERLAP` | `200` | Characters shared between adjacent chunks. Prevents important information from being cut at chunk boundaries. Typically 10-20% of chunk size. Affects new indexing only. | APP |
| `local_search_chunk_size` | `LDR_LOCAL_SEARCH_CHUNK_SIZE` | `1000` | Number of characters per chunk when splitting documents for embedding. Larger chunks (1000+) keep more context but search is less precise. Smaller chunks (<500) are more granular but may cut off important context. Affects new indexing only. | APP |
| `local_search_distance_metric` | `LDR_LOCAL_SEARCH_DISTANCE_METRIC` | `cosine` | How chunk vectors are compared during retrieval. Cosine similarity is the standard recommendation for text embeddings. L2 (Euclidean) and dot product are alternatives whose suitability depends on whether the embedding model is trained to produce normalized vectors. | APP |
-| `local_search_embedding_model` | `LDR_LOCAL_SEARCH_EMBEDDING_MODEL` | `all-MiniLM-L6-v2` | Embedding model used for the local-document search index. Free-form text because available models vary by provider (e.g. Sentence Transformers ships a fixed list, Ollama/OpenAI-compatible servers expose whatever is installed). Defaults to all-MiniLM-L6-v2 (384d) which is fast and good for general use. | APP |
+| `local_search_embedding_model` | `LDR_LOCAL_SEARCH_EMBEDDING_MODEL` | `Alibaba-NLP/gte-modernbert-base` | Embedding model used for the local-document search index. Model names vary by provider: Sentence Transformers uses LDR's vetted list, while Ollama/OpenAI-compatible servers expose whatever is installed. Defaults to Alibaba-NLP/gte-modernbert-base (768d); curated Sentence Transformers models require a one-time policy-authorized download, then reuse the local cache. | APP |
| `local_search_embedding_provider` | `LDR_LOCAL_SEARCH_EMBEDDING_PROVIDER` | `sentence_transformers` | Embedding provider used for the local-document search index. Drives which models the Embeddings page lists and which provider runs when documents are indexed. The model dropdown is rebuilt to match this provider. | APP |
| `local_search_index_type` | `LDR_LOCAL_SEARCH_INDEX_TYPE` | `flat` | FAISS index type used for the local-document search index. Flat: exact search, recommended for <10K documents. HNSW: approximate but ~50x faster, recommended for large collections (>10K docs). IVF: balanced for collections that are updated frequently. Changing this requires re-indexing existing collections. | APP |
| `local_search_normalize_vectors` | `LDR_LOCAL_SEARCH_NORMALIZE_VECTORS` | `true` | L2-normalize embedding vectors after generation. Recommended: ensures fair similarity comparison regardless of source document length. Some embedding models already produce normalized output; in that case this is a no-op. | APP |
diff --git a/docs/egress-modes.md b/docs/egress-modes.md
index 3734bc6ffa..ec9ed31c08 100644
--- a/docs/egress-modes.md
+++ b/docs/egress-modes.md
@@ -126,6 +126,26 @@ Independent of the scope, you can force local inference any time:
Both are **implied automatically** under *Private only* (and Adaptive-private),
which is why those toggles auto-check and lock when you select Private only.
+LDR's curated Sentence Transformers models, including the default, require a
+one-time policy-authorized download before they can be used from the local
+cache. A model from the vetted list that is not already cached cannot be
+downloaded while local embeddings are required. To install one using
+**Library → Embedding Settings**, temporarily select *Public only*, or use
+*Adaptive* with a public primary and no
+private collection selected; turn off *Require local embeddings* if you enabled
+it, then select the model and click **Test Embedding Model**. Restore your
+preferred restrictive scope after the test succeeds. Runtime inference then
+uses the local cache. If a download was interrupted, repeating the test under
+an authorized public scope can repair its missing files at the same revision.
+Curated cache checks require the module list, pooling and tokenizer configuration,
+and each model's declared Transformer configuration before an offline load. This
+preserves pooling, tokenizer selection, and token limits when metadata downloads
+are interrupted.
+Cached models outside the curated list and confined local model paths remain
+cache-only and require compatible safetensors weights with remote code disabled.
+An existing curated cache with no trustworthy immutable revision is refused,
+even under a public scope; restore its trusted metadata or select another model.
+
---
## Per-research overrides
diff --git a/docs/library-and-rag.md b/docs/library-and-rag.md
index 9edecfb1d0..efdf34828d 100644
--- a/docs/library-and-rag.md
+++ b/docs/library-and-rag.md
@@ -175,15 +175,53 @@ Choose the embedding model based on your needs.
#### Sentence Transformers (Local - Default)
-Runs locally, no API key required.
+Runs locally with no API key. Curated Sentence Transformers models, including
+the recommended default, require a one-time policy-authorized download and are
+then reused from the local cache.
| Model | Dimensions | Best For |
|-------|------------|----------|
+| `Alibaba-NLP/gte-modernbert-base` | 768 | Recommended default; higher-quality English retrieval and longer inputs |
| `all-MiniLM-L6-v2` | 384 | General use (fast) |
| `all-mpnet-base-v2` | 768 | Higher quality |
| `multi-qa-MiniLM-L6-cos-v1` | 384 | Q&A tasks |
| `paraphrase-multilingual-MiniLM-L12-v2` | 384 | Multi-language |
+On **Library → Embedding Settings**, temporarily use **Public only**, or
+**Adaptive** with a public primary and no private collection selected. Turn
+off **Require local embeddings** if you enabled it, select the model, and use
+**Test Embedding Model**. Once the test succeeds, return to your preferred
+scope; subsequent inference uses the local cache. Collection content is not
+used for this test.
+
+New Hugging Face downloads are restricted to the vetted entries above.
+Existing cached models outside that list and confined local models can be
+reused offline when compatible with safetensors weights and disabled remote
+code. Binary-only weights and models requiring remote Python code to be enabled
+are not supported by this provider. For an existing model, supply a trusted
+compatible safetensors export under the application's models directory, or use
+Ollama.
+Local model paths must resolve inside that directory and load without network
+access. A model directory there that resolves inside the models directory
+takes precedence in every scope, including when its name matches a catalog
+entry, and the substitution is written to the policy audit log. A symlink
+there that points outside the models directory is ignored, and the curated
+Hub model of that name is used instead. Arbitrary server paths are refused.
+
+If a download was interrupted, repeat the test under an authorized public
+scope to repair missing files. Existing cached legacy models are repaired at
+their cached revision, without advancing to newer model bytes. Repair requires
+a known immutable revision; models outside the catalog remain cache-only.
+If configuration and module metadata are both missing, the local Hub reference
+still pins repair to the cached revision. Existing cache state with no single
+trustworthy revision is refused instead of silently advancing the model behind
+an index. To recover, either delete that model's cache directory (its
+`models--...` folder under the Hugging Face cache) and download it again under
+a public-capable scope — only when no collection was indexed with it — or place
+a trusted copy under the application's models directory and select that,
+or select a different model.
+Use Ollama for a broader choice of locally managed embedding models.
+
#### Ollama (Local)
Uses your local Ollama installation.
@@ -191,6 +229,7 @@ Uses your local Ollama installation.
- Default model: `nomic-embed-text`
- Requires Ollama running locally
- Configure URL in Settings → LLM → Ollama
+- Recommended when you want a wider choice of local embedding models
#### OpenAI (Cloud)
@@ -204,7 +243,7 @@ Uses OpenAI's embedding API.
1. Go to **Library** → **Embedding Settings**
2. Select provider and model
-3. Click **Save**
+3. Use **Test Embedding Model** before indexing; changes save automatically
> **Note:** Changing models requires reindexing existing collections.
diff --git a/scripts/ldr_entrypoint.sh b/scripts/ldr_entrypoint.sh
index c7418336fa..559f100629 100755
--- a/scripts/ldr_entrypoint.sh
+++ b/scripts/ldr_entrypoint.sh
@@ -54,4 +54,7 @@ if ! setpriv --reuid=ldruser --regid=ldruser --init-groups -- true 2>/dev/null;
exit 1
fi
export HOME=/home/ldruser
+# Hugging Face Hub must never discover or send a user token implicitly. The
+# Sentence Transformers provider also passes token=False at every load site.
+export HF_HUB_DISABLE_IMPLICIT_TOKEN=1
exec setpriv --reuid=ldruser --regid=ldruser --init-groups -- "$@"
diff --git a/src/local_deep_research/config/paths.py b/src/local_deep_research/config/paths.py
index bf94dc8eec..27c0d1ac1f 100644
--- a/src/local_deep_research/config/paths.py
+++ b/src/local_deep_research/config/paths.py
@@ -188,6 +188,26 @@ def get_models_directory() -> Path:
return _ensure_dir("models", label="models")
+def get_sentence_transformers_home() -> str | None:
+ """
+ Get the sentence-transformers ecosystem cache override, if set.
+
+ Environment variable:
+ SENTENCE_TRANSFORMERS_HOME: Third-party override (honored by the
+ sentence-transformers library itself) for where model
+ snapshots are stored. Read at call time so the live
+ environment always wins, mirroring how the library
+ resolves its own cache root. The raw value is returned
+ (no Path coercion, empty string stays empty) so callers
+ can preserve the library's precedence exactly.
+
+ Returns:
+ The override path as a string, or None when unset (callers fall
+ back to the HuggingFace Hub default cache).
+ """
+ return os.getenv("SENTENCE_TRANSFORMERS_HOME")
+
+
def get_backup_directory() -> Path:
"""Get the base backup directory for all users."""
return _ensure_dir("encrypted_databases/backups")
diff --git a/src/local_deep_research/constants.py b/src/local_deep_research/constants.py
index bc9ba9e8cc..02a8092ce3 100644
--- a/src/local_deep_research/constants.py
+++ b/src/local_deep_research/constants.py
@@ -94,7 +94,7 @@ FILE_PATH_SENTINELS = (
# Must match the registered defaults in defaults/settings_local_search.json —
# pinned by tests/test_constants.py::test_default_local_search_settings_match_registry.
DEFAULT_LOCAL_SEARCH_PROVIDER: str = "sentence_transformers"
-DEFAULT_LOCAL_SEARCH_MODEL: str = "all-MiniLM-L6-v2"
+DEFAULT_LOCAL_SEARCH_MODEL: str = "Alibaba-NLP/gte-modernbert-base"
DEFAULT_LOCAL_SEARCH_CHUNK_SIZE: int = 1000
DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP: int = 200
DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE: str = "recursive"
diff --git a/src/local_deep_research/defaults/settings_local_search.json b/src/local_deep_research/defaults/settings_local_search.json
index d1bfe94c7d..f645d9bc33 100644
--- a/src/local_deep_research/defaults/settings_local_search.json
+++ b/src/local_deep_research/defaults/settings_local_search.json
@@ -19,7 +19,7 @@
},
"local_search_embedding_model": {
"category": "embeddings",
- "description": "Embedding model used for the local-document search index. Free-form text because available models vary by provider (e.g. Sentence Transformers ships a fixed list, Ollama/OpenAI-compatible servers expose whatever is installed). Defaults to all-MiniLM-L6-v2 (384d) which is fast and good for general use.",
+ "description": "Embedding model used for the local-document search index. Model names vary by provider: Sentence Transformers uses LDR's vetted list, while Ollama/OpenAI-compatible servers expose whatever is installed. Defaults to Alibaba-NLP/gte-modernbert-base (768d); curated Sentence Transformers models require a one-time policy-authorized download, then reuse the local cache.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -28,7 +28,7 @@
"step": null,
"type": "APP",
"ui_element": "text",
- "value": "all-MiniLM-L6-v2",
+ "value": "Alibaba-NLP/gte-modernbert-base",
"visible": true
},
"local_search_chunk_size": {
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 b254bde508..e0126a50ac 100644
--- a/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py
+++ b/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py
@@ -1,5 +1,6 @@
"""Sentence Transformers embedding provider."""
+import errno
import re
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
@@ -8,6 +9,11 @@ from langchain_core.embeddings import Embeddings
from ....security.secure_logging import logger
from ....config.thread_settings import get_setting_from_snapshot
+from ...sentence_transformer_models import (
+ DEFAULT_SENTENCE_TRANSFORMER_MODEL,
+ SENTENCE_TRANSFORMER_MODELS,
+ get_sentence_transformer_model_spec,
+)
from ..base import BaseEmbeddingProvider, Exposure
@@ -24,30 +30,13 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
requires_api_key = False
supports_local = True
egress_exposure = Exposure.CONTAINED
- default_model = "all-MiniLM-L6-v2" # type: ignore[assignment]
+ default_model = DEFAULT_SENTENCE_TRANSFORMER_MODEL # type: ignore[assignment]
- # Available models with metadata
+ # Preserve the provider API's legacy metadata shape while centralizing the
+ # curated allowlist and the default model's immutable revision.
AVAILABLE_MODELS = {
- "all-MiniLM-L6-v2": {
- "dimensions": 384,
- "description": "Fast, lightweight model. Good for general use.",
- "max_seq_length": 256,
- },
- "all-mpnet-base-v2": {
- "dimensions": 768,
- "description": "Higher quality, slower. Best accuracy.",
- "max_seq_length": 384,
- },
- "multi-qa-MiniLM-L6-cos-v1": {
- "dimensions": 384,
- "description": "Optimized for question-answering tasks.",
- "max_seq_length": 512,
- },
- "paraphrase-multilingual-MiniLM-L12-v2": {
- "dimensions": 384,
- "description": "Supports multiple languages.",
- "max_seq_length": 128,
- },
+ model_name: spec.display_metadata()
+ for model_name, spec in SENTENCE_TRANSFORMER_MODELS.items()
}
@classmethod
@@ -61,7 +50,7 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
Create Sentence Transformers embeddings instance.
Args:
- model: Model name (defaults to all-MiniLM-L6-v2)
+ model: Model name (defaults to Alibaba-NLP/gte-modernbert-base)
settings_snapshot: Optional settings snapshot
**kwargs: Additional parameters (device, etc.)
@@ -93,162 +82,300 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
f"Creating SentenceTransformerEmbeddings with model={model}, device={device}"
)
- # Path confinement (security): the embedding model setting is
- # user-editable free text. ``SentenceTransformer`` loads ANY value
- # that resolves to an existing filesystem path (its ``os.path.exists``
- # branch), so without a guard an authenticated user could point this
- # setting at an arbitrary absolute server path — turning it into a
- # whole-filesystem existence/structure probe and an arbitrary
- # local-model loader. Classify the value ONCE:
- # * a file/dir confined UNDER the app's models directory is a
- # legitimate local model -> load it from its safe absolute path;
- # * a filesystem-path-shaped value that ESCAPES the models dir is
- # refused outright (never handed to the loader);
- # * anything else is treated as a HuggingFace repo id (default).
- local_model_path = cls._confined_local_model_path(model)
- if local_model_path is None and cls._looks_like_filesystem_path(model):
- logger.bind(policy_audit=True).warning(
- "refusing sentence-transformers embedding model {!r}: "
- "filesystem paths must resolve under the app models directory",
- model,
- )
- raise ValueError(
- "Invalid embedding model path: local model paths must "
- "resolve under the application's models directory."
- )
-
- # Egress policy: if the user opted into local-only embeddings,
- # refuse to trigger a HuggingFace download on first use. The
- # SentenceTransformer constructor reaches out to huggingface.co
- # when the requested model isn't cached locally — silent
- # outbound traffic that violates ``embeddings.require_local=True``.
- #
- # Resolve the requirement through the egress CONTEXT, not the raw
- # ``embeddings.require_local`` flag: under PRIVATE_ONLY,
- # context_from_snapshot forces require_local_embeddings=True even
- # when the user left the flag at its default False. Reading the raw
- # flag here would let a PRIVATE_ONLY (offline) run silently download
- # an uncached model from HuggingFace. An unknown/corrupt scope
- # raises PolicyDeniedError out of context_from_snapshot — fail
- # closed, do not download.
- require_local = False
+ # Constructing a cache-missing model is itself an egress action. It is
+ # allowed only under a resolved public scope (or the explicit
+ # UNPROTECTED escape hatch), never merely because the local-embedding
+ # flag is false. Snapshot-less, STRICT, PRIVATE_ONLY, and adaptive
+ # contexts that resolve BOTH therefore remain cache-only.
+ download_allowed = False
if settings_snapshot is not None:
try:
from ....security.egress.policy import (
+ EgressScope,
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).
+ # No fallback primary: an incomplete snapshot cannot widen the
+ # constructor into a network-capable state.
_primary = resolve_run_primary_engine(settings_snapshot)
- require_local = context_from_snapshot(
+ context = context_from_snapshot(
settings_snapshot,
_primary,
username=username_from_snapshot(settings_snapshot),
- ).require_local_embeddings
- except ValueError:
- # No usable primary / invalid scope: fail CLOSED to local-only
- # (block any remote model download) rather than reading the raw
- # opt-in flag. The get_embeddings PEP already refuses a
- # primary-less snapshot upstream, so this is defense-in-depth.
- require_local = True
- model_kwargs = {"device": device}
- if require_local:
- if not cls._is_model_cached_locally(model):
- from ....security.egress.policy import (
- Decision,
- PolicyDeniedError,
)
+ download_allowed = (
+ not context.require_local_embeddings
+ and context.scope
+ in {EgressScope.PUBLIC_ONLY, EgressScope.UNPROTECTED}
+ )
+ except ValueError:
+ # No usable primary: fail closed to cache-only. Unknown scopes
+ # raise PolicyDeniedError and intentionally propagate.
+ pass
+
+ spec = (
+ get_sentence_transformer_model_spec(model)
+ if isinstance(model, str)
+ else None
+ )
+ # Keep existing explicit local models confined to the application's
+ # models directory. The confined models directory is app-owned state,
+ # so an operator-placed model there wins in every scope — including
+ # when its name matches a catalog key or repository. That is the
+ # pre-catalog behavior and the only offline-usable form for an
+ # air-gapped install; resolving such a name to the Hub artifact
+ # instead would silently embed with different bytes than the
+ # collection was indexed with. The substitution is audited below so
+ # it is never silent. (This is unrelated to
+ # ``_reject_shadowed_hub_model``, which refuses an unconfined
+ # working-directory match for a name that was admitted as a Hub id.)
+ local_model_path = cls._confined_local_model_path(model)
+ if local_model_path is not None and spec is not None:
+ logger.bind(policy_audit=True).warning(
+ "using the confined local model directory {!r} for "
+ "embedding model {!r} instead of the curated Hub model {!r}",
+ str(local_model_path),
+ model,
+ spec.repository,
+ )
+ if local_model_path is None and cls._looks_like_filesystem_path(model):
+ raise ValueError(
+ "Invalid embedding model path: local model paths must "
+ "resolve under the application's models directory."
+ )
+ cache_dir = cls._model_cache_directory()
+ if local_model_path is not None:
+ return SentenceTransformerEmbeddings(
+ model_name=str(local_model_path),
+ cache_folder=cache_dir,
+ model_kwargs={
+ "device": device,
+ "trust_remote_code": False,
+ "token": False,
+ "model_kwargs": {"use_safetensors": True},
+ "local_files_only": True,
+ },
+ )
- # Render the model into the message (loguru brace
- # formatting), not as a bound kwarg: kwargs land in
- # ``record["extra"]``, which none of our sinks render,
- # so a bound value is invisible to operators. ``{!r}``
- # also makes a degenerate empty/whitespace config
- # self-evident (shows as ``''``).
- logger.bind(policy_audit=True).warning(
- "refusing SentenceTransformer download for {!r} "
- "under embeddings.require_local=True",
+ if spec is None:
+ # Legacy compatibility: if the model is already cached locally
+ # from a previous installation, allow loading it in local-only
+ # mode. This preserves access to existing collections indexed
+ # with non-catalog models without permitting new downloads of
+ # unvetted artifacts.
+ if isinstance(model, str) and cls._is_model_cached_locally(
+ model, cache_dir=cache_dir
+ ):
+ cls._reject_shadowed_hub_model(model)
+ logger.info(
+ "Loading legacy cached SentenceTransformer model {!r} "
+ "in local-only mode (not in catalog but already cached)",
model,
)
- raise PolicyDeniedError(
- Decision(False, "embeddings_model_not_cached"),
- target=model,
+ return SentenceTransformerEmbeddings(
+ model_name=model,
+ cache_folder=cache_dir,
+ model_kwargs={
+ "device": device,
+ "trust_remote_code": False,
+ "token": False,
+ "model_kwargs": {"use_safetensors": True},
+ "local_files_only": True,
+ },
)
- # Force the inner ``transformers``/``sentence_transformers``
- # call to use cached files only. Defence in depth for the
- # HF-cache branch — but LOAD-BEARING for the local-path admit
- # in ``_is_model_cached_locally``: that admit only checks the
- # path exists, doing zero content validation, so an existing
- # model dir whose config references an UNCACHED remote base
- # would otherwise fetch it here. Keep this set for every
- # require_local admit; do not relax it on the assumption that
- # the pre-flight already proved the model fully local.
- model_kwargs["local_files_only"] = True
- # Load a confined local model from its safe absolute path; otherwise
- # hand the (repo-id) value to the loader unchanged.
- return SentenceTransformerEmbeddings(
- model_name=(
- str(local_model_path) if local_model_path is not None else model
- ),
- model_kwargs=model_kwargs,
+ from ....security.egress.policy import (
+ Decision,
+ PolicyDeniedError,
+ )
+
+ # New downloads are restricted to the catalog. Existing local
+ # models were handled through the confined path above.
+ logger.bind(policy_audit=True).warning(
+ "refusing non-curated SentenceTransformer model {!r}", model
+ )
+ raise PolicyDeniedError(
+ Decision(False, "embeddings_model_not_curated"),
+ target=str(model),
+ )
+
+ # The new GTE key has an immutable artifact revision. Legacy keys must
+ # remain unpinned until collections persist a revision/digest; changing
+ # the bytes behind an existing key would silently invalidate its index.
+ resolved_model = spec.repository if spec.revision is not None else model
+ cls._reject_shadowed_hub_model(resolved_model)
+ # Resolve an already cached legacy snapshot without consulting the
+ # network. Repair must use these same bytes, never a newer remote main.
+ resolved_revision = spec.revision or cls._cached_model_revision(
+ spec.repository, cache_dir=cache_dir
)
+ model_kwargs = {
+ "device": device,
+ "trust_remote_code": False,
+ "token": False,
+ # Forwarded by SentenceTransformer to the nested transformers
+ # AutoModel.from_pretrained call. Do not accept pickle-based weights.
+ "model_kwargs": {"use_safetensors": True},
+ }
+ if resolved_revision is not None:
+ model_kwargs["revision"] = resolved_revision
+ cached = cls._is_model_cached_locally(
+ spec.repository, revision=resolved_revision, cache_dir=cache_dir
+ )
+ else:
+ # Preserve the exact legacy key/alias lookup semantics. The
+ # local-only constructor below reuses refs/main without checking
+ # for, or advancing to, a newer remote artifact.
+ cached = cls._is_model_cached_locally(model, cache_dir=cache_dir)
+
+ if cached:
+ # Probe the cache before considering policy-authorized network
+ # acquisition in every scope. This prevents repeat network
+ # checks and keeps a legacy collection on its existing bytes.
+ model_kwargs["local_files_only"] = True
+ elif not download_allowed:
+ from ....security.egress.policy import (
+ Decision,
+ PolicyDeniedError,
+ )
+
+ logger.bind(policy_audit=True).warning(
+ "refusing SentenceTransformer download for {!r} "
+ "outside a resolved public egress scope",
+ model,
+ )
+ raise PolicyDeniedError(
+ Decision(False, "embeddings_model_not_cached"),
+ target=str(model),
+ )
+
+ elif (
+ spec.revision is None
+ and resolved_revision is None
+ and cls._has_model_cache_state(spec.repository, cache_dir=cache_dir)
+ ):
+ from ....security.egress.policy import Decision, PolicyDeniedError
+
+ # A partially cached model is not a first install. Without a
+ # trustworthy revision, a floating download could change the
+ # vectors behind an existing collection's model key.
+ raise PolicyDeniedError(
+ Decision(False, "embeddings_cache_revision_unknown"),
+ target=str(model),
+ )
+
+ try:
+ return SentenceTransformerEmbeddings(
+ model_name=resolved_model,
+ cache_folder=cache_dir,
+ model_kwargs=model_kwargs,
+ )
+ except OSError as error:
+ # Metadata is evidence of a snapshot, not proof it is complete.
+ # An interrupted download can leave config/modules but no weights.
+ # Try the cache first; repair only under an authorized public scope
+ # and at an immutable known revision (including legacy snapshots).
+ #
+ # An environment fault is not an incomplete snapshot. The repair
+ # runs at the same commit revision, and the Hub client returns a
+ # file already present in that snapshot without fetching it again,
+ # so e.g. an unreadable modules.json or config (PermissionError,
+ # EACCES) fails identically on the retry. The retry could only
+ # reproduce the fault, now with network access enabled, and would
+ # replace the original, actionable error. Surface those unchanged.
+ # (Unreadable weights are different: safetensors reports them as
+ # FileNotFoundError without an errno, so they enter the repair,
+ # which likewise reuses the existing blob and fails the same way.)
+ if isinstance(error, PermissionError) or error.errno in (
+ errno.EACCES,
+ errno.EPERM,
+ errno.ENOSPC,
+ errno.EROFS,
+ ):
+ raise
+ if not (
+ model_kwargs.get("local_files_only")
+ and download_allowed
+ and resolved_revision is not None
+ ):
+ raise
+ repair_kwargs = dict(model_kwargs)
+ repair_kwargs.pop("local_files_only")
+ return SentenceTransformerEmbeddings(
+ model_name=resolved_model,
+ cache_folder=cache_dir,
+ model_kwargs=repair_kwargs,
+ )
+
+ @staticmethod
+ def _model_cache_directory() -> str:
+ """Use the loader's cache root for admission, revision and repair.
+
+ Sentence Transformers gives its own environment override precedence
+ over the Hub default. Resolve it once per load and pass it explicitly
+ to both cache probes and constructors.
+ """
+ from ....config.paths import get_sentence_transformers_home
+ from huggingface_hub.constants import HF_HUB_CACHE
+
+ cache_dir = get_sentence_transformers_home()
+ return HF_HUB_CACHE if cache_dir is None else cache_dir
@classmethod
- def _is_model_cached_locally(cls, model_name: str) -> bool:
- """Best-effort check whether ``model_name`` is available WITHOUT any
- network access.
-
- Admissible in two ordered cases:
-
- 1. ``model_name`` resolves to an existing file/dir CONFINED under the
- application's models directory (see
- :meth:`_confined_local_model_path`). Such a model is already on
- disk and ``SentenceTransformer.__init__`` loads it via its
- ``os.path.exists`` branch without touching the network.
-
- Security: the confinement check decides containment lexically and
- NEVER probes an arbitrary user-supplied path with
- ``Path(model_name).exists()``. A path outside the models dir can
- therefore no longer be used as a whole-filesystem existence oracle.
-
- 2. Otherwise ``model_name`` is treated as a HuggingFace repo id and the
- hub cache is probed for both the bare and the
- ``sentence-transformers/``-namespaced forms (the two cache keys the
- loader can request for a bare input).
-
- Returns False if the lookup itself fails, which fails closed under
- ``require_local=True``. A degenerate model_name (None, empty,
- whitespace) also fails closed.
+ def _is_model_cached_locally(
+ cls,
+ model_name: str,
+ revision: Optional[str] = None,
+ *,
+ cache_dir: Optional[str] = None,
+ ) -> bool:
+ """Check the Hub cache for an offline-loadable configuration.
+
+ Confined local models never reach this helper: ``create_embeddings``
+ resolves ``_confined_local_model_path`` first and returns from its own
+ branch, so this is purely a repo-id cache probe (a filesystem-shaped
+ name is a miss, not an existence probe).
+
+ Curated models require every file in their spec's
+ ``required_cache_files`` (model config, module list, pooling config,
+ tokenizer config and, where the artifact publishes one, the
+ Transformer module config) plus at least one file from each group in
+ ``required_cache_file_alternatives`` (the tokenizer vocabulary:
+ ``tokenizer.json`` or ``vocab.txt`` for the legacy WordPiece/MPNet
+ models, ``tokenizer.json`` for the others). Any of them missing can
+ silently change pooling, truncation, tokenizer selection or the
+ vocabulary itself without the offline constructor raising, so none of
+ it is left to the missing-weight repair path. Weights are not probed:
+ a missing weights file does raise from the offline constructor, which
+ a policy-authorized load repairs at the cache's existing revision.
+ Names outside the catalog need only ``config.json`` (config-only
+ vanilla transformer snapshots remain compatible).
"""
+ if not model_name or not isinstance(model_name, str):
+ return False
+ if cls._looks_like_filesystem_path(model_name):
+ return False
try:
- # 1. A legitimate local model confined under the app models dir.
- if cls._confined_local_model_path(model_name) is not None:
- return True
-
- # 2. Treat the value as an HF repo id and probe the hub cache
- # ONLY. try_to_load_from_cache keys on the string as a repo_id
- # inside the HF cache directory, so a non-confined path is never
- # reached on the real filesystem here.
from huggingface_hub import try_to_load_from_cache
# Probe both the bare and the namespaced cache keys when the
- # input has no "/", because ``SentenceTransformer.__init__``
- # resolves bare names two different ways:
- # - names in its ``basic_transformer_models`` allowlist
+ # input has no "/", because the upstream loader resolves bare
+ # names two different ways:
+ # - names in ``sentence_transformers.util.misc``'s
+ # ``ORIGINAL_TRANSFORMER_MODELS`` edge-case list
# (bert-base-uncased, gpt2, t5-base, ...) are requested
# from the BARE repo_id;
- # - everything else is prefixed with
+ # - everything else is prefixed with the model class's
+ # ``default_huggingface_organization`` — for
+ # ``SentenceTransformer`` the value re-exported as
# ``__MODEL_HUB_ORGANIZATION__`` (e.g. "all-MiniLM-L6-v2"
# -> "sentence-transformers/all-MiniLM-L6-v2").
# The HF hub cache is keyed on whichever form the loader
# requests, so probing both is the only way to be correct
- # for both classes without mirroring the upstream allowlist
- # (a local list inside ``SentenceTransformer.__init__``).
+ # for both classes without mirroring that upstream list.
if "/" in model_name:
candidates = [model_name]
else:
@@ -261,19 +388,125 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
f"{__MODEL_HUB_ORGANIZATION__}/{model_name}",
]
- # try_to_load_from_cache returns a path string when cached,
- # None when missing, and the sentinel _CACHED_NO_EXIST for
- # known-absent. Treat anything but a string path as a miss.
- for repo_id in candidates:
- cached = try_to_load_from_cache(
- repo_id=repo_id, filename="config.json"
+ if cache_dir is None:
+ cache_dir = cls._model_cache_directory()
+ spec = get_sentence_transformer_model_spec(model_name)
+ required_files = (
+ spec.required_cache_files if spec else ("config.json",)
+ )
+ alternatives = spec.required_cache_file_alternatives if spec else ()
+
+ def is_cached(repo_id: str, filename: str) -> bool:
+ cache_kwargs = {
+ "repo_id": repo_id,
+ "filename": filename,
+ "cache_dir": cache_dir,
+ }
+ if revision is not None:
+ cache_kwargs["revision"] = revision
+ cached = try_to_load_from_cache(**cache_kwargs)
+ return isinstance(cached, str) and bool(cached)
+
+ # Every required file, and at least one file of every group.
+ return any(
+ all(is_cached(repo_id, name) for name in required_files)
+ and all(
+ any(is_cached(repo_id, name) for name in group)
+ for group in alternatives
)
- if isinstance(cached, str) and bool(cached):
- return True
- return False
+ for repo_id in candidates
+ )
except Exception: # pragma: no cover - defensive
return False
+ @classmethod
+ def _cached_model_revision(
+ cls, repository: str, *, cache_dir: Optional[str] = None
+ ) -> Optional[str]:
+ """Read a snapshot commit from local metadata or the Hub's refs/main.
+
+ Hub cache lookup returns a lexical snapshots/<commit>/<file> path;
+ resolving its symlink would lose the commit by pointing into blobs/.
+ Reject ambiguous or unrecognized paths rather than repair at main.
+ """
+ try:
+ from huggingface_hub import try_to_load_from_cache
+
+ if cache_dir is None:
+ cache_dir = cls._model_cache_directory()
+ revisions = set()
+ for filename in ("config.json", "modules.json"):
+ cached = try_to_load_from_cache(
+ repo_id=repository, filename=filename, cache_dir=cache_dir
+ )
+ if not isinstance(cached, str) or not cached:
+ continue
+ snapshot = Path(cached).parent
+ if snapshot.parent.name != "snapshots" or not re.fullmatch(
+ r"[0-9a-f]{40}", snapshot.name
+ ):
+ return None
+ revisions.add(snapshot.name)
+ # The Hub's local ref survives loss of both metadata anchors.
+ # Read it without resolving a model file or contacting the Hub.
+ reference = (
+ Path(cache_dir)
+ / ("models--" + repository.replace("/", "--"))
+ / "refs"
+ / "main"
+ )
+ try:
+ cached_revision = reference.read_text(encoding="ascii").strip()
+ except FileNotFoundError:
+ cached_revision = None
+ if cached_revision is not None:
+ if not re.fullmatch(r"[0-9a-f]{40}", cached_revision):
+ return None
+ revisions.add(cached_revision)
+ return next(iter(revisions)) if len(revisions) == 1 else None
+ except Exception: # pragma: no cover - cache lookup is best-effort
+ return None
+
+ @classmethod
+ def _has_model_cache_state(
+ cls, repository: str, *, cache_dir: Optional[str] = None
+ ) -> bool:
+ """Distinguish an empty cache from an unresolved existing snapshot.
+
+ Only curated repository names reach this helper. Any existing entry
+ counts as cache state; inaccessible state must not permit a floating
+ download. An absent or completely empty repository cache is a new
+ installation.
+ """
+ if cache_dir is None:
+ cache_dir = cls._model_cache_directory()
+ cache = Path(cache_dir) / ("models--" + repository.replace("/", "--"))
+ try:
+ return next(cache.iterdir(), None) is not None
+ except FileNotFoundError:
+ return False
+ except OSError:
+ return True
+
+ @staticmethod
+ def _reject_shadowed_hub_model(model_name: str) -> None:
+ """Prevent the loader from interpreting an admitted Hub ID as a CWD path.
+
+ Call only after catalog/cache admission and lexical path checks, so
+ arbitrary absolute server paths never reach this existence check.
+ Explicit local models use the separately confined absolute path.
+ """
+ try:
+ shadowed = Path(model_name).exists()
+ except (OSError, ValueError):
+ shadowed = True
+ if shadowed:
+ raise ValueError(
+ "Embedding model identifier conflicts with a local path. "
+ "Use an explicit path under the application's models directory "
+ "for a local model."
+ )
+
@classmethod
def _confined_local_model_path(
cls,
@@ -434,9 +667,9 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
"""
Get list of available Sentence Transformer models.
- Note: Since there's no centralized API for Sentence Transformers,
- we return a curated list of commonly used models. Users can also
- specify any model name from HuggingFace directly in settings.
+ The catalog controls new Hub downloads. Existing non-catalog Hub
+ snapshots and models confined to the application's models directory
+ remain available in local-only mode.
"""
return [
{
diff --git a/src/local_deep_research/embeddings/sentence_transformer_models.py b/src/local_deep_research/embeddings/sentence_transformer_models.py
new file mode 100644
index 0000000000..aeaa0748fa
--- /dev/null
+++ b/src/local_deep_research/embeddings/sentence_transformer_models.py
@@ -0,0 +1,142 @@
+"""Curated Sentence Transformer model identities.
+
+The model key is the stable value stored in user settings and collection
+metadata. Only newly introduced keys may pin a different Hugging Face artifact:
+legacy keys must keep their historic floating-revision semantics because
+collection metadata does not yet persist an artifact revision.
+
+Pinned ``revision`` values are immutable Hugging Face commit hashes
+that identify the exact model artifact bytes fetched at download time.
+"""
+
+from dataclasses import dataclass
+from types import MappingProxyType
+from typing import Mapping
+
+
+from ..constants import (
+ DEFAULT_LOCAL_SEARCH_MODEL as DEFAULT_SENTENCE_TRANSFORMER_MODEL,
+)
+
+
+@dataclass(frozen=True)
+class SentenceTransformerModelSpec:
+ """Artifact policy and display metadata for a curated model."""
+
+ repository: str
+ revision: str | None
+ dimensions: int
+ description: str
+ max_seq_length: int
+ # Require behavior-changing metadata before an offline load. Missing
+ # Transformer or tokenizer configuration can silently change truncation
+ # or tokenizer selection without raising a missing-weight error.
+ required_cache_files: tuple[str, ...] = (
+ "config.json",
+ "modules.json",
+ "1_Pooling/config.json",
+ "tokenizer_config.json",
+ "sentence_bert_config.json",
+ )
+ # Tokenizer vocabulary, as groups of which at least one file must be
+ # cached. Without it the offline constructor does not fail: it builds a
+ # placeholder tokenizer from the special tokens alone and embeds every
+ # text as the same few ids, which the missing-weight repair never sees.
+ # Legacy WordPiece/MPNet repositories publish both the fast
+ # ``tokenizer.json`` and the slow ``vocab.txt``; either one alone rebuilds
+ # the same tokenizer, so a cache holding only one of them still loads.
+ required_cache_file_alternatives: tuple[tuple[str, ...], ...] = (
+ ("tokenizer.json", "vocab.txt"),
+ )
+
+ def display_metadata(self) -> dict[str, int | str]:
+ """Return the legacy metadata shape consumed by provider APIs."""
+
+ return {
+ "dimensions": self.dimensions,
+ "description": self.description,
+ "max_seq_length": self.max_seq_length,
+ }
+
+
+SENTENCE_TRANSFORMER_MODELS: Mapping[str, SentenceTransformerModelSpec] = (
+ MappingProxyType(
+ {
+ DEFAULT_SENTENCE_TRANSFORMER_MODEL: SentenceTransformerModelSpec(
+ repository=DEFAULT_SENTENCE_TRANSFORMER_MODEL,
+ revision="e7f32e3c00f91d699e8c43b53106206bcc72bb22",
+ dimensions=768,
+ description=(
+ "Recommended default with higher-quality English and "
+ "long-context document retrieval."
+ ),
+ max_seq_length=8192,
+ # This pinned artifact has no sentence_bert_config.json;
+ # its token limit is inferred from model and tokenizer config.
+ required_cache_files=(
+ "config.json",
+ "modules.json",
+ "1_Pooling/config.json",
+ "tokenizer_config.json",
+ ),
+ # ModernBERT ships a BPE ``tokenizer.json`` and no vocab.txt.
+ required_cache_file_alternatives=(("tokenizer.json",),),
+ ),
+ "all-MiniLM-L6-v2": SentenceTransformerModelSpec(
+ repository="sentence-transformers/all-MiniLM-L6-v2",
+ revision=None,
+ dimensions=384,
+ description="Fast, lightweight model. Good for general use.",
+ max_seq_length=256,
+ ),
+ "all-mpnet-base-v2": SentenceTransformerModelSpec(
+ repository="sentence-transformers/all-mpnet-base-v2",
+ revision=None,
+ dimensions=768,
+ description="Higher quality, slower. Best accuracy.",
+ max_seq_length=384,
+ ),
+ "multi-qa-MiniLM-L6-cos-v1": SentenceTransformerModelSpec(
+ repository=("sentence-transformers/multi-qa-MiniLM-L6-cos-v1"),
+ revision=None,
+ dimensions=384,
+ description="Optimized for question-answering tasks.",
+ max_seq_length=512,
+ ),
+ "paraphrase-multilingual-MiniLM-L12-v2": (
+ SentenceTransformerModelSpec(
+ repository=(
+ "sentence-transformers/"
+ "paraphrase-multilingual-MiniLM-L12-v2"
+ ),
+ revision=None,
+ dimensions=384,
+ description="Supports multiple languages.",
+ max_seq_length=128,
+ # An XLM-R SentencePiece tokenizer, not WordPiece: there
+ # is no vocab.txt fallback, so require ``tokenizer.json``.
+ required_cache_file_alternatives=(("tokenizer.json",),),
+ )
+ ),
+ }
+ )
+)
+
+
+def get_sentence_transformer_model_spec(
+ model_name: str,
+) -> SentenceTransformerModelSpec | None:
+ """Resolve either a stable catalog key or its full repository name."""
+
+ spec = SENTENCE_TRANSFORMER_MODELS.get(model_name)
+ if spec is not None:
+ return spec
+
+ return next(
+ (
+ candidate
+ for candidate in SENTENCE_TRANSFORMER_MODELS.values()
+ if candidate.repository == model_name
+ ),
+ None,
+ )
diff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.py
index fb51012ad4..78b4e08ffc 100644
--- a/src/local_deep_research/web/routers/rag.py
+++ b/src/local_deep_research/web/routers/rag.py
@@ -103,6 +103,11 @@ _RAG_CHUNK_OVERLAP_MAX = 1_000
router = APIRouter(prefix="/library", tags=["rag"])
+_EMBEDDING_TEST_SENTENCE = (
+ "This is a test sentence to verify the embedding model is working "
+ "correctly."
+)
+
# Process-local registry tracking active SSE indexing streams for cancellation.
# Keyed by (username, collection_id) -> Set[threading.Event]
# NOTE: Process-local registry assumes single-process deployment (or sticky sessions).
@@ -752,7 +757,6 @@ async def test_embedding(
return json_body_error("success", "Request body must be valid JSON")
provider = data.get("provider")
model = data.get("model")
- test_text = data.get("test_text", "This is a test.")
if not provider or not model:
return JSONResponse(
@@ -786,7 +790,7 @@ async def test_embedding(
model_name=model,
settings_snapshot=settings_snapshot,
)
- emb = ef([test_text])[0]
+ emb = ef([_EMBEDDING_TEST_SENTENCE])[0]
return emb, int((time.time() - start) * 1000)
# run_db_sync (not raw to_thread): the thunk opens a
@@ -817,14 +821,39 @@ async def test_embedding(
from ...security.egress.policy import PolicyDeniedError
if isinstance(e, PolicyDeniedError):
+ reason = e.decision.reason
+ if reason == "embeddings_model_not_curated":
+ return JSONResponse(
+ {
+ "success": False,
+ "error": f"Sentence Transformers model '{model}' is not in LDR's vetted model list. Choose one of the listed models, or use Ollama for custom locally managed embedding models. Direct arbitrary Hugging Face downloads are disabled.",
+ "reason_code": reason,
+ },
+ status_code=400,
+ )
+ if reason == "embeddings_cache_revision_unknown":
+ return JSONResponse(
+ {
+ "success": False,
+ "error": f"The existing Sentence Transformers cache for '{model}' does not identify a single immutable model revision, so a new download is refused: it could change the model behind an existing index. To start over, delete that model's cache directory (the 'models--...' folder under the Hugging Face cache, by default ~/.cache/huggingface/hub) and run this test again under Public only — do this only if no collection was indexed with it. To keep an existing index, put a trusted copy of the model under the application's models directory and select it by that name instead, or select a different model.",
+ "reason_code": reason,
+ },
+ status_code=400,
+ )
+ if reason == "embeddings_model_not_cached":
+ return JSONResponse(
+ {
+ "success": False,
+ "error": f"Sentence Transformers model '{model}' has not been downloaded yet. Set Egress Scope to Public only, or use Adaptive with a public primary and no private collection selected. If 'Require local embeddings' is enabled, turn it off for this download, then run this test again. After the download completes, you can return to your preferred restrictive scope.",
+ "reason_code": reason,
+ },
+ status_code=400,
+ )
return JSONResponse(
{
"success": False,
- "error": (
- f"Embedding provider '{provider}' refused by egress "
- f"policy ({e.decision.reason}). Disable 'Require "
- "local embeddings' or pick a local provider."
- ),
+ "error": f"Embedding provider '{provider}' refused by egress policy ({reason}). Disable 'Require local embeddings' or pick a local provider.",
+ "reason_code": reason,
},
status_code=400,
)
diff --git a/src/local_deep_research/web/static/js/config/constants.js b/src/local_deep_research/web/static/js/config/constants.js
index b43f7acf0e..f6854072ef 100644
--- a/src/local_deep_research/web/static/js/config/constants.js
+++ b/src/local_deep_research/web/static/js/config/constants.js
@@ -30,7 +30,7 @@ if (typeof LDR_CONSTANTS !== 'undefined') {
SEMANTIC: 'semantic',
},
DEFAULT_LOCAL_SEARCH_PROVIDER: _injectedLocalSearchDefaults.provider || 'sentence_transformers',
- DEFAULT_LOCAL_SEARCH_MODEL: _injectedLocalSearchDefaults.model || 'all-MiniLM-L6-v2',
+ DEFAULT_LOCAL_SEARCH_MODEL: _injectedLocalSearchDefaults.model || 'Alibaba-NLP/gte-modernbert-base',
DEFAULT_LOCAL_SEARCH_CHUNK_SIZE: _injectedLocalSearchDefaults.chunk_size ?? 1000,
DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP: _injectedLocalSearchDefaults.chunk_overlap ?? 200,
DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE: _injectedLocalSearchDefaults.splitter_type || 'recursive',
diff --git a/src/local_deep_research/web/static/js/embedding_settings.js b/src/local_deep_research/web/static/js/embedding_settings.js
index 6afcc5bf32..3d768ddbd7 100644
--- a/src/local_deep_research/web/static/js/embedding_settings.js
+++ b/src/local_deep_research/web/static/js/embedding_settings.js
@@ -28,7 +28,7 @@ function getLocalSearchDefaults() {
const constants = (typeof LDR_CONSTANTS !== 'undefined' ? LDR_CONSTANTS : (typeof window !== 'undefined' && window.LDR_CONSTANTS)) || {};
return {
provider: constants.DEFAULT_LOCAL_SEARCH_PROVIDER || 'sentence_transformers',
- model: constants.DEFAULT_LOCAL_SEARCH_MODEL || 'all-MiniLM-L6-v2',
+ model: constants.DEFAULT_LOCAL_SEARCH_MODEL || 'Alibaba-NLP/gte-modernbert-base',
chunk_size: constants.DEFAULT_LOCAL_SEARCH_CHUNK_SIZE ?? 1000,
chunk_overlap: constants.DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP ?? 200,
splitter_type: constants.DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE || 'recursive',
@@ -994,11 +994,7 @@ async function testConfiguration() {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
},
- body: JSON.stringify({
- provider,
- model,
- test_text: 'This is a test sentence to verify the embedding model is working correctly.'
- })
+ body: JSON.stringify({ provider, model })
});
const data = await response.json();
diff --git a/src/local_deep_research/web/templates/pages/embedding_settings.html b/src/local_deep_research/web/templates/pages/embedding_settings.html
index a8db2c7635..85442c4576 100644
--- a/src/local_deep_research/web/templates/pages/embedding_settings.html
+++ b/src/local_deep_research/web/templates/pages/embedding_settings.html
@@ -48,6 +48,18 @@
Test the currently selected embedding model to ensure it's working correctly.
</p>
+ <div class="ldr-alert ldr-alert-info" id="sentence-transformers-download-notice" role="note" style="margin-bottom: 15px;">
+ <i aria-hidden="true" class="fas fa-download"></i>
+ <strong>Using another Sentence Transformers model?</strong>
+ Sentence Transformers models require a one-time download before they can be used offline.
+ Temporarily set <strong>Egress Scope</strong> to <strong>Public only</strong>, or use <strong>Adaptive</strong> while it resolves to public
+ (a public primary search engine with no private collection selected). If you enabled <strong>Require local embeddings</strong>,
+ turn it off for this download. Select the model under Configuration, then click
+ <strong>Test Embedding Model</strong>. After the test passes, LDR can reuse the local cache when you return to a more restrictive scope.
+ Direct arbitrary Hugging Face model IDs are not downloaded. For a broader choice of locally managed embedding models, we recommend using <strong>Ollama</strong>.
+ Change this in <a href="/settings/">Settings &rarr; Search Engines &rarr; Egress Scope</a>.
+ </div>
+
<div class="ldr-operations-grid">
<button class="ldr-btn ldr-btn-success ldr-btn-lg" onclick="testConfiguration()" id="test-config-btn">
<i aria-hidden="true" class="fas fa-play"></i> Test Embedding Model
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 652e0c1248..4067476ba1 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
@@ -153,7 +153,7 @@ class LocalEmbeddingManager:
return get_embeddings(
provider="sentence_transformers",
- model=None, # provider default (all-MiniLM-L6-v2)
+ model=None, # provider default (DEFAULT_SENTENCE_TRANSFORMER_MODEL)
settings_snapshot=self.settings_snapshot,
)
diff --git a/tests/embeddings/test_sentence_transformer_cache_metadata.py b/tests/embeddings/test_sentence_transformer_cache_metadata.py
new file mode 100644
index 0000000000..cac00fdec1
--- /dev/null
+++ b/tests/embeddings/test_sentence_transformer_cache_metadata.py
@@ -0,0 +1,545 @@
+"""Interrupted curated caches must not silently change embedding behavior."""
+
+import json
+from unittest.mock import patch
+
+import pytest
+
+from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider as Provider,
+)
+from local_deep_research.embeddings.sentence_transformer_models import (
+ DEFAULT_SENTENCE_TRANSFORMER_MODEL,
+ get_sentence_transformer_model_spec,
+)
+from local_deep_research.security.egress.policy import PolicyDeniedError
+
+
+LEGACY_MODELS = [
+ "all-MiniLM-L6-v2",
+ "sentence-transformers/all-MiniLM-L6-v2",
+ "all-mpnet-base-v2",
+ "multi-qa-MiniLM-L6-cos-v1",
+ "paraphrase-multilingual-MiniLM-L12-v2",
+]
+
+# Repositories whose tokenizer vocabulary is published only as tokenizer.json.
+TOKENIZER_JSON_ONLY_MODELS = {
+ DEFAULT_SENTENCE_TRANSFORMER_MODEL,
+ "paraphrase-multilingual-MiniLM-L12-v2",
+}
+
+POLICIES = [
+ pytest.param(None, False, id="snapshotless"),
+ pytest.param(
+ {"policy.egress_scope": "strict", "search.tool": "arxiv"},
+ False,
+ id="strict",
+ ),
+ pytest.param(
+ {"policy.egress_scope": "private_only", "search.tool": "library"},
+ False,
+ id="private",
+ ),
+ pytest.param(
+ {
+ "policy.egress_scope": "public_only",
+ "search.tool": "arxiv",
+ "embeddings.require_local": True,
+ },
+ False,
+ id="public-local-only",
+ ),
+ pytest.param(
+ {"policy.egress_scope": "public_only", "search.tool": "arxiv"},
+ True,
+ id="public",
+ ),
+]
+
+
+def _cached_snapshot(tmp_path, monkeypatch, model, missing_file=None):
+ """Use the real Hub cache lookup with metadata files and refs/main.
+
+ ``missing_file`` is one file name, or a tuple of names, left out of the
+ snapshot. The tokenizer vocabulary mirrors each repository's layout:
+ the legacy WordPiece/MPNet models publish ``tokenizer.json`` and
+ ``vocab.txt``; GTE ModernBERT and multilingual MiniLM publish only
+ ``tokenizer.json`` of the two.
+ """
+ missing = (
+ set(missing_file) if isinstance(missing_file, tuple) else {missing_file}
+ )
+ from huggingface_hub import constants
+
+ spec = get_sentence_transformer_model_spec(model)
+ revision = spec.revision or "a" * 40
+ monkeypatch.delenv("SENTENCE_TRANSFORMERS_HOME", raising=False)
+ monkeypatch.setattr(constants, "HF_HUB_CACHE", str(tmp_path))
+ repository = tmp_path / ("models--" + spec.repository.replace("/", "--"))
+ snapshot = repository / "snapshots" / revision
+ (repository / "refs").mkdir(parents=True)
+ (repository / "refs" / "main").write_text(revision)
+ inferred_limit = (
+ 8192 if model == DEFAULT_SENTENCE_TRANSFORMER_MODEL else 512
+ )
+ metadata = {
+ "config.json": {"max_position_embeddings": inferred_limit},
+ "modules.json": [
+ {
+ "idx": 0,
+ "path": "",
+ "type": "sentence_transformers.models.Transformer",
+ },
+ {
+ "idx": 1,
+ "path": "1_Pooling",
+ "type": "sentence_transformers.models.Pooling",
+ },
+ ],
+ "1_Pooling/config.json": {"word_embedding_dimension": spec.dimensions},
+ "tokenizer_config.json": {"model_max_length": inferred_limit},
+ }
+ # The pinned GTE artifact does not publish a Transformer module config.
+ if model != DEFAULT_SENTENCE_TRANSFORMER_MODEL:
+ metadata["sentence_bert_config.json"] = {
+ "max_seq_length": spec.max_seq_length,
+ "do_lower_case": False,
+ }
+ for filename, contents in metadata.items():
+ if filename not in missing:
+ path = snapshot / filename
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(contents))
+ vocabulary = ["tokenizer.json"]
+ if model not in TOKENIZER_JSON_ONLY_MODELS:
+ vocabulary.append("vocab.txt")
+ for filename in vocabulary:
+ if filename not in missing:
+ (snapshot / filename).write_text("{}")
+ return snapshot, revision
+
+
[email protected]("model", LEGACY_MODELS)
[email protected]("missing_file", [None, "sentence_bert_config.json"])
[email protected]("settings_snapshot,download_allowed", POLICIES)
+def test_transformer_metadata_admission_preserves_policy_and_revision(
+ model,
+ missing_file,
+ settings_snapshot,
+ download_allowed,
+ tmp_path,
+ monkeypatch,
+):
+ _, revision = _cached_snapshot(tmp_path, monkeypatch, model, missing_file)
+ with patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings"
+ ) as constructor:
+ if missing_file and not download_allowed:
+ with pytest.raises(PolicyDeniedError) as error:
+ Provider.create_embeddings(
+ model=model, settings_snapshot=settings_snapshot
+ )
+ assert error.value.decision.reason == "embeddings_model_not_cached"
+ constructor.assert_not_called()
+ return
+ Provider.create_embeddings(
+ model=model, settings_snapshot=settings_snapshot
+ )
+
+ constructor.assert_called_once()
+ kwargs = constructor.call_args.kwargs["model_kwargs"]
+ assert kwargs.get("local_files_only", False) is (missing_file is None)
+ assert kwargs["revision"] == revision
+ assert kwargs["token"] is False
+ assert kwargs["trust_remote_code"] is False
+ assert kwargs["model_kwargs"]["use_safetensors"] is True
+
+
[email protected]("missing_file", [None, "tokenizer_config.json"])
+ "model", [DEFAULT_SENTENCE_TRANSFORMER_MODEL, *LEGACY_MODELS]
+)
[email protected]("download_allowed", [False, True])
+def test_tokenizer_metadata_is_required_for_curated_loads(
+ model, missing_file, download_allowed, tmp_path, monkeypatch
+):
+ _, revision = _cached_snapshot(tmp_path, monkeypatch, model, missing_file)
+ settings_snapshot = {
+ "policy.egress_scope": "public_only"
+ if download_allowed
+ else "private_only",
+ "search.tool": "arxiv",
+ }
+ with patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings"
+ ) as constructor:
+ if missing_file and not download_allowed:
+ with pytest.raises(PolicyDeniedError) as error:
+ Provider.create_embeddings(
+ model=model, settings_snapshot=settings_snapshot
+ )
+ assert error.value.decision.reason == "embeddings_model_not_cached"
+ constructor.assert_not_called()
+ return
+ Provider.create_embeddings(
+ model=model, settings_snapshot=settings_snapshot
+ )
+
+ constructor.assert_called_once()
+ kwargs = constructor.call_args.kwargs["model_kwargs"]
+ assert kwargs.get("local_files_only", False) is (missing_file is None)
+ assert kwargs["revision"] == revision
+ assert kwargs["token"] is False
+ assert kwargs["trust_remote_code"] is False
+ assert kwargs["model_kwargs"]["use_safetensors"] is True
+
+
+ ("model", "missing", "admitted"),
+ [
+ pytest.param(
+ DEFAULT_SENTENCE_TRANSFORMER_MODEL,
+ ("tokenizer.json",),
+ False,
+ id="gte-no-tokenizer-json",
+ ),
+ pytest.param(
+ "paraphrase-multilingual-MiniLM-L12-v2",
+ ("tokenizer.json",),
+ False,
+ id="multilingual-no-tokenizer-json",
+ ),
+ pytest.param(
+ "all-MiniLM-L6-v2",
+ ("tokenizer.json", "vocab.txt"),
+ False,
+ id="legacy-no-vocabulary",
+ ),
+ pytest.param(
+ "sentence-transformers/all-mpnet-base-v2",
+ ("tokenizer.json", "vocab.txt"),
+ False,
+ id="legacy-alias-no-vocabulary",
+ ),
+ pytest.param(
+ "all-MiniLM-L6-v2",
+ ("tokenizer.json",),
+ True,
+ id="legacy-vocab-txt-only",
+ ),
+ pytest.param(
+ "multi-qa-MiniLM-L6-cos-v1",
+ ("vocab.txt",),
+ True,
+ id="legacy-tokenizer-json-only",
+ ),
+ ],
+)
[email protected]("download_allowed", [False, True])
+def test_tokenizer_vocabulary_is_required_for_offline_admission(
+ model, missing, admitted, download_allowed, tmp_path, monkeypatch
+):
+ """A cache without any tokenizer vocabulary must never load offline.
+
+ The offline constructor does not raise for it: it builds a placeholder
+ tokenizer from the special tokens alone, so every text embeds as the same
+ few ids and the missing-weight repair never runs. Either WordPiece file
+ alone rebuilds the real tokenizer, so a legacy cache holding just one of
+ them is still admitted.
+ """
+ _, revision = _cached_snapshot(tmp_path, monkeypatch, model, missing)
+ settings_snapshot = {
+ "policy.egress_scope": "public_only"
+ if download_allowed
+ else "private_only",
+ "search.tool": "arxiv",
+ }
+ with patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings"
+ ) as constructor:
+ if not admitted and not download_allowed:
+ with pytest.raises(PolicyDeniedError) as error:
+ Provider.create_embeddings(
+ model=model, settings_snapshot=settings_snapshot
+ )
+ assert error.value.decision.reason == "embeddings_model_not_cached"
+ constructor.assert_not_called()
+ return
+ Provider.create_embeddings(
+ model=model, settings_snapshot=settings_snapshot
+ )
+
+ constructor.assert_called_once()
+ kwargs = constructor.call_args.kwargs["model_kwargs"]
+ # Not admitted: the authorized download stays on the cached revision.
+ assert kwargs.get("local_files_only", False) is admitted
+ assert kwargs["revision"] == revision
+ assert kwargs["token"] is False
+ assert kwargs["trust_remote_code"] is False
+ assert kwargs["model_kwargs"]["use_safetensors"] is True
+
+
+def test_actual_transformer_loader_accepts_missing_token_limit_metadata(
+ tmp_path, monkeypatch
+):
+ """The missing-weight OSError retry cannot detect this silent fallback."""
+ from sentence_transformers.models import Transformer
+
+ snapshot, _ = _cached_snapshot(tmp_path, monkeypatch, "all-MiniLM-L6-v2")
+ complete = Transformer.load_config(
+ str(snapshot), local_files_only=True, token=False
+ )
+ assert complete["max_seq_length"] == 256
+
+ (snapshot / "sentence_bert_config.json").unlink()
+ incomplete = Transformer.load_config(
+ str(snapshot), local_files_only=True, token=False
+ )
+ assert "max_seq_length" not in incomplete
+
+
+def test_actual_tokenizer_loader_changes_special_tokens_without_metadata(
+ tmp_path,
+):
+ """Multilingual MiniLM explicitly selects a generic fast tokenizer over BERT.
+
+ Its model config says BERT while its tokenizer config selects the generic
+ fast tokenizer with XLM-R-style special tokens. A tiny local vocabulary
+ demonstrates the same silent fallback without downloading model weights.
+ """
+ from tokenizers import Tokenizer
+ from tokenizers.models import WordPiece
+ from transformers import AutoTokenizer
+
+ vocabulary = {
+ "<s>": 0,
+ "<pad>": 1,
+ "</s>": 2,
+ "<unk>": 3,
+ "<mask>": 4,
+ "hello": 5,
+ }
+ tokenizer = Tokenizer(WordPiece(vocab=vocabulary, unk_token="<unk>"))
+ tokenizer.save(str(tmp_path / "tokenizer.json"))
+ (tmp_path / "config.json").write_text(json.dumps({"model_type": "bert"}))
+ tokenizer_config = tmp_path / "tokenizer_config.json"
+ tokenizer_config.write_text(
+ json.dumps(
+ {
+ "tokenizer_class": "PreTrainedTokenizerFast",
+ "cls_token": "<s>",
+ "sep_token": "</s>",
+ "unk_token": "<unk>",
+ "pad_token": "<pad>",
+ "mask_token": "<mask>",
+ "model_max_length": 512,
+ }
+ )
+ )
+
+ load_kwargs = {
+ "local_files_only": True,
+ "token": False,
+ "trust_remote_code": False,
+ }
+ complete = AutoTokenizer.from_pretrained(str(tmp_path), **load_kwargs)
+ assert complete.cls_token == "<s>"
+ assert complete.cls_token_id == 0
+
+ tokenizer_config.unlink()
+ incomplete = AutoTokenizer.from_pretrained(str(tmp_path), **load_kwargs)
+ assert incomplete.cls_token == "[CLS]"
+ assert incomplete.cls_token_id != complete.cls_token_id
+
+
[email protected]("reference", ["valid", "missing", "malformed"])
[email protected]("download_allowed", [False, True])
+def test_missing_revision_anchors_preserve_existing_cache_identity(
+ reference, download_allowed, tmp_path, monkeypatch
+):
+ """Missing config/modules must never turn cache repair into a fresh model.
+
+ The remaining cache files belong to revision A. Floating upstream main
+ could point at different model bytes, invalidating existing index vectors.
+ """
+ model = "all-MiniLM-L6-v2"
+ snapshot, revision = _cached_snapshot(tmp_path, monkeypatch, model)
+ (snapshot / "config.json").unlink()
+ (snapshot / "modules.json").unlink()
+ ref = snapshot.parent.parent / "refs" / "main"
+ if reference == "missing":
+ ref.unlink()
+ elif reference == "malformed":
+ ref.write_text("unresolved-main")
+ settings = {
+ "policy.egress_scope": "public_only"
+ if download_allowed
+ else "private_only",
+ "search.tool": "arxiv",
+ }
+ with patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings"
+ ) as constructor:
+ if not download_allowed or reference != "valid":
+ with pytest.raises(PolicyDeniedError) as error:
+ Provider.create_embeddings(
+ model=model, settings_snapshot=settings
+ )
+ expected = (
+ "embeddings_cache_revision_unknown"
+ if download_allowed
+ else "embeddings_model_not_cached"
+ )
+ assert error.value.decision.reason == expected
+ constructor.assert_not_called()
+ return
+ Provider.create_embeddings(model=model, settings_snapshot=settings)
+ constructor.assert_called_once()
+ kwargs = constructor.call_args.kwargs["model_kwargs"]
+ assert kwargs["revision"] == revision
+ assert "local_files_only" not in kwargs
+ assert kwargs["token"] is False
+ assert kwargs["trust_remote_code"] is False
+ assert kwargs["model_kwargs"]["use_safetensors"] is True
+
+
[email protected]("cache_state", ["absent", "empty", "unresolved"])
+def test_only_fresh_cache_allows_a_floating_first_install(
+ cache_state, tmp_path, monkeypatch
+):
+ """Unknown existing state must not inherit the first-install permission."""
+ from huggingface_hub import constants
+
+ monkeypatch.delenv("SENTENCE_TRANSFORMERS_HOME", raising=False)
+ monkeypatch.setattr(constants, "HF_HUB_CACHE", str(tmp_path))
+ repository = "sentence-transformers/all-MiniLM-L6-v2"
+ cache = tmp_path / ("models--" + repository.replace("/", "--"))
+ if cache_state != "absent":
+ cache.mkdir()
+ if cache_state == "unresolved":
+ (cache / "snapshots").mkdir()
+ with patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings"
+ ) as constructor:
+ settings = {
+ "policy.egress_scope": "public_only",
+ "search.tool": "arxiv",
+ }
+ if cache_state == "unresolved":
+ with pytest.raises(PolicyDeniedError) as error:
+ Provider.create_embeddings(
+ model="all-MiniLM-L6-v2", settings_snapshot=settings
+ )
+ assert (
+ error.value.decision.reason
+ == "embeddings_cache_revision_unknown"
+ )
+ constructor.assert_not_called()
+ return
+ Provider.create_embeddings(
+ model="all-MiniLM-L6-v2", settings_snapshot=settings
+ )
+ constructor.assert_called_once()
+ kwargs = constructor.call_args.kwargs["model_kwargs"]
+ assert "revision" not in kwargs
+ assert "local_files_only" not in kwargs
+ assert kwargs["model_kwargs"]["use_safetensors"] is True
+
+
[email protected]("download_allowed", [False, True])
+ "custom_state", ["complete", "partial", "unresolved", "absent"]
+)
+def test_custom_cache_controls_revision_admission_and_loading(
+ download_allowed, custom_state, tmp_path, monkeypatch
+):
+ """A default-cache revision must never replace the active custom revision."""
+ from huggingface_hub import constants
+
+ model = "all-MiniLM-L6-v2"
+ default_root = tmp_path / "default"
+ custom_root = tmp_path / "custom"
+ _cached_snapshot(default_root, monkeypatch, model)
+ custom_snapshot, _ = _cached_snapshot(custom_root, monkeypatch, model)
+ custom_revision = "b" * 40
+ renamed = custom_snapshot.with_name(custom_revision)
+ custom_snapshot.rename(renamed)
+ reference = renamed.parent.parent / "refs/main"
+ reference.write_text(custom_revision)
+ if custom_state in ("partial", "unresolved"):
+ (renamed / "config.json").unlink()
+ (renamed / "modules.json").unlink()
+ if custom_state == "unresolved":
+ reference.unlink()
+ if custom_state == "absent":
+ custom_root = tmp_path / "absent"
+ monkeypatch.setattr(constants, "HF_HUB_CACHE", str(default_root))
+ monkeypatch.setenv("SENTENCE_TRANSFORMERS_HOME", str(custom_root))
+ settings = {
+ "policy.egress_scope": "public_only"
+ if download_allowed
+ else "private_only",
+ "search.tool": "arxiv",
+ }
+ with patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings"
+ ) as constructor:
+ if custom_state != "complete" and (
+ not download_allowed or custom_state == "unresolved"
+ ):
+ with pytest.raises(PolicyDeniedError) as error:
+ Provider.create_embeddings(
+ model=model, settings_snapshot=settings
+ )
+ assert error.value.decision.reason == (
+ "embeddings_cache_revision_unknown"
+ if download_allowed
+ else "embeddings_model_not_cached"
+ )
+ constructor.assert_not_called()
+ return
+ Provider.create_embeddings(model=model, settings_snapshot=settings)
+ constructor.assert_called_once()
+ assert constructor.call_args.kwargs["cache_folder"] == str(custom_root)
+ kwargs = constructor.call_args.kwargs["model_kwargs"]
+ if custom_state == "absent":
+ assert "revision" not in kwargs
+ else:
+ assert kwargs["revision"] == custom_revision
+ assert kwargs.get("local_files_only", False) is (custom_state == "complete")
+ assert kwargs["token"] is False
+ assert kwargs["trust_remote_code"] is False
+
+
+def test_custom_cache_missing_weights_repair_keeps_directory_and_revision(
+ tmp_path, monkeypatch
+):
+ """An offline miss may repair only the same custom-cache snapshot."""
+ from huggingface_hub import constants
+
+ root = tmp_path / "custom"
+ _, revision = _cached_snapshot(root, monkeypatch, "all-MiniLM-L6-v2")
+ monkeypatch.setenv("SENTENCE_TRANSFORMERS_HOME", str(root))
+ monkeypatch.setattr(constants, "HF_HUB_CACHE", str(tmp_path / "unused"))
+ with patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings",
+ side_effect=[OSError("missing weights"), object()],
+ ) as constructor:
+ Provider.create_embeddings(
+ model="all-MiniLM-L6-v2",
+ settings_snapshot={
+ "policy.egress_scope": "public_only",
+ "search.tool": "arxiv",
+ },
+ )
+ assert constructor.call_count == 2
+ first, second = [call.kwargs for call in constructor.call_args_list]
+ assert first["cache_folder"] == second["cache_folder"] == str(root)
+ assert (
+ first["model_kwargs"]["revision"]
+ == second["model_kwargs"]["revision"]
+ == revision
+ )
+ assert first["model_kwargs"]["local_files_only"] is True
+ assert "local_files_only" not in second["model_kwargs"]
diff --git a/tests/embeddings/test_sentence_transformer_model_catalog.py b/tests/embeddings/test_sentence_transformer_model_catalog.py
new file mode 100644
index 0000000000..74cea3946e
--- /dev/null
+++ b/tests/embeddings/test_sentence_transformer_model_catalog.py
@@ -0,0 +1,792 @@
+"""Tests for curated Sentence Transformer model resolution."""
+
+import errno
+from unittest.mock import ANY, MagicMock, call, patch
+
+import pytest
+
+from local_deep_research.embeddings.sentence_transformer_models import (
+ DEFAULT_SENTENCE_TRANSFORMER_MODEL,
+ SENTENCE_TRANSFORMER_MODELS,
+ get_sentence_transformer_model_spec,
+)
+
+
+def _isolate_hub_cache(tmp_path, monkeypatch):
+ """Point the loader's cache root at ``tmp_path`` for this test.
+
+ ``_cached_model_revision`` and ``_has_model_cache_state`` read the cache
+ directory from disk directly (``models--<repo>/refs/main``, and the
+ repository directory's contents), which ``try_to_load_from_cache`` patches
+ cannot intercept. Without this the tests below read the developer's or
+ runner's real ``~/.cache/huggingface/hub``: a warm cache for the same
+ legacy model contributes a second, different revision, the resolver
+ refuses the ambiguity, and the test fails for an environmental reason.
+ Mirrors ``tests/embeddings/test_sentence_transformer_cache_metadata.py``::
+
+ monkeypatch.delenv("SENTENCE_TRANSFORMERS_HOME", raising=False)
+ monkeypatch.setattr(constants, "HF_HUB_CACHE", str(tmp_path))
+ """
+ from huggingface_hub import constants
+
+ monkeypatch.delenv("HF_HUB_CACHE", raising=False)
+ monkeypatch.delenv("SENTENCE_TRANSFORMERS_HOME", raising=False)
+ monkeypatch.setattr(constants, "HF_HUB_CACHE", str(tmp_path))
+
+
+def _admission_files(spec):
+ """Every file the cache probe requires: all required files plus the
+ first file of each any-of group (the tokenizer vocabulary)."""
+ return (
+ *spec.required_cache_files,
+ *(group[0] for group in spec.required_cache_file_alternatives),
+ )
+
+
+def test_catalog_keeps_legacy_keys_and_pins_default():
+ assert DEFAULT_SENTENCE_TRANSFORMER_MODEL == (
+ "Alibaba-NLP/gte-modernbert-base"
+ )
+ assert {
+ "all-MiniLM-L6-v2",
+ "all-mpnet-base-v2",
+ "multi-qa-MiniLM-L6-cos-v1",
+ "paraphrase-multilingual-MiniLM-L12-v2",
+ }.issubset(SENTENCE_TRANSFORMER_MODELS)
+
+ default_spec = SENTENCE_TRANSFORMER_MODELS[
+ DEFAULT_SENTENCE_TRANSFORMER_MODEL
+ ]
+ assert default_spec.revision == "e7f32e3c00f91d699e8c43b53106206bcc72bb22"
+ assert default_spec.dimensions == 768
+
+
+def test_catalog_resolves_legacy_key_and_full_repository_alias():
+ by_key = get_sentence_transformer_model_spec("all-MiniLM-L6-v2")
+ by_repository = get_sentence_transformer_model_spec(
+ "sentence-transformers/all-MiniLM-L6-v2"
+ )
+
+ assert by_key is by_repository
+ assert by_key is not None
+ assert by_key.revision is None
+ assert all(
+ spec.revision is None
+ for key, spec in SENTENCE_TRANSFORMER_MODELS.items()
+ if key != DEFAULT_SENTENCE_TRANSFORMER_MODEL
+ )
+
+
+def test_public_curated_legacy_model_can_download_without_repinning():
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider,
+ )
+
+ stub = object()
+ with (
+ patch.object(
+ SentenceTransformersProvider,
+ "_cached_model_revision",
+ return_value=None,
+ ),
+ patch.object(
+ SentenceTransformersProvider,
+ "_is_model_cached_locally",
+ return_value=False,
+ ),
+ patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings",
+ return_value=stub,
+ ) as embedding_cls,
+ ):
+ result = SentenceTransformersProvider.create_embeddings(
+ model="all-MiniLM-L6-v2",
+ settings_snapshot={
+ "policy.egress_scope": "public_only",
+ "search.tool": "arxiv",
+ },
+ )
+
+ assert result is stub
+ kwargs = embedding_cls.call_args.kwargs
+ assert kwargs["model_name"] == "all-MiniLM-L6-v2"
+ assert kwargs["model_kwargs"] == {
+ "device": "cpu",
+ "trust_remote_code": False,
+ "token": False,
+ "model_kwargs": {"use_safetensors": True},
+ }
+
+
+def test_public_scope_rejects_non_curated_hugging_face_model():
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider,
+ )
+
+ from local_deep_research.security.egress.policy import (
+ PolicyDeniedError,
+ )
+
+ cache_check = MagicMock(return_value=False)
+ with (
+ patch.object(
+ SentenceTransformersProvider,
+ "_is_model_cached_locally",
+ cache_check,
+ ),
+ patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings"
+ ) as embedding_cls,
+ ):
+ with pytest.raises(PolicyDeniedError) as excinfo:
+ SentenceTransformersProvider.create_embeddings(
+ model="owner/custom",
+ settings_snapshot={
+ "policy.egress_scope": "public_only",
+ "search.tool": "arxiv",
+ },
+ )
+
+ assert excinfo.value.decision.reason == "embeddings_model_not_curated"
+ # Non-curated model that is NOT cached should still be rejected.
+ # The cache is now checked for legacy compatibility before rejection.
+ cache_check.assert_called_once()
+ embedding_cls.assert_not_called()
+
+
+def test_legacy_cached_non_curated_model_loads_locally():
+ """A non-catalog model already in the HF cache loads in local-only mode.
+
+ This preserves access to existing collections indexed with models that
+ predate the catalog without permitting new downloads of unvetted artifacts.
+ """
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider,
+ )
+
+ cache_check = MagicMock(return_value=True)
+ with (
+ patch.object(
+ SentenceTransformersProvider,
+ "_is_model_cached_locally",
+ cache_check,
+ ),
+ patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings"
+ ) as embedding_cls,
+ ):
+ SentenceTransformersProvider.create_embeddings(
+ model="owner/custom",
+ settings_snapshot={
+ "policy.egress_scope": "public_only",
+ "search.tool": "arxiv",
+ },
+ )
+
+ # The model should load in local-only mode with the full
+ # security-hardening kwargs: use_safetensors=True is the only
+ # pickle-refusal guard for a grandfathered cache entry.
+ embedding_cls.assert_called_once()
+ call_kwargs = embedding_cls.call_args
+ assert call_kwargs.kwargs["model_name"] == "owner/custom"
+ assert call_kwargs.kwargs["model_kwargs"] == {
+ "device": "cpu",
+ "trust_remote_code": False,
+ "token": False,
+ "model_kwargs": {"use_safetensors": True},
+ "local_files_only": True,
+ }
+
+
+def test_local_only_uses_exact_pinned_cache_offline():
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider,
+ )
+
+ default_spec = SENTENCE_TRANSFORMER_MODELS[
+ DEFAULT_SENTENCE_TRANSFORMER_MODEL
+ ]
+ cache_check = MagicMock(return_value=True)
+ with (
+ patch.object(
+ SentenceTransformersProvider,
+ "_is_model_cached_locally",
+ cache_check,
+ ),
+ patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings",
+ return_value=object(),
+ ) as embedding_cls,
+ ):
+ SentenceTransformersProvider.create_embeddings(
+ model=DEFAULT_SENTENCE_TRANSFORMER_MODEL,
+ settings_snapshot={},
+ )
+
+ cache_check.assert_called_once_with(
+ default_spec.repository, revision=default_spec.revision, cache_dir=ANY
+ )
+ kwargs = embedding_cls.call_args.kwargs
+ assert kwargs["model_name"] == default_spec.repository
+ assert kwargs["model_kwargs"] == {
+ "device": "cpu",
+ "revision": default_spec.revision,
+ "local_files_only": True,
+ "trust_remote_code": False,
+ "token": False,
+ "model_kwargs": {"use_safetensors": True},
+ }
+
+
+def test_snapshotless_legacy_cache_is_reused_offline():
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider,
+ )
+
+ cache_check = MagicMock(return_value=True)
+ with (
+ patch.object(
+ SentenceTransformersProvider,
+ "_cached_model_revision",
+ return_value=None,
+ ),
+ patch.object(
+ SentenceTransformersProvider,
+ "_is_model_cached_locally",
+ cache_check,
+ ),
+ patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings",
+ return_value=object(),
+ ) as embedding_cls,
+ ):
+ SentenceTransformersProvider.create_embeddings(
+ model="all-MiniLM-L6-v2",
+ )
+
+ cache_check.assert_called_once_with("all-MiniLM-L6-v2", cache_dir=ANY)
+ kwargs = embedding_cls.call_args.kwargs
+ assert kwargs["model_name"] == "all-MiniLM-L6-v2"
+ assert kwargs["model_kwargs"] == {
+ "device": "cpu",
+ "local_files_only": True,
+ "trust_remote_code": False,
+ "token": False,
+ "model_kwargs": {"use_safetensors": True},
+ }
+
+
+def test_cache_probe_forwards_exact_revision():
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider,
+ )
+
+ with patch(
+ "huggingface_hub.try_to_load_from_cache",
+ return_value="/cache/config.json",
+ ) as cache_lookup:
+ assert SentenceTransformersProvider._is_model_cached_locally(
+ "Alibaba-NLP/gte-modernbert-base", revision="immutable-revision"
+ )
+
+ assert cache_lookup.call_args_list == [
+ call(
+ repo_id="Alibaba-NLP/gte-modernbert-base",
+ filename=filename,
+ revision="immutable-revision",
+ cache_dir=ANY,
+ )
+ for filename in (
+ "config.json",
+ "modules.json",
+ "1_Pooling/config.json",
+ "tokenizer_config.json",
+ "tokenizer.json",
+ )
+ ]
+
+
+def test_cache_probe_recognizes_config_only_legacy_snapshot():
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider,
+ )
+
+ with patch(
+ "huggingface_hub.try_to_load_from_cache",
+ side_effect=["/cache/config.json", None],
+ ):
+ # Presence is only a hint: the offline constructor verifies artifacts.
+ assert SentenceTransformersProvider._is_model_cached_locally(
+ "owner/incomplete"
+ )
+
+
+ ("settings_snapshot", "case"),
+ [
+ (None, "snapshotless"),
+ (
+ {"policy.egress_scope": "strict", "search.tool": "arxiv"},
+ "strict",
+ ),
+ (
+ {"policy.egress_scope": "private_only", "search.tool": "library"},
+ "private",
+ ),
+ (
+ {"policy.egress_scope": "adaptive", "search.tool": "auto"},
+ "adaptive-unclassified",
+ ),
+ (
+ {
+ "policy.egress_scope": "public_only",
+ "search.tool": "arxiv",
+ "embeddings.require_local": True,
+ },
+ "public-require-local",
+ ),
+ ],
+ ids=lambda value: value if isinstance(value, str) else None,
+)
+def test_cache_miss_download_requires_public_capability(
+ settings_snapshot, case
+):
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider,
+ )
+ from local_deep_research.security.egress.policy import PolicyDeniedError
+
+ with (
+ patch.object(
+ SentenceTransformersProvider,
+ "_is_model_cached_locally",
+ return_value=False,
+ ),
+ patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings"
+ ) as embedding_cls,
+ ):
+ with pytest.raises(PolicyDeniedError) as excinfo:
+ SentenceTransformersProvider.create_embeddings(
+ model="all-MiniLM-L6-v2",
+ settings_snapshot=settings_snapshot,
+ )
+
+ assert case
+ assert excinfo.value.decision.reason == "embeddings_model_not_cached"
+ embedding_cls.assert_not_called()
+
+
+ "settings_snapshot",
+ [
+ {"policy.egress_scope": "adaptive", "search.tool": "arxiv"},
+ {"policy.egress_scope": "unprotected", "search.tool": "auto"},
+ ],
+ ids=["adaptive-public", "unprotected"],
+)
+def test_explicit_public_capability_allows_curated_cache_miss(
+ settings_snapshot,
+ monkeypatch,
+):
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider,
+ )
+
+ if settings_snapshot["policy.egress_scope"] == "unprotected":
+ monkeypatch.setenv("LDR_POLICY_ALLOW_UNPROTECTED_EGRESS", "true")
+
+ with (
+ patch.object(
+ SentenceTransformersProvider,
+ "_cached_model_revision",
+ return_value=None,
+ ),
+ patch.object(
+ SentenceTransformersProvider,
+ "_is_model_cached_locally",
+ return_value=False,
+ ),
+ patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings",
+ return_value=object(),
+ ) as embedding_cls,
+ ):
+ SentenceTransformersProvider.create_embeddings(
+ model="all-MiniLM-L6-v2",
+ settings_snapshot=settings_snapshot,
+ )
+
+ kwargs = embedding_cls.call_args.kwargs
+ assert kwargs["model_name"] == "all-MiniLM-L6-v2"
+ assert "local_files_only" not in kwargs["model_kwargs"]
+ assert kwargs["model_kwargs"]["token"] is False
+ assert kwargs["model_kwargs"]["trust_remote_code"] is False
+ assert kwargs["model_kwargs"]["model_kwargs"] == {"use_safetensors": True}
+
+
+def test_public_gte_cache_miss_keeps_immutable_revision():
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider,
+ )
+
+ spec = SENTENCE_TRANSFORMER_MODELS[DEFAULT_SENTENCE_TRANSFORMER_MODEL]
+ with (
+ patch.object(
+ SentenceTransformersProvider,
+ "_is_model_cached_locally",
+ return_value=False,
+ ),
+ patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings",
+ return_value=object(),
+ ) as embedding_cls,
+ ):
+ SentenceTransformersProvider.create_embeddings(
+ model=DEFAULT_SENTENCE_TRANSFORMER_MODEL,
+ settings_snapshot={
+ "policy.egress_scope": "public_only",
+ "search.tool": "arxiv",
+ },
+ )
+
+ kwargs = embedding_cls.call_args.kwargs
+ assert kwargs["model_name"] == spec.repository
+ assert kwargs["model_kwargs"]["revision"] == spec.revision
+ assert "local_files_only" not in kwargs["model_kwargs"]
+
+
+def test_existing_filesystem_path_is_not_a_trusted_model(tmp_path):
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider,
+ )
+
+ with patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings"
+ ) as embedding_cls:
+ with pytest.raises(ValueError, match="models directory"):
+ SentenceTransformersProvider.create_embeddings(
+ model=str(tmp_path),
+ settings_snapshot={
+ "policy.egress_scope": "public_only",
+ "search.tool": "arxiv",
+ },
+ )
+
+ embedding_cls.assert_not_called()
+
+
+ "model",
+ [
+ DEFAULT_SENTENCE_TRANSFORMER_MODEL,
+ "all-MiniLM-L6-v2",
+ "sentence-transformers/all-MiniLM-L6-v2",
+ "owner/cached-custom",
+ ],
+)
+def test_hub_id_cannot_select_a_matching_working_directory(
+ model, tmp_path, monkeypatch
+):
+ """Removing the shadow check hands this directory to the upstream loader."""
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider as Provider,
+ )
+
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / model).mkdir(parents=True)
+ with (
+ patch.object(Provider, "_confined_local_model_path", return_value=None),
+ patch.object(Provider, "_is_model_cached_locally", return_value=True),
+ patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings"
+ ) as constructor,
+ ):
+ with pytest.raises(ValueError, match="conflicts with a local path"):
+ Provider.create_embeddings(model=model, settings_snapshot={})
+ constructor.assert_not_called()
+
+
+ "model", [DEFAULT_SENTENCE_TRANSFORMER_MODEL, "all-MiniLM-L6-v2"]
+)
+def test_partial_cache_repair_stays_on_the_same_revision(
+ model, tmp_path, monkeypatch
+):
+ """Offline failure may repair missing files, but must never advance a legacy ref."""
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider as Provider,
+ )
+
+ _isolate_hub_cache(tmp_path, monkeypatch)
+ spec = get_sentence_transformer_model_spec(model)
+ revision = spec.revision or "a" * 40
+ snapshot = tmp_path / "snapshots" / revision
+ snapshot.mkdir(parents=True)
+ for filename in _admission_files(spec):
+ metadata_file = snapshot / filename
+ metadata_file.parent.mkdir(parents=True, exist_ok=True)
+ metadata_file.write_text("{}")
+ loaded = object()
+ with (
+ patch(
+ "huggingface_hub.try_to_load_from_cache",
+ side_effect=lambda repo_id, filename, **kw: (
+ str(snapshot / filename)
+ if (snapshot / filename).is_file()
+ else None
+ ),
+ ),
+ patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings",
+ 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
+ )
+ 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
+ assert "local_files_only" not in second["model_kwargs"]
+ for kwargs in (first, second):
+ assert kwargs["model_kwargs"]["revision"] == revision
+ assert kwargs["model_kwargs"]["token"] is False
+ assert kwargs["model_kwargs"]["trust_remote_code"] is False
+ assert kwargs["model_kwargs"]["model_kwargs"]["use_safetensors"] is True
+
+
+ "error",
+ [
+ PermissionError(errno.EACCES, "Permission denied", "modules.json"),
+ OSError(errno.EACCES, "Permission denied"),
+ OSError(errno.EPERM, "Operation not permitted"),
+ OSError(errno.ENOSPC, "No space left on device"),
+ OSError(errno.EROFS, "Read-only file system"),
+ ],
+ ids=["PermissionError", "EACCES", "EPERM", "ENOSPC", "EROFS"],
+)
+def test_environment_fault_on_offline_load_is_not_repaired(
+ error, tmp_path, monkeypatch
+):
+ """An unreadable or unwritable cache fails the same way on a repair.
+
+ The repair runs at the same commit revision and reuses the snapshot's
+ existing files, so it can only reproduce the fault with network access
+ enabled. The original error must surface from a single construction.
+ """
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider as Provider,
+ )
+
+ _isolate_hub_cache(tmp_path, monkeypatch)
+ spec = get_sentence_transformer_model_spec(
+ DEFAULT_SENTENCE_TRANSFORMER_MODEL
+ )
+ snapshot = tmp_path / "snapshots" / spec.revision
+ for filename in _admission_files(spec):
+ path = snapshot / filename
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("{}")
+ with (
+ patch(
+ "huggingface_hub.try_to_load_from_cache",
+ side_effect=lambda repo_id, filename, **kw: (
+ str(snapshot / filename)
+ if (snapshot / filename).is_file()
+ else None
+ ),
+ ),
+ patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings",
+ side_effect=[error, object()],
+ ) as constructor,
+ ):
+ with pytest.raises(OSError) as raised:
+ Provider.create_embeddings(
+ model=DEFAULT_SENTENCE_TRANSFORMER_MODEL,
+ settings_snapshot={
+ "policy.egress_scope": "public_only",
+ "search.tool": "arxiv",
+ },
+ )
+ assert raised.value is error
+ constructor.assert_called_once()
+ assert (
+ constructor.call_args.kwargs["model_kwargs"]["local_files_only"] is True
+ )
+
+
+ "snapshot",
+ [
+ None,
+ {},
+ {"policy.egress_scope": "strict", "search.tool": "arxiv"},
+ {"policy.egress_scope": "private_only", "search.tool": "library"},
+ {
+ "policy.egress_scope": "public_only",
+ "search.tool": "arxiv",
+ "embeddings.require_local": True,
+ },
+ ],
+)
+def test_partial_cache_never_repairs_under_restrictive_policy(snapshot):
+ """Removing the policy check turns the offline failure into a network retry."""
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider as Provider,
+ )
+
+ with (
+ patch.object(Provider, "_is_model_cached_locally", return_value=True),
+ patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings",
+ side_effect=OSError("missing weights"),
+ ) as constructor,
+ ):
+ with pytest.raises(OSError, match="missing weights"):
+ Provider.create_embeddings(
+ model=DEFAULT_SENTENCE_TRANSFORMER_MODEL,
+ settings_snapshot=snapshot,
+ )
+ constructor.assert_called_once()
+ assert (
+ constructor.call_args.kwargs["model_kwargs"]["local_files_only"] is True
+ )
+
+
[email protected]("model", ["all-MiniLM-L6-v2", "owner/cached-custom"])
+def test_unknown_legacy_revision_or_non_catalog_cache_never_repairs(model):
+ """No repair at floating main, nor any non-catalog download, is authorized."""
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider as Provider,
+ )
+
+ with (
+ patch.object(Provider, "_confined_local_model_path", return_value=None),
+ patch.object(Provider, "_is_model_cached_locally", return_value=True),
+ patch.object(Provider, "_cached_model_revision", return_value=None),
+ patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings",
+ side_effect=OSError("missing weights"),
+ ) as constructor,
+ ):
+ with pytest.raises(OSError, match="missing weights"):
+ Provider.create_embeddings(
+ model=model,
+ settings_snapshot={
+ "policy.egress_scope": "public_only",
+ "search.tool": "arxiv",
+ },
+ )
+ constructor.assert_called_once()
+
+
+ ("paths", "expected"),
+ [
+ (["/cache/snapshots/" + "a" * 40 + "/config.json", None], "a" * 40),
+ ([None, "/cache/snapshots/" + "b" * 40 + "/modules.json"], "b" * 40),
+ (
+ [
+ "/cache/snapshots/" + "a" * 40 + "/config.json",
+ "/cache/snapshots/" + "b" * 40 + "/modules.json",
+ ],
+ None,
+ ),
+ (["/cache/blobs/" + "a" * 40, None], None),
+ (["/cache/snapshots/main/config.json", None], None),
+ ([None, None], None),
+ ],
+)
+def test_cached_revision_requires_one_immutable_snapshot(paths, expected):
+ """Reject missing/ambiguous/floating revisions before authorizing repair."""
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider as Provider,
+ )
+
+ with patch("huggingface_hub.try_to_load_from_cache", side_effect=paths):
+ assert Provider._cached_model_revision("owner/model") == expected
+
+
+ "model",
+ [
+ DEFAULT_SENTENCE_TRANSFORMER_MODEL,
+ "all-MiniLM-L6-v2",
+ "sentence-transformers/all-MiniLM-L6-v2",
+ ],
+)
+ "missing_file", ["modules.json", "1_Pooling/config.json"]
+)
[email protected]("scope", ["public_only", "private_only"])
+def test_incomplete_module_metadata_never_loads_curated_model_offline(
+ model, missing_file, scope, tmp_path, monkeypatch
+):
+ """Config-only admission loses pooling or fails before missing-weight repair.
+
+ Reverting the metadata requirement admits an offline constructor here:
+ absent modules can silently choose mean pooling, while absent pooling
+ config can raise TypeError. Public repair must keep the cached revision.
+ """
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider as Provider,
+ )
+ from local_deep_research.security.egress.policy import PolicyDeniedError
+
+ _isolate_hub_cache(tmp_path, monkeypatch)
+ spec = get_sentence_transformer_model_spec(model)
+ revision = spec.revision or "a" * 40
+ snapshot = tmp_path / "snapshots" / revision
+ for filename in _admission_files(spec):
+ if filename == missing_file:
+ continue
+ path = snapshot / filename
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("{}")
+
+ def cache_lookup(repo_id, filename, **kwargs):
+ assert repo_id == spec.repository
+ assert kwargs.get("revision", revision) == revision
+ path = snapshot / filename
+ return str(path) if path.is_file() else None
+
+ with (
+ patch(
+ "huggingface_hub.try_to_load_from_cache", side_effect=cache_lookup
+ ),
+ patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings"
+ ) as constructor,
+ ):
+ snapshot_settings = {
+ "policy.egress_scope": scope,
+ "search.tool": "arxiv",
+ }
+ if scope == "private_only":
+ with pytest.raises(PolicyDeniedError) as error:
+ Provider.create_embeddings(
+ model=model, settings_snapshot=snapshot_settings
+ )
+ assert error.value.decision.reason == "embeddings_model_not_cached"
+ constructor.assert_not_called()
+ else:
+ Provider.create_embeddings(
+ model=model, settings_snapshot=snapshot_settings
+ )
+ constructor.assert_called_once()
+ kwargs = constructor.call_args.kwargs["model_kwargs"]
+ assert "local_files_only" not in kwargs
+ assert kwargs["revision"] == revision
+ assert kwargs["trust_remote_code"] is False
+ assert kwargs["token"] is False
+ assert kwargs["model_kwargs"]["use_safetensors"] is True
diff --git a/tests/embeddings/test_sentence_transformers.py b/tests/embeddings/test_sentence_transformers.py
index 41ce6b9140..71202d3641 100644
--- a/tests/embeddings/test_sentence_transformers.py
+++ b/tests/embeddings/test_sentence_transformers.py
@@ -14,6 +14,12 @@ from unittest.mock import patch, MagicMock
import pytest
+PUBLIC_SETTINGS = {
+ "policy.egress_scope": "public_only",
+ "search.tool": "arxiv",
+}
+
+
class TestSentenceTransformersProviderMetadata:
"""Tests for SentenceTransformersProvider class metadata."""
@@ -60,7 +66,9 @@ class TestSentenceTransformersProviderMetadata:
SentenceTransformersProvider,
)
- assert SentenceTransformersProvider.default_model == "all-MiniLM-L6-v2"
+ assert SentenceTransformersProvider.default_model == (
+ "Alibaba-NLP/gte-modernbert-base"
+ )
class TestSentenceTransformersProviderAvailableModels:
@@ -142,18 +150,22 @@ class TestSentenceTransformersProviderCreateEmbeddings:
"langchain_community.embeddings.SentenceTransformerEmbeddings",
return_value=mock_embeddings,
) as mock_class:
- result = SentenceTransformersProvider.create_embeddings()
+ result = SentenceTransformersProvider.create_embeddings(
+ settings_snapshot=PUBLIC_SETTINGS
+ )
assert result is mock_embeddings
mock_class.assert_called_once()
call_kwargs = mock_class.call_args[1]
# Default model should be used
- assert call_kwargs["model_name"] == "all-MiniLM-L6-v2"
+ assert call_kwargs["model_name"] == (
+ "Alibaba-NLP/gte-modernbert-base"
+ )
# CPU is default device
assert call_kwargs["model_kwargs"]["device"] == "cpu"
- def test_create_embeddings_with_custom_model(self):
- """Test creating embeddings with custom model."""
+ def test_create_embeddings_with_curated_model(self):
+ """Test creating embeddings with another curated model."""
from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
SentenceTransformersProvider,
)
@@ -165,7 +177,8 @@ class TestSentenceTransformersProviderCreateEmbeddings:
return_value=mock_embeddings,
) as mock_class:
SentenceTransformersProvider.create_embeddings(
- model="all-mpnet-base-v2"
+ model="all-mpnet-base-v2",
+ settings_snapshot=PUBLIC_SETTINGS,
)
call_kwargs = mock_class.call_args[1]
@@ -181,13 +194,17 @@ class TestSentenceTransformersProviderCreateEmbeddings:
with patch(
"local_deep_research.embeddings.providers.implementations.sentence_transformers.get_setting_from_snapshot",
- return_value=None,
+ side_effect=lambda key, default=None, settings_snapshot=None: (
+ default
+ ),
):
with patch(
"langchain_community.embeddings.SentenceTransformerEmbeddings",
return_value=mock_embeddings,
) as mock_class:
- SentenceTransformersProvider.create_embeddings(device="cuda")
+ SentenceTransformersProvider.create_embeddings(
+ device="cuda", settings_snapshot=PUBLIC_SETTINGS
+ )
call_kwargs = mock_class.call_args[1]
assert call_kwargs["model_kwargs"]["device"] == "cuda"
@@ -213,7 +230,9 @@ class TestSentenceTransformersProviderCreateEmbeddings:
"langchain_community.embeddings.SentenceTransformerEmbeddings",
return_value=mock_embeddings,
) as mock_class:
- SentenceTransformersProvider.create_embeddings()
+ SentenceTransformersProvider.create_embeddings(
+ settings_snapshot=PUBLIC_SETTINGS
+ )
call_kwargs = mock_class.call_args[1]
assert call_kwargs["model_kwargs"]["device"] == "cpu"
@@ -229,13 +248,13 @@ class TestSentenceTransformersProviderCreateEmbeddings:
# => require_local stays off, so this model-reading test is not
# diverted into the require-local download guard.
settings = {
- "embeddings.sentence_transformers.model": "custom-model",
+ "embeddings.sentence_transformers.model": "all-mpnet-base-v2",
"search.tool": "searxng",
}
def mock_get_setting(key, default=None, settings_snapshot=None):
if key == "embeddings.sentence_transformers.model":
- return "custom-model"
+ return "all-mpnet-base-v2"
if key == "embeddings.sentence_transformers.device":
return "cpu"
return default
@@ -253,7 +272,7 @@ class TestSentenceTransformersProviderCreateEmbeddings:
)
call_kwargs = mock_class.call_args[1]
- assert call_kwargs["model_name"] == "custom-model"
+ assert call_kwargs["model_name"] == "all-mpnet-base-v2"
class TestSentenceTransformersProviderIsAvailable:
@@ -456,6 +475,11 @@ class TestSentenceTransformersProviderPathConfinement:
"""A model directory genuinely UNDER the app's models dir still loads:
it is classified as local (by absolute and by relative reference) and
admitted without an HF cache probe.
+
+ ``create_embeddings`` resolves the confined path itself and returns
+ before the Hub-cache helper runs, so the helper classifies a
+ filesystem-shaped name as a repo-id miss (and, crucially, still never
+ probes the Hub cache for it).
"""
provider = self._provider()
tmp_path = tmp_path.resolve()
@@ -478,7 +502,24 @@ class TestSentenceTransformersProviderPathConfinement:
== model_dir.resolve()
)
with patch("huggingface_hub.try_to_load_from_cache") as mock_cache:
- assert provider._is_model_cached_locally(str(model_dir)) is True
+ assert (
+ provider._is_model_cached_locally(str(model_dir)) is False
+ )
+ mock_cache.assert_not_called()
+ # ...and the end-to-end load takes the confined-path branch.
+ with (
+ patch("huggingface_hub.try_to_load_from_cache") as mock_cache,
+ patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings",
+ return_value=MagicMock(),
+ ) as mock_st,
+ ):
+ provider.create_embeddings(
+ model="custom-st-model", device="cpu"
+ )
+ assert mock_st.call_args.kwargs["model_name"] == str(
+ model_dir.resolve()
+ )
mock_cache.assert_not_called()
def test_create_embeddings_loads_confined_local_model_by_abs_path(
@@ -508,6 +549,150 @@ class TestSentenceTransformersProviderPathConfinement:
assert mock_st.call_args.kwargs["model_name"] == str(
model_dir.resolve()
)
+ # Pin the full security-hardening kwargs for this load
+ # site: a planted local model dir must never opt into
+ # remote code, authenticated Hub access, or pickle weights.
+ assert mock_st.call_args.kwargs["model_kwargs"] == {
+ "device": "cpu",
+ "trust_remote_code": False,
+ "token": False,
+ "model_kwargs": {"use_safetensors": True},
+ "local_files_only": True,
+ }
+
+ # ---- (b'') a confined dir outranks a curated model of the same name -----
+
+ @pytest.mark.parametrize(
+ "settings_snapshot",
+ [
+ {"policy.egress_scope": "public_only", "search.tool": "arxiv"},
+ {"policy.egress_scope": "strict", "search.tool": "arxiv"},
+ {"policy.egress_scope": "private_only", "search.tool": "library"},
+ ],
+ ids=["public_only", "strict", "private_only"],
+ )
+ def test_confined_local_dir_named_like_a_catalog_key_wins_under_every_scope(
+ self, tmp_path, settings_snapshot, loguru_caplog
+ ):
+ """An operator-placed model directory whose name matches a catalog key
+ is still the model that loads, in every egress scope.
+
+ The confined models directory is app-owned state: an operator who
+ copies a model there is naming THAT artifact, and a collection indexed
+ from it must keep embedding with the same bytes. Resolving the name to
+ the curated Hub repository instead would silently swap the artifact
+ under a public scope (different vectors for the same collection) and
+ refuse the load outright under STRICT / PRIVATE_ONLY — where the local
+ directory is precisely the offline-usable form. The substitution is
+ also never silent: it is announced on the policy audit channel, naming
+ the directory and the curated model it displaces.
+ """
+ provider = self._provider()
+ tmp_path = tmp_path.resolve()
+ models_dir = tmp_path / "models"
+ model_dir = models_dir / "all-MiniLM-L6-v2"
+ model_dir.mkdir(parents=True)
+
+ with (
+ patch(
+ "local_deep_research.config.paths.get_models_directory",
+ return_value=models_dir,
+ ),
+ patch("huggingface_hub.try_to_load_from_cache") as mock_cache,
+ patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings",
+ return_value=MagicMock(),
+ ) as mock_st,
+ loguru_caplog.at_level("WARNING"),
+ ):
+ # The audit flag is a bound record extra, not rendered text, so
+ # it needs a sink that sees the loguru record itself.
+ from loguru import logger as loguru_logger
+
+ records = []
+ sink_id = loguru_logger.add(
+ lambda message: records.append(message.record),
+ level="WARNING",
+ )
+ try:
+ provider.create_embeddings(
+ model="all-MiniLM-L6-v2",
+ settings_snapshot=settings_snapshot,
+ device="cpu",
+ )
+ finally:
+ loguru_logger.remove(sink_id)
+
+ # The local directory, loaded offline from its safe absolute path.
+ assert mock_st.call_args.kwargs["model_name"] == str(
+ model_dir.resolve()
+ )
+ model_kwargs = mock_st.call_args.kwargs["model_kwargs"]
+ assert model_kwargs["local_files_only"] is True
+ assert model_kwargs["token"] is False
+ assert model_kwargs["trust_remote_code"] is False
+ assert model_kwargs["model_kwargs"]["use_safetensors"] is True
+ # No Hub artifact is involved: no revision pin, and the Hub cache is
+ # never consulted for a model that was resolved on disk.
+ assert "revision" not in model_kwargs
+ mock_cache.assert_not_called()
+ # The shadowing is audited, naming both the directory and the model
+ # it displaces.
+ assert str(model_dir.resolve()) in loguru_caplog.text
+ assert "sentence-transformers/all-MiniLM-L6-v2" in loguru_caplog.text
+ # ...on the policy audit channel, not as an ordinary warning.
+ shadow_records = [
+ record
+ for record in records
+ if str(model_dir.resolve()) in record["message"]
+ ]
+ assert len(shadow_records) == 1
+ assert shadow_records[0]["extra"].get("policy_audit") is True
+
+ def test_hub_id_cannot_select_a_matching_working_directory_unpatched(
+ self, tmp_path, monkeypatch
+ ):
+ """Precedence check with nothing patched out: a directory in the
+ PROCESS WORKING DIRECTORY named like a Hub id is still refused.
+
+ The confined-models-dir precedence above is about the application's
+ OWN models directory. A same-named directory that merely happens to
+ sit in the working directory is a different concern — upstream's
+ ``os.path.exists`` branch would load it — and stays refused. The
+ catalog-file version of this test patches ``_confined_local_model_path``
+ and ``_is_model_cached_locally`` out; here both run for real.
+ """
+ provider = self._provider()
+ tmp_path = tmp_path.resolve()
+ models_dir = tmp_path / "models"
+ models_dir.mkdir() # empty: nothing is confined
+ workdir = tmp_path / "cwd"
+ (workdir / "sentence-transformers" / "all-MiniLM-L6-v2").mkdir(
+ parents=True
+ )
+ (workdir / "all-MiniLM-L6-v2").mkdir()
+ monkeypatch.chdir(workdir)
+
+ with patch(
+ "local_deep_research.config.paths.get_models_directory",
+ return_value=models_dir,
+ ):
+ for model in (
+ "all-MiniLM-L6-v2",
+ "sentence-transformers/all-MiniLM-L6-v2",
+ ):
+ with patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings"
+ ) as mock_st:
+ with pytest.raises(
+ ValueError, match="conflicts with a local path"
+ ):
+ provider.create_embeddings(
+ model=model,
+ settings_snapshot=PUBLIC_SETTINGS,
+ device="cpu",
+ )
+ mock_st.assert_not_called()
# ---- (b') a symlinked ancestor must not refuse a legit model ------------
@@ -631,10 +816,13 @@ class TestSentenceTransformersProviderPathConfinement:
# ---- (c) a normal HF id still works -------------------------------------
- def test_hf_id_treated_as_repo_id(self, tmp_path):
+ @pytest.mark.parametrize(
+ "model", ["all-MiniLM-L6-v2", "sentence-transformers/all-MiniLM-L6-v2"]
+ )
+ def test_hf_id_treated_as_repo_id(self, tmp_path, model):
"""A normal HuggingFace id — bare, or ``org/name`` containing ``/`` but
not a filesystem path — is NOT classified as a local path and is passed
- through to the loader unchanged as a repo id.
+ through to the loader unchanged as a repo id when cached.
"""
provider = self._provider()
tmp_path = tmp_path.resolve()
@@ -656,9 +844,19 @@ class TestSentenceTransformersProviderPathConfinement:
)
assert provider._confined_local_model_path(namespaced) is None
- with patch(
- "langchain_community.embeddings.SentenceTransformerEmbeddings",
- return_value=MagicMock(),
- ) as mock_st:
- provider.create_embeddings(model=namespaced, device="cpu")
- assert mock_st.call_args.kwargs["model_name"] == namespaced
+ with (
+ patch(
+ "huggingface_hub.try_to_load_from_cache",
+ return_value="/cache/config.json",
+ ),
+ patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings",
+ return_value=MagicMock(),
+ ) as mock_st,
+ ):
+ provider.create_embeddings(model=model, device="cpu")
+ assert mock_st.call_args.kwargs["model_name"] == model
+ assert (
+ mock_st.call_args.kwargs["model_kwargs"]["local_files_only"]
+ is True
+ )
diff --git a/tests/js/embedding-test-configuration-runtime.test.js b/tests/js/embedding-test-configuration-runtime.test.js
index 221b4edd8b..8f7f80a39c 100644
--- a/tests/js/embedding-test-configuration-runtime.test.js
+++ b/tests/js/embedding-test-configuration-runtime.test.js
@@ -29,7 +29,7 @@ afterEach(() => {
document.body.replaceChildren();
});
-it('POSTs the selected model with CSRF and renders the migrated success envelope', async () => {
+it('POSTs only the selected model with CSRF for a server-owned text probe', async () => {
document.body.innerHTML = `
<select id="embedding-provider">
<option value="sentence_transformers" selected>Sentence Transformers</option>
@@ -70,7 +70,6 @@ it('POSTs the selected model with CSRF and renders the migrated success envelope
body: JSON.stringify({
provider: 'sentence_transformers',
model: 'all-MiniLM-L6-v2',
- test_text: 'This is a test sentence to verify the embedding model is working correctly.',
}),
},
);
diff --git a/tests/research_library/routes/test_rag_routes_coverage_main_port.py b/tests/research_library/routes/test_rag_routes_coverage_main_port.py
index d00d797946..b8fba34717 100644
--- a/tests/research_library/routes/test_rag_routes_coverage_main_port.py
+++ b/tests/research_library/routes/test_rag_routes_coverage_main_port.py
@@ -603,6 +603,99 @@ class TestTestEmbedding:
assert data["success"] is True
assert data["dimension"] == 3
+ def test_uses_server_owned_probe_text(self):
+ """Reverting to request test_text sends caller content to the provider."""
+ from local_deep_research.web.routers.rag import test_embedding
+
+ inner_func = Mock(return_value=[[0.1, 0.2]])
+ with (
+ _route_env(),
+ patch(
+ f"{_EMBEDDINGS}.get_embedding_function", return_value=inner_func
+ ),
+ patch(f"{MODULE}._EMBEDDING_TEST_SENTENCE", "server-owned"),
+ ):
+ data = asyncio.run(
+ test_embedding(
+ _json_request(
+ {
+ "provider": "sentence_transformers",
+ "model": "test-model",
+ "test_text": "private caller text",
+ }
+ ),
+ username="testuser",
+ )
+ )
+ assert data["success"] is True
+ inner_func.assert_called_once_with(["server-owned"])
+
+ @pytest.mark.parametrize(
+ ("reason", "expected"),
+ [
+ (
+ "embeddings_model_not_curated",
+ [
+ "vetted model list",
+ "Ollama",
+ "arbitrary Hugging Face downloads are disabled",
+ ],
+ ),
+ (
+ "embeddings_cache_revision_unknown",
+ # The remedy must name what the operator can actually do —
+ # re-download from scratch, or pin a confined local copy —
+ # not just "restore its trusted cache metadata".
+ [
+ "immutable model revision",
+ "delete that model's cache directory",
+ "Public only",
+ "models directory",
+ "existing index",
+ ],
+ ),
+ (
+ "embeddings_model_not_cached",
+ [
+ "Public only",
+ "Adaptive",
+ "no private collection selected",
+ "return to your preferred restrictive scope",
+ ],
+ ),
+ ],
+ )
+ def test_model_policy_reason_and_remedy(self, reason, expected):
+ """Reverting the route port loses the machine-readable reason/remedy."""
+ from local_deep_research.web.routers.rag import test_embedding
+ from local_deep_research.security.egress.policy import (
+ Decision,
+ PolicyDeniedError,
+ )
+
+ denial = PolicyDeniedError(Decision(False, reason), target="synthetic")
+ with (
+ _route_env(),
+ patch(f"{_EMBEDDINGS}.get_embedding_function", side_effect=denial),
+ ):
+ response = asyncio.run(
+ test_embedding(
+ _json_request(
+ {
+ "provider": "sentence_transformers",
+ "model": "synthetic",
+ }
+ ),
+ username="testuser",
+ )
+ )
+ assert response.status_code == 400
+ data = _body(response)
+ assert data["success"] is False
+ assert data["reason_code"] == reason
+ for text in expected:
+ assert text in data["error"]
+
# ---------------------------------------------------------------------------
# GET /library/api/rag/models
diff --git a/tests/research_library/services/test_rag_service_factory.py b/tests/research_library/services/test_rag_service_factory.py
index e67d025d9a..269efbce36 100644
--- a/tests/research_library/services/test_rag_service_factory.py
+++ b/tests/research_library/services/test_rag_service_factory.py
@@ -173,7 +173,7 @@ class TestGetRagServiceDefaults:
with patch(f"{FACTORY_MODULE}.get_settings_manager", return_value=mgr):
get_rag_service("alice")
kwargs = mock_rag_cls.call_args.kwargs
- assert kwargs["embedding_model"] == "all-MiniLM-L6-v2"
+ assert kwargs["embedding_model"] == "Alibaba-NLP/gte-modernbert-base"
assert kwargs["embedding_provider"] == "sentence_transformers"
assert kwargs["chunk_size"] == 1000
assert kwargs["chunk_overlap"] == 200
diff --git a/tests/security/test_egress_policy.py b/tests/security/test_egress_policy.py
index c82554339e..a4b88c57f3 100644
--- a/tests/security/test_egress_policy.py
+++ b/tests/security/test_egress_policy.py
@@ -2121,7 +2121,7 @@ def test_sbert_cache_check_probes_both_forms_for_bare_sbert_name():
are downloaded under the sentence-transformers org, so the loader
requests the namespaced repo_id and the HF hub cache is keyed on
that. The check probes BOTH the bare and the namespaced forms so
- it also covers names in the loader's ``basic_transformer_models``
+ it also covers names in the loader's ``ORIGINAL_TRANSFORMER_MODELS``
allowlist (which use the bare key) — but the namespaced form is
the one that hits for shipped SBERT defaults.
"""
@@ -2131,7 +2131,7 @@ def test_sbert_cache_check_probes_both_forms_for_bare_sbert_name():
probed_repo_ids = []
- def fake_try_to_load_from_cache(repo_id, filename):
+ def fake_try_to_load_from_cache(repo_id, filename, *, cache_dir=None):
probed_repo_ids.append(repo_id)
if repo_id == "sentence-transformers/all-MiniLM-L6-v2":
return "/fake/path/config.json"
@@ -2154,9 +2154,11 @@ def test_sbert_cache_check_probes_both_forms_for_bare_sbert_name():
def test_sbert_cache_check_probes_bare_form_for_basic_transformer_name():
- """Vanilla transformer models in SentenceTransformer's
- ``basic_transformer_models`` allowlist (bert-base-uncased, gpt2,
- t5-base, ...) are loaded from the BARE repo_id, not prefixed. The
+ """Vanilla transformer models in the loader's
+ ``sentence_transformers.util.misc.ORIGINAL_TRANSFORMER_MODELS`` list
+ (bert-base-uncased, gpt2, t5-base, ...) are loaded from the BARE
+ repo_id, never prefixed with the class's
+ ``default_huggingface_organization``. The
check must find them under the bare key — probed first — so a
correctly cached vanilla transformer is admitted under
require_local instead of false-negativing.
@@ -2167,7 +2169,7 @@ def test_sbert_cache_check_probes_bare_form_for_basic_transformer_name():
probed_repo_ids = []
- def fake_try_to_load_from_cache(repo_id, filename):
+ def fake_try_to_load_from_cache(repo_id, filename, *, cache_dir=None):
probed_repo_ids.append(repo_id)
if repo_id == "bert-base-uncased":
return "/fake/path/config.json"
@@ -2197,7 +2199,7 @@ def test_sbert_cache_check_does_not_double_prefix_namespaced_input():
probed_repo_ids = []
- def fake_try_to_load_from_cache(repo_id, filename):
+ def fake_try_to_load_from_cache(repo_id, filename, *, cache_dir=None):
probed_repo_ids.append(repo_id)
return
@@ -2255,6 +2257,11 @@ def test_sbert_cache_check_admits_local_model_confined_under_models_dir(
``tests/embeddings/test_sentence_transformers.py`` for the escape cases).
The admit checks only that the confined path exists (no config.json /
model-structure validation), mirroring the loader's os.path.exists guard.
+
+ The admission is asserted through ``create_embeddings``, which is where
+ the confined path is resolved: it returns from its own branch before the
+ Hub-cache helper is ever consulted (the empty snapshot has no resolvable
+ primary, so the gate fails closed to local-only — the require_local case).
"""
from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
SentenceTransformersProvider,
@@ -2268,23 +2275,40 @@ def test_sbert_cache_check_admits_local_model_confined_under_models_dir(
"local_deep_research.config.paths.get_models_directory",
return_value=models_dir,
):
- with patch("huggingface_hub.try_to_load_from_cache") as mock_cache:
- # Absolute path under the models dir.
- assert (
- SentenceTransformersProvider._is_model_cached_locally(
- str(model_dir)
- )
- is True
+ # Absolute path under the models dir, and a path relative to it.
+ assert (
+ SentenceTransformersProvider._confined_local_model_path(
+ str(model_dir)
)
- # Path relative to the models dir.
- assert (
- SentenceTransformersProvider._is_model_cached_locally(
- "my-local-model"
- )
- is True
+ == model_dir.resolve()
+ )
+ assert (
+ SentenceTransformersProvider._confined_local_model_path(
+ "my-local-model"
)
- # Confined-local admission short-circuits before any HF cache probe.
- mock_cache.assert_not_called()
+ == model_dir.resolve()
+ )
+ for reference in (str(model_dir), "my-local-model"):
+ with (
+ patch("huggingface_hub.try_to_load_from_cache") as mock_cache,
+ patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings"
+ ) as constructor,
+ ):
+ SentenceTransformersProvider.create_embeddings(
+ model=reference, settings_snapshot={}, device="cpu"
+ )
+ assert constructor.call_args.kwargs["model_name"] == str(
+ model_dir.resolve()
+ )
+ assert (
+ constructor.call_args.kwargs["model_kwargs"][
+ "local_files_only"
+ ]
+ is True
+ )
+ # Admission short-circuits before any HF cache probe.
+ mock_cache.assert_not_called()
def test_sbert_cache_check_blank_name_not_treated_as_existing_path():
@@ -2320,17 +2344,33 @@ def test_sentence_transformers_model_hub_organization_pin():
misleading ``embeddings_model_not_cached``. Importing it here
surfaces removal in CI; the value assert catches silent cache-key
drift if upstream ever ships a different org string.
+
+ ``__MODEL_HUB_ORGANIZATION__`` is only the re-export; the prefix the
+ loader actually applies is the model class's
+ ``default_huggingface_organization`` (5.7.0, ``base/model.py``, for
+ every bare name outside ``util.misc.ORIGINAL_TRANSFORMER_MODELS``).
+ Pin the two together so a future upstream split — the class prefixing
+ with one value while the module constant keeps another — surfaces here
+ instead of as a silent cache-key miss.
"""
- from sentence_transformers import __MODEL_HUB_ORGANIZATION__
+ from sentence_transformers import (
+ SentenceTransformer,
+ __MODEL_HUB_ORGANIZATION__,
+ )
assert __MODEL_HUB_ORGANIZATION__ == "sentence-transformers"
+ assert (
+ SentenceTransformer.default_huggingface_organization
+ == __MODEL_HUB_ORGANIZATION__
+ )
-def test_create_embeddings_admits_cached_default_model_under_require_local():
+def test_create_embeddings_admits_cached_legacy_catalog_model_under_require_local():
"""End-to-end admit path — the exact regression the fix targets.
- Under require_local, a shipped-default model that IS cached (only
- under the ``sentence-transformers/`` namespaced HF key) must be
+ Under require_local, a legacy catalog model (``all-MiniLM-L6-v2``,
+ the pre-curation default) that IS cached (only under the
+ ``sentence-transformers/`` namespaced HF key) must be
admitted through the gate: no PolicyDeniedError, and the load forced
offline with ``local_files_only=True``. Before the fix, the gate's
cache probe used the bare name, missed the namespaced key, and
@@ -2343,7 +2383,7 @@ def test_create_embeddings_admits_cached_default_model_under_require_local():
SentenceTransformersProvider,
)
- def fake_cache(repo_id, filename):
+ def fake_cache(repo_id, filename, *, cache_dir=None):
# Only the namespaced key hits — what the loader actually
# requests for a bare SBERT default, and what the old code missed.
if repo_id == "sentence-transformers/all-MiniLM-L6-v2":
@@ -2391,7 +2431,7 @@ def test_create_embeddings_denies_uncached_model_under_require_local():
):
with pytest.raises(PolicyDeniedError) as excinfo:
SentenceTransformersProvider.create_embeddings(
- model="definitely-not-cached-zzz",
+ model="all-mpnet-base-v2",
settings_snapshot={},
device="cpu",
)
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index ca6668a329..02ffbed5a6 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -1799,7 +1799,7 @@
},
"local_search_embedding_model": {
"category": "embeddings",
- "description": "Embedding model used for the local-document search index. Free-form text because available models vary by provider (e.g. Sentence Transformers ships a fixed list, Ollama/OpenAI-compatible servers expose whatever is installed). Defaults to all-MiniLM-L6-v2 (384d) which is fast and good for general use.",
+ "description": "Embedding model used for the local-document search index. Model names vary by provider: Sentence Transformers uses LDR's vetted list, while Ollama/OpenAI-compatible servers expose whatever is installed. Defaults to Alibaba-NLP/gte-modernbert-base (768d); curated Sentence Transformers models require a one-time policy-authorized download, then reuse the local cache.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -1808,7 +1808,7 @@
"step": null,
"type": "APP",
"ui_element": "text",
- "value": "all-MiniLM-L6-v2",
+ "value": "Alibaba-NLP/gte-modernbert-base",
"visible": true
},
"local_search_embedding_provider": {
diff --git a/tests/ui_tests/playwright/tests/embedding-settings-dropdown.spec.js b/tests/ui_tests/playwright/tests/embedding-settings-dropdown.spec.js
index 85974563a8..c398549c1c 100644
--- a/tests/ui_tests/playwright/tests/embedding-settings-dropdown.spec.js
+++ b/tests/ui_tests/playwright/tests/embedding-settings-dropdown.spec.js
@@ -31,6 +31,24 @@ const {
test.describe('Embedding settings — model dropdown preservation (#3863)', () => {
test.skip(({ isMobile }) => isMobile, 'desktop-only form-state test');
+ test('explains the one-time Sentence Transformers download requirements', async ({ page }) => {
+ await mockEmbeddingApis(page, defaultSettings());
+
+ await page.goto('/library/embedding-settings');
+
+ const notice = page.locator('#sentence-transformers-download-notice');
+ await expect(notice).toBeVisible();
+ await expect(notice).toContainText('Sentence Transformers models require a one-time download');
+ await expect(notice).toContainText('Public only');
+ await expect(notice).toContainText('Adaptive');
+ await expect(notice).toContainText('no private collection selected');
+ await expect(notice).toContainText('Require local embeddings');
+ await expect(notice).toContainText('Test Embedding Model');
+ await expect(notice).toContainText('arbitrary Hugging Face model IDs');
+ await expect(notice).toContainText('Ollama');
+ await expect(notice.locator('a')).toHaveAttribute('href', '/settings/');
+ });
+
test('per-field auto-save fires on model change and persists across reload', async ({ page }) => {
// This is a happy-path smoke test for the per-field auto-save
// contract that replaced the deleted batch-save button. It does not
diff --git a/tests/web_search_engines/engines/test_embedding_manager_coverage.py b/tests/web_search_engines/engines/test_embedding_manager_coverage.py
index 31659fb917..9298e16d9b 100644
--- a/tests/web_search_engines/engines/test_embedding_manager_coverage.py
+++ b/tests/web_search_engines/engines/test_embedding_manager_coverage.py
@@ -361,7 +361,7 @@ class TestDeleteChunksFromDb:
class TestInitialization:
def test_defaults(self):
mgr = LocalEmbeddingManager()
- assert mgr.embedding_model == "all-MiniLM-L6-v2"
+ assert mgr.embedding_model == "Alibaba-NLP/gte-modernbert-base"
assert mgr.embedding_device == "cpu"
assert mgr.embedding_model_type == "sentence_transformers"
assert mgr.ollama_base_url is None