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: enforce parent-first langchain splitter imports (#6226)

Abarnaa Sree N83be9f0395c4
diff --git a/docs/release_notes/1.8.1.md b/docs/release_notes/1.8.1.md
index b1bc1e4b0e..c83b178285 100644
--- a/docs/release_notes/1.8.1.md
+++ b/docs/release_notes/1.8.1.md
@@ -170,7 +170,7 @@
- **LangGraph agent no longer crashes with `BadRequestError` on reasoning-mode LLMs.** `ProcessingLLMWrapper` (the central `<think>` stripper applied to every LLM returned by `get_llm`) previously let `bind_tools` bypass the stripper via its `__getattr__` shim, so `langgraph_agent_strategy.create_agent()` ended up calling the raw reasoning model. Qwen 3.x and deepseek-r1 then emitted `<think>…</think>` text directly inside tool-call `content`, which the OpenAI-compatible provider rejected with `400 Failed to parse input at pos 0: <think>…`. `bind_tools` is now overridden to re-wrap the tool-bound model so the stripper survives the agent tool-binding step (#4804). ([#4804](https://github.com/LearningCircuit/local-deep-research/pull/4804))
- **TinyFish search engine no longer logs your search query on request errors.** When a TinyFish Search/Fetch call failed, the request exception (which embeds the query in the URL) was written to the error log; failures now record only a static message plus the HTTP status. Also restores `ruff format` on the TinyFish test files so the pre-commit gate passes. ([#4806](https://github.com/LearningCircuit/local-deep-research/pull/4806))
- **Star Reviews announces the real load error to screen readers.** A failed refresh now speaks the actual error message via the dashboard's live region instead of a generic "failed to load", and a no-op clear that never re-announced was removed. ([#4828](https://github.com/LearningCircuit/local-deep-research/pull/4828))
-- 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. ([#4829](https://github.com/LearningCircuit/local-deep-research/pull/4829))
+- Server startup no longer eagerly imports the heavy `langchain_text_splitters`/sentence-transformers stack; it is loaded lazily on the RAG indexing path instead. This speeds up boot and fixes intermittent UI-test server-start failures. ([#4829](https://github.com/LearningCircuit/local-deep-research/pull/4829))
- Journal-quality data downloads now follow OpenAlex's 2026-06 "standard-format" snapshot layout (`data/jsonl/<entity>/manifest.json`). The previous paths started returning 404, breaking the OpenAlex sources and institutions downloads. ([#4830](https://github.com/LearningCircuit/local-deep-research/pull/4830))
- The manual **Run now** button and the manual overdue-subscription sweep now actually start research. Both previously made a server-internal loopback HTTP POST to `/research/api/start`, which sits on a CSRF-protected blueprint and so always failed with HTTP 400 ("CSRF token is missing") — the "Run now" button reported `Failed to start research: 400`. They now invoke the research handler in-process, bypassing the HTTP/CSRF layer while still resolving the user's encrypted-database credentials. (Scheduled subscription runs were unaffected.) ([#4834](https://github.com/LearningCircuit/local-deep-research/pull/4834))
- A failed `commit()`/`flush()` inside a `get_user_db_session()` block no longer poisons the thread's reused database session. The context manager now rolls the session back (and re-raises) when the block errors, so a single failed transaction can't cascade `PendingRollbackError` into every later operation on that thread. Paths that catch and swallow such a failure while reusing the session are also recovered explicitly: a PDF download or text extraction that fails mid-write, and a multi-file library upload where one bad file would otherwise fail the whole batch. ([#4841](https://github.com/LearningCircuit/local-deep-research/pull/4841))
diff --git a/src/local_deep_research/embeddings/splitters/bounded_semantic_chunker.py b/src/local_deep_research/embeddings/splitters/bounded_semantic_chunker.py
index 1ac6fcd8bc..d4af591c5b 100644
--- a/src/local_deep_research/embeddings/splitters/bounded_semantic_chunker.py
+++ b/src/local_deep_research/embeddings/splitters/bounded_semantic_chunker.py
@@ -34,14 +34,11 @@ class BoundedSemanticChunker(BaseDocumentTransformer):
"""Create recursive pre- and post-semantic bounding stages.
Note:
- This constructor performs a submodule import from
- ``langchain_text_splitters.character``. Callers (such as
- ``get_text_splitter``) must ensure the parent package
- ``langchain_text_splitters`` has already been warmed up
- parent-first (under ``_LANGCHAIN_TEXT_SPLITTERS_IMPORT_LOCK``)
- to prevent CPython ``_DeadlockError`` from submodule-first import
- order inversion during concurrent cold starts.
+ The parent ``langchain_text_splitters`` package is imported before
+ its ``character`` submodule to preserve the parent-first import
+ invariant required for safe concurrent cold imports.
"""
+ import langchain_text_splitters # noqa: F401
from langchain_text_splitters.character import (
RecursiveCharacterTextSplitter,
)
diff --git a/src/local_deep_research/embeddings/splitters/text_splitter_registry.py b/src/local_deep_research/embeddings/splitters/text_splitter_registry.py
index ca3c21a884..60f4c12c15 100644
--- a/src/local_deep_research/embeddings/splitters/text_splitter_registry.py
+++ b/src/local_deep_research/embeddings/splitters/text_splitter_registry.py
@@ -8,7 +8,6 @@ based on configuration, similar to how embeddings_config.py works for embeddings
from __future__ import annotations
import re
-import threading
from typing import Optional, List, Any, TYPE_CHECKING
from loguru import logger
@@ -33,19 +32,14 @@ from ...constants import (
# 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. In CPython,
-# concurrent submodule-first imports (e.g. two threads importing different
-# concrete submodules like ``langchain_text_splitters.character`` and
-# ``langchain_text_splitters.base`` before the parent package is initialized)
-# cause import lock order inversion, raising ``_DeadlockError`` or deadlocking
-# during package initialization.
+# ``langchain_text_splitters`` must always be imported parent-first before
+# importing any of its submodules. In CPython, concurrent submodule-first
+# imports can create import-lock order inversion and raise ``_DeadlockError``.
#
-# The load-bearing fix is the parent-first import invariant: warming the
-# parent package (``import langchain_text_splitters``) once under this lock
-# executes package ``__init__`` and populates ``sys.modules`` before any
-# thread performs submodule-level imports. Once warm, subsequent submodule
-# imports are fast dictionary lookups and the lock is uncontended.
-_LANGCHAIN_TEXT_SPLITTERS_IMPORT_LOCK = threading.Lock()
+# Keep these imports function-local and lazy so the package stays off the
+# application startup path. The AST guard in the test suite enforces that
+# every source import of ``langchain_text_splitters.<submodule>`` has a
+# parent-package import earlier in the same executable scope.
if TYPE_CHECKING:
from langchain_core.embeddings import Embeddings
@@ -107,14 +101,12 @@ def get_text_splitter(
# importing the package eagerly pulls torch/sentence-transformers and
# must stay off the app-startup import path.
#
- # Enforce the parent-first import invariant: warm the parent package
- # under the lock before any submodule-level imports occur. Non-semantic
- # branches warm it here; the semantic branch warms it below only after
- # embeddings and dependency validation, before constructing its
- # BoundedSemanticChunker (which imports langchain_text_splitters.character).
+ # Enforce the parent-first import invariant before any submodule-level
+ # imports occur. Non-semantic branches warm it here; the semantic branch
+ # warms it below after dependency validation and before constructing its
+ # BoundedSemanticChunker.
if splitter_type != "semantic":
- with _LANGCHAIN_TEXT_SPLITTERS_IMPORT_LOCK:
- import langchain_text_splitters # noqa: F401
+ import langchain_text_splitters # noqa: F401
if splitter_type == "token":
from langchain_text_splitters.base import TokenTextSplitter
@@ -188,11 +180,9 @@ def get_text_splitter(
) from e
# Enforce the parent-first import invariant before constructing
- # BoundedSemanticChunker: BoundedSemanticChunker.__init__ imports
- # langchain_text_splitters.character. Warming the parent package here
- # ensures sys.modules is populated and prevents CPython _DeadlockError.
- with _LANGCHAIN_TEXT_SPLITTERS_IMPORT_LOCK:
- import langchain_text_splitters # noqa: F401
+ # BoundedSemanticChunker.__init__ imports
+ # langchain_text_splitters.character, so warm the parent package first.
+ import langchain_text_splitters # noqa: F401
from .bounded_semantic_chunker import BoundedSemanticChunker
diff --git a/tests/embeddings/splitters/test_lazy_import_guard.py b/tests/embeddings/splitters/test_lazy_import_guard.py
index c0131d5670..ddc524ccf8 100644
--- a/tests/embeddings/splitters/test_lazy_import_guard.py
+++ b/tests/embeddings/splitters/test_lazy_import_guard.py
@@ -16,10 +16,20 @@ test"). It must run in a fresh interpreter: inside the pytest process
assertion would be meaningless.
"""
+import ast
+import pathlib
import subprocess
import sys
import textwrap
+_SRC_ROOT = pathlib.Path(__file__).parents[3] / "src"
+
+
+def _iter_source_files():
+ """Yield every Python source file under ``src/``."""
+ yield from sorted(_SRC_ROOT.rglob("*.py"))
+
+
# 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).
@@ -60,3 +70,113 @@ def test_startup_chain_does_not_eagerly_import_text_splitters():
f"stdout: {result.stdout}\nstderr: {result.stderr[-1500:]}"
)
assert "OK" in result.stdout
+
+
+def _iter_executable_scopes(tree):
+ """Yield executable scopes without crossing nested scopes."""
+ yield tree
+
+ def visit(node):
+ for child in ast.iter_child_nodes(node):
+ if isinstance(
+ child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)
+ ):
+ yield child
+ yield from visit(child)
+ else:
+ yield from visit(child)
+
+ yield from visit(tree)
+
+
+def _iter_imports_in_scope(scope):
+ """Yield imports in lexical order without entering nested scopes."""
+
+ def visit(node):
+ for child in ast.iter_child_nodes(node):
+ if isinstance(
+ child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)
+ ):
+ continue
+
+ if isinstance(child, (ast.Import, ast.ImportFrom)):
+ yield child
+ else:
+ yield from visit(child)
+
+ yield from visit(scope)
+
+
+def _scope_import_violations(scope):
+ """Return submodule imports without an earlier parent import."""
+ parent_imported = False
+ violations = []
+
+ for node in _iter_imports_in_scope(scope):
+ if isinstance(node, ast.Import):
+ for alias in node.names:
+ if alias.name == "langchain_text_splitters":
+ parent_imported = True
+ elif alias.name.startswith("langchain_text_splitters."):
+ if not parent_imported:
+ violations.append(node.lineno)
+
+ elif isinstance(node, ast.ImportFrom):
+ module = node.module or ""
+ if module.startswith("langchain_text_splitters."):
+ if not parent_imported:
+ violations.append(node.lineno)
+
+ return violations
+
+
+def test_langchain_text_splitter_imports_are_parent_first():
+ """Every splitter submodule import must follow a parent import in its scope."""
+ scanned = 0
+ violations = []
+
+ for path in _iter_source_files():
+ scanned += 1
+ tree = ast.parse(
+ path.read_text(encoding="utf-8"),
+ filename=str(path),
+ )
+
+ for scope in _iter_executable_scopes(tree):
+ for lineno in _scope_import_violations(scope):
+ violations.append(f"{path}:{lineno}")
+
+ assert scanned > 0, "AST sweep found no Python source files"
+ assert violations == [], (
+ "langchain_text_splitters submodule imports must be preceded by "
+ "a parent-package import in the same executable scope: "
+ + ", ".join(violations)
+ )
+
+
+def test_langchain_text_splitter_import_guard_rejects_import_submodule_first():
+ """The AST guard must reject dotted imports before the parent package."""
+ tree = ast.parse(
+ """
+import langchain_text_splitters.character
+import langchain_text_splitters
+"""
+ )
+
+ violations = _scope_import_violations(tree)
+
+ assert violations == [2]
+
+
+def test_langchain_text_splitter_import_guard_rejects_from_import_submodule_first():
+ """The AST guard must reject from-imports before the parent package."""
+ tree = ast.parse(
+ """
+from langchain_text_splitters.character import RecursiveCharacterTextSplitter
+import langchain_text_splitters
+"""
+ )
+
+ violations = _scope_import_violations(tree)
+
+ assert violations == [2]