~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(startup): defer heavy ML imports off the app-boot path (fixes UI test gates) (#4829)
LearningCircuit24ace2acd58a
diff --git a/changelog.d/4829.bugfix.md b/changelog.d/4829.bugfix.mdnew file mode 100644index 0000000000..915fd0265a--- /dev/null+++ b/changelog.d/4829.bugfix.md@@ -0,0 +1 @@+Server startup no longer eagerly imports the heavy `langchain_text_splitters`/sentence-transformers stack; it is loaded lazily (and thread-safely) on the RAG indexing path instead. This speeds up boot and fixes intermittent UI-test server-start failures, and avoids a rare concurrent-import error that could silently skip document indexing right after a restart.diff --git a/src/local_deep_research/embeddings/splitters/text_splitter_registry.py b/src/local_deep_research/embeddings/splitters/text_splitter_registry.pyindex f92ad3efec..50a29706e4 100644--- a/src/local_deep_research/embeddings/splitters/text_splitter_registry.py+++ b/src/local_deep_research/embeddings/splitters/text_splitter_registry.py@@ -5,20 +5,42 @@ This module provides a factory function to create different types of text splittbased on configuration, similar to how embeddings_config.py works for embeddings."""-from typing import Optional, List, Any--# Import from concrete submodules instead of the package root: the root-# __init__ eagerly imports every splitter module (spacy, nltk, konlpy, ...),-# so a broken optional package in the user's site-packages would crash app-# startup via the scheduler import chain (see issue #4490).-from langchain_text_splitters.base import TokenTextSplitter-from langchain_text_splitters.character import RecursiveCharacterTextSplitter-from langchain_text_splitters.sentence_transformers import (- SentenceTransformersTokenTextSplitter,-)-from langchain_core.embeddings import Embeddings+from __future__ import annotations++import threading+from typing import Optional, List, Any, TYPE_CHECKING+from loguru import logger+# ``langchain_text_splitters`` is imported lazily inside ``get_text_splitter``+# (see below), NOT at module load. Importing *any* of its submodules runs the+# package ``__init__``, which eagerly pulls sentence-transformers, torch,+# spacy, nltk and konlpy — ~4-8 s and hundreds of MB of RSS. Because this+# module sits on the app-startup import chain (scheduler / blueprints /+# search engines all import ``LibraryRAGService`` → ``embeddings.splitters``),+# importing it eagerly added ~19 s to server boot on CI and tripped the+# UI-test startup watchdog. Deferring the import to call time keeps boot+# cheap and also means a broken optional splitter dependency (spacy / konlpy)+# can no longer crash startup — only the indexing path that actually needs+# it (the original intent of issue #4490, which the concrete-submodule+# imports did not actually achieve since they still run the package init).++# Serializes the cold ``langchain_text_splitters`` import. Its package+# ``__init__`` eagerly imports ~14 splitter submodules with enough internal+# cross-referencing that importing different submodules from multiple threads+# at once observes a partially-initialized package and raises+# ``ImportError: cannot import name ... from partially initialized module``.+# The module-level import this replaced warmed ``sys.modules`` single-threaded+# at boot; deferring it to call time reintroduced the race for the RAG+# auto-index ``ThreadPoolExecutor`` and the per-user document scheduler, which+# call ``get_text_splitter`` from several threads. Warm the package once under+# this lock before the function-local submodule imports; once warm the lock is+# uncontended (a ``sys.modules`` hit).+_LANGCHAIN_TEXT_SPLITTERS_IMPORT_LOCK = threading.Lock()++if TYPE_CHECKING:+ from langchain_core.embeddings import Embeddings+# Valid splitter type optionsVALID_SPLITTER_TYPES = ["recursive",@@ -70,14 +92,33 @@ def get_text_splitter(f"chunk_size={chunk_size}, chunk_overlap={chunk_overlap}")- # Create the appropriate splitter+ # Create the appropriate splitter. The ``langchain_text_splitters``+ # imports are intentionally function-local — see the module docstring:+ # importing the package eagerly pulls torch/sentence-transformers and+ # must stay off the app-startup import path.+ #+ # Every branch except "semantic" (which uses langchain_experimental)+ # imports from ``langchain_text_splitters``. Warm the whole package once+ # under the lock first so concurrent first-callers can't observe a+ # half-initialized package (see the lock's definition); after this the+ # per-branch ``from ... import`` are plain ``sys.modules`` lookups.+ if splitter_type != "semantic":+ with _LANGCHAIN_TEXT_SPLITTERS_IMPORT_LOCK:+ import langchain_text_splitters # noqa: F401+if splitter_type == "token":+ from langchain_text_splitters.base import TokenTextSplitter+return TokenTextSplitter(chunk_size=chunk_size,chunk_overlap=chunk_overlap,)if splitter_type == "sentence":+ from langchain_text_splitters.sentence_transformers import (+ SentenceTransformersTokenTextSplitter,+ )+return SentenceTransformersTokenTextSplitter(chunk_overlap=chunk_overlap,tokens_per_chunk=chunk_size,@@ -131,6 +172,10 @@ def get_text_splitter() from eelse: # "recursive" or default+ from langchain_text_splitters.character import (+ RecursiveCharacterTextSplitter,+ )+# Use custom separators if provided, otherwise use defaultsif text_separators is None:text_separators = ["\n\n", "\n", ". ", " ", ""]diff --git a/tests/embeddings/splitters/test_lazy_import_guard.py b/tests/embeddings/splitters/test_lazy_import_guard.pynew file mode 100644index 0000000000..c0131d5670--- /dev/null+++ b/tests/embeddings/splitters/test_lazy_import_guard.py@@ -0,0 +1,62 @@+"""Boot-lightness guard for the lazy text-splitter import.++``text_splitter_registry`` deliberately imports ``langchain_text_splitters``+(which eagerly pulls sentence-transformers / torch / spaCy / nltk, ~500 MB)+*lazily*, inside ``get_text_splitter`` — so it stays off the app-startup+import chain (scheduler / blueprints / search engines all import+``LibraryRAGService`` -> ``embeddings.splitters``). Importing it at boot+added ~17 s to CI server startup and tipped the UI-test gates over.++This test makes that contract explicit and enforced. The UI gates only+fail when boot breaks *entirely*; this fails fast and deterministically the+moment someone re-adds an eager heavy import to the startup chain — which is+the textbook mitigation for lazy imports ("cover the lazy path with a+test"). It must run in a fresh interpreter: inside the pytest process+``langchain_text_splitters`` is already imported by sibling tests, so the+assertion would be meaningless.+"""++import subprocess+import sys+import textwrap++# allow: no-sut-import — the modules under test are imported inside the+# subprocess driver below; the boot-lightness property only holds in a fresh+# interpreter (sibling tests warm these modules in the pytest process).++# Import the two modules that sit on the app-startup chain and must NOT drag+# in the heavy splitter stack, then assert it stayed unimported.+_DRIVER = textwrap.dedent(+ """+ import sys++ import local_deep_research.embeddings.splitters.text_splitter_registry # noqa: F401+ import local_deep_research.research_library.services.library_rag_service # noqa: F401++ eager = [+ m for m in ("langchain_text_splitters", "sentence_transformers")+ if m in sys.modules+ ]+ if eager:+ print(f"FAIL: app-startup import chain eagerly loaded {eager}")+ sys.exit(1)+ print("OK")+ """+)+++def test_startup_chain_does_not_eagerly_import_text_splitters():+ """The startup import chain must not pull in langchain_text_splitters."""+ result = subprocess.run(+ [sys.executable, "-c", _DRIVER],+ capture_output=True,+ text=True,+ timeout=120,+ )+ assert result.returncode == 0, (+ "Boot-lightness regression: a module on the app-startup chain now "+ "eagerly imports the heavy text-splitter stack. Keep the "+ "langchain_text_splitters import lazy (inside get_text_splitter).\n"+ f"stdout: {result.stdout}\nstderr: {result.stderr[-1500:]}"+ )+ assert "OK" in result.stdoutdiff --git a/tests/embeddings/splitters/test_text_splitter_concurrency.py b/tests/embeddings/splitters/test_text_splitter_concurrency.pynew file mode 100644index 0000000000..08b941d87c--- /dev/null+++ b/tests/embeddings/splitters/test_text_splitter_concurrency.py@@ -0,0 +1,83 @@+"""Concurrency regression test for ``get_text_splitter``.++``get_text_splitter`` imports ``langchain_text_splitters`` lazily (to keep the+heavy torch/sentence-transformers stack off the app-startup path). That+package's ``__init__`` eagerly imports ~14 splitter submodules with enough+internal cross-referencing that a *cold* import from several threads at once+can observe a partially-initialized package and raise+``ImportError: cannot import name ... from partially initialized module``.++The RAG auto-index ``ThreadPoolExecutor`` and the per-user document scheduler+both build ``LibraryRAGService`` (→ ``get_text_splitter``) from multiple worker+threads, so this is reachable in production after a restart. ``get_text_splitter``+serializes the cold import behind a module-level lock to prevent it.++This must run in a *fresh* interpreter: inside the pytest process+``langchain_text_splitters`` is already imported (warm), so the race window is+gone. We therefore exercise it in a subprocess. Without the lock this fails+deterministically (~2 of 16 threads raise); with it, all threads succeed.+"""++import subprocess+import sys+import textwrap++import pytest++# allow: no-sut-import — the SUT (get_text_splitter) is imported inside the+# subprocess driver below, because the cold-import race only reproduces in a+# fresh interpreter (it is already warm in the pytest process).++# Driver run in a fresh interpreter: 16 threads, barrier-synced so they all hit+# the cold ``langchain_text_splitters`` import simultaneously. recursive/token+# only — both trigger the package init (the race source) without the+# sentence-transformers model download.+_DRIVER = textwrap.dedent(+ """+ import sys+ import threading++ from local_deep_research.embeddings.splitters import get_text_splitter++ N = 16+ barrier = threading.Barrier(N)+ errors = []++ def worker(i):+ splitter_type = ("recursive", "token")[i % 2]+ try:+ barrier.wait()+ get_text_splitter(+ splitter_type, chunk_size=128, chunk_overlap=10+ )+ except Exception as exc: # noqa: BLE001 - report any failure+ errors.append(f"{type(exc).__name__}: {exc}")++ threads = [threading.Thread(target=worker, args=(i,)) for i in range(N)]+ for t in threads:+ t.start()+ for t in threads:+ t.join()++ if errors:+ print(f"FAIL {len(errors)}/{N}: {errors[0]}")+ sys.exit(1)+ print("OK")+ """+)+++def test_get_text_splitter_concurrent_cold_import_is_safe():+ """Concurrent first-calls must not race on the lazy package import."""+ result = subprocess.run(+ [sys.executable, "-c", _DRIVER],+ capture_output=True,+ text=True,+ timeout=180,+ )+ assert result.returncode == 0, (+ "Concurrent get_text_splitter cold-import raced.\n"+ f"stdout: {result.stdout}\nstderr: {result.stderr[-2000:]}"+ )+ assert "OK" in result.stdoutdiff --git a/tests/embeddings/splitters/test_text_splitter_edge_cases.py b/tests/embeddings/splitters/test_text_splitter_edge_cases.pyindex 9f32ec2997..bbb1c1e316 100644--- a/tests/embeddings/splitters/test_text_splitter_edge_cases.py+++ b/tests/embeddings/splitters/test_text_splitter_edge_cases.py@@ -78,8 +78,12 @@ class TestNormalizationAcrossTypes:"""from unittest.mock import patch as _patch+ # ``get_text_splitter`` imports this class lazily (function-local) so+ # the heavy langchain_text_splitters/torch stack stays off the+ # app-startup path — patch it at its source module, which is where+ # the function-local ``from ... import`` resolves it.with _patch(- "local_deep_research.embeddings.splitters.text_splitter_registry.SentenceTransformersTokenTextSplitter"+ "langchain_text_splitters.sentence_transformers.SentenceTransformersTokenTextSplitter") as mock_cls:mock_cls.return_value = MagicMock()get_text_splitter(" Sentence ")