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.

refactor: centralize thread cleanup into @thread_cleanup decorator (#2499)

LearningCircuit9161c1a607ea
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_service.py b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
index bd8c916471..60f466101a 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_service.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
@@ -22,6 +22,7 @@ from ...web.services.socket_service import SocketIOService
from ..datasets import load_dataset
from ..graders import extract_answer_from_response, grade_single_result
from ..runners import format_query
+from ...database.thread_local_session import thread_cleanup
class BenchmarkTaskStatus(Enum):
@@ -371,6 +372,7 @@ class BenchmarkService:
session.commit()
return False
+ @thread_cleanup
def _run_benchmark_thread(self, benchmark_run_id: int):
"""Main benchmark execution thread."""
# IMPORTANT: This runs in a background thread, so we cannot access the user database
@@ -421,10 +423,7 @@ class BenchmarkService:
settings_context = SettingsContext(settings_snapshot, username)
# Set the context in thread-local storage
- from ...config.thread_settings import (
- clear_settings_context,
- set_settings_context,
- )
+ from ...config.thread_settings import set_settings_context
set_settings_context(settings_context)
@@ -609,21 +608,6 @@ class BenchmarkService:
"error_message": str(e),
}
finally:
- # Clear thread-local settings context to prevent leaks
- clear_settings_context()
-
- # Clean up thread-local database session and NullPool engine.
- # Benchmark threads may create DB sessions during task processing;
- # without cleanup, engines accumulate leaking ~3 FDs each.
- try:
- from ...database.thread_local_session import (
- cleanup_current_thread,
- )
-
- cleanup_current_thread()
- except Exception:
- pass
-
# Clean up active run tracking
if benchmark_run_id in self.active_runs:
# Mark that thread is done but keep data for database update
diff --git a/src/local_deep_research/database/thread_local_session.py b/src/local_deep_research/database/thread_local_session.py
index cd21ae4550..8ced41547e 100644
--- a/src/local_deep_research/database/thread_local_session.py
+++ b/src/local_deep_research/database/thread_local_session.py
@@ -3,6 +3,7 @@ Thread-local database session management.
Each thread gets its own database session that persists for the thread's lifetime.
"""
+import functools
import threading
from typing import Optional, Dict, Tuple
from sqlalchemy import text
@@ -186,6 +187,38 @@ def cleanup_current_thread():
thread_session_manager.cleanup_thread()
+def thread_cleanup(func):
+ """Decorator ensuring all thread-local resources are cleaned up when func exits.
+
+ Use on any function that runs in a background thread, ThreadPoolExecutor,
+ or APScheduler job.
+ """
+
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ try:
+ return func(*args, **kwargs)
+ finally:
+ try:
+ cleanup_current_thread()
+ except Exception:
+ pass
+ try:
+ from ..config.thread_settings import clear_settings_context
+
+ clear_settings_context()
+ except Exception:
+ pass
+ try:
+ from ..utilities.thread_context import clear_search_context
+
+ clear_search_context()
+ except Exception:
+ pass
+
+ return wrapper
+
+
# Context manager for automatic cleanup
class ThreadSessionContext:
"""
diff --git a/src/local_deep_research/news/subscription_manager/scheduler.py b/src/local_deep_research/news/subscription_manager/scheduler.py
index 7896c28a35..9f9183059d 100644
--- a/src/local_deep_research/news/subscription_manager/scheduler.py
+++ b/src/local_deep_research/news/subscription_manager/scheduler.py
@@ -16,6 +16,7 @@ from local_deep_research.settings.logger import log_settings
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.base import JobLookupError
from ...constants import ResearchStatus
+from ...database.thread_local_session import thread_cleanup
# RAG indexing imports
from ...research_library.services.library_rag_service import LibraryRAGService
@@ -604,6 +605,7 @@ class NewsScheduler:
f"Error scheduling document processing for {username}"
)
+ @thread_cleanup
def _process_user_documents(self, username: str):
"""Process documents for a user."""
logger.info(f"[DOC_SCHEDULER] Processing documents for user {username}")
@@ -963,11 +965,6 @@ class NewsScheduler:
logger.exception(
f"[DOC_SCHEDULER] Error processing documents for user {username}"
)
- finally:
- # Clean up thread-local session after job completes
- from ...database.thread_local_session import cleanup_current_thread
-
- cleanup_current_thread()
def get_document_scheduler_status(self, username: str) -> Dict[str, Any]:
"""Get document scheduler status for a specific user."""
@@ -1064,6 +1061,7 @@ class NewsScheduler:
)
return False
+ @thread_cleanup
def _check_user_overdue_subscriptions(self, username: str):
"""Check and immediately run any overdue subscriptions for a user."""
try:
@@ -1121,12 +1119,8 @@ class NewsScheduler:
logger.exception(
f"Error checking overdue subscriptions for {username}"
)
- finally:
- # Clean up thread-local session after job completes
- from ...database.thread_local_session import cleanup_current_thread
-
- cleanup_current_thread()
+ @thread_cleanup
def _check_subscription(self, username: str, subscription_id: int):
"""Check and refresh a single subscription."""
logger.info(
@@ -1217,23 +1211,12 @@ class NewsScheduler:
except Exception:
logger.exception(f"Error checking subscription {subscription_id}")
- finally:
- # Clean up thread-local session after job completes
- from ...database.thread_local_session import cleanup_current_thread
-
- cleanup_current_thread()
def _trigger_subscription_research_sync(
self, username: str, subscription: Dict[str, Any]
):
"""Trigger research for a subscription using programmatic API."""
- # Import clear_settings_context before try so it is always
- # available in the finally block, even if an early return or
- # exception occurs before the lazy imports inside try.
- from ...config.thread_settings import (
- clear_settings_context,
- set_settings_context,
- )
+ from ...config.thread_settings import set_settings_context
try:
# Get user's password from session info
@@ -1366,19 +1349,6 @@ class NewsScheduler:
logger.exception(
f"Error triggering research for subscription {subscription['id']}"
)
- finally:
- clear_settings_context()
- # Defensive: clean up thread-local database session.
- # Caller (_check_subscription) also has cleanup, but this ensures
- # the function is self-contained if called from other contexts.
- try:
- from ...database.thread_local_session import (
- cleanup_current_thread,
- )
-
- cleanup_current_thread()
- except Exception:
- pass
def _store_research_result(
self,
diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.py
index 5d0a45e6fc..9a6cae5c86 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -47,6 +47,7 @@ from ...database.models.library import (
EmbeddingProvider,
)
from ...database.models.queue import TaskMetadata
+from ...database.thread_local_session import thread_cleanup
from ...web.utils.rate_limiter import limiter
from ...config.paths import get_library_directory
@@ -2359,6 +2360,7 @@ def trigger_auto_index(
)
+@thread_cleanup
def _auto_index_documents_worker(
document_ids: list[str],
collection_id: str,
@@ -2400,18 +2402,9 @@ def _auto_index_documents_worker(
except Exception:
logger.exception("Auto-indexing worker failed")
- finally:
- # Clean up thread-local database session and NullPool engine.
- # This worker runs in a ThreadPoolExecutor; without cleanup,
- # engines accumulate in _thread_engines leaking ~3 FDs each.
- try:
- from ...database.thread_local_session import cleanup_current_thread
-
- cleanup_current_thread()
- except Exception:
- pass
+@thread_cleanup
def _background_index_worker(
task_id: str,
collection_id: str,
@@ -2567,15 +2560,6 @@ def _background_index_worker(
status="failed",
error_message=str(e),
)
- finally:
- # Clean up thread-local database session and NullPool engine.
- # Background indexing threads create DB sessions that leak ~3 FDs without this.
- try:
- from ...database.thread_local_session import cleanup_current_thread
-
- cleanup_current_thread()
- except Exception:
- pass
def _update_task_status(
diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.py
index a3c2f26036..cf1d1c47db 100644
--- a/src/local_deep_research/web/auth/routes.py
+++ b/src/local_deep_research/web/auth/routes.py
@@ -21,6 +21,7 @@ from loguru import logger
from ...database.auth_db import get_auth_db_session
from ...database.encrypted_db import db_manager
from ...database.models.auth import User
+from ...database.thread_local_session import thread_cleanup
from sqlalchemy.exc import IntegrityError
from ...utilities.threading_utils import thread_context, thread_with_app_context
from .session_manager import SessionManager
@@ -151,6 +152,7 @@ def login():
return redirect(url_for("index"))
+@thread_cleanup
def _perform_post_login_tasks(username: str, password: str) -> None:
"""Run non-critical post-login operations in a background thread.
@@ -249,15 +251,6 @@ def _perform_post_login_tasks(username: str, password: str) -> None:
logger.info(f"Post-login tasks completed for user {username}")
- # Clean up thread-local database session created during post-login DB operations.
- # This daemon thread opens NullPool engines that leak ~3 FDs without cleanup.
- try:
- from ...database.thread_local_session import cleanup_current_thread
-
- cleanup_current_thread()
- except Exception:
- pass
-
@auth_bp.route("/register", methods=["GET"])
def register_page():
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 45aed0cd46..7fa3ec7312 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -16,6 +16,7 @@ from ...config.search_config import get_search
from ...constants import ResearchStatus
from ...database.models import ResearchHistory, ResearchStrategy
from ...database.session_context import get_user_db_session
+from ...database.thread_local_session import thread_cleanup
from ...error_handling.report_generator import ErrorReportGenerator
from ...utilities.thread_context import set_search_context
from ...report_generator import IntegratedReportGenerator
@@ -285,6 +286,7 @@ def _generate_report_path(query: str) -> Path:
@log_for_research
+@thread_cleanup
def run_research_process(
research_id, query, mode, active_research, termination_flags, **kwargs
):
@@ -396,7 +398,6 @@ def run_research_process(
# Set the settings context for this thread
from ...config.thread_settings import (
- clear_settings_context,
set_settings_context,
)
@@ -1646,23 +1647,6 @@ def run_research_process(
research_id, active_research, termination_flags, username
)
- finally:
- # Clear thread-local contexts to prevent leaks when threads are reused
- from ...utilities.thread_context import clear_search_context
- from ...config.thread_settings import clear_settings_context
-
- clear_search_context()
- clear_settings_context()
-
- # Clean up thread-local database session and NullPool engine to prevent
- # FD leaks (~3 FDs per research run from WAL-mode SQLCipher).
- try:
- from ...database.thread_local_session import cleanup_current_thread
-
- cleanup_current_thread()
- except Exception:
- pass
-
def cleanup_research_resources(
research_id, active_research, termination_flags, username=None