~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: add resource cleanup for SQLAlchemy engines, HTTP sessions, and subprocesses
LearningCircuit94e0385eb2fc
diff --git a/src/local_deep_research/library/download_management/database_init.py b/src/local_deep_research/library/download_management/database_init.pyindex 435d907993..efa096aca0 100644--- a/src/local_deep_research/library/download_management/database_init.py+++ b/src/local_deep_research/library/download_management/database_init.py@@ -4,7 +4,7 @@ Database Initialization for Download ManagementCreates the necessary database tables for tracking download status and retry logic."""-from sqlalchemy import create_engine+from sqlalchemy import create_engine, inspectfrom loguru import loggerfrom .models import Base@@ -16,11 +16,19 @@ def init_database():# Create engine - use same path as research_library moduleengine = create_engine("sqlite:///data/research_library.db")- # Create tables- Base.metadata.create_all(engine)+ try:+ # Create tables+ Base.metadata.create_all(engine)+ logger.info(+ "Download management database tables initialized successfully"+ )+ finally:+ # Always dispose engine to prevent file descriptor leaks+ engine.dispose()- logger.info("Download management database tables initialized successfully")- return engine+ # Return None since engine is disposed - callers should create their own+ # engine/session if they need to interact with the database+ return Nonedef verify_table_exists():@@ -28,15 +36,20 @@ def verify_table_exists():engine = create_engine("sqlite:///data/research_library.db")- # Check if table exists- inspector = engine.dialect.get_table_names(engine)-- if "resource_download_status" in inspector:- logger.info("✓ resource_download_status table exists")- return True- else:- logger.warning("✗ resource_download_status table missing")- return False+ try:+ # Check if table exists using SQLAlchemy's inspect function+ inspector = inspect(engine)+ table_names = inspector.get_table_names()++ if "resource_download_status" in table_names:+ logger.info("✓ resource_download_status table exists")+ return True+ else:+ logger.warning("✗ resource_download_status table missing")+ return False+ finally:+ # Always dispose engine to prevent file descriptor leaks+ engine.dispose()if __name__ == "__main__":diff --git a/src/local_deep_research/research_library/downloaders/base.py b/src/local_deep_research/research_library/downloaders/base.pyindex 1d289107ab..aebb496ac4 100644--- a/src/local_deep_research/research_library/downloaders/base.py+++ b/src/local_deep_research/research_library/downloaders/base.py@@ -54,6 +54,34 @@ class BaseDownloader(ABC):programmatic_mode=False # We want to persist rate limit data)+ def close(self):+ """+ Close the HTTP session and clean up resources.++ Call this method when done using the downloader to prevent+ connection/file descriptor leaks.+ """+ if hasattr(self, "session") and self.session:+ try:+ self.session.close()+ except Exception:+ logger.exception("Error closing downloader session")+ finally:+ self.session = None++ def __del__(self):+ """Destructor to ensure session is closed."""+ self.close()++ def __enter__(self):+ """Context manager entry."""+ return self++ def __exit__(self, exc_type, exc_val, exc_tb):+ """Context manager exit - ensures session cleanup."""+ self.close()+ return False+@abstractmethoddef can_handle(self, url: str) -> bool:"""diff --git a/src/local_deep_research/utilities/search_cache.py b/src/local_deep_research/utilities/search_cache.pyindex 41af753680..52ebe608f7 100644--- a/src/local_deep_research/utilities/search_cache.py+++ b/src/local_deep_research/utilities/search_cache.py@@ -434,6 +434,26 @@ class SearchCache:logger.exception("Failed to clear search cache")return False+ def dispose(self):+ """+ Dispose of the database engine and clean up resources.++ Call this method during application shutdown to prevent file descriptor leaks.+ After calling dispose(), this cache instance should no longer be used.+ """+ if hasattr(self, "engine") and self.engine:+ try:+ self.engine.dispose()+ logger.debug("SearchCache engine disposed")+ except Exception:+ logger.exception("Error disposing SearchCache engine")+ finally:+ self.engine = None++ def __del__(self):+ """Destructor to ensure engine is disposed."""+ self.dispose()+def get_stats(self) -> Dict[str, Any]:"""Get cache statistics."""try:diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex 34cf2e0a58..0b97d1add5 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -960,9 +960,17 @@ def open_file_location():# If it's a directory, just open itsubprocess.run(["explorer", str(file_path)], check=True)elif platform.system() == "Darwin": # macOS- subprocess.run(["open", str(file_path)], check=True)+ # Use start_new_session to fully detach subprocess+ subprocess.run(+ ["open", str(file_path)], start_new_session=True, check=True+ )else: # Linux and others- subprocess.run(["xdg-open", str(file_path.parent)], check=True)+ # Use start_new_session to fully detach subprocess+ subprocess.run(+ ["xdg-open", str(file_path.parent)],+ start_new_session=True,+ check=True,+ )return jsonify({"status": "success"})except Exception:diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex ccb492af77..3028144d8f 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -1781,12 +1781,18 @@ def open_file_location():file_path = resolved_path # Use resolved path going forward# Open the directory in the file explorer+ # Use subprocess.run with start_new_session to prevent zombie processes+ # and file descriptor leaks from unreleased Popen handlesif platform.system() == "Windows":- subprocess.Popen(["explorer", str(dir_path)])+ subprocess.run(["explorer", str(dir_path)], check=False)elif platform.system() == "Darwin": # macOS- subprocess.Popen(["open", str(dir_path)])+ subprocess.run(+ ["open", str(dir_path)], start_new_session=True, check=False+ )else: # Linux- subprocess.Popen(["xdg-open", str(dir_path)])+ subprocess.run(+ ["xdg-open", str(dir_path)], start_new_session=True, check=False+ )flash(f"Opening folder: {dir_path}", "success")except Exception as e:diff --git a/src/local_deep_research/web/services/socket_service.py b/src/local_deep_research/web/services/socket_service.pyindex cb9c7cfe5c..812b472f64 100644--- a/src/local_deep_research/web/services/socket_service.py+++ b/src/local_deep_research/web/services/socket_service.py@@ -188,6 +188,22 @@ class SocketIOService:if request.sid in self.__socket_subscriptions:del self.__socket_subscriptions[request.sid]self.__log_info(f"Removed subscription for client {request.sid}")++ # Clean up any thread-local database sessions that may have been+ # created during socket handler execution. This prevents file+ # descriptor leaks from unclosed SQLAlchemy sessions.+ try:+ from ...database.thread_local_session import (+ cleanup_current_thread,+ )++ cleanup_current_thread()+ except ImportError:+ pass # Module not available, skip cleanup+ except Exception:+ self.__log_exception(+ "Error cleaning up thread session on disconnect"+ )except Exception as e:self.__log_exception(f"Error handling disconnect: {e}")diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py b/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.pyindex d6846f07d1..749df1bb06 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py@@ -147,6 +147,34 @@ class SemanticScholarSearchEngine(BaseSearchEngine):return session+ def close(self):+ """+ Close the HTTP session and clean up resources.++ Call this method when done using the search engine to prevent+ connection/file descriptor leaks.+ """+ if hasattr(self, "session") and self.session:+ try:+ self.session.close()+ except Exception:+ logger.exception("Error closing SemanticScholar session")+ finally:+ self.session = None++ def __del__(self):+ """Destructor to ensure session is closed."""+ self.close()++ def __enter__(self):+ """Context manager entry."""+ return self++ def __exit__(self, exc_type, exc_val, exc_tb):+ """Context manager exit - ensures session cleanup."""+ self.close()+ return False+def _respect_rate_limit(self):"""Apply rate limiting between requests"""# Apply rate limiting before request