~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(database): wrap SQLCipher driver errors (#6916)
LearningCircuit91728614a4a1
diff --git a/changelog.d/+sqlcipher-dialect-errors.bugfix.md b/changelog.d/+sqlcipher-dialect-errors.bugfix.mdnew file mode 100644index 0000000000..73a056fd7b--- /dev/null+++ b/changelog.d/+sqlcipher-dialect-errors.bugfix.md@@ -0,0 +1 @@+Use SQLCipher's database driver for encrypted SQLAlchemy engines so constraint violations and lock contention reach the existing error handlers. Concurrent chat sends now return the intended conflict response instead of an internal server error.diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex 89efd897ba..438ab2e106 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -1044,6 +1044,8 @@ class DatabaseManager:engine = create_engine("sqlite://",creator=create_engine_connection,+ # Match the creator's DBAPI so SQLAlchemy can wrap errors.+ module=get_sqlcipher_module().dbapi2,poolclass=self._pool_class,echo=False,hide_parameters=True,@@ -1532,6 +1534,7 @@ class DatabaseManager:engine = create_engine("sqlite://",creator=create_open_connection,+ module=get_sqlcipher_module().dbapi2,poolclass=self._pool_class,echo=False,hide_parameters=True,diff --git a/tests/chat/test_chat_followup_contracts.py b/tests/chat/test_chat_followup_contracts.pyindex d503decf90..33209a85c6 100644--- a/tests/chat/test_chat_followup_contracts.py+++ b/tests/chat/test_chat_followup_contracts.py@@ -27,9 +27,8 @@ endpoint return 200":* ``TestConcurrentSends`` -- two sends racing on one session.* ``TestErrorSurfaces`` -- the LLM boundary raises; is the session stillusable afterwards?-* ``TestUserDatabaseErrorWrapping`` -- the root cause behind the one real- defect found here: SQLAlchemy never wraps the encrypted driver's errors,- so every ``except IntegrityError`` guarding a user-database write is dead.+* ``TestUserDatabaseErrorWrapping`` -- encrypted driver errors must reach+ SQLAlchemy exception handlers, just like errors from ordinary SQLite.Known-and-filed defects deliberately NOT re-tested here: #5803 (deleting anon-newest attempt bricks the session) and #5793 (the follow-up router's@@ -1005,27 +1004,6 @@ class TestConcurrentSends:# finished; the loser never left one behind either.assert db.query(UserActiveResearch).all() == []- @pytest.mark.xfail(- strict=True,- reason=(- "DEFECT: send_message's `except IntegrityError` (sqlalchemy.exc) "- "never fires on a real per-user database, so the commit-time "- "concurrency collision escapes as an unhandled exception and the "- "client gets an opaque 500 {'error': 'Server error'} instead of "- "the designed 409 with `active_research_id`. Mechanism: "- "encrypted_db.py builds the engine as create_engine('sqlite://', "- "creator=<sqlcipher3 connection>), so SQLAlchemy's dialect loads "- "sqlite3 as its DBAPI while connections come from sqlcipher3; "- "_handle_dbapi_exception only wraps exceptions that are instances "- "of the loaded DBAPI's Error, so sqlcipher3.dbapi2.IntegrityError "- "propagates RAW past every `except sqlalchemy.exc.*` handler. "- "See test_unique_violation_is_not_a_sqlalchemy_error below. "- "Fix: create the engine with a URL whose dialect matches the "- "driver (sqlite+pysqlcipher://) or register sqlcipher3 as the "- "dialect's dbapi, so DBAPI errors are wrapped as usual; a "- "narrower stop-gap is to catch the driver's Error class too."- ),- )def test_commit_collision_should_be_409_not_500(self, app, stub_research_boundary):@@ -1042,15 +1020,15 @@ class TestConcurrentSends:class TestUserDatabaseErrorWrapping:- """Why the 409 above is unreachable: DBAPI errors are never wrapped."""+ """SQLAlchemy wraps encrypted DBAPI errors for application handlers."""def test_plain_sqlite_wraps_a_unique_violation_positive_control(self, tmp_path):"""CONTROL: on an ordinary SQLAlchemy sqlite engine the very sameduplicate insert DOES raise ``sqlalchemy.exc.IntegrityError`` -- so- the xfail below is about the encrypted-engine wiring, not about- SQLAlchemy or the model.+ the encrypted-engine test exercises the same SQLAlchemy contract+ with the production driver."""import sqlalchemy.excfrom sqlalchemy import create_engine@@ -1086,26 +1064,7 @@ class TestUserDatabaseErrorWrapping:)db.commit()- @pytest.mark.xfail(- strict=True,- reason=(- "DEFECT (root cause of the 500 above): a UNIQUE violation on a "- "real per-user encrypted database raises the RAW driver "- "exception sqlcipher3.dbapi2.IntegrityError, which is not a "- "sqlalchemy.exc.IntegrityError and not even a SQLAlchemyError. "- "encrypted_db.py builds the engine as create_engine('sqlite://', "- "creator=<sqlcipher3 connection>), so dialect.loaded_dbapi is "- "stdlib sqlite3 and SQLAlchemy declines to wrap the sqlcipher3 "- "error class. Consequence: EVERY `except IntegrityError` / "- "`except SQLAlchemyError` guard around a write to a user "- "database is dead code in production -- the guards are only "- "exercised by tests that run against a plain sqlite engine. "- "Fix: give the engine a dialect that matches the driver "- "(sqlite+pysqlcipher://... , or set the dialect's dbapi to "- "sqlcipher3.dbapi2) so error wrapping resumes."- ),- )- def test_unique_violation_is_not_a_sqlalchemy_error(self, app):+ def test_encrypted_unique_violation_is_wrapped(self, app):import sqlalchemy.excfrom local_deep_research.database.models import ResearchHistorydiff --git a/tests/database/test_sqlcipher_integration.py b/tests/database/test_sqlcipher_integration.pyindex 2c3852ecf7..8948364395 100644--- a/tests/database/test_sqlcipher_integration.py+++ b/tests/database/test_sqlcipher_integration.py@@ -60,6 +60,78 @@ def isolated_db_manager(tmp_path, monkeypatch):class TestSQLCipherIntegration:"""Real SQLCipher tests (not mocked)."""+ @pytest.mark.parametrize("reopen", [False, True], ids=["create", "reopen"])+ def test_constraint_error_wraps_and_transaction_rolls_back(+ self, isolated_db_manager, reopen+ ):+ """A failed encrypted write rolls back the whole unit of work."""+ from sqlalchemy import text+ from sqlalchemy.exc import IntegrityError++ engine = isolated_db_manager.create_user_database(+ "errors", "TestPass1!"+ )+ with engine.begin() as conn:+ conn.execute(+ text("CREATE TABLE error_probe (id INTEGER PRIMARY KEY)")+ )+ conn.execute(text("INSERT INTO error_probe VALUES (1)"))+ if reopen:+ isolated_db_manager.close_user_database("errors")+ engine = isolated_db_manager.open_user_database(+ "errors", "TestPass1!"+ )+ assert engine is not None++ with pytest.raises(IntegrityError):+ with engine.begin() as conn:+ conn.execute(text("INSERT INTO error_probe VALUES (2)"))+ conn.execute(text("INSERT INTO error_probe VALUES (1)"))++ with engine.begin() as conn:+ assert conn.execute(+ text("SELECT id FROM error_probe")+ ).scalars().all() == [1]+ # The pool/session remains usable after rollback.+ conn.execute(text("INSERT INTO error_probe VALUES (2)"))++ @pytest.mark.parametrize("reopen", [False, True], ids=["create", "reopen"])+ def test_lock_error_wraps_and_connection_can_retry(+ self, isolated_db_manager, reopen+ ):+ """Real lock contention reaches OperationalError handlers, then recovers."""+ from sqlalchemy import text+ from sqlalchemy.exc import OperationalError++ engine = isolated_db_manager.create_user_database(+ "locked", "TestPass1!"+ )+ with engine.begin() as conn:+ conn.execute(+ text("CREATE TABLE lock_probe (id INTEGER PRIMARY KEY)")+ )+ if reopen:+ isolated_db_manager.close_user_database("locked")+ engine = isolated_db_manager.open_user_database(+ "locked", "TestPass1!"+ )+ assert engine is not None++ with engine.connect() as writer, engine.connect() as contender:+ # Fail promptly while the other connection owns the write lock.+ contender.execute(text("PRAGMA busy_timeout = 1"))+ contender.rollback()+ writer.execute(text("INSERT INTO lock_probe VALUES (1)"))+ with pytest.raises(OperationalError, match="database is locked"):+ contender.execute(text("INSERT INTO lock_probe VALUES (2)"))+ contender.rollback()+ writer.rollback()+ contender.execute(text("INSERT INTO lock_probe VALUES (2)"))+ contender.commit()+ assert contender.execute(+ text("SELECT id FROM lock_probe")+ ).scalars().all() == [2]+def test_register_then_immediate_login(self, isolated_db_manager):"""Critical test: Registration followed by immediate login.diff --git a/tests/security/test_notes_chat_followup_cross_user.py b/tests/security/test_notes_chat_followup_cross_user.pyindex e8e0af7e89..27854f2276 100644--- a/tests/security/test_notes_chat_followup_cross_user.py+++ b/tests/security/test_notes_chat_followup_cross_user.py@@ -445,25 +445,26 @@ def test_notes_link_research_no_cross_user_row_persisted(two_users):"""A cannot end up with a persisted NoteResearch link from A's note toB's research_id.- NOTE: this only asserts the underlying DATA-ISOLATION invariant (no- cross-user row is ever committed) -- it deliberately does NOT assert on- the HTTP status code here. As of this run, POST- /notes/api/notes/<note_id>/research with a foreign research_id returns- HTTP 500 instead of the intended 404 ("Research run not found") --- tracked in #5721 (the route's IntegrityError handler never matches on- the encrypted DB backend, because SQLAlchemy never wraps the SQLCipher- driver's errors; same root cause as- tests/chat/test_chat_followup_contracts.py::TestUserDatabaseErrorWrapping).- No B data is returned and no link is created either way, so isolation- holds even though the error-status contract is broken. Narrow this to- ``== 404`` when #5721 lands.+ POST /notes/api/notes/<note_id>/research with a foreign research_id+ answers 404 ("Research run not found"): B's research run does not exist+ in A's own database, so the insert violates a foreign key. The engine+ loads the SQLCipher DBAPI, so SQLAlchemy wraps the driver's error as+ ``sqlalchemy.exc.IntegrityError`` and the route's IntegrityError handler+ maps it to 404 (#5721). Before that the driver's raw error skipped the+ handler and the route answered 500; see+ tests/chat/test_chat_followup_contracts.py::TestUserDatabaseErrorWrapping.+ No B data is returned and no link is created."""app, a, b = two_usersresp = a.client.post(f"/notes/api/notes/{a.note_id}/research",json={"research_id": b.research_id},)- assert resp.status_code in (404, 500), resp.get_data(as_text=True)+ _assert_ownership_404(+ resp,+ "A must not be able to link B's research run to A's note",+ expected_error_fragment="research run not found",+ )assert b.marker not in resp.get_data(as_text=True)# No NoteResearch row was persisted linking A's note to B's research,diff --git a/tests/security/test_user_db_error_parameter_redaction.py b/tests/security/test_user_db_error_parameter_redaction.pyindex 68bcd9007b..b35d378f11 100644--- a/tests/security/test_user_db_error_parameter_redaction.py+++ b/tests/security/test_user_db_error_parameter_redaction.py@@ -3,7 +3,7 @@import pytestfrom loguru import loggerfrom sqlalchemy import text-from sqlalchemy.exc import StatementError+from sqlalchemy.exc import IntegrityError, StatementErrorfrom unittest.mock import MagicMock, patchfrom local_deep_research.database.encrypted_db import DatabaseManager@@ -27,9 +27,12 @@ def manager(tmp_path, monkeypatch, request):def _assert_duplicate_url_is_hidden(engine, url):- # Plain SQLite is wrapped as SQLAlchemy IntegrityError; SQLCipher's- # driver raises its own IntegrityError directly in this path.- with pytest.raises(Exception, match="UNIQUE constraint failed") as failure:+ # SQLAlchemy wraps the errors of plain SQLite and of the SQLCipher driver+ # alike as IntegrityError. The wrapper's message renders the statement's+ # bound values unless hide_parameters is set.+ with pytest.raises(+ IntegrityError, match="UNIQUE constraint failed"+ ) as failure:with engine.begin() as connection:connection.execute(text("INSERT INTO url_canary (url) VALUES (:url)"),@@ -37,7 +40,6 @@ def _assert_duplicate_url_is_hidden(engine, url):)rendered = str(failure.value)- assert type(failure.value).__name__ == "IntegrityError"assert "user:private-password" not in renderedassert "private-path" not in renderedassert "private-token" not in rendered