~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(ci): prepare shared offline models for library release tests (#7621)
LearningCircuit390bd95c3290
diff --git a/.github/workflows/ci-policy-tests.yml b/.github/workflows/ci-policy-tests.ymlindex bbbb83a0f6..4b4e4bc4db 100644--- a/.github/workflows/ci-policy-tests.yml+++ b/.github/workflows/ci-policy-tests.yml@@ -10,10 +10,13 @@ on:- ".github/scripts/check_release_deadline.py"- ".github/scripts/retire_json_to_sarif.py"- ".github/scripts/run_osv_scan.py"+ - "scripts/ci/prepare_library_embeddings.py"+ - "tests/ui_tests/seed_legacy_pkl_migration.py"- ".github/release-scan-policy.json"- "tests/ci/standalone/test_release_scan_*.py"- "tests/ci/standalone/test_pytest_scheduling.py"- "tests/ci/standalone/test_osv_scan.py"+ - "tests/ci/standalone/test_library_embedding_fixture.py"workflow_dispatch:permissions:@@ -42,3 +45,5 @@ jobs:run: python -m unittest discover -s tests/ci/standalone -p 'test_pytest_scheduling.py' -v- name: Test OSV scan completion and reportingrun: python -m unittest discover -s tests/ci/standalone -p 'test_osv_scan.py' -v+ - name: Test library model preparation and offline server setup+ run: python -m unittest discover -s tests/ci/standalone -p 'test_library_embedding_fixture.py' -vdiff --git a/.github/workflows/docker-tests.yml b/.github/workflows/docker-tests.ymlindex 36a7fe46e5..1135b4916d 100644--- a/.github/workflows/docker-tests.yml+++ b/.github/workflows/docker-tests.yml@@ -982,12 +982,28 @@ jobs:# and the server so the seeded encrypted DB opens at login. Writes# <LDR_DATA_DIR>/migtest_manifest.json for the node test to consume.if [ "${SHARD}" = "library" ]; then+ echo "::group::Prepare library embedding cache"+ # Model acquisition needs an explicit public setup snapshot.+ # Keep its artifacts on the same /data volume as the cache-only+ # seed and server; the throwaway setup container is removed.+ docker run --rm \+ -v "${GITHUB_WORKSPACE}":/app \+ -v "${GITHUB_WORKSPACE}/ci-data":/data \+ -e TEST_ENV=true \+ -e LDR_DATA_DIR=/data \+ -e HF_HUB_CACHE=/data/cache/huggingface/hub \+ -w /app/src \+ "${TEST_IMAGE}" \+ python ../scripts/ci/prepare_library_embeddings.py+ echo "::endgroup::"+echo "::group::Seed legacy .pkl migration fixtures"docker run --rm \-v "${GITHUB_WORKSPACE}":/app \-v "${GITHUB_WORKSPACE}/ci-data":/data \-e TEST_ENV=true \-e LDR_DATA_DIR=/data \+ -e HF_HUB_CACHE=/data/cache/huggingface/hub \-e LDR_DB_CONFIG_KDF_ITERATIONS=1000 \-e LDR_TEST_MODE=1 \-w /app/src \@@ -1034,7 +1050,19 @@ jobs:echo "::group::Start application server"SERVER_OPTIONS=()SERVER_COMMAND=(ldr-web)- if [ "${SHARD}" = "research-completion" ]; then+ if [ "${SHARD}" = "library" ]; then+ # Test new collections with the same small, real model used by+ # the legacy fixture. Prove the prepared cache is sufficient:+ # no server-side model download or Hub request is permitted.+ SERVER_OPTIONS=(+ -e LDR_LOCAL_SEARCH_EMBEDDING_PROVIDER=sentence_transformers+ -e LDR_LOCAL_SEARCH_EMBEDDING_MODEL=all-MiniLM-L6-v2+ -e LDR_EMBEDDINGS_REQUIRE_LOCAL=true+ -e HF_HUB_CACHE=/data/cache/huggingface/hub+ -e HF_HUB_OFFLINE=1+ -e TRANSFORMERS_OFFLINE=1+ )+ elif [ "${SHARD}" = "research-completion" ]; then# Only this release shard serves the real ASGI app with its# model/search egress replaced by deterministic test stubs.SERVER_OPTIONS=(diff --git a/scripts/ci/prepare_library_embeddings.py b/scripts/ci/prepare_library_embeddings.pynew file mode 100644index 0000000000..2b308df245--- /dev/null+++ b/scripts/ci/prepare_library_embeddings.py@@ -0,0 +1,43 @@+#!/usr/bin/env python3+"""Prepare the library UI shard's real MiniLM model before offline tests.++Only this setup process requests public model acquisition. The seed and server+reuse the shared data-volume cache without relaxing their egress policy.+"""++import math+import os+++def prepare_embeddings():+ if not os.environ.get("LDR_DATA_DIR"):+ raise ValueError(+ "LDR_DATA_DIR must name the disposable CI data directory"+ )++ from local_deep_research.embeddings.embeddings_config import get_embeddings+ from local_deep_research.utilities.resource_utils import safe_close++ embeddings = get_embeddings(+ provider="sentence_transformers",+ model="all-MiniLM-L6-v2",+ device="cpu",+ settings_snapshot={+ "policy.egress_scope": "public_only",+ "search.tool": "arxiv",+ "embeddings.require_local": False,+ },+ )+ try:+ # Load the actual weights/tokenizer, rather than accepting cache+ # metadata alone as proof that an interrupted download completed.+ vector = embeddings.embed_query("Synthetic library CI readiness check")+ if len(vector) != 384 or not all(math.isfinite(x) for x in vector):+ raise ValueError("The library fixture requires finite 384d vectors")+ finally:+ safe_close(embeddings, "library fixture embeddings")+ print("Library MiniLM embedding cache is ready")+++if __name__ == "__main__":+ prepare_embeddings()diff --git a/tests/ci/standalone/test_library_embedding_fixture.py b/tests/ci/standalone/test_library_embedding_fixture.pynew file mode 100644index 0000000000..457e7fc846--- /dev/null+++ b/tests/ci/standalone/test_library_embedding_fixture.py@@ -0,0 +1,272 @@+"""Exercise library setup and fixture privacy without app imports."""++from contextlib import redirect_stdout+import importlib.util+import io+import json+import os+from pathlib import Path+import subprocess+import sys+import tempfile+import textwrap+from types import ModuleType+import unittest+from unittest.mock import Mock, patch+++ROOT = Path(__file__).resolve().parents[3]+++class ModelPreparationTests(unittest.TestCase):+ def setUp(self):+ spec = importlib.util.spec_from_file_location(+ "prepare_library_embeddings",+ ROOT / "scripts/ci/prepare_library_embeddings.py",+ )+ self.script = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(self.script)+ self.embeddings = Mock()+ self.embeddings.embed_query.return_value = [0.25] * 384+ self.get_embeddings = Mock(return_value=self.embeddings)+ module = ModuleType("local_deep_research.embeddings.embeddings_config")+ module.get_embeddings = self.get_embeddings+ # Exercise the real cleanup helper without importing the application.+ self.logger = Mock()+ loguru = ModuleType("loguru")+ loguru.logger = self.logger+ cleanup_spec = importlib.util.spec_from_file_location(+ "local_deep_research.utilities.resource_utils",+ ROOT / "src/local_deep_research/utilities/resource_utils.py",+ )+ cleanup = importlib.util.module_from_spec(cleanup_spec)+ with patch.dict(sys.modules, {"loguru": loguru}):+ cleanup_spec.loader.exec_module(cleanup)+ self.modules = patch.dict(+ sys.modules,+ {module.__name__: module, cleanup.__name__: cleanup},+ )+ self.modules.start()+ self.addCleanup(self.modules.stop)+ self.environment = patch.dict(os.environ, {"LDR_DATA_DIR": "/data"})+ self.environment.start()+ self.addCleanup(self.environment.stop)++ def test_preparation_explicitly_authorizes_only_public_local_model_setup(+ self,+ ):+ self.script.prepare_embeddings()+ self.get_embeddings.assert_called_once_with(+ provider="sentence_transformers",+ model="all-MiniLM-L6-v2",+ device="cpu",+ settings_snapshot={+ "policy.egress_scope": "public_only",+ "search.tool": "arxiv",+ "embeddings.require_local": False,+ },+ )+ self.embeddings.embed_query.assert_called_once()+ self.embeddings.close.assert_called_once()++ def test_incomplete_model_failure_propagates_and_closes_the_handle(self):+ failure = OSError("synthetic incomplete model")+ self.embeddings.embed_query.side_effect = failure+ with self.assertRaises(OSError) as raised:+ self.script.prepare_embeddings()+ self.assertIs(raised.exception, failure)+ self.embeddings.close.assert_called_once()++ def test_model_failure_is_preserved_when_cleanup_also_fails(self):+ failure = OSError("synthetic incomplete model")+ self.embeddings.embed_query.side_effect = failure+ self.embeddings.close.side_effect = RuntimeError(+ "synthetic cleanup failure"+ )++ with self.assertRaises(OSError) as raised:+ self.script.prepare_embeddings()++ self.assertIs(raised.exception, failure)+ self.embeddings.close.assert_called_once()+ self.logger.warning.assert_called_once_with(+ "Failed to close library fixture embeddings"+ )++ def test_cleanup_failure_is_logged_without_private_exception_details(self):+ private_value = "synthetic-private-cleanup-detail"+ self.embeddings.close.side_effect = RuntimeError(private_value)++ self.script.prepare_embeddings()++ self.embeddings.close.assert_called_once()+ self.logger.warning.assert_called_once_with(+ "Failed to close library fixture embeddings"+ )+ self.assertNotIn(private_value, repr(self.logger.mock_calls))++ def test_wrong_dimension_or_nonfinite_vectors_fail_setup(self):+ for vector in ([0.25] * 768, [float("nan")] * 384):+ with self.subTest(dimension=len(vector)):+ self.embeddings.reset_mock()+ self.embeddings.embed_query.return_value = vector+ with self.assertRaises(ValueError):+ self.script.prepare_embeddings()+ self.embeddings.close.assert_called_once()++ def test_missing_data_directory_fails_before_model_acquisition(self):+ with patch.dict(os.environ, {"LDR_DATA_DIR": ""}):+ with self.assertRaises(ValueError):+ self.script.prepare_embeddings()+ self.get_embeddings.assert_not_called()+++class ManifestPrivacyTests(unittest.TestCase):+ def setUp(self):+ spec = importlib.util.spec_from_file_location(+ "seed_legacy_pkl_migration",+ ROOT / "tests/ui_tests/seed_legacy_pkl_migration.py",+ )+ self.seed = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(self.seed)+ self.temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self.temporary.cleanup)+ self.directory = Path(self.temporary.name)+ self.manifest = {+ "username": "synthetic-private-fixture-user",+ "password": "synthetic-private-fixture-password",+ "collections": {},+ }++ def test_manifest_remains_usable_without_printing_credentials(self):+ output = io.StringIO()+ with redirect_stdout(output):+ path = self.seed._write_manifest(self.directory, self.manifest)+ self.assertEqual(json.loads(path.read_text()), self.manifest)+ self.assertEqual(path.stat().st_mode & 0o777, 0o600)+ self.assertNotIn(self.manifest["password"], output.getvalue())+ self.assertNotIn(self.manifest["username"], output.getvalue())++ def test_replacing_an_old_manifest_repairs_permissive_permissions(self):+ path = self.directory / "migtest_manifest.json"+ path.write_text("old fixture")+ path.chmod(0o644)+ self.seed._write_manifest(self.directory, self.manifest)+ self.assertEqual(path.stat().st_mode & 0o777, 0o600)+ self.assertEqual(json.loads(path.read_text()), self.manifest)++ def test_failed_serialization_preserves_old_manifest_and_removes_tempfile(+ self,+ ):+ path = self.directory / "migtest_manifest.json"+ path.write_text("old fixture")+ with self.assertRaises(TypeError):+ self.seed._write_manifest(self.directory, {"invalid": object()})+ self.assertEqual(path.read_text(), "old fixture")+ self.assertEqual(list(self.directory.iterdir()), [path])++ def test_destination_symlink_does_not_overwrite_another_file(self):+ target = self.directory / "unrelated"+ target.write_text("synthetic unrelated content")+ path = self.directory / "migtest_manifest.json"+ path.symlink_to(target)+ self.seed._write_manifest(self.directory, self.manifest)+ self.assertFalse(path.is_symlink())+ self.assertEqual(target.read_text(), "synthetic unrelated content")+ self.assertEqual(path.stat().st_mode & 0o777, 0o600)+++class LibraryWorkflowTests(unittest.TestCase):+ def invoke(self, shard, fail_preparation=False):+ source = (ROOT / ".github/workflows/docker-tests.yml").read_text()+ step = source.split(+ " - name: Run UI tests with retry (fresh server per attempt)\n",+ 1,+ )[1]+ # Execute the real setup through the server launch, stopping before+ # the health-check loop. Only Docker itself is replaced.+ command = step.split(" command: |\n", 1)[1].split(+ " # --max-time bounds", 1+ )[0]+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ calls = root / "docker-calls.jsonl"+ docker = root / "docker"+ docker.write_text(+ f"#!{sys.executable}\n"+ "import json, os, sys\n"+ "with open(os.environ['DOCKER_CALLS'], 'a') as output:\n"+ " output.write(json.dumps(sys.argv[1:]) + '\\n')\n"+ "if os.environ['FAIL_PREPARATION'] == '1' and any(\n"+ " arg.endswith('/prepare_library_embeddings.py')\n"+ " for arg in sys.argv\n"+ "):\n"+ " sys.exit(17)\n"+ )+ docker.chmod(0o700)+ result = subprocess.run(+ ["bash", "-c", textwrap.dedent(command)],+ env={+ **os.environ,+ "PATH": f"{root}:/usr/bin:/bin",+ "SHARD": shard,+ "TEST_IMAGE": "fixture-image",+ "GITHUB_WORKSPACE": str(root / "workspace with spaces"),+ "DOCKER_CALLS": str(calls),+ "FAIL_PREPARATION": str(int(fail_preparation)),+ },+ capture_output=True,+ text=True,+ timeout=10,+ )+ invocations = [+ json.loads(line) for line in calls.read_text().splitlines()+ ]+ return result, invocations++ def test_library_prepares_and_seeds_shared_cache_before_offline_server(+ self,+ ):+ result, calls = self.invoke("library")+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertEqual(+ [call[-1] for call in calls],+ [+ "../scripts/ci/init_test_database.py",+ "../scripts/ci/prepare_library_embeddings.py",+ "../tests/ui_tests/seed_legacy_pkl_migration.py",+ "ldr-web",+ ],+ )+ for call in calls:+ self.assertIn("LDR_DATA_DIR=/data", call)+ self.assertTrue(any(arg.endswith("/ci-data:/data") for arg in call))+ # ldr-test does not inherit the production image's HF_HUB_CACHE env.+ # Each disposable process must explicitly select the shared mount.+ for call in calls[1:]:+ self.assertIn("HF_HUB_CACHE=/data/cache/huggingface/hub", call)+ server = calls[-1]+ for setting in (+ "LDR_LOCAL_SEARCH_EMBEDDING_PROVIDER=sentence_transformers",+ "LDR_LOCAL_SEARCH_EMBEDDING_MODEL=all-MiniLM-L6-v2",+ "LDR_EMBEDDINGS_REQUIRE_LOCAL=true",+ "HF_HUB_OFFLINE=1",+ "TRANSFORMERS_OFFLINE=1",+ ):+ self.assertIn(setting, server)++ def test_failed_acquisition_prevents_seed_and_server_startup(self):+ result, calls = self.invoke("library", fail_preparation=True)+ self.assertEqual(result.returncode, 17)+ self.assertEqual(len(calls), 2)++ def test_other_shards_do_not_acquire_or_override_embedding_models(self):+ result, calls = self.invoke("auth-login")+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertEqual(len(calls), 2)+ self.assertFalse(any("EMBEDDING" in arg for arg in calls[-1]))+ self.assertNotIn("HF_HUB_OFFLINE=1", calls[-1])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/ui_tests/run_legacy_pkl_migration.sh b/tests/ui_tests/run_legacy_pkl_migration.shindex 907881d837..a8c4a55ec4 100755--- a/tests/ui_tests/run_legacy_pkl_migration.sh+++ b/tests/ui_tests/run_legacy_pkl_migration.sh@@ -25,6 +25,7 @@ set -uPORT="${1:-5099}"export LDR_DATA_DIR="${LDR_DATA_DIR:-/tmp/ldr-migtest}"+export HF_HUB_CACHE="${HF_HUB_CACHE:-${LDR_DATA_DIR}/cache/huggingface/hub}"# Resolve repo root from this script's location.SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"@@ -49,6 +50,10 @@ rm -rf "${LDR_DATA_DIR}"mkdir -p "${LDR_DATA_DIR}"echo "=== 2/4 Seed legacy .pkl fixtures + encrypted-DB rows (before boot) ==="+if ! pdm run python scripts/ci/prepare_library_embeddings.py; then+ echo "Embedding model preparation FAILED" >&2+ exit 1+fiif ! pdm run python tests/ui_tests/seed_legacy_pkl_migration.py; thenecho "Seed FAILED" >&2exit 1diff --git a/tests/ui_tests/seed_legacy_pkl_migration.py b/tests/ui_tests/seed_legacy_pkl_migration.pyindex a7a6988cfa..36b717b3cb 100644--- a/tests/ui_tests/seed_legacy_pkl_migration.py+++ b/tests/ui_tests/seed_legacy_pkl_migration.py@@ -31,6 +31,9 @@ extracted into the RIGHT sidecar / index (no cross-contamination):* collection A carries the distinctive token SECRET_A,* collection B (the decoy) carries SECRET_B.+Prepare that model first with ``scripts/ci/prepare_library_embeddings.py``+under the same data-volume cache. This seed deliberately remains cache-only.+Both indexes are built with the SAME real all-MiniLM-L6-v2 (384-dim) model theserver re-embeds the query with at search time, so cosine similarity ismeaningful and the rekey dimension guard (``old.d != embedding_dimension``)@@ -42,20 +45,19 @@ Env (all optional, sensible defaults):LDR_MIGTEST_USER seeded username (default: migtest_user)LDR_MIGTEST_PASS seeded password (default: MigTest!Secure#2026$LDR)-Writes a manifest JSON to ``<LDR_DATA_DIR>/migtest_manifest.json`` (and prints-it to stdout) for the node test to consume — it shares the filesystem with the-server, so no path recomputation in JS is needed.+Writes a private manifest JSON to ``<LDR_DATA_DIR>/migtest_manifest.json`` for+the node test to consume — it shares the filesystem with the server, so no path+recomputation in JS is needed. Credentials stay in that file, out of stdout."""import hashlibimport jsonimport osimport sys+import tempfileimport uuidfrom pathlib import Path-from langchain_community.vectorstores import FAISS-# --------------------------------------------------------------------------# Distinctive, unambiguous per-collection content. The tokens are what the# node test greps the on-disk sidecars/cache for (must be ABSENT — text-free)@@ -73,6 +75,8 @@ def _make_legacy_index(dir_path: Path, ids, texts, embeddings, index_name):"""Write a REAL old-format ``<index_name>.faiss`` + plaintext``<index_name>.pkl`` pair, exactly as the pre-cutover LangChain-FAISSwrapper did (mirrors tests/vector_stores' ``_make_legacy_index``)."""+ from langchain_community.vectorstores import FAISS+dir_path.mkdir(parents=True, exist_ok=True)metadatas = [{"chunk": i} for i in range(len(texts))]vs = FAISS.from_texts(texts, embeddings, metadatas=metadatas, ids=ids)@@ -90,6 +94,31 @@ def _user_scope(username: str) -> str:return hashlib.sha256(username.encode("utf-8")).hexdigest()[:16]+def _write_manifest(data_dir: Path, manifest: dict) -> Path:+ """Keep fixture credentials private, including when replacing an old file."""+ manifest_path = data_dir / "migtest_manifest.json"+ temporary_path = None+ try:+ # NamedTemporaryFile creates the file with 0600 regardless of umask.+ # Replacing the destination also repairs an existing permissive mode+ # and avoids following a destination symlink.+ with tempfile.NamedTemporaryFile(+ mode="w",+ encoding="utf-8",+ dir=data_dir,+ prefix=".migtest_manifest-",+ delete=False,+ ) as output:+ temporary_path = Path(output.name)+ json.dump(manifest, output, indent=2)+ temporary_path.replace(manifest_path)+ finally:+ if temporary_path is not None:+ temporary_path.unlink(missing_ok=True)+ print("Legacy migration fixture manifest is ready")+ return manifest_path++def main() -> int:data_dir = os.environ.get("LDR_DATA_DIR")if not data_dir:@@ -151,8 +180,8 @@ def main() -> int:db_manager.create_user_database(username, password)# Real all-MiniLM-L6-v2 embeddings — same model the server re-embeds the- # query with at search time. Building the vectors here also warms the HF- # cache the server reuses.+ # query with at search time. The setup process must have prepared the+ # shared HF cache already; this snapshot-less load cannot download it.embeddings = get_embeddings(provider=EMBEDDING_PROVIDER, model=EMBEDDING_MODEL)@@ -226,6 +255,12 @@ def main() -> int:id=collection_id,name=spec["name"],collection_type="user_collection",+ # Search uses collection settings before consulting the+ # RAGIndex. Keep the legacy model explicit even when the+ # application's default model changes.+ embedding_model=EMBEDDING_MODEL,+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,+ embedding_dimension=EMBEDDING_DIM,))@@ -335,10 +370,7 @@ def main() -> int:session.commit()- manifest_path = data_dir / "migtest_manifest.json"- manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")-- print(json.dumps(manifest, indent=2))+ manifest_path = _write_manifest(data_dir, manifest)print(f"\nSeed complete. Manifest: {manifest_path}", file=sys.stderr)print(f"Legacy fixtures seeded under: {user_dir}\n"diff --git a/tests/ui_tests/test_rag_index_search_ci.js b/tests/ui_tests/test_rag_index_search_ci.jsindex 9ab78cb634..1401a878a1 100644--- a/tests/ui_tests/test_rag_index_search_ci.js+++ b/tests/ui_tests/test_rag_index_search_ci.js@@ -19,13 +19,13 @@* upload endpoint directly (with the session cookie + CSRF token) to keep the* setup robust and the assertions focused on indexing + search.*- * Requires a working embedding provider on the server: the default is- * sentence-transformers + all-MiniLM-L6-v2 (a core dependency). The model must- * be available — on first use it is fetched from the HuggingFace hub (the- * default egress posture permits this); locally it lives in the HF cache. A- * one-time model warm-up before the server starts makes CI fast + network-- * independent. Indexing has NO embedder-free code path, so success proves the- * embedder ran end-to-end.+ * Requires a working embedding provider on the server. The library CI shard+ * explicitly selects sentence-transformers + all-MiniLM-L6-v2 and prepares it+ * with scripts/ci/prepare_library_embeddings.py before seeding and startup.+ * The server then runs with local-only embeddings and the HuggingFace hub in+ * offline mode. Indexing has NO embedder-free code path, so success proves the+ * real cached model ran end-to-end. Local runs must prepare a model and select+ * the same provider/model in their disposable server's settings.** Registered in the `library` shard (tests/ui_tests/run_all_tests.js). Server* base URL is overridable via LDR_TEST_URL (defaults to the shard default).