~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(auth): atomic post-login settings + regression test, supersedes #3487 (#3502)
LearningCircuitd18887df2497
diff --git a/docs/decisions/0004-nullpool-for-sqlcipher.md b/docs/decisions/0004-nullpool-for-sqlcipher.mdindex 102e97ef8a..df82ab2fbd 100644--- a/docs/decisions/0004-nullpool-for-sqlcipher.md+++ b/docs/decisions/0004-nullpool-for-sqlcipher.md@@ -73,3 +73,31 @@ Periodic `dispose()` mitigates the SQLCipher+WAL handle leak.theoretically spike past 60 simultaneous checkouts. Sessions areshort-lived (millisecond metric writes), so sustained contention isunlikely. Flagged as a known follow-up.++## Addendum — PR #3487 investigation (2026-04-16)++PR #3487 proposed skipping the 30-min `engine.dispose()` for any engine+with `pool.checkedout() > 0`, citing a claim that dispose orphans+checked-out connections and causes torn writes in the post-login bulk+settings import. Investigation found:++- **SA 2.0 source disagrees.** `QueuePool.dispose` only drains idle+ queue entries (`_pool.get(False)`); `Engine.dispose` replaces the+ pool via `pool.recreate()`. SA docs: *"Connections that are still+ checked out will not be closed."* A thread holding a checked-out+ connection keeps using it until return.+- **Real root cause was elsewhere.** The sticky-loop symptom came+ from the post-login path committing twice+ (`load_from_defaults_file(commit=True)` then `update_db_version()`+ with its own commit), which left `app.version` unwritten on any+ inter-commit failure. Fix: one session, one terminal commit, both+ calls use `commit=False`. See `web/auth/routes.py` ATOMICITY+ INVARIANT comment.+- **Regression guard:** `tests/database/test_post_login_settings_atomicity.py`+ locks in both properties — the atomic all-or-nothing write and the+ SA 2.0 checked-out-survives-dispose contract — so neither can+ silently regress.++Future refactors of the cleanup cycle should preserve the+checked-out-survival property; do not add a `checkedout()` skip guard+without a real reproducer.diff --git a/src/local_deep_research/settings/manager.py b/src/local_deep_research/settings/manager.pyindex a5b741fa81..3b97d064ef 100644--- a/src/local_deep_research/settings/manager.py+++ b/src/local_deep_research/settings/manager.py@@ -1026,7 +1026,12 @@ class SettingsManager(ISettingsManager):Import settings from the defaults settings file.Args:- commit: Whether to commit changes to database+ commit: Whether to commit changes to database. The post-login+ atomic block in `web/auth/routes.py` passes ``commit=False``+ and combines this call with ``update_db_version(commit=False)``+ under a single terminal ``db_session.commit()`` — preserving+ the all-or-nothing invariant is what prevents the sticky-loop+ bug where `app.version` is missing after a partial write.**kwargs: Will be passed to `import_settings`."""@@ -1046,10 +1051,19 @@ class SettingsManager(ISettingsManager):return bool(db_version == package_version)- def update_db_version(self) -> None:+ def update_db_version(self, commit: bool = True) -> None:"""Updates the version saved in the DB based on the package version.+ Args:+ commit: Whether to commit the version write to the database.+ Callers that want to combine this with other writes into+ a single atomic transaction should pass commit=False and+ commit the session themselves. The post-login block in+ `web/auth/routes.py` relies on this to bundle the defaults+ import and the `app.version` write into one SQLite+ transaction; splitting them risks the sticky-loop state+ where `app.version` never gets written."""logger.debug(f"Updating saved DB version to {package_version}.")@@ -1068,7 +1082,8 @@ class SettingsManager(ISettingsManager):if self.db_session is None:raise RuntimeError("Database session is not initialized")self.db_session.add(version)- self.db_session.commit()+ if commit:+ self.db_session.commit()def import_settings(self,diff --git a/src/local_deep_research/web/auth/connection_cleanup.py b/src/local_deep_research/web/auth/connection_cleanup.pyindex f6ac8c48f7..10e2db5967 100644--- a/src/local_deep_research/web/auth/connection_cleanup.py+++ b/src/local_deep_research/web/auth/connection_cleanup.py@@ -131,9 +131,26 @@ def cleanup_idle_connections(session_manager, db_manager):# --- 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.+ # connections out of open-order (ADR-0004). Periodically calling+ # dispose() on all engines closes ALL pooled connections, releasing any+ # leaked handles. The pool is transparently recreated on the next DB+ # operation.+ #+ # Safe to run against engines with checked-out connections: SA 2.0+ # `QueuePool.dispose` only drains idle queue entries and+ # `Engine.dispose` calls `pool.recreate()`; a thread holding a+ # checked-out connection keeps using it until return. SA docs are+ # explicit — "Connections that are still checked out will not be+ # closed". The post-login bulk write (_perform_post_login_tasks in+ # web/auth/routes.py) is additionally protected by being a single+ # atomic transaction, so any interruption (dispose, crash, OOM)+ # rolls back cleanly without leaving partial state.+ #+ # Do not add a `checkedout() > 0` skip guard here without first+ # reproducing a real torn-write against the actual SA source path:+ # see PR #3487 discussion — the speculative skip introduces an+ # unbounded "skip forever" risk on busy engines in exchange for+ # preventing a failure mode that SA 2.0 does not produce.global _last_dispose_timenow = time.monotonic()if now - _last_dispose_time >= _DISPOSE_INTERVAL_SECONDS:diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.pyindex c0e9ec0070..bde2fe45b1 100644--- a/src/local_deep_research/web/auth/routes.py+++ b/src/local_deep_research/web/auth/routes.py@@ -189,6 +189,19 @@ def _perform_post_login_tasks(username: str, password: str) -> None:idempotent and safe to retry on the next login."""# 1. Settings version check + migration+ #+ # ATOMICITY INVARIANT: the defaults import and the `app.version`+ # marker MUST be written in one `get_user_db_session(...)` scope+ # with a single terminal `db_session.commit()`. SQLite WAL rollback+ # then guarantees either both land or neither does — the only+ # acceptable states for `db_version_matches_package()` to behave+ # correctly on the next login. Splitting into two commits regresses+ # to the "sticky loop": `app.version` stays unwritten, every+ # subsequent login re-runs the ~498-row bulk insert (app.version is+ # not in default_settings.json, only `update_db_version()` writes+ # it). Do not factor these calls into separate sessions or allow+ # `load_from_defaults_file`/`update_db_version` to commit internally+ # here — both must be called with `commit=False`.try:from ...settings.manager import SettingsManagerfrom ...database.session_context import get_user_db_session@@ -201,9 +214,10 @@ def _perform_post_login_tasks(username: str, password: str) -> None:"- loading missing default settings")settings_manager.load_from_defaults_file(- commit=True, overwrite=False+ commit=False, overwrite=False)- settings_manager.update_db_version()+ settings_manager.update_db_version(commit=False)+ db_session.commit()logger.info(f"Missing default settings loaded and version "f"updated for user {username}"diff --git a/tests/database/test_post_login_settings_atomicity.py b/tests/database/test_post_login_settings_atomicity.pynew file mode 100644index 0000000000..e48aeeda4f--- /dev/null+++ b/tests/database/test_post_login_settings_atomicity.py@@ -0,0 +1,342 @@+"""+Regression tests for the post-login settings atomicity invariant.++Three load-bearing properties are locked in here:++1. On failure mid-write, the DB rolls back cleanly — no partial rows,+ no orphaned `app.version`. The next login retries from a clean+ state instead of entering the sticky loop+ (commit 621d8d0d — fix(auth): atomic settings reload + app.version+ update on login).++2. On success, both the defaults import AND `app.version` persist+ together — the invariant that makes+ `db_version_matches_package()` useful.++3. `engine.dispose()` on a busy engine does NOT break a thread holding+ a checked-out connection. This is the SA 2.0 contract+ (`QueuePool.dispose` drains only idle queue entries,+ `Engine.dispose` calls `pool.recreate()`, checked-out connections+ keep working) and we lock it in so a future SA upgrade cannot+ silently change it. This test makes PR #3487's "dispose orphans+ checked-out" mechanism claim falsifiable — if it ever starts being+ true for our SQLCipher+WAL path, this test fails.+"""++import sys+import tempfile+import threading+from pathlib import Path++import pytest+from sqlalchemy.orm import sessionmaker++sys.path.insert(0, str(Path(__file__).parent.parent.parent.resolve()))++from local_deep_research.database.encrypted_db import DatabaseManager+from local_deep_research.database.models import Setting+from local_deep_research.settings.manager import SettingsManager+++def temp_data_dir():+ """Per-test temporary directory for encrypted databases."""+ with tempfile.TemporaryDirectory() as tmpdir:+ yield Path(tmpdir)+++def db_manager(temp_data_dir, monkeypatch):+ """DatabaseManager pointed at a temp directory.++ Production QueuePool is used (not StaticPool) so the dispose-vs-+ checkout test exercises the real code path.+ """+ monkeypatch.setattr(+ "local_deep_research.database.encrypted_db.get_data_directory",+ lambda: temp_data_dir,+ )+ monkeypatch.delenv("TESTING", raising=False)+ manager = DatabaseManager()+ yield manager+ for username in list(manager.connections.keys()):+ try:+ manager.close_user_database(username)+ except Exception:+ pass+++def user_engine(db_manager):+ """Fresh per-test SQLCipher engine for a unique user.++ After `create_user_database`, the engine is already populated by+ `initialize_database` with the full defaults set + `app.version`.+ Tests that need a pre-import state delete the relevant rows in+ their arrange step.+ """+ username = "atomicity_user"+ password = "AtomicityPass123!"+ engine = db_manager.create_user_database(username, password)+ yield username, password, engine+++def _has_setting(engine, key: str) -> bool:+ Session = sessionmaker(bind=engine)+ with Session() as s:+ return s.query(Setting).filter(Setting.key == key).first() is not None+++def _delete_keys(engine, keys):+ Session = sessionmaker(bind=engine)+ with Session() as s:+ s.query(Setting).filter(Setting.key.in_(list(keys))).delete(+ synchronize_session=False+ )+ s.commit()+++def _run_post_login_atomic_block(engine, raise_after_stage: bool = False):+ """Mirror the atomic block in `_perform_post_login_tasks` step 1.++ We call the SettingsManager methods directly against a real engine+ instead of routing through `get_user_db_session` so the test does+ not depend on Flask session state. The transaction scope is+ identical: one session, one terminal commit.++ Args:+ engine: SQLCipher engine for the user DB.+ raise_after_stage: If True, raise after load_from_defaults_file+ has staged rows but before the terminal commit. This models+ a mid-write crash / thread death / dispose-triggered error+ whose rollback must leave the DB in a clean pre-write state.+ """+ Session = sessionmaker(bind=engine)+ with Session() as db_session:+ settings_manager = SettingsManager(db_session)+ settings_manager.load_from_defaults_file(commit=False, overwrite=False)+ if raise_after_stage:+ raise RuntimeError("simulated mid-write failure")+ settings_manager.update_db_version(commit=False)+ db_session.commit()+++class TestPostLoginSettingsAtomicity:+ """The invariant fixed by commit 621d8d0d must stay fixed."""++ def test_atomic_block_restores_deleted_keys_and_app_version(+ self, user_engine+ ):+ """+ Happy path: if the pre-login state is missing `app.version` and+ some defaults (simulating a version-mismatch + manual-cleanup+ scenario), the atomic block restores everything in one commit.+ """+ _, _, engine = user_engine+ probe_keys = {"app.version", "app.debug"}++ _delete_keys(engine, probe_keys)+ for k in probe_keys:+ assert not _has_setting(engine, k), (+ f"test precondition: {k} deleted"+ )++ _run_post_login_atomic_block(engine)++ for k in probe_keys:+ assert _has_setting(engine, k), (+ f"{k} must be restored after a successful atomic block"+ )++ def test_mid_write_failure_rolls_back_to_pre_write_state(self, user_engine):+ """+ Sticky-loop regression guard. Without atomicity the pre-621d8d0d+ path committed the defaults import first and then tried to+ commit `app.version` separately; any failure between the two+ commits left `app.version` unwritten while staged rows had+ already landed — every subsequent login re-ran the bulk+ insert.++ With the atomic block, a failure between staging and commit+ rolls back ALL staged changes — the probe keys deleted below+ remain deleted, and `app.version` is still absent. Next login+ retries from an unchanged pre-write state.+ """+ _, _, engine = user_engine+ probe_keys = {"app.version", "app.debug"}++ _delete_keys(engine, probe_keys)+ for k in probe_keys:+ assert not _has_setting(engine, k)++ with pytest.raises(RuntimeError, match="simulated mid-write failure"):+ _run_post_login_atomic_block(engine, raise_after_stage=True)++ for k in probe_keys:+ assert not _has_setting(engine, k), (+ f"{k} was deleted before the atomic block; a mid-write "+ f"failure must roll back all staged changes and leave "+ f"it deleted. If it exists now, the two-commit split "+ f"has regressed and the sticky loop is back."+ )++ _run_post_login_atomic_block(engine)+ for k in probe_keys:+ assert _has_setting(engine, k)++ def test_post_login_routes_uses_commit_false_for_both_calls(self):+ """+ Structural guard: lock in that `_perform_post_login_tasks` calls+ `load_from_defaults_file` and `update_db_version` with+ `commit=False` and emits a single terminal `db_session.commit()`.+ Any refactor that regresses to the two-commit form will fail+ this test before production sees a sticky loop.+ """+ import inspect++ from local_deep_research.web.auth import routes++ src = inspect.getsource(routes._perform_post_login_tasks)++ assert "load_from_defaults_file(" in src+ assert "update_db_version(commit=False)" in src, (+ "update_db_version must be called with commit=False so the "+ "atomic block controls the terminal commit"+ )+ lfd_idx = src.index("load_from_defaults_file(")+ lfd_tail = src[lfd_idx : lfd_idx + 200]+ assert "commit=False" in lfd_tail, (+ "load_from_defaults_file must be called with commit=False "+ "so the atomic block controls the terminal commit"+ )+ assert "db_session.commit()" in src, (+ "the atomic block must end with a single db_session.commit()"+ )+++class TestCheckedOutConnectionSurvivesDispose:+ """Lock in the SA 2.0 contract that PR #3487 misread."""++ @pytest.mark.parametrize("iteration", range(20))+ def test_checked_out_session_completes_after_dispose(+ self, user_engine, iteration+ ):+ """+ Mid-transaction dispose from another thread MUST NOT break the+ writer's session. SA 2.0 `QueuePool.dispose` drains only idle+ entries and `Engine.dispose` calls `pool.recreate()` — a thread+ holding a checked-out connection keeps using it until return.+ 20 iterations surface races.+ """+ _, _, engine = user_engine++ key = f"atomicity.test.survival.{iteration}"+ writer_ready = threading.Event()+ main_disposed = threading.Event()+ writer_result = {}++ def writer():+ Session = sessionmaker(bind=engine)+ try:+ with Session() as session:+ session.add(+ Setting(+ key=key,+ value=f"value_{iteration}",+ name=key,+ type="APP",+ visible=False,+ editable=False,+ )+ )+ session.flush()+ writer_ready.set()+ if not main_disposed.wait(timeout=5.0):+ writer_result["error"] = (+ "main thread did not signal dispose within 5s"+ )+ return+ session.commit()+ writer_result["ok"] = True+ except Exception as exc:+ writer_result["error"] = repr(exc)++ t = threading.Thread(target=writer, daemon=True)+ t.start()++ assert writer_ready.wait(timeout=5.0), (+ f"writer did not start; result={writer_result}"+ )+ engine.dispose()+ main_disposed.set()+ t.join(timeout=10.0)+ assert not t.is_alive(), "writer thread did not finish"++ assert writer_result.get("ok") is True, (+ "engine.dispose() must NOT break a thread holding a "+ "checked-out connection — if this fires, either SA 2.0 "+ "semantics changed or SQLCipher introduced a hook that "+ "violates them. Error: "+ f"{writer_result.get('error')}"+ )++ Session = sessionmaker(bind=engine)+ with Session() as s:+ row = s.query(Setting).filter(Setting.key == key).first()+ assert row is not None, (+ "writer's committed row must be readable from a fresh "+ "session after dispose"+ )+ assert row.value == f"value_{iteration}"++ def test_dispose_without_checked_out_connections_is_noop_for_clients(+ self, user_engine+ ):+ """Sanity: dispose on an idle engine leaves subsequent sessions+ working normally."""+ _, _, engine = user_engine++ Session = sessionmaker(bind=engine)+ with Session() as s:+ s.add(+ Setting(+ key="atomicity.test.pre_dispose",+ value="before",+ name="atomicity.test.pre_dispose",+ type="APP",+ visible=False,+ editable=False,+ )+ )+ s.commit()++ engine.dispose()++ with Session() as s:+ row = (+ s.query(Setting)+ .filter(Setting.key == "atomicity.test.pre_dispose")+ .first()+ )+ assert row is not None+ assert row.value == "before"+ s.add(+ Setting(+ key="atomicity.test.post_dispose",+ value="after",+ name="atomicity.test.post_dispose",+ type="APP",+ visible=False,+ editable=False,+ )+ )+ s.commit()++ with Session() as s:+ row = (+ s.query(Setting)+ .filter(Setting.key == "atomicity.test.post_dispose")+ .first()+ )+ assert row is not None+ assert row.value == "after"diff --git a/tests/settings/test_settings_manager.py b/tests/settings/test_settings_manager.pyindex e45fcd094e..19a3dfbd12 100644--- a/tests/settings/test_settings_manager.py+++ b/tests/settings/test_settings_manager.py@@ -801,6 +801,22 @@ class TestSettingsManagerVersioning:mock_session.add.assert_called_once()mock_session.commit.assert_called_once()+ def test_update_db_version_commit_false(self):+ """update_db_version(commit=False) must stage the version row but+ NOT call session.commit() — callers that bundle writes into a+ single atomic transaction rely on this.+ """+ mock_session = MagicMock()+ mock_session.query.return_value.count.return_value = 1++ manager = SettingsManager(db_session=mock_session)++ with patch.object(manager, "delete_setting"):+ manager.update_db_version(commit=False)++ mock_session.add.assert_called_once()+ mock_session.commit.assert_not_called()+class TestSettingsManagerStaticMethods:"""Tests for static helper methods."""