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(db): roll back reused thread-local session on with-block exception (#4841)

LearningCircuitd05fdd4b41f1
diff --git a/changelog.d/4841.bugfix.md b/changelog.d/4841.bugfix.md
new file mode 100644
index 0000000000..f16aca4ead
--- /dev/null
+++ b/changelog.d/4841.bugfix.md
@@ -0,0 +1 @@
+A failed `commit()`/`flush()` inside a `get_user_db_session()` block no longer poisons the thread's reused database session. The context manager now rolls the session back (and re-raises) when the block errors, so a single failed transaction can't cascade `PendingRollbackError` into every later operation on that thread. Paths that catch and swallow such a failure while reusing the session are also recovered explicitly: a PDF download or text extraction that fails mid-write, and a multi-file library upload where one bad file would otherwise fail the whole batch.
diff --git a/src/local_deep_research/database/session_context.py b/src/local_deep_research/database/session_context.py
index c3712b8b93..2f1284ce8e 100644
--- a/src/local_deep_research/database/session_context.py
+++ b/src/local_deep_research/database/session_context.py
@@ -179,7 +179,21 @@ def get_user_db_session(
if password and has_app_context():
g.user_password = password
- yield session
+ # Wrap only the yield: the session is established and non-None here,
+ # and we want to recover *the caller's* block — not setup failures
+ # above, where there may be no usable session to roll back.
+ try:
+ yield session
+ except Exception:
+ # The yielded session is a *reused* thread-local session, not a
+ # fresh one closed on exit. If the caller's ``with`` block raised
+ # (most importantly a failed ``session.commit()``/``flush()``),
+ # the session is left in ``PendingRollbackError`` state and the
+ # next operation on this thread cascades. Roll it back here so an
+ # unguarded ``with`` block can't poison the thread, then re-raise
+ # so the original error still surfaces to the caller.
+ safe_rollback(session, "get_user_db_session")
+ raise
finally:
# Only close if we created a new session (which we don't anymore)
diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.py
index de67b271b2..541da591ea 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -1604,7 +1604,10 @@ def update_collection(collection_id):
@upload_rate_limit_ip
def upload_to_collection(collection_id):
"""Upload files to a collection."""
- from ...database.session_context import get_user_db_session
+ from ...database.session_context import (
+ get_user_db_session,
+ safe_rollback,
+ )
from ...security import sanitize_filename, UnsafeFilenameError
from pathlib import Path
import hashlib
@@ -1947,6 +1950,13 @@ def upload_to_collection(collection_id):
)
except Exception:
+ # A failed flush / save_pdf / ensure_in_collection above
+ # poisons the shared request session. Without a rollback the
+ # NEXT file in the loop — and the post-loop commit — cascade
+ # into PendingRollbackError, failing the whole batch (and
+ # 500ing files that already succeeded). Recover so one bad
+ # file doesn't take the rest down.
+ safe_rollback(db_session, "upload_to_collection")
errors.append(
{
"filename": filename,
diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.py
index 04243467e5..cbab04dbfe 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -925,15 +925,34 @@ class DownloadService:
except Exception as e:
logger.exception(f"Download failed for {url}")
- attempt.succeeded = False
- attempt.error_type = type(e).__name__
- # Surfaced to the browser via the download SSE stream, and
- # request/network errors can echo a resource URL carrying an
- # api_key/token or user:pass@host — scrub before returning.
- attempt.error_message = sanitize_error_for_client(str(e))
+ # The error may have come from a failed flush/commit in the
+ # success path above (e.g. save_pdf / ensure_in_collection),
+ # leaving the *shared* session in PendingRollbackError. The caller
+ # (download_resource) keeps using this same session and commits
+ # again, so roll back here or that commit cascades. This swallow-
+ # and-return path is invisible to get_user_db_session's own
+ # rollback (we don't propagate), hence the explicit recovery.
+ safe_rollback(session, "_download_pdf")
tracker.is_accessible = False
- # Sanitize error message before returning to API
- safe_error = attempt.error_message
+ # request/network errors can echo a resource URL carrying an
+ # api_key/token or user:pass@host — scrub before returning. The
+ # message is surfaced to the browser via the download SSE stream.
+ safe_error = sanitize_error_for_client(str(e))
+ # The rollback discarded the pending ``attempt`` row added above,
+ # so re-record the failed attempt on the now-clean session for
+ # download_resource to commit.
+ session.add(
+ DownloadAttempt(
+ url_hash=tracker.url_hash,
+ attempt_number=tracker.download_attempts.count() + 1
+ if hasattr(tracker, "download_attempts")
+ else 1,
+ attempted_at=datetime.now(UTC),
+ succeeded=False,
+ error_type=type(e).__name__,
+ error_message=safe_error,
+ )
+ )
return False, safe_error, None
def _extract_text_from_pdf(self, pdf_content: bytes) -> Optional[str]:
@@ -1251,6 +1270,12 @@ class DownloadService:
logger.exception(
f"Failed to extract text from existing PDF: {pdf_path}"
)
+ # The commit above can fail and poison the shared session.
+ # download_as_text swallows this None and may then return cleanly
+ # (e.g. a non-retry decision), so the with-block exits without an
+ # exception — get_user_db_session's rollback never fires. Recover
+ # the session here or the next operation on this thread cascades.
+ safe_rollback(session, "_try_existing_pdf_extraction")
return None # Fall through to other methods
def _try_api_text_extraction(
@@ -1309,6 +1334,12 @@ class DownloadService:
)
return True, None
except Exception as e:
+ # Roll back FIRST: the failed commit/flush poisoned the shared
+ # session, and even dereferencing resource.id in the log line below
+ # can trigger a refresh that re-raises PendingRollbackError.
+ # download_as_text reuses this session (_record_retry_attempt)
+ # after we return, so it must be clean.
+ safe_rollback(session, "_try_api_text_extraction")
logger.exception(f"Failed to save text for resource {resource.id}")
# Sanitize error message before returning to API
safe_error = sanitize_error_for_client(
@@ -1390,6 +1421,11 @@ class DownloadService:
)
return True, None
except Exception as e:
+ # Roll back FIRST (see _try_api_text_extraction): dereferencing
+ # resource.id while the session is poisoned would itself re-raise
+ # PendingRollbackError. download_as_text reuses this session after
+ # we return.
+ safe_rollback(session, "_fallback_pdf_extraction")
logger.exception(f"Failed to save text for resource {resource.id}")
# Sanitize error message before returning to API
safe_error = sanitize_error_for_client(
diff --git a/tests/database/test_session_context_rollback.py b/tests/database/test_session_context_rollback.py
new file mode 100644
index 0000000000..60d93d350b
--- /dev/null
+++ b/tests/database/test_session_context_rollback.py
@@ -0,0 +1,137 @@
+"""Regression tests: ``get_user_db_session`` rolls back the reused thread-local
+session when the caller's ``with`` block raises.
+
+Root cause behind the family of bare-``session.commit()`` cascade bugs: the
+session yielded by ``get_user_db_session`` is a *reused* thread-local session
+that is never closed on exit. Before this fix, an exception escaping the
+``with`` block — most commonly a failed ``commit()``/``flush()`` — left the
+session in ``PendingRollbackError`` state, and the *next* operation on that
+thread cascaded. The context manager now rolls the session back on exception
+exit and re-raises, so a single unguarded block can no longer poison the whole
+thread.
+"""
+
+from unittest.mock import Mock, patch
+
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.exc import IntegrityError
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import SourceType
+
+import local_deep_research.database.session_context as _sc_mod
+
+SC = "local_deep_research.database.session_context"
+TLS = "local_deep_research.database.thread_local_session.get_metrics_session"
+
+# Captured at module import — before any test runs, so before a sibling test
+# (e.g. the rag-route suites) can leak a patch over this attribute that its
+# teardown failed to restore. The autouse fixture below pins it back so these
+# tests, which exercise the real context manager, are order-independent.
+_REAL_GET_USER_DB_SESSION = _sc_mod.get_user_db_session
+
+
+class TestGetUserDbSessionRollback:
+ """Rollback-on-exception behaviour of the get_user_db_session context manager."""
+
+ @pytest.fixture(autouse=True)
+ def _isolate_session_context(self):
+ """Make these tests immune to leaked global state from sibling suites.
+
+ Two guards:
+ - Restore the real ``get_user_db_session`` (a rag-route test leaks a
+ MagicMock over it that its teardown fails to clear; without this our
+ ``with get_user_db_session(...)`` would yield that mock, not our
+ injected session).
+ - Force ``get_g_db_session`` to None so we deterministically exercise
+ the thread-local branch regardless of any leaked ``g.current_user``.
+ """
+ with (
+ patch.object(
+ _sc_mod, "get_user_db_session", _REAL_GET_USER_DB_SESSION
+ ),
+ patch.object(_sc_mod, "get_g_db_session", return_value=None),
+ ):
+ yield
+
+ def test_real_thread_local_session_recovered_after_failed_commit(self, app):
+ """End-to-end proof with a real SQLite session: a failed commit in one
+ ``with`` block must not poison the next block on the same thread-local
+ session. Without the fix, block 2's commit raises PendingRollbackError.
+ """
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ real_session = sessionmaker(bind=engine)()
+ # Pre-existing row so the duplicate-PK insert below is a *real*
+ # constraint failure at commit time.
+ real_session.add(SourceType(id="dup", name="a", display_name="A"))
+ real_session.commit()
+
+ with app.test_request_context():
+ with patch(f"{SC}.db_manager") as mock_db:
+ mock_db.has_encryption = False
+ with patch(TLS, return_value=real_session):
+ # Block 1: a bare commit fails on a duplicate primary key.
+ with pytest.raises(IntegrityError):
+ with get_user_db_session(
+ username="u", password="p"
+ ) as s:
+ s.add(
+ SourceType(id="dup", name="b", display_name="B")
+ )
+ s.commit()
+
+ # Block 2: the SAME thread-local session must be usable.
+ with get_user_db_session(username="u", password="p") as s:
+ s.add(SourceType(id="ok", name="ok", display_name="OK"))
+ s.commit()
+
+ assert real_session.query(SourceType).filter_by(id="ok").count() == 1
+ real_session.close()
+ engine.dispose()
+
+ def test_clean_exit_does_not_roll_back(self, app):
+ """Normal (non-exception) exit must NOT roll back — intentional pending
+ state is the caller's to commit; we only recover on error.
+ """
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+
+ with app.test_request_context():
+ with patch(f"{SC}.db_manager") as mock_db:
+ mock_db.has_encryption = False
+ mock_session = Mock()
+ with patch(TLS, return_value=mock_session):
+ with get_user_db_session(username="u", password="p"):
+ pass
+
+ mock_session.rollback.assert_not_called()
+
+ def test_secondary_rollback_failure_does_not_mask_original_error(self, app):
+ """If the recovery rollback itself raises, the ORIGINAL error must
+ still propagate (safe_rollback swallows the rollback failure).
+ """
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+
+ with app.test_request_context():
+ with patch(f"{SC}.db_manager") as mock_db:
+ mock_db.has_encryption = False
+ mock_session = Mock()
+ mock_session.rollback.side_effect = RuntimeError(
+ "rollback boom"
+ )
+ with patch(TLS, return_value=mock_session):
+ with pytest.raises(ValueError, match="original"):
+ with get_user_db_session(username="u", password="p"):
+ raise ValueError("original")
+
+ mock_session.rollback.assert_called_once()
diff --git a/tests/research_library/routes/test_rag_routes_upload_coverage.py b/tests/research_library/routes/test_rag_routes_upload_coverage.py
index 4a68770e78..94ee73f7ec 100644
--- a/tests/research_library/routes/test_rag_routes_upload_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_upload_coverage.py
@@ -198,6 +198,53 @@ def app():
class TestUploadToCollection:
"""Tests for the upload_to_collection route."""
+ def test_upload_rolls_back_per_failed_file_so_batch_survives(self, app):
+ """A per-file DB failure must roll back the shared request session so
+ the next file in the batch — and the post-loop commit — don't cascade
+ into PendingRollbackError and 500 the whole upload.
+
+ Mocked session can't reproduce the real cascade (it never enters
+ PendingRollbackError), so this pins the fix is *wired*: rollback runs
+ once per failed file. Without ``safe_rollback`` in the except, rollback
+ is never called and this fails.
+ """
+ mock_coll = Mock()
+ mock_coll.id = "coll-1"
+
+ db_session = _make_db_session()
+ call_count = {"n": 0}
+
+ def query_side_effect(model):
+ call_count["n"] += 1
+ if call_count["n"] == 1:
+ # Collection existence check passes.
+ return _build_mock_query(first_result=mock_coll)
+ # Every per-file Document hash lookup raises, poisoning the session.
+ raise RuntimeError("simulated DB failure")
+
+ db_session.query = Mock(side_effect=query_side_effect)
+
+ with _auth_client(app, mock_db_session=db_session) as (client, ctx):
+ resp = client.post(
+ "/library/api/collections/coll-1/upload",
+ data={
+ "files": [
+ (BytesIO(b"file one"), "a.txt"),
+ (BytesIO(b"file two"), "b.txt"),
+ ]
+ },
+ content_type="multipart/form-data",
+ )
+
+ # Batch survives as a 200 (not a 500); both files errored, none uploaded.
+ assert resp.status_code == 200
+ rdata = resp.get_json()
+ assert rdata["success"] is True
+ assert len(rdata["uploaded"]) == 0
+ assert len(rdata["errors"]) == 2
+ # The fix: each failed file rolled the shared session back.
+ assert db_session.rollback.call_count == 2
+
def test_upload_no_files_key(self, app):
"""POST with no 'files' key in the request returns 400."""
with _auth_client(app) as (client, ctx):
diff --git a/tests/research_library/services/test_download_service_session_rollback.py b/tests/research_library/services/test_download_service_session_rollback.py
new file mode 100644
index 0000000000..5bd67ff2fd
--- /dev/null
+++ b/tests/research_library/services/test_download_service_session_rollback.py
@@ -0,0 +1,246 @@
+"""Regression tests: ``_download_pdf`` rolls back the *shared* session on a
+success-path failure.
+
+``_download_pdf`` receives the session owned by its caller ``download_resource``
+and that caller keeps using it — it records a retry attempt, updates the queue
+row, and commits — after ``_download_pdf`` returns. ``_download_pdf``'s broad
+``except`` swallows the error and returns ``False`` rather than propagating, so
+the rollback added to ``get_user_db_session`` cannot see it. If a DB error in
+the success path (flush / save_pdf / ensure_in_collection) leaves the session in
+``PendingRollbackError``, the caller's later commit cascades.
+
+The fix rolls the shared session back inside that ``except`` and re-records the
+failed ``DownloadAttempt`` (the rollback discards the pending one), so the
+caller inherits a clean, committable session.
+"""
+
+import uuid
+from unittest.mock import MagicMock, patch
+
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.download_tracker import (
+ DownloadAttempt,
+ DownloadTracker,
+)
+from local_deep_research.database.models.library import SourceType
+from local_deep_research.database.models.research import (
+ ResearchHistory,
+ ResearchResource,
+)
+from local_deep_research.research_library.services.download_service import (
+ DownloadService,
+)
+
+MODULE = "local_deep_research.research_library.services.download_service"
+
+
+def svc():
+ """DownloadService stub wired just enough to reach the success path."""
+ with patch.object(DownloadService, "__init__", lambda self, *a, **kw: None):
+ s = DownloadService.__new__(DownloadService)
+ s.username = "test_user"
+ s.password = "test_pass"
+ s.library_root = "/tmp/ldr-test-library"
+ s._closed = False
+ settings = MagicMock()
+ settings.get_setting = lambda key, default=None: {
+ "research_library.pdf_storage_mode": "none",
+ "research_library.max_pdf_size_mb": 50,
+ }.get(key, default)
+ s.settings = settings
+ # Allow every URL through the egress gate.
+ s._check_url_against_policy = lambda url: (True, "ok")
+ # One downloader that "succeeds" with PDF bytes -> enters success path.
+ downloader = MagicMock()
+ downloader.can_handle.return_value = True
+ downloader.download_with_result.return_value = MagicMock(
+ is_success=True,
+ content=b"%PDF-1.4 fake",
+ status_code=200,
+ skip_reason=None,
+ )
+ s.downloaders = [downloader]
+ return s
+
+
+def test_download_pdf_rolls_back_shared_session_and_records_attempt(svc):
+ """A success-path failure must roll back the shared session and still add a
+ failed DownloadAttempt for the caller to commit.
+ """
+ session = MagicMock()
+ resource = MagicMock(url="https://arxiv.org/pdf/2401.0001", id=7)
+ tracker = MagicMock(url_hash="abc123")
+ # MagicMock auto-creates download_attempts; make .count() a real int so the
+ # attempt_number arithmetic doesn't blow up.
+ tracker.download_attempts.count.return_value = 0
+
+ with patch(f"{MODULE}.PDFStorageManager"):
+ with patch(
+ f"{MODULE}.get_document_for_resource",
+ side_effect=RuntimeError("simulated flush failure"),
+ ):
+ success, error_msg, status_code = svc._download_pdf(
+ resource, tracker, session
+ )
+
+ assert success is False
+ assert status_code is None
+ session.rollback.assert_called_once()
+
+ # The failed attempt was re-recorded on the now-clean session.
+ added = [c.args[0] for c in session.add.call_args_list if c.args]
+ failed_attempts = [
+ a
+ for a in added
+ if isinstance(a, DownloadAttempt) and a.succeeded is False
+ ]
+ assert failed_attempts, "a failed DownloadAttempt should be recorded"
+ assert tracker.is_accessible is False
+
+
+def test_download_pdf_real_session_recovered_after_db_error(svc):
+ """End-to-end with a real SQLite session: after a success-path DB error
+ poisons the shared session, ``_download_pdf`` returns it clean so the
+ caller's subsequent commit succeeds (it would otherwise cascade).
+ """
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+
+ session.add(
+ SourceType(
+ id=str(uuid.uuid4()),
+ name="research_download",
+ display_name="Research Download",
+ )
+ )
+ rh = ResearchHistory(
+ id=str(uuid.uuid4()),
+ query="q",
+ mode="quick",
+ status="completed",
+ created_at="2026-05-09T00:00:00",
+ )
+ session.add(rh)
+ # Row whose primary key the poison step will collide with.
+ session.add(SourceType(id="dup", name="dup", display_name="Dup"))
+ session.commit()
+
+ resource = ResearchResource(
+ research_id=rh.id,
+ title="Test Paper",
+ url="https://arxiv.org/pdf/2401.0002",
+ source_type="academic",
+ created_at="2026-05-09T00:00:00",
+ )
+ session.add(resource)
+ session.commit()
+ tracker = DownloadTracker(
+ url=resource.url,
+ url_hash="hash-2401-0002",
+ first_resource_id=resource.id,
+ is_downloaded=False,
+ )
+ session.add(tracker)
+ session.commit()
+
+ def poison(sess, res):
+ # Mimic a failed flush deep in the success path: a duplicate primary
+ # key leaves the real session in PendingRollbackError.
+ sess.add(SourceType(id="dup", name="dup2", display_name="Dup2"))
+ sess.flush()
+
+ with patch(f"{MODULE}.PDFStorageManager"):
+ with patch(f"{MODULE}.get_document_for_resource", side_effect=poison):
+ success, error_msg, status_code = svc._download_pdf(
+ resource, tracker, session
+ )
+
+ assert success is False
+
+ # The caller commits the shared session after _download_pdf returns.
+ # Pre-fix this raised PendingRollbackError; now it succeeds.
+ session.commit()
+
+ recorded = (
+ session.query(DownloadAttempt)
+ .filter_by(url_hash="hash-2401-0002", succeeded=False)
+ .count()
+ )
+ assert recorded == 1
+
+ session.close()
+ engine.dispose()
+
+
+def test_try_api_text_extraction_rolls_back_shared_session(svc):
+ """Sibling swallow-then-reuse site in the download_as_text chain: a failed
+ save/commit in _try_api_text_extraction must roll back the shared session
+ so download_as_text's subsequent reuse (_record_retry_attempt) doesn't
+ cascade. Like _download_pdf, the except swallows and returns, so the
+ get_user_db_session rollback can't see it.
+ """
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+
+ rh = ResearchHistory(
+ id=str(uuid.uuid4()),
+ query="q",
+ mode="quick",
+ status="completed",
+ created_at="2026-05-09T00:00:00",
+ )
+ session.add(rh)
+ # Row whose primary key the poison step collides with. poison() MUST do a
+ # real failed flush (not a bare ``raise IntegrityError``): a real flush
+ # both poisons the session AND expires ``resource``, so the except's
+ # ``logger.exception(... resource.id)`` would refresh resource.id on the
+ # poisoned session and re-raise PendingRollbackError unless safe_rollback
+ # runs FIRST. That ordering is exactly what this test pins — keep the
+ # poison a real flush or the ordering coverage silently disappears.
+ session.add(SourceType(id="dup", name="dup", display_name="Dup"))
+ session.commit()
+
+ resource = ResearchResource(
+ research_id=rh.id,
+ title="Test Paper",
+ url="https://arxiv.org/abs/2401.0003",
+ source_type="academic",
+ created_at="2026-05-09T00:00:00",
+ )
+ session.add(resource)
+ session.commit()
+
+ # Downloader returns text content so we reach the save+commit path.
+ downloader = MagicMock()
+ downloader.download_with_result.return_value = MagicMock(
+ is_success=True, content=b"some extracted text"
+ )
+ svc._get_downloader = lambda url: downloader
+
+ def poison(*args, **kwargs):
+ # Mimic a failed flush/commit in the save path on the shared session.
+ session.add(SourceType(id="dup", name="dup2", display_name="Dup2"))
+ session.flush()
+
+ with patch.object(svc, "_save_text_with_db", side_effect=poison):
+ result = svc._try_api_text_extraction(session, resource)
+
+ # Swallowed into a (False, message) tuple, not raised.
+ assert result is not None
+ assert result[0] is False
+
+ # download_as_text reuses the shared session next; pre-fix this raised
+ # PendingRollbackError, now it succeeds.
+ session.add(SourceType(id="ok", name="ok", display_name="OK"))
+ session.commit()
+ assert session.query(SourceType).filter_by(id="ok").count() == 1
+
+ session.close()
+ engine.dispose()