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(api): isolate long research from auth workers (#7090)

LearningCircuit7285f497a491
diff --git a/changelog.d/5921.bugfix.md b/changelog.d/5921.bugfix.md
new file mode 100644
index 0000000000..f9a3df10d2
--- /dev/null
+++ b/changelog.d/5921.bugfix.md
@@ -0,0 +1 @@
+Isolated long API v1 research calls from authenticated-request database checks so concurrent reports cannot exhaust their shared worker pool.
diff --git a/src/local_deep_research/web/dependencies/threadpool.py b/src/local_deep_research/web/dependencies/threadpool.py
index 3f5a650239..393a1a1a0a 100644
--- a/src/local_deep_research/web/dependencies/threadpool.py
+++ b/src/local_deep_research/web/dependencies/threadpool.py
@@ -12,16 +12,21 @@ mixing at worst).
``WorkerCleanupAPIRoute`` supplies that owner-thread boundary for plain
``def`` endpoints. ``WorkerCleanupStreamingResponse`` supplies it for each
-worker that advances a synchronous response body, and ``run_db_sync`` does
-the same for explicit ``asyncio.to_thread`` DB work inside asynchronous
-endpoints.
+worker that advances a synchronous response body. ``run_db_sync`` and
+``run_research_sync`` do the same for explicit DB work dispatched from
+asynchronous endpoints. Long research calls use a separate executor so
+they cannot fill the default executor used by authenticated requests.
"""
from __future__ import annotations
import asyncio
+import atexit
import functools
+import threading
from collections.abc import AsyncIterable, Iterable, Iterator
+from concurrent.futures import ThreadPoolExecutor
+from contextvars import copy_context
from typing import TYPE_CHECKING, Any, Callable, TypeVar
from fastapi.encoders import jsonable_encoder
@@ -36,6 +41,36 @@ T = TypeVar("T")
_WORKER_CLEANUP_MARKER = "__ldr_worker_thread_cleanup__"
+# Long API v1 research calls must not occupy asyncio's default executor:
+# every authenticated request uses that executor to open/check its user DB.
+# Keep this pool separate from the short DB dispatches in run_db_sync.
+_API_RESEARCH_WORKERS = 8
+_api_research_executor: ThreadPoolExecutor | None = None
+_api_research_executor_lock = threading.Lock()
+
+
+def _get_api_research_executor() -> ThreadPoolExecutor:
+ global _api_research_executor
+ with _api_research_executor_lock:
+ if _api_research_executor is None:
+ _api_research_executor = ThreadPoolExecutor(
+ max_workers=_API_RESEARCH_WORKERS,
+ thread_name_prefix="ldr-api-research",
+ )
+ return _api_research_executor
+
+
+def _shutdown_api_research_executor() -> None:
+ global _api_research_executor
+ with _api_research_executor_lock:
+ executor = _api_research_executor
+ _api_research_executor = None
+ if executor is not None:
+ executor.shutdown(wait=True, cancel_futures=True)
+
+
+atexit.register(_shutdown_api_research_executor)
+
def wrap_sync_route_with_cleanup(dependant: "Dependant") -> None:
"""Wrap a synchronous FastAPI endpoint in an owner-thread cleanup.
@@ -309,17 +344,12 @@ def prepare_router_for_worker_cleanup(router: APIRouter) -> None:
wrap_sync_route_with_cleanup(route.dependant)
-async def run_db_sync(fn: Callable[..., T], /, *args: Any, **kwargs: Any) -> T:
- """Run a sync DB-touching function on the asyncio default
- threadpool, then clean up the worker's thread-local DB session.
-
- Use this in place of ``await asyncio.to_thread(fn, ...)`` when
- ``fn`` opens a ``get_user_db_session(...)`` block. If ``fn`` is
- purely CPU-bound and never opens a DB session, prefer
- ``asyncio.to_thread`` directly — the cleanup call is cheap but
- not free.
- """
-
+async def _run_db_sync(
+ fn: Callable[..., T],
+ args: tuple[Any, ...],
+ kwargs: dict[str, Any],
+ executor: ThreadPoolExecutor | None,
+) -> T:
def _wrapped() -> T:
try:
return fn(*args, **kwargs)
@@ -347,14 +377,13 @@ async def run_db_sync(fn: Callable[..., T], /, *args: Any, **kwargs: Any) -> T:
# and the stderr sink's default ``backtrace=True`` extends
# the trace upward through the executor frames. Today no
# displayed line names ``args`` (this frame's is the
- # ``cleanup_current_thread()`` call, and
- # ``asyncio.to_thread`` hands the executor a zero-argument
- # ``partial``, so ``_WorkItem.args`` is empty), but that is
- # an accident of which line raises, not a property anyone
- # maintains: any traceback formatted from inside a closure
- # holding a password is one refactor away from rendering
- # it, and the redaction-invariant test cannot catch this
- # call site. So: never ``logger.exception()`` here.
+ # ``cleanup_current_thread()`` call), but that is an accident
+ # of which line raises, not a property anyone maintains.
+ # Both the default and dedicated executors can change their
+ # call frames; a traceback from a closure holding a password
+ # is one refactor away from rendering it, and the
+ # redaction-invariant test cannot catch this call site.
+ # So: never ``logger.exception()`` here.
logger.debug(
"run_db_sync: cleanup_current_thread failed",
exc_info=True,
@@ -406,7 +435,34 @@ async def run_db_sync(fn: Callable[..., T], /, *args: Any, **kwargs: Any) -> T:
exc_info=True,
)
- return await asyncio.to_thread(_wrapped)
+ if executor is None:
+ return await asyncio.to_thread(_wrapped)
+ # run_in_executor does not copy contextvars as asyncio.to_thread does.
+ # The research pipeline needs its request owner and egress scope there.
+ context = copy_context()
+ return await asyncio.get_running_loop().run_in_executor(
+ executor, context.run, _wrapped
+ )
+
+
+async def run_db_sync(fn: Callable[..., T], /, *args: Any, **kwargs: Any) -> T:
+ """Run short sync DB work on the default executor with worker cleanup.
+
+ Use this in place of ``await asyncio.to_thread(fn, ...)`` when ``fn``
+ opens a per-user DB session. Long research calls use
+ :func:`run_research_sync` so they cannot starve authenticated requests.
+ """
+ return await _run_db_sync(fn, args, kwargs, None)
+
+
+async def run_research_sync(
+ fn: Callable[..., T], /, *args: Any, **kwargs: Any
+) -> T:
+ """Run long DB-touching research on its own eight-worker executor.
+
+ Preserves the caller's contextvars and cleans worker thread-local state.
+ """
+ return await _run_db_sync(fn, args, kwargs, _get_api_research_executor())
__all__ = [
@@ -415,5 +471,6 @@ __all__ = [
"iterate_sync_with_cleanup",
"prepare_router_for_worker_cleanup",
"run_db_sync",
+ "run_research_sync",
"wrap_sync_route_with_cleanup",
]
diff --git a/src/local_deep_research/web/routers/api_v1.py b/src/local_deep_research/web/routers/api_v1.py
index 1d9f2b7bcd..058226656c 100644
--- a/src/local_deep_research/web/routers/api_v1.py
+++ b/src/local_deep_research/web/routers/api_v1.py
@@ -30,7 +30,7 @@ from ..dependencies.rate_limit import (
api_rate_limit,
set_request_api_rate_limit,
)
-from ..dependencies.threadpool import run_db_sync
+from ..dependencies.threadpool import run_db_sync, run_research_sync
from ..routes.research_validation import (
ITERATIONS_MAX,
ITERATIONS_MIN,
@@ -1126,10 +1126,10 @@ async def api_quick_summary(
try:
from ...api.research_functions import quick_summary
- # run_db_sync (not raw to_thread): the research call opens per-user
- # DB sessions (metrics writes, local-collection search) on the worker
- # thread; to_thread reuses workers and would leak the session.
- result = await run_db_sync(quick_summary, query, **params)
+ # Keep long research calls off the default executor used by every
+ # authenticated request's database check. The dedicated dispatch
+ # still cleans up worker-owned sessions and thread context.
+ result = await run_research_sync(quick_summary, query, **params)
# Serialize Document objects
converted = result.copy()
@@ -1254,9 +1254,8 @@ async def api_generate_report(
try:
from ...api.research_functions import generate_report
- # run_db_sync: see quick_summary — offload with thread-local session
- # cleanup, not a bare to_thread.
- result = await run_db_sync(generate_report, query, **params)
+ # See quick_summary: isolate long research from login DB checks.
+ result = await run_research_sync(generate_report, query, **params)
if (
result
@@ -1373,9 +1372,8 @@ async def api_analyze_documents(
from ...security.egress.policy import PolicyDeniedError
try:
- # run_db_sync: analyze_documents runs local-collection search which
- # opens the per-user DB session on the worker thread.
- result = await run_db_sync(
+ # Local-collection search can also be long-running.
+ result = await run_research_sync(
analyze_documents, query, collection_name, **params
)
# CWE-209 / CodeQL #8019: same boundary scrub as api_quick_summary.
diff --git a/tests/web/test_api_v1_research_executor.py b/tests/web/test_api_v1_research_executor.py
new file mode 100644
index 0000000000..272dad78c6
--- /dev/null
+++ b/tests/web/test_api_v1_research_executor.py
@@ -0,0 +1,135 @@
+"""Long API v1 research must leave the default auth/DB executor available."""
+
+import asyncio
+import threading
+from concurrent.futures import ThreadPoolExecutor
+from contextvars import ContextVar
+from unittest.mock import patch
+
+import pytest
+
+from local_deep_research.config.thread_settings import (
+ get_settings_context,
+ set_settings_context,
+)
+from local_deep_research.web.dependencies import threadpool
+
+
+ ("path", "target", "body", "result"),
+ [
+ (
+ "/api/v1/quick_summary",
+ "local_deep_research.api.research_functions.quick_summary",
+ {"query": "q"},
+ {"summary": "ok", "findings": []},
+ ),
+ (
+ "/api/v1/generate_report",
+ "local_deep_research.api.research_functions.generate_report",
+ {"query": "q"},
+ {"content": "ok", "metadata": {}},
+ ),
+ (
+ "/api/v1/analyze_documents",
+ "local_deep_research.web.routers.api_v1.analyze_documents",
+ {"query": "q", "collection_name": "Library"},
+ {"summary": "ok"},
+ ),
+ ],
+)
+def test_research_routes_use_the_dedicated_workers(
+ authenticated_client, path, target, body, result
+):
+ observed_threads = []
+
+ def fake_research(*args, **kwargs):
+ observed_threads.append(threading.current_thread().name)
+ return result
+
+ with patch(target, side_effect=fake_research):
+ response = authenticated_client.post(path, json=body)
+
+ assert response.status_code == 200, response.text[:300]
+ assert len(observed_threads) == 1
+ assert observed_threads[0].startswith("ldr-api-research"), observed_threads
+
+
+def test_research_does_not_starve_a_single_default_db_worker(monkeypatch):
+ entered = threading.Event()
+ release = threading.Event()
+ research_pool = ThreadPoolExecutor(max_workers=1)
+ monkeypatch.setattr(
+ threadpool, "_get_api_research_executor", lambda: research_pool
+ )
+
+ def hold_research_worker():
+ entered.set()
+ assert release.wait(timeout=10), "research worker was not released"
+
+ async def scenario():
+ loop = asyncio.get_running_loop()
+ loop.set_default_executor(ThreadPoolExecutor(max_workers=1))
+ research = asyncio.create_task(
+ threadpool.run_research_sync(hold_research_worker)
+ )
+ try:
+ for _ in range(200):
+ if entered.is_set():
+ break
+ await asyncio.sleep(0.01)
+ assert entered.is_set(), "research did not start"
+ # This models ensure_user_database on an authenticated request.
+ assert (
+ await asyncio.wait_for(
+ threadpool.run_db_sync(lambda: "auth-ready"), timeout=3
+ )
+ == "auth-ready"
+ )
+ finally:
+ release.set()
+ await asyncio.wait_for(research, timeout=10)
+
+ try:
+ asyncio.run(scenario())
+ finally:
+ release.set()
+ research_pool.shutdown(wait=True)
+
+
+def test_research_dispatch_copies_request_context_and_clears_worker_state(
+ monkeypatch,
+):
+ research_pool = ThreadPoolExecutor(max_workers=1)
+ monkeypatch.setattr(
+ threadpool, "_get_api_research_executor", lambda: research_pool
+ )
+ owner = ContextVar("api_research_owner", default=None)
+
+ async def scenario():
+ token = owner.set("alice")
+ try:
+
+ def first_call():
+ set_settings_context({"secret": "alice"})
+ return threading.get_ident(), owner.get()
+
+ first_thread, seen_owner = await threadpool.run_research_sync(
+ first_call
+ )
+ second_thread, settings = await threadpool.run_research_sync(
+ lambda: (threading.get_ident(), get_settings_context())
+ )
+ return first_thread, second_thread, seen_owner, settings
+ finally:
+ owner.reset(token)
+
+ try:
+ first_thread, second_thread, seen_owner, settings = asyncio.run(
+ scenario()
+ )
+ finally:
+ research_pool.shutdown(wait=True)
+ assert first_thread == second_thread
+ assert seen_owner == "alice"
+ assert settings is None