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.

docs: update pool-sizing comments, FD calculations, and create ADR-0004 (#3477)

LearningCircuitbc3680d21c04
diff --git a/docs/decisions/0004-nullpool-for-sqlcipher.md b/docs/decisions/0004-nullpool-for-sqlcipher.md
new file mode 100644
index 0000000000..102e97ef8a
--- /dev/null
+++ b/docs/decisions/0004-nullpool-for-sqlcipher.md
@@ -0,0 +1,75 @@
+# ADR-0004: QueuePool (not NullPool) for SQLCipher databases
+
+**Date:** 2026-04-13
+**Status:** Accepted
+
+## Context
+
+Each user has their own SQLCipher-encrypted SQLite database, opened at
+login and closed at logout. Background threads (research workers,
+metric writers, news scheduler jobs) need database sessions for the
+same user concurrently with Flask request handlers.
+
+### Why QueuePool
+
+SQLCipher's `PRAGMA key` adds ~0.2 ms per connection open. With 20–30
+queries per page load, NullPool (new connection per checkout) adds a
+noticeable 4–6 ms overhead vs QueuePool's ~1.5 ms for pool-resident
+connections.
+
+### Why not per-thread NullPool engines
+
+An earlier design maintained a second engine system: one NullPool
+engine per `(username, thread_id)` in `_thread_engines`, used by
+background threads for metric writes. This was removed in PR #3441
+because:
+
+1. **FD leak.** Each SQLCipher + WAL connection holds 3 file
+ descriptors (main db + WAL + SHM). Orphaned thread engines — left
+ behind when `@thread_cleanup` did not fire — accumulated FDs
+ unboundedly, eventually exhausting the 1024 soft limit and crashing
+ the server with `OSError: [Errno 24] Too many open files`.
+
+2. **Architectural redundancy.** The per-user QueuePool engine is
+ already created with `check_same_thread=False`, making it safe for
+ background threads. Routing all work through one bounded pool per
+ user keeps FD usage at `pool_size + max_overflow` (currently 60)
+ instead of scaling with background-thread count.
+
+### SQLCipher + WAL handle leak workaround
+
+SQLCipher in WAL mode leaks file handles when pooled connections close
+out of open-order (a known issue with WAL-mode SQLite engines under
+connection pooling). The cleanup scheduler in `connection_cleanup.py`
+calls `engine.dispose()` on all per-user engines every 30 minutes,
+closing all idle pooled connections and resetting handle state. This is
+a workaround, not a root fix — it limits accumulation to a 30-minute
+window.
+
+### Current pool sizing
+
+```
+pool_size = 20
+max_overflow = 40
+pool_timeout = 10 # seconds; fail fast rather than queue
+pool_recycle = 3600 # seconds; recycle stale connections
+pool_pre_ping = True
+```
+
+Peak FD usage per user: `(20 + 40) × 2 + 1 = 121` (WAL mode).
+
+## Decision
+
+Use a single shared QueuePool engine per user for all threads (request
+handlers and background workers). Do not maintain per-thread engines.
+Periodic `dispose()` mitigates the SQLCipher+WAL handle leak.
+
+## Consequences
+
+- FD usage is bounded and predictable.
+- `pool_timeout=10` makes pool exhaustion a loud error rather than a
+ silent deadlock.
+- The `ParallelConstrainedStrategy` (`max_workers=100`) could
+ theoretically spike past 60 simultaneous checkouts. Sessions are
+ short-lived (millisecond metric writes), so sustained contention is
+ unlikely. Flagged as a known follow-up.
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index 7321344a2c..904cae373f 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -578,7 +578,7 @@ sudo lsof -i :5000 # May need sudo for system services
**Why it happens:**
-Each SQLCipher WAL-mode connection uses 2 file descriptors (main db + WAL), plus 1 shared SHM fd per database. With per-user encrypted databases, the QueuePool alone uses `users × (pool_size × 2 + 1)` FDs at steady state (21 per user with defaults), up to `users × ((10 + 30) × 2 + 1) = users × 81` under load. Background research threads add transient FDs. The default Linux soft ulimit of 1024 is tight for multi-user deployments.
+Each SQLCipher WAL-mode connection uses 2 file descriptors (main db + WAL), plus 1 shared SHM fd per database. With per-user encrypted databases, the QueuePool alone uses `users × (pool_size × 2 + 1)` FDs at steady state (41 per user with defaults), up to `users × ((20 + 40) × 2 + 1) = users × 121` under load. The default Linux soft ulimit of 1024 is tight for multi-user deployments.
**Diagnosis:**
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.py
index bbb67f2208..01a8133602 100644
--- a/src/local_deep_research/database/encrypted_db.py
+++ b/src/local_deep_research/database/encrypted_db.py
@@ -46,10 +46,10 @@ class DatabaseManager:
self.has_encryption = self._check_encryption_available()
# ----------------------------------------------------------------
- # Pool class selection
+ # Pool class selection — see ADR-0004
#
- # We use QueuePool (pool_size=20, max_overflow=40) for production
- # and StaticPool for tests.
+ # We use QueuePool (pool_size=20, max_overflow=40,
+ # pool_timeout=10) for production and StaticPool for tests.
#
# Why pool_size=20:
#
@@ -778,8 +778,7 @@ class DatabaseManager:
if engine is None:
raise ValueError(f"Failed to open database for user {username}")
- # Use SQLAlchemy's default expire_on_commit=True to match the
- # previous NullPool path's behavior.
+ # Use SQLAlchemy's default expire_on_commit=True.
Session = sessionmaker(bind=engine)
return Session()