Skip to content

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

fix(embeddings): check namespaced repo_id for bare SBERT model names (#4887)

LearningCircuit261c3cf85270
diff --git a/changelog.d/4887.bugfix.md b/changelog.d/4887.bugfix.md
new file mode 100644
index 0000000000..e6c3985fa7
--- /dev/null
+++ b/changelog.d/4887.bugfix.md
@@ -0,0 +1 @@
+Under `embeddings.require_local=True` (or any `PRIVATE_ONLY` egress scope, which forces it), searching a library collection whose embedding model was indexed by bare name — e.g. the shipped default `all-MiniLM-L6-v2` — raised `policy_denied: embeddings_model_not_cached` even when the model was present in the local HuggingFace cache. The pre-flight cache check used the bare name as the `repo_id`, but the SentenceTransformer loader requests the namespaced form (`sentence-transformers/all-MiniLM-L6-v2`) and the HF hub cache is keyed on whichever form the loader requests. The check now probes both forms (matching the loader's resolution for both SBERT-curated names and the `basic_transformer_models` allowlist of vanilla transformers like `bert-base-uncased`), so a correctly cached model is admitted.
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 70d01e5ea9..c4938f8759 100644
--- a/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py
+++ b/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py
@@ -133,10 +133,16 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
PolicyDeniedError,
)
+ # 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 under "
- "embeddings.require_local=True",
- model=model,
+ "refusing SentenceTransformer download for {!r} "
+ "under embeddings.require_local=True",
+ model,
)
raise PolicyDeniedError(
Decision(False, "embeddings_model_not_cached"),
@@ -156,20 +162,53 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
def _is_model_cached_locally(model_name: str) -> bool:
"""Best-effort check whether ``model_name`` is already cached.
- Looks at the HuggingFace hub cache directory; returns False if
- the cache lookup itself fails, which fails closed under
- ``require_local=True``.
+ Probes the HuggingFace hub cache for both the bare and the
+ ``sentence-transformers/``-namespaced forms of the name (the
+ two cache keys the SentenceTransformer 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: the
+ cache probe below either raises — caught by the broad except —
+ or misses, so no special-casing is needed.
"""
try:
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
+ # (bert-base-uncased, gpt2, t5-base, ...) are requested
+ # from the BARE repo_id;
+ # - everything else is prefixed with
+ # ``__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__``).
+ if "/" in model_name:
+ candidates = [model_name]
+ else:
+ from sentence_transformers import (
+ __MODEL_HUB_ORGANIZATION__,
+ )
+
+ candidates = [
+ model_name,
+ 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.
- cached = try_to_load_from_cache(
- repo_id=model_name, filename="config.json"
- )
- return isinstance(cached, str) and bool(cached)
+ for repo_id in candidates:
+ cached = try_to_load_from_cache(
+ repo_id=repo_id, filename="config.json"
+ )
+ if isinstance(cached, str) and bool(cached):
+ return True
+ return False
except Exception: # pragma: no cover - defensive
return False
diff --git a/tests/security/test_egress_policy.py b/tests/security/test_egress_policy.py
index 54e52c4788..ff478771ff 100644
--- a/tests/security/test_egress_policy.py
+++ b/tests/security/test_egress_policy.py
@@ -5,6 +5,7 @@ from __future__ import annotations
from unittest.mock import patch
import pytest
+from huggingface_hub import _CACHED_NO_EXIST
from local_deep_research.security.egress.policy import (
Decision,
@@ -1937,6 +1938,222 @@ def test_n17_research_context_carries_settings_snapshot():
)
+def test_sbert_cache_check_probes_both_forms_for_bare_sbert_name():
+ """Bare SentenceTransformer model names (e.g. "all-MiniLM-L6-v2")
+ 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``
+ allowlist (which use the bare key) — but the namespaced form is
+ the one that hits for shipped SBERT defaults.
+ """
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider,
+ )
+
+ probed_repo_ids = []
+
+ def fake_try_to_load_from_cache(repo_id, filename):
+ probed_repo_ids.append(repo_id)
+ if repo_id == "sentence-transformers/all-MiniLM-L6-v2":
+ return "/fake/path/config.json"
+ return None
+
+ with patch(
+ "huggingface_hub.try_to_load_from_cache",
+ side_effect=fake_try_to_load_from_cache,
+ ):
+ assert (
+ SentenceTransformersProvider._is_model_cached_locally(
+ "all-MiniLM-L6-v2"
+ )
+ is True
+ )
+ # The namespaced form is the hit for SBERT-curated defaults; assert
+ # it was probed (order-independent — the bare-key probe is covered
+ # by the basic-transformer test below).
+ assert "sentence-transformers/all-MiniLM-L6-v2" in probed_repo_ids
+
+
+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
+ 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.
+ """
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider,
+ )
+
+ probed_repo_ids = []
+
+ def fake_try_to_load_from_cache(repo_id, filename):
+ probed_repo_ids.append(repo_id)
+ if repo_id == "bert-base-uncased":
+ return "/fake/path/config.json"
+ return None
+
+ with patch(
+ "huggingface_hub.try_to_load_from_cache",
+ side_effect=fake_try_to_load_from_cache,
+ ):
+ assert (
+ SentenceTransformersProvider._is_model_cached_locally(
+ "bert-base-uncased"
+ )
+ is True
+ )
+ assert "bert-base-uncased" in probed_repo_ids
+
+
+def test_sbert_cache_check_does_not_double_prefix_namespaced_input():
+ """Already-namespaced inputs (e.g. 'BAAI/bge-small-en') must be
+ probed verbatim — not re-prefixed to
+ 'sentence-transformers/BAAI/bge-small-en', which would always miss.
+ """
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider,
+ )
+
+ probed_repo_ids = []
+
+ def fake_try_to_load_from_cache(repo_id, filename):
+ probed_repo_ids.append(repo_id)
+ return
+
+ with patch(
+ "huggingface_hub.try_to_load_from_cache",
+ side_effect=fake_try_to_load_from_cache,
+ ):
+ assert (
+ SentenceTransformersProvider._is_model_cached_locally(
+ "BAAI/bge-small-en"
+ )
+ is False
+ )
+ assert probed_repo_ids == ["BAAI/bge-small-en"]
+
+
+ "miss_value",
+ [None, _CACHED_NO_EXIST],
+ ids=["never_probed", "known_absent"],
+)
+def test_sbert_cache_check_treats_non_string_returns_as_misses(miss_value):
+ """try_to_load_from_cache returns None for never-probed files and
+ the _CACHED_NO_EXIST sentinel for confirmed-absent ones. Both must
+ be treated as cache misses so require_local keeps blocking — a
+ known-absent file is not a cached file.
+ """
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider,
+ )
+
+ with patch(
+ "huggingface_hub.try_to_load_from_cache",
+ return_value=miss_value,
+ ):
+ assert (
+ SentenceTransformersProvider._is_model_cached_locally(
+ "all-MiniLM-L6-v2"
+ )
+ is False
+ )
+
+
+def test_sentence_transformers_model_hub_organization_pin():
+ """Pin the private ``__MODEL_HUB_ORGANIZATION__`` constant that
+ ``_is_model_cached_locally`` uses to build the namespaced cache key
+ (``sentence-transformers/<name>``) for bare SBERT model names.
+
+ If upstream renames or removes it, the import inside the cache
+ check raises ``ImportError``, the broad ``except`` swallows it, and
+ every ``require_local=True`` run silently fail-closes with a
+ 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.
+ """
+ from sentence_transformers import __MODEL_HUB_ORGANIZATION__
+
+ assert __MODEL_HUB_ORGANIZATION__ == "sentence-transformers"
+
+
+def test_create_embeddings_admits_cached_default_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
+ 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
+ raised ``embeddings_model_not_cached`` for a model that was present
+ — so this test fails on the old single-probe code and passes with
+ the fix. The unit test pins ``_is_model_cached_locally``; this pins
+ the wiring from that check through ``create_embeddings`` to admission.
+ """
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider,
+ )
+
+ def fake_cache(repo_id, filename):
+ # 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":
+ return "/fake/path/config.json"
+ return None
+
+ stub = object()
+ # Empty snapshot: resolve_run_primary_engine raises (no primary), so
+ # create_embeddings fails closed to require_local=True and the gate
+ # actually runs — no need to synthesise a PRIVATE_ONLY scope.
+ with (
+ patch("huggingface_hub.try_to_load_from_cache", side_effect=fake_cache),
+ patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings",
+ return_value=stub,
+ ) as mock_st,
+ ):
+ result = SentenceTransformersProvider.create_embeddings(
+ model="all-MiniLM-L6-v2",
+ settings_snapshot={},
+ device="cpu",
+ )
+
+ assert result is stub
+ # Admitted, and forced offline for defence in depth.
+ assert mock_st.call_args.kwargs["model_kwargs"]["local_files_only"] is True
+
+
+def test_create_embeddings_denies_uncached_model_under_require_local():
+ """End-to-end deny path through the same gate: a genuinely uncached
+ model under require_local raises ``embeddings_model_not_cached`` and
+ the SentenceTransformer loader is never invoked — so no HuggingFace
+ download is triggered. Guards the fail-closed direction against a
+ future change that widens admission too far.
+ """
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider,
+ )
+
+ with (
+ patch("huggingface_hub.try_to_load_from_cache", return_value=None),
+ patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings"
+ ) as mock_st,
+ ):
+ with pytest.raises(PolicyDeniedError) as excinfo:
+ SentenceTransformersProvider.create_embeddings(
+ model="definitely-not-cached-zzz",
+ settings_snapshot={},
+ device="cpu",
+ )
+
+ assert excinfo.value.decision.reason == "embeddings_model_not_cached"
+ mock_st.assert_not_called()
+
+
def test_local_embedding_manager_propagates_policy_denied():
"""LocalEmbeddingManager._initialize_embeddings catches Exception
broadly and falls back to HuggingFaceEmbeddings. Without an