~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
docs(resource-cleanup) + fix: Round 9 audit results + per-user lock-dict cleanup (#4077)
LearningCircuite79a9fb76a78
diff --git a/changelog.d/+per-user-lock-dict-cleanup.bugfix.md b/changelog.d/+per-user-lock-dict-cleanup.bugfix.mdnew file mode 100644index 0000000000..f12c0ee580--- /dev/null+++ b/changelog.d/+per-user-lock-dict-cleanup.bugfix.md@@ -0,0 +1 @@+Three module-level per-user lock dicts (`_user_init_locks` in `database/library_init.py`, `_user_locks` in `database/backup/backup_service.py`, `_user_critical_locks` on `QueueProcessorV2`) previously accumulated one `threading.Lock` entry per username over the process lifetime with no removal hook on user-close. Bounded by total user count (~900 bytes/user across all three), so not visible on typical self-hosted instances — but long-lived multi-user deployments with user-account churn would see slow memory creep. The three modules now expose `pop_user_*_lock(username)` helpers and a shared `_pop_per_user_locks` call in the connection-cleanup module fires them from both the idle-cleanup sweeper and the logout / password-change paths, matching the cleanup already done for scheduler-job registrations and session-password store.diff --git a/docs/developing/resource-cleanup.md b/docs/developing/resource-cleanup.mdindex 940bc64799..2c7ac7b7dd 100644--- a/docs/developing/resource-cleanup.md+++ b/docs/developing/resource-cleanup.md@@ -385,6 +385,79 @@ generalized to introspect either a chat model or an embeddingsinstance with the same `_client` / `_async_client` shape. Theextension is a small type-check broadening, not a redesign.+### Round 9 — broader resource audit (May 2026)++Once the FD-leak classes were closed, a follow-up audit looked for+*other* slow-growth patterns that wouldn't trip the FD counters but+could still degrade a long-running container: memory and cache growth,+thread / asyncio Task / lock lifecycle, DB state hygiene beyond+connections. Three parallel agents per round, two rounds (Round 1+hypothesis generation, Round 2 fact-check), captured here in+verified form so the next contributor doesn't re-derive the same+conclusions.++#### Refuted (false positives from Round 1, verified in Round 2)++- **`@cache` on `get_available_providers`** (`config/llm_config.py:158`).+ Round 1 claimed unbounded cache growth if the function were called+ with differing `settings_snapshot` dicts. Round 2 verified: dicts+ are unhashable, so `@cache` would raise `TypeError` on them, not+ silently grow. In practice the call sites pass `settings_snapshot=None`+ (hashable, cardinality 1). Not a leak.+- **Thread-local Session identity-map growth**+ (`database/thread_local_session.py`). Round 1 claimed long-running+ research threads would accumulate ORM objects in the per-thread+ Session's identity map. Round 2 verified: SQLAlchemy's default+ `expire_on_commit=True` clears the identity map at every commit;+ the codebase commits periodically. Bounded by typical query volume,+ not unbounded by uptime.+- **`token_usage` table unbounded growth.** Append-only per LLM call+ with no TTL or retention job. Round 2 verified: **feature by+ design**. Schema has compound time-series indexes+ (`idx_token_research_timestamp`, etc.); `/api/context-overflow` and+ `/metrics/api/metrics` explicitly query historical windows for cost+ analysis. The table is a permanent audit trail by intent. Adding+ retention would break the metrics dashboards.+- **`search_calls` table unbounded growth.** Same shape and same+ verdict — compound time-series indexes confirm intentional design+ as a permanent search-analytics record.++#### Fixed in this PR — three per-user lock dicts++- **Three per-user lock dicts** — `_user_init_locks` and `_user_locks`+ are module-level dicts in `database/library_init.py` and+ `database/backup/backup_service.py` respectively; `_user_critical_locks`+ is an instance attribute on the `QueueProcessorV2` singleton in+ `web/queue/processor_v2.py`. Each stored one `threading.Lock` per+ username with no removal hook. Bounded ceiling (~296 bytes/entry ×+ 3 dicts at 1000 users = ~900 KB), so not urgent — but easy to fix+ cleanly. The two module-level dicts now expose+ `pop_user_init_lock` / `pop_user_lock` functions; the queue+ processor exposes the equivalent as an instance method+ `queue_processor.pop_user_critical_lock`. A shared+ `_pop_per_user_locks(username)` helper in `connection_cleanup.py`+ calls all three with lazy imports and individual try/except+ (WARNING-level so dict accumulation is observable, matching the+ sibling scheduler-unregister error path). The helper is invoked+ unconditionally — outside the `close_user_database` try/except so+ it still runs when the DB close itself fails — in both the+ idle-connection sweeper (`connection_cleanup.py:cleanup_idle_connections`)+ and the logout / password-change paths (`web/auth/routes.py`).+ Tests in `tests/web/auth/test_connection_cleanup.py::TestPopPerUserLocks`+ cover the helper directly and through the idle-close path.++#### Real but small (survives verification)++- **`app_logs` (ResearchLog) table — no automatic retention.** Grows+ by ~100s-1000s of rows per research. Cleaned only via cascade-delete+ when the parent `Research` row is deleted manually. Unlike+ `token_usage` / `search_calls`, this table has no UI dashboard or+ time-series API consuming it — it's debug context for a specific+ research session, not an analytics record. For users who keep all+ research, logs accumulate indefinitely. See "Intentionally not done+ (deferred)" for the retention design when a symptom report+ justifies it.+---## Debugging FD leaks — playbook for the next one@@ -756,7 +829,25 @@ reference this section first.bugs); PR #3036 added `utilities/fd_monitor.py` for cross-platform FDreading. A type/inode-breakdown extension is feasible but deferreduntil an active leak hunt actually needs it.-+- **`app_logs` (ResearchLog) retention setting + scheduled cleanup+ job.** Identified in Round 9; the only audit finding that wasn't+ refuted but also isn't impactful enough today. *Trigger to do this+ work:* a user reports the SQLCipher DB growing >100 MB and+ complains about query slowdown, OR a self-hosted instance keeping+ research logs for >1 year sees DB bloat, OR the metrics dashboard+ starts noting research-detail page load slowdown traced to+ `app_logs` joins. *Implementation sketch:* add+ `logs.research_log_retention_days` to+ `defaults/default_settings.json` (default `0` = disabled, preserves+ current behavior; e.g. `30` to keep last 30 days). Extend the+ existing `BackgroundJobScheduler` in `scheduler/background.py`+ (which already runs `cleanup_inactive_users` hourly and+ `_reload_config` every 30 min) with a daily `_cleanup_old_research_logs`+ job that deletes `ResearchLog` rows older than the retention+ window. Skip rows belonging to favorited / starred researches if a+ flag exists. ~30 LOC + a regression test that inserts old rows,+ triggers the job, asserts old rows are deleted and recent ones+ survive. Add `changelog.d/<id>.feature.md`.---## Glossarydiff --git a/src/local_deep_research/database/backup/backup_service.py b/src/local_deep_research/database/backup/backup_service.pyindex 5d583a5203..ebf56a0cab 100644--- a/src/local_deep_research/database/backup/backup_service.py+++ b/src/local_deep_research/database/backup/backup_service.py@@ -54,6 +54,18 @@ def _get_user_lock(username: str) -> threading.Lock:return _user_locks[username]+def pop_user_lock(username: str) -> None:+ """Remove the per-user backup lock for ``username`` from the registry.++ Called from the user-close path so the module-level dict doesn't+ accumulate one entry per username across the process lifetime. The+ next backup operation lazily re-creates the lock if needed — the+ lock has no state that needs to persist across login/logout.+ """+ with _user_locks_lock:+ _user_locks.pop(username, None)++@dataclassclass BackupResult:"""Result of a backup operation."""diff --git a/src/local_deep_research/database/library_init.py b/src/local_deep_research/database/library_init.pyindex 1ba70c8420..290c0fdd0e 100644--- a/src/local_deep_research/database/library_init.py+++ b/src/local_deep_research/database/library_init.py@@ -42,6 +42,20 @@ def _get_user_init_lock(username: str) -> threading.Lock:return lock+def pop_user_init_lock(username: str) -> None:+ """Remove the per-user init lock for ``username`` from the registry.++ Called from the user-close path (``db_manager.close_user_database``+ callers in ``web/auth/connection_cleanup.py`` and ``web/auth/routes.py``)+ so the module-level dict doesn't accumulate one entry per username+ across the process lifetime. The next login lazily re-creates the+ lock, which is fine — the lock has no state that needs to persist+ across login/logout.+ """+ with _user_init_locks_lock:+ _user_init_locks.pop(username, None)++def seed_source_types(username: str, password: str = None) -> None:"""Seed the source_types table with predefined document source types.diff --git a/src/local_deep_research/web/auth/connection_cleanup.py b/src/local_deep_research/web/auth/connection_cleanup.pyindex e97d66746a..77203caef0 100644--- a/src/local_deep_research/web/auth/connection_cleanup.py+++ b/src/local_deep_research/web/auth/connection_cleanup.py@@ -47,6 +47,49 @@ _DISPOSE_INTERVAL_SECONDS = 1800_last_dispose_time = 0.0+def _pop_per_user_locks(username: str) -> None:+ """Pop ``username`` from the three module-level per-user lock dicts.++ The library-init, backup, and queue-processor modules each maintain+ a ``dict[username, threading.Lock]`` for serialising per-user+ critical sections. None of them had a removal hook, so without+ this the dicts accumulated one entry per username across the+ process lifetime — bounded by total users (~296 bytes/entry × 3 =+ ~900 B/user/dict) but real on long-lived self-hosted instances+ with churn. Called from the user-close paths so the next login+ starts with fresh locks (the locks hold no state worth preserving+ across login/logout).++ Lazy-imported here to keep this module's import graph shallow:+ ``connection_cleanup`` runs at startup and shouldn't pull in the+ queue / backup / library-init modules eagerly.+ """+ try:+ from ...database.library_init import pop_user_init_lock++ pop_user_init_lock(username)+ except Exception:+ # Surface at WARNING to match the sibling scheduler-unregister+ # error handler in this same module (line ~111). A failure+ # here means the lock-dict entry will accumulate on every+ # subsequent close cycle for this user; we want it visible.+ logger.warning(f"Failed to pop _user_init_locks for {username}")++ try:+ from ...database.backup.backup_service import pop_user_lock++ pop_user_lock(username)+ except Exception:+ logger.warning(f"Failed to pop _user_locks for {username}")++ try:+ from ...web.queue.processor_v2 import queue_processor++ queue_processor.pop_user_critical_lock(username)+ except Exception:+ logger.warning(f"Failed to pop _user_critical_locks for {username}")++def _count_open_fds() -> int:"""Count open file descriptors for the current process."""proc_fd = Path("/proc/self/fd")@@ -117,6 +160,12 @@ def cleanup_idle_connections(session_manager, db_manager):logger.debug(f"Closed idle connection for {username}")except Exception:logger.warning(f"Connection cleanup failed for {username}")+ # Pop lock-dict entries regardless of whether close succeeded.+ # The lock-dict cleanup is independent of DB-engine teardown;+ # putting it inside the try above would skip pop on the very+ # failure path it most matters for (close raises -> next login+ # rebuilds the engine but the stale lock entries linger).+ _pop_per_user_locks(username)if closed:logger.info(f"Connection cleanup: closed {closed} idle connection(s)")diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.pyindex e6a9384aff..0599c98ec8 100644--- a/src/local_deep_research/web/auth/routes.py+++ b/src/local_deep_research/web/auth/routes.py@@ -602,6 +602,15 @@ def logout():# Close database connectiondb_manager.close_user_database(username)+ # Drop per-user lock-dict entries (library-init, backup,+ # queue-processor critical sections). Matches the cleanup+ # done by the idle-connection sweeper; without this, those+ # three module-level dicts accumulate one entry per username+ # across the process lifetime.+ from .connection_cleanup import _pop_per_user_locks++ _pop_per_user_locks(username)+# Clear sessionif session_id:session_manager.destroy_session(session_id)@@ -721,6 +730,11 @@ def change_password():# an explicit close here is defensive — harmless if redundant.db_manager.close_user_database(username)+ # 2a. Drop per-user lock-dict entries (matches logout path).+ from .connection_cleanup import _pop_per_user_locks++ _pop_per_user_locks(username)+# 2b. Purge old backups (encrypted with old key) and create# a fresh backup with the new key. Old-key backups are a# security risk per NIST SP 800-57 / OWASP A02 — they remaindiff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.pyindex 86e972e954..ff9a868086 100644--- a/src/local_deep_research/web/queue/processor_v2.py+++ b/src/local_deep_research/web/queue/processor_v2.py@@ -103,6 +103,18 @@ class QueueProcessorV2:self._user_critical_locks[username] = lockreturn lock+ def pop_user_critical_lock(self, username: str) -> None:+ """Remove the per-user critical-section lock for ``username``.++ Called from the user-close path so this instance dict doesn't+ accumulate one entry per username across the process lifetime.+ The next direct-research submission for that user lazily+ re-creates the lock if needed — the lock has no state that+ needs to persist across login/logout.+ """+ with self._user_critical_locks_lock:+ self._user_critical_locks.pop(username, None)+def _bump_spawn_retry_count(self, research_id: str) -> int:"""Atomically increment and return the spawn-retry counter for``research_id``. Extracted so tests can exercise the realdiff --git a/tests/web/auth/test_connection_cleanup.py b/tests/web/auth/test_connection_cleanup.pyindex 7848db4e3a..4cca97bb60 100644--- a/tests/web/auth/test_connection_cleanup.py+++ b/tests/web/auth/test_connection_cleanup.py@@ -282,6 +282,141 @@ class TestCleanupIdleConnections:mock_clear_pwd.assert_called_once_with("alice")+class TestPopPerUserLocks:+ """Tests for ``_pop_per_user_locks``: drops the three module-level+ per-user lock-dict entries (library-init, backup, queue-processor+ critical sections) on user-close. Without this each dict grew one+ entry per username over process lifetime.+ """++ def test_pops_all_three_lock_dicts(self):+ from local_deep_research.web.auth.connection_cleanup import (+ _pop_per_user_locks,+ )+ from local_deep_research.database.library_init import (+ _get_user_init_lock,+ _user_init_locks,+ )+ from local_deep_research.database.backup.backup_service import (+ _get_user_lock,+ _user_locks,+ )+ from local_deep_research.web.queue.processor_v2 import (+ queue_processor,+ )++ # Populate each dict with a unique test username so we don't+ # collide with state any other test might have left behind.+ u = "test-pop-locks-user-zzz"+ _get_user_init_lock(u)+ _get_user_lock(u)+ queue_processor._get_user_critical_lock(u)++ assert u in _user_init_locks+ assert u in _user_locks+ assert u in queue_processor._user_critical_locks++ _pop_per_user_locks(u)++ assert u not in _user_init_locks+ assert u not in _user_locks+ assert u not in queue_processor._user_critical_locks++ def test_idempotent_on_missing_user(self):+ """Pop on a username that was never inserted must not raise."""+ from local_deep_research.web.auth.connection_cleanup import (+ _pop_per_user_locks,+ )++ # Should silently no-op.+ _pop_per_user_locks("never-registered-user-zzz")++ def test_pop_called_from_idle_close_path(self, sm, db):+ """Integration: ``cleanup_idle_connections`` calls+ ``_pop_per_user_locks`` for each user it closes — verified+ by asserting all three lock-dict entries are gone, so a+ regression that drops the call (or breaks one of the three+ pop hops) would be caught.+ """+ from local_deep_research.database.library_init import (+ _get_user_init_lock,+ _user_init_locks,+ )+ from local_deep_research.database.backup.backup_service import (+ _get_user_lock,+ _user_locks,+ )+ from local_deep_research.web.queue.processor_v2 import (+ queue_processor,+ )++ # Use a dedicated test username (not "alice") to avoid colliding+ # with other tests that may also touch these module-level dicts.+ u = "test-idle-close-user-zzz"+ _get_user_init_lock(u)+ _get_user_lock(u)+ queue_processor._get_user_critical_lock(u)++ assert u in _user_init_locks+ assert u in _user_locks+ assert u in queue_processor._user_critical_locks++ db.get_connected_usernames.return_value = {u}++ with (+ patch(+ "local_deep_research.web.auth.connection_cleanup.get_usernames_with_active_research",+ return_value=set(),+ ),+ patch(+ "local_deep_research.scheduler.background.get_background_job_scheduler",+ ),+ ):+ cleanup_idle_connections(sm, db)++ # All three lock-dict entries removed by the idle-close path.+ assert u not in _user_init_locks+ assert u not in _user_locks+ assert u not in queue_processor._user_critical_locks++ def test_pop_runs_even_when_close_user_database_fails(self, sm, db):+ """Regression for the original PR: ``_pop_per_user_locks`` was+ previously inside the same try/except as ``close_user_database``,+ so a DB-close failure (the very path+ ``test_close_failure_does_not_abort_loop`` exercises) would skip+ the pop and leak the lock-dict entry. Now the pop is outside+ the try; this test pins that behavior.+ """+ from local_deep_research.database.library_init import (+ _get_user_init_lock,+ _user_init_locks,+ )++ u = "test-close-fails-user-zzz"+ _get_user_init_lock(u)+ assert u in _user_init_locks++ db.get_connected_usernames.return_value = {u}+ db.close_user_database.side_effect = RuntimeError(+ "simulated DB close failure"+ )++ with (+ patch(+ "local_deep_research.web.auth.connection_cleanup.get_usernames_with_active_research",+ return_value=set(),+ ),+ patch(+ "local_deep_research.scheduler.background.get_background_job_scheduler",+ ),+ ):+ cleanup_idle_connections(sm, db)++ # Despite close_user_database raising, the lock-dict entry+ # is still popped.+ assert u not in _user_init_locks++class TestStartConnectionCleanupScheduler:"""Tests for start_connection_cleanup_scheduler()."""