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(journal_quality): close the session when the caller's block raises (#6080)

Ehsan566a4ed9596d
diff --git a/changelog.d/6032.bugfix.md b/changelog.d/6032.bugfix.md
new file mode 100644
index 0000000000..bc75f33dcb
--- /dev/null
+++ b/changelog.d/6032.bugfix.md
@@ -0,0 +1 @@
+Journal-quality database sessions are now closed when the calling block raises an unexpected error, so repeated failures no longer strand a SQLite connection and file descriptor. The production case is `InterfaceError` from #5931: it is a `DBAPIError` but not a `DatabaseError`, so it missed the `except (OperationalError, DatabaseError)` arm that used to hold the only close on the error path.
diff --git a/tests/journal_quality/test_db.py b/tests/journal_quality/test_db.py
index ba4507fdd3..1836ba7393 100644
--- a/tests/journal_quality/test_db.py
+++ b/tests/journal_quality/test_db.py
@@ -913,3 +913,61 @@ class TestUnlinkUnusableDbLogs:
for rec in loguru_caplog.records
if rec.levelname == "WARNING"
)
+
+
+class TestSessionCleanup:
+ """The session closes however the caller's block ends."""
+
+ class _FakeSession:
+ def __init__(self):
+ self.closed = False
+
+ def close(self):
+ self.closed = True
+
+ class _FakeEngine:
+ def __init__(self):
+ self.disposed = False
+
+ def dispose(self):
+ self.disposed = True
+
+ def _db_with(self, session):
+ from local_deep_research.journal_quality.db import JournalQualityDB
+
+ db = JournalQualityDB()
+ # A non-None engine makes _ensure_engine return early, so the test
+ # touches no file and needs no built DB.
+ db._engine = self._FakeEngine()
+ db._SessionLocal = lambda: session
+ return db
+
+ def test_closes_on_success(self):
+ session = self._FakeSession()
+ db = self._db_with(session)
+ with db.session():
+ pass
+ assert session.closed
+
+ def test_closes_when_the_block_raises_an_unexpected_error(self):
+ """A ValueError from the caller's block still closes the session.
+
+ Under NullPool every skipped close strands a connection and an FD.
+ """
+ session = self._FakeSession()
+ db = self._db_with(session)
+ with pytest.raises(ValueError):
+ with db.session():
+ raise ValueError("boom")
+ assert session.closed
+
+ def test_database_error_still_resets_the_engine(self):
+ from sqlalchemy.exc import OperationalError
+
+ session = self._FakeSession()
+ db = self._db_with(session)
+ with pytest.raises(OperationalError):
+ with db.session():
+ raise OperationalError("stmt", {}, Exception("gone"))
+ assert session.closed
+ assert db._engine is None