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: minimal QueuePool with periodic dispose to prevent FD exhaustion (alternative) (#3340)

LearningCircuit94d4a580b50e
diff --git a/src/local_deep_research/database/auth_db.py b/src/local_deep_research/database/auth_db.py
index e972a88519..59cab447d7 100644
--- a/src/local_deep_research/database/auth_db.py
+++ b/src/local_deep_research/database/auth_db.py
@@ -72,12 +72,13 @@ def _get_auth_engine() -> Engine:
if not auth_db_path.exists():
init_auth_database()
- # Create engine with connection pooling
+ # Minimal pool — auth DB is unencrypted SQLite, low concurrency.
+ # See ADR-0004 for pool sizing rationale.
_auth_engine = create_engine(
f"sqlite:///{auth_db_path}",
poolclass=QueuePool,
- pool_size=5,
- max_overflow=10,
+ pool_size=1,
+ max_overflow=2,
pool_pre_ping=POOL_PRE_PING,
pool_recycle=POOL_RECYCLE_SECONDS,
echo=False,
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.py
index 6e98a56740..2caaf4a6f9 100644
--- a/src/local_deep_research/database/encrypted_db.py
+++ b/src/local_deep_research/database/encrypted_db.py
@@ -51,22 +51,47 @@ class DatabaseManager:
# Check SQLCipher availability
self.has_encryption = self._check_encryption_available()
- # Determine pool class based on environment
- # Use StaticPool for testing to avoid locking issues
+ # ----------------------------------------------------------------
+ # Pool class selection — see ADR-0004 (docs/decisions/0004-nullpool-for-sqlcipher.md)
+ #
+ # We use a minimal QueuePool (pool_size=1, max_overflow=2) for
+ # production and StaticPool for tests.
+ #
+ # Why minimal pool_size=1 instead of the default 10:
+ #
+ # 1. SQLCipher + WAL mode can leak file handles when connections
+ # close out of open-order. Fewer pooled connections = fewer
+ # opportunities for out-of-order closes during pool_recycle.
+ # See: https://github.com/sqlcipher/android-database-sqlcipher/issues/6
+ # See: https://github.com/dotnet/efcore/issues/35010
+ #
+ # 2. SQLite serializes all writes through a single file lock.
+ # Multiple pooled connections don't improve throughput — they
+ # just hold FDs (up to 3 per connection in WAL mode).
+ #
+ # 3. The cleanup scheduler periodically calls engine.dispose()
+ # to release all pooled connections, preventing long-lived
+ # handles from accumulating over days of idle operation.
+ #
+ # Why not NullPool: SQLCipher's PRAGMA key adds ~0.2ms per
+ # connection open. With 20-30 queries per page load, NullPool
+ # adds a noticeable 4-6ms overhead vs QueuePool's ~1.5ms.
+ # ----------------------------------------------------------------
self._use_static_pool = bool(os.environ.get("TESTING"))
self._pool_class = StaticPool if self._use_static_pool else QueuePool
def _get_pool_kwargs(self) -> Dict[str, Any]:
"""Get pool configuration kwargs based on pool type.
- StaticPool doesn't support pool_size or max_overflow,
- so we only include them for QueuePool.
+ StaticPool doesn't support pool_size or max_overflow.
+ QueuePool uses minimal sizing to limit FD usage.
+ See ADR-0004 for rationale.
"""
if self._use_static_pool:
return {}
return {
- "pool_size": 10,
- "max_overflow": 30, # Increase overflow so we don't run out of connections
+ "pool_size": 1,
+ "max_overflow": 2,
"pool_pre_ping": POOL_PRE_PING,
"pool_recycle": POOL_RECYCLE_SECONDS,
}
diff --git a/src/local_deep_research/database/pool_config.py b/src/local_deep_research/database/pool_config.py
index 242fde0b44..9387571619 100644
--- a/src/local_deep_research/database/pool_config.py
+++ b/src/local_deep_research/database/pool_config.py
@@ -7,6 +7,8 @@ different databases have different concurrency profiles.
# Validate connections before checkout (detects stale/broken connections)
POOL_PRE_PING = True
-# Recycle connections after 4 hours to release file handles
-# in long-running processes
-POOL_RECYCLE_SECONDS = 14400
+# Recycle connections after 1 hour to release stale file handles.
+# SQLite reopens are cheap (no network roundtrip), so a shorter
+# interval reduces the window for WAL handle accumulation.
+# See ADR-0004.
+POOL_RECYCLE_SECONDS = 3600
diff --git a/src/local_deep_research/web/auth/connection_cleanup.py b/src/local_deep_research/web/auth/connection_cleanup.py
index c3db0347db..4567eb81e4 100644
--- a/src/local_deep_research/web/auth/connection_cleanup.py
+++ b/src/local_deep_research/web/auth/connection_cleanup.py
@@ -4,8 +4,15 @@ Automatic cleanup of idle database connections.
Periodically closes database connections for users who have no active sessions
and no active research, preventing resource leaks when users close their browser
without logging out.
+
+Also periodically disposes all QueuePool engines to release accumulated WAL/SHM
+file handles. See ADR-0004 for why this is necessary with SQLCipher + WAL mode.
"""
+import os
+import time
+from pathlib import Path
+
from apscheduler.schedulers.background import BackgroundScheduler
from loguru import logger
@@ -13,6 +20,54 @@ from ...database.session_passwords import session_password_store
from ...database.thread_local_session import cleanup_dead_threads
from ...web.routes.globals import get_usernames_with_active_research
+# ---------------------------------------------------------------------------
+# File Descriptor Monitoring
+# ---------------------------------------------------------------------------
+# WHY: After days of idle operation in Docker, the app crashed with
+# OSError: [Errno 24] Too many open files
+# This monitoring logs the FD count every 5 minutes so we can correlate
+# FD growth with specific events and find leaks.
+#
+# WHAT IT LOGS:
+# - open_fds: total open file descriptors for the process
+# - pool_engines: number of per-user QueuePool engines
+# - thread_engines: number of per-thread NullPool engines (should be 0
+# when idle — nonzero means @thread_cleanup didn't fire)
+# - protected_users: users with active sessions
+#
+# HOW TO USE: grep "Resource monitor" in container logs. If open_fds
+# grows steadily over hours, something is leaking.
+# ---------------------------------------------------------------------------
+
+# Dispose all pool engines every 30 minutes to release WAL/SHM handles.
+# SQLCipher + WAL mode leaks handles when connections close out of order
+# (which QueuePool's pool_recycle causes). Periodic dispose() closes ALL
+# pooled connections at once, resetting the handle state cleanly.
+# The next DB operation transparently reopens a fresh connection.
+_DISPOSE_INTERVAL_SECONDS = 1800
+_last_dispose_time = 0.0
+
+
+def _count_open_fds() -> int:
+ """Count open file descriptors for the current process."""
+ proc_fd = Path("/proc/self/fd")
+ if proc_fd.is_dir():
+ try:
+ return len(list(proc_fd.iterdir()))
+ except OSError:
+ pass
+ import resource
+
+ soft_limit = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
+ count = 0
+ for fd in range(soft_limit):
+ try:
+ os.fstat(fd)
+ count += 1
+ except OSError:
+ pass
+ return count
+
def cleanup_idle_connections(session_manager, db_manager):
"""Close db connections for users with no active sessions and no active research."""
@@ -77,6 +132,48 @@ def cleanup_idle_connections(session_manager, db_manager):
# session sweep runs unconditionally but is lightweight.
cleanup_dead_threads()
+ # --- Periodic pool dispose to release WAL/SHM handles ---
+ # SQLCipher + WAL mode accumulates file handles when QueuePool recycles
+ # connections out of open-order. Periodically calling dispose() on all
+ # engines closes ALL pooled connections, releasing any leaked handles.
+ # The pool is transparently recreated on the next DB operation.
+ global _last_dispose_time
+ now = time.monotonic()
+ if now - _last_dispose_time >= _DISPOSE_INTERVAL_SECONDS:
+ _last_dispose_time = now
+ disposed = 0
+ with db_manager._connections_lock:
+ for username, engine in list(db_manager.connections.items()):
+ try:
+ engine.dispose()
+ disposed += 1
+ except Exception:
+ logger.debug(f"Error disposing engine for {username}")
+ if disposed:
+ logger.info(
+ f"Pool dispose: reset {disposed} engine(s) to release "
+ f"WAL/SHM handles"
+ )
+
+ # --- FD monitoring ---
+ try:
+ fd_count = _count_open_fds()
+ thread_engine_count = len(db_manager._thread_engines)
+ pool_engine_count = len(db_manager.connections)
+ logger.debug(
+ f"Resource monitor: open_fds={fd_count}, "
+ f"pool_engines={pool_engine_count}, "
+ f"thread_engines={thread_engine_count}, "
+ f"protected_users={len(protected)}"
+ )
+ if fd_count > 800:
+ logger.warning(
+ f"High FD count ({fd_count}) — approaching system limit. "
+ f"Check for resource leaks."
+ )
+ except Exception:
+ logger.debug("FD monitoring failed") # noqa: silent-exception
+
def start_connection_cleanup_scheduler(
session_manager, db_manager, interval_seconds=300
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index d4e033a256..359f0e6e90 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -381,7 +381,33 @@ def start_research():
# Use existing session from g to check active researches
try:
if hasattr(g, "db_session") and g.db_session:
- # Count active researches for this user
+ # First, clean up stale entries where the research thread has died
+ # (e.g. crashed with an unhandled exception before cleanup ran).
+ # Without this, dead researches permanently block the queue.
+ from ..routes.globals import (
+ is_research_thread_alive,
+ cleanup_research,
+ )
+
+ stale_rows = (
+ g.db_session.query(UserActiveResearch)
+ .filter_by(username=username, status=ResearchStatus.IN_PROGRESS)
+ .all()
+ )
+ for row in stale_rows:
+ if not is_research_thread_alive(row.research_id):
+ logger.warning(
+ f"Cleaning up stale research {row.research_id} "
+ f"(thread dead, started {row.started_at})"
+ )
+ row.status = ResearchStatus.FAILED
+ cleanup_research(row.research_id)
+ if any(
+ not is_research_thread_alive(r.research_id) for r in stale_rows
+ ):
+ g.db_session.commit()
+
+ # Now count truly active researches
active_count = (
g.db_session.query(UserActiveResearch)
.filter_by(username=username, status=ResearchStatus.IN_PROGRESS)
diff --git a/tests/database/test_database_manager_extended.py b/tests/database/test_database_manager_extended.py
index 6352bad8d7..7176ea954e 100644
--- a/tests/database/test_database_manager_extended.py
+++ b/tests/database/test_database_manager_extended.py
@@ -161,8 +161,8 @@ class TestConnectionPooling:
kwargs = manager._get_pool_kwargs()
assert "pool_size" in kwargs
- assert kwargs["pool_size"] == 10
- assert kwargs["max_overflow"] == 30
+ assert kwargs["pool_size"] == 1
+ assert kwargs["max_overflow"] == 2
@patch("local_deep_research.database.encrypted_db.get_data_directory")
def test_connection_storage(self, mock_data_dir):
diff --git a/tests/database/test_encrypted_db_manager.py b/tests/database/test_encrypted_db_manager.py
index 87e5af0a0e..b4787bd9b5 100644
--- a/tests/database/test_encrypted_db_manager.py
+++ b/tests/database/test_encrypted_db_manager.py
@@ -1198,8 +1198,8 @@ class TestPoolConfiguration:
kwargs = manager._get_pool_kwargs()
assert "pool_size" in kwargs
- assert kwargs["pool_size"] == 10
- assert kwargs["max_overflow"] == 30
+ assert kwargs["pool_size"] == 1
+ assert kwargs["max_overflow"] == 2
class TestValidEncryptionKey:
diff --git a/tests/database/test_pool_config.py b/tests/database/test_pool_config.py
index ab30185872..b48eb035ba 100644
--- a/tests/database/test_pool_config.py
+++ b/tests/database/test_pool_config.py
@@ -19,7 +19,7 @@ class TestPoolConfigConstants:
POOL_RECYCLE_SECONDS,
)
- assert POOL_RECYCLE_SECONDS == 14400
+ assert POOL_RECYCLE_SECONDS == 3600
def test_pool_recycle_is_positive_integer(self):
from local_deep_research.database.pool_config import (