~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(db): don't load report_content/chunk_text into memory in list queries (#4560) (#4574)
LearningCircuit3a71c3dcbce1
diff --git a/changelog.d/4574.bugfix.md b/changelog.d/4574.bugfix.mdnew file mode 100644index 0000000000..94e1fdbb8a--- /dev/null+++ b/changelog.d/4574.bugfix.md@@ -0,0 +1 @@+Fixed a `MemoryError` when listing or clearing history on large libraries — history/report list queries no longer load full report bodies into memory.diff --git a/src/local_deep_research/research_library/services/library_rag_service.py b/src/local_deep_research/research_library/services/library_rag_service.pyindex a15948006d..41dd709b9a 100644--- a/src/local_deep_research/research_library/services/library_rag_service.py+++ b/src/local_deep_research/research_library/services/library_rag_service.py@@ -1814,9 +1814,12 @@ class LibraryRAGService:with get_user_db_session(self.username, self.db_password) as session:- # Get all chunk IDs for this collection+ # Get all chunk IDs for this collection. Select only the+ # id column — loading full DocumentChunk rows would pull+ # every chunk's text into memory just to build the id+ # list (#4560).chunks = (- session.query(DocumentChunk)+ session.query(DocumentChunk.id).filter_by(collection_name=collection_name).all())diff --git a/src/local_deep_research/storage/database.py b/src/local_deep_research/storage/database.pyindex 6130bbc568..4f6a93a784 100644--- a/src/local_deep_research/storage/database.py+++ b/src/local_deep_research/storage/database.py@@ -128,9 +128,17 @@ class DatabaseReportStorage(ReportStorage):) -> List[Dict[str, Any]]:"""List reports from database."""try:- query = self.session.query(ResearchHistory).filter(- ResearchHistory.report_content.isnot(None)- )+ # Select only the metadata columns the listing returns —+ # never load the large ``report_content`` body, which would+ # pull every report into memory at once (#4560). Filtering on+ # the column does not load it.+ query = self.session.query(+ ResearchHistory.id,+ ResearchHistory.query,+ ResearchHistory.mode,+ ResearchHistory.created_at,+ ResearchHistory.completed_at,+ ).filter(ResearchHistory.report_content.isnot(None))results = query.all()return [{diff --git a/src/local_deep_research/web/routes/history_routes.py b/src/local_deep_research/web/routes/history_routes.pyindex dce40da4ac..8f1c47dfcb 100644--- a/src/local_deep_research/web/routes/history_routes.py+++ b/src/local_deep_research/web/routes/history_routes.py@@ -50,10 +50,22 @@ def get_history():offset = max(0, offset)with get_user_db_session(username) as db_session:- # Single query with JOIN to get history + document counts+ # Single query with JOIN to get history + document counts.+ # Select only the columns the response needs — never the+ # large ``report_content`` Text body — so listing history+ # doesn't pull every report into memory (#4560).results = (db_session.query(- ResearchHistory,+ ResearchHistory.id,+ ResearchHistory.title,+ ResearchHistory.query,+ ResearchHistory.mode,+ ResearchHistory.status,+ ResearchHistory.created_at,+ ResearchHistory.completed_at,+ ResearchHistory.duration_seconds,+ ResearchHistory.research_meta,+ ResearchHistory.chat_session_id,func.count(Document.id).label("document_count"),).outerjoin(Document, Document.research_id == ResearchHistory.id)@@ -68,7 +80,7 @@ def get_history():# Convert to list of dictshistory = []- for research, doc_count in results:+ for research in results:item = {"id": research.id,"title": research.title,@@ -78,7 +90,7 @@ def get_history():"created_at": research.created_at,"completed_at": research.completed_at,"duration_seconds": research.duration_seconds,- "document_count": doc_count,+ "document_count": research.document_count,}item["metadata"] = filter_research_metadata(diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex e1ea0c9b98..02043086d7 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -1157,8 +1157,13 @@ def clear_history():try:with get_user_db_session(username) as db_session:- # Get all research records first to clean up files- research_records = db_session.query(ResearchHistory).all()+ # Get all research records first to clean up files. Select+ # only id + report_path (the columns the cleanup loop uses)+ # so clearing history doesn't load every report body into+ # memory (#4560).+ research_records = db_session.query(+ ResearchHistory.id, ResearchHistory.report_path+ ).all()# Get IDs of currently active research (snapshot)active_ids = get_active_research_ids()@@ -1314,9 +1319,23 @@ def get_history():try:with get_user_db_session(username) as db_session:- # Query all research history ordered by created_at+ # Query all research history ordered by created_at. Project+ # only the metadata columns the loop below consumes — never+ # the large ``report_content`` Text body — so this listing+ # doesn't pull every report into memory (#4560). This mirrors+ # the projection used by the symmetric /history/api endpoint.research_records = (- db_session.query(ResearchHistory)+ db_session.query(+ ResearchHistory.id,+ ResearchHistory.title,+ ResearchHistory.query,+ ResearchHistory.mode,+ ResearchHistory.status,+ ResearchHistory.created_at,+ ResearchHistory.completed_at,+ ResearchHistory.research_meta,+ ResearchHistory.chat_session_id,+ ).order_by(ResearchHistory.created_at.desc()).all())diff --git a/tests/storage/test_database_storage.py b/tests/storage/test_database_storage.pyindex 679de45a6d..01ec81c4af 100644--- a/tests/storage/test_database_storage.py+++ b/tests/storage/test_database_storage.py@@ -332,6 +332,29 @@ class TestListReports:assert result == []+ def test_projects_columns_not_full_entity(self, mock_session):+ """list_reports must select only metadata columns, never the full+ ResearchHistory entity — querying the entity eagerly loads the+ large report_content body into memory. Regression guard for #4560+ (a revert to query(ResearchHistory) is output-identical and would+ otherwise pass silently)."""+ from local_deep_research.database.models import ResearchHistory++ mock_session.query.return_value.filter.return_value.all.return_value = []++ storage = DatabaseReportStorage(mock_session)+ storage.list_reports()++ # Identity checks: a SQLAlchemy column's __eq__ builds a SQL+ # clause, so `in`/`==` membership tests are unsafe here.+ selected = mock_session.query.call_args.args+ assert not any(arg is ResearchHistory for arg in selected), (+ "list_reports must not query the full ResearchHistory entity"+ )+ assert not any(+ arg is ResearchHistory.report_content for arg in selected+ ), "list_reports must not load the report_content body"+def test_filters_records_with_report_content(self, mock_session):"""Should query with isnot(None) filter on report_content."""mock_session.query.return_value.filter.return_value.all.return_value = []diff --git a/tests/web/routes/test_history_routes.py b/tests/web/routes/test_history_routes.pyindex 8f1b6ac12a..f0e220a391 100644--- a/tests/web/routes/test_history_routes.py+++ b/tests/web/routes/test_history_routes.py@@ -136,10 +136,13 @@ class TestGetHistory:mock_research.progress_log = []mock_research.chat_session_id = None- # Set up query chain for JOIN query+ # Set up query chain for JOIN query. The projected query+ # yields flat Rows (document_count is a labeled column), so+ # the loop iterates `for research in results`.+ mock_research.document_count = 0mock_query = MagicMock()mock_query.outerjoin.return_value.group_by.return_value.order_by.return_value.limit.return_value.offset.return_value.all.return_value = [- (mock_research, 0)+ mock_research]mock_session.query.return_value = mock_query@@ -158,6 +161,42 @@ class TestGetHistory:assert "research_meta" not in itemassert "settings_snapshot" not in str(item.get("metadata", {}))+ def test_query_projects_columns_not_full_entity(self, authenticated_client):+ """get_history must project only metadata columns, never the full+ ResearchHistory entity — querying the entity eagerly loads the+ large report_content Text body into memory. Regression guard for+ #4560 (a revert to query(ResearchHistory) is output-identical and+ would otherwise pass silently)."""+ from local_deep_research.database.models import ResearchHistory++ with patch(+ "local_deep_research.web.routes.history_routes.get_user_db_session"+ ) as mock_session_ctx:+ mock_session = MagicMock()+ mock_session_ctx.return_value.__enter__ = MagicMock(+ return_value=mock_session+ )+ mock_session_ctx.return_value.__exit__ = MagicMock(+ return_value=None+ )++ mock_query = MagicMock()+ mock_query.outerjoin.return_value.group_by.return_value.order_by.return_value.limit.return_value.offset.return_value.all.return_value = []+ mock_session.query.return_value = mock_query++ response = authenticated_client.get(f"{HISTORY_PREFIX}/api")++ assert response.status_code == 200+ # Identity checks: a SQLAlchemy column's __eq__ builds a SQL+ # clause, so `in`/`==` membership tests are unsafe here.+ selected = mock_session.query.call_args.args+ assert not any(arg is ResearchHistory for arg in selected), (+ "get_history must not query the full ResearchHistory entity"+ )+ assert not any(+ arg is ResearchHistory.report_content for arg in selected+ ), "get_history must not load the report_content body"+def test_filters_settings_snapshot_from_metadata(self, authenticated_client):@@ -188,9 +227,10 @@ class TestGetHistory:}mock_research.chat_session_id = None+ mock_research.document_count = 3mock_query = MagicMock()mock_query.outerjoin.return_value.group_by.return_value.order_by.return_value.limit.return_value.offset.return_value.all.return_value = [- (mock_research, 3)+ mock_research]mock_session.query.return_value = mock_query@@ -803,10 +843,11 @@ class TestGetHistoryMetadataParsing:mock_research.report_path = "/path/to/report.md"mock_research.research_meta = {"strategy": "evidence_based"}mock_research.chat_session_id = None+ mock_research.document_count = 0mock_query = MagicMock()mock_query.outerjoin.return_value.group_by.return_value.order_by.return_value.limit.return_value.offset.return_value.all.return_value = [- (mock_research, 0)+ mock_research]mock_session.query.return_value = mock_query@@ -842,10 +883,11 @@ class TestGetHistoryMetadataParsing:mock_research.report_path = "/path/to/report.md"mock_research.research_meta = Nonemock_research.chat_session_id = None+ mock_research.document_count = 0mock_query = MagicMock()mock_query.outerjoin.return_value.group_by.return_value.order_by.return_value.limit.return_value.offset.return_value.all.return_value = [- (mock_research, 0)+ mock_research]mock_session.query.return_value = mock_querydiff --git a/tests/web/routes/test_history_routes_coverage.py b/tests/web/routes/test_history_routes_coverage.pyindex 6006abc206..03c6c0a3e2 100644--- a/tests/web/routes/test_history_routes_coverage.py+++ b/tests/web/routes/test_history_routes_coverage.py@@ -70,12 +70,17 @@ def _make_db_ctx_raising(exc):return ctx-def _build_join_chain(results):- """Build chained SQLAlchemy mock for the outerjoin query in get_history."""+def _build_join_chain(rows):+ """Build chained SQLAlchemy mock for the outerjoin query in get_history.++ ``rows`` are the flat result Rows the projected query yields — each row+ exposes the selected columns plus a ``document_count`` label as+ attributes (get_history iterates ``for research in results``).+ """q = MagicMock()(q.outerjoin.return_value.group_by.return_value.order_by.return_value.limit.return_value.offset.return_value.all- ).return_value = results+ ).return_value = rowsreturn q@@ -102,6 +107,7 @@ def _make_research(**overrides):"progress_log": "[]","report_path": None,"chat_session_id": None,+ "document_count": 0,}defaults.update(overrides)for k, v in defaults.items():@@ -157,9 +163,9 @@ class TestHistoryPage:class TestGetHistorySuccess:def test_returns_history_items_with_duration(self, client):"""get_history returns items when duration_seconds is already set."""- research = _make_research(duration_seconds=300)+ research = _make_research(duration_seconds=300, document_count=2)mock_session = MagicMock()- mock_session.query.return_value = _build_join_chain([(research, 2)])+ mock_session.query.return_value = _build_join_chain([research])with (patch(AUTH_DB_MANAGER, _mock_db_manager()),@@ -186,7 +192,7 @@ class TestGetHistorySuccess:completed_at="2024-01-01T10:05:00",)mock_session = MagicMock()- mock_session.query.return_value = _build_join_chain([(research, 0)])+ mock_session.query.return_value = _build_join_chain([research])with (patch(AUTH_DB_MANAGER, _mock_db_manager()),@@ -210,7 +216,7 @@ class TestGetHistorySuccess:completed_at="also-not-a-date",)mock_session = MagicMock()- mock_session.query.return_value = _build_join_chain([(research, 0)])+ mock_session.query.return_value = _build_join_chain([research])with (patch(AUTH_DB_MANAGER, _mock_db_manager()),diff --git a/tests/web/routes/test_history_routes_extended.py b/tests/web/routes/test_history_routes_extended.pyindex fafdb4485f..7072e5b33d 100644--- a/tests/web/routes/test_history_routes_extended.py+++ b/tests/web/routes/test_history_routes_extended.py@@ -170,11 +170,10 @@ class TestGetHistoryDurationRecalculation:mock_research.duration_seconds = Nonemock_research.research_meta = Nonemock_research.chat_session_id = None+ mock_research.document_count = 0mock_session = MagicMock()- mock_session.query.return_value = _build_query_chain(- [(mock_research, 0)]- )+ mock_session.query.return_value = _build_query_chain([mock_research])with (patch(diff --git a/tests/web/routes/test_research_routes.py b/tests/web/routes/test_research_routes.pyindex 62571d7aa9..45e7305d5c 100644--- a/tests/web/routes/test_research_routes.py+++ b/tests/web/routes/test_research_routes.py@@ -324,6 +324,41 @@ class TestGetHistoryApi:)assert response.status_code == 200, response.status_code+ def test_query_projects_columns_not_full_entity(self, authenticated_client):+ """/api/history must project only metadata columns, never the+ full ResearchHistory entity — querying the entity eagerly loads+ the large report_content Text body into memory. Regression guard+ for #4560 (a revert to query(ResearchHistory) is output-identical+ and would otherwise pass silently)."""+ from local_deep_research.database.models import ResearchHistory++ mock_session = MagicMock()+ mock_session.query.return_value.order_by.return_value.all.return_value = []+ with patch(f"{_RR}.get_user_db_session") as mock_db:+ mock_db.return_value.__enter__ = lambda s: mock_session+ mock_db.return_value.__exit__ = MagicMock(return_value=False)+ response = authenticated_client.get(+ f"{RESEARCH_PREFIX}/api/history"+ )+ assert response.status_code == 200, response.status_code++ # Identity checks: a SQLAlchemy column's __eq__ builds a SQL clause,+ # so `in`/`==` membership tests are unsafe here. Inspect EVERY query()+ # call (not a positional index) so the guard stays robust if queries+ # are reordered/added: the listing must never load the full+ # ResearchHistory entity or its report_content body in any of them.+ all_selected = [+ arg+ for call in mock_session.query.call_args_list+ for arg in call.args+ ]+ assert not any(arg is ResearchHistory for arg in all_selected), (+ "get_history must not query the full ResearchHistory entity"+ )+ assert not any(+ arg is ResearchHistory.report_content for arg in all_selected+ ), "get_history must not load the report_content body"+class TestGetResearchDetailsApi:"""Tests for /api/research/<id> endpoint."""