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(library): defer text_content in collection document loads (#4560) (#4598)

LearningCircuit55d838e302d2
diff --git a/changelog.d/+bound-library-document-loads.bugfix.md b/changelog.d/+bound-library-document-loads.bugfix.md
new file mode 100644
index 0000000000..65c292811c
--- /dev/null
+++ b/changelog.d/+bound-library-document-loads.bugfix.md
@@ -0,0 +1 @@
+Library document indexing, collection document listing, and filesystem sync no longer load every document's full text body into memory at once — the large `text_content` column is now deferred (and a document's "has text" flag is computed in SQL), preventing `MemoryError` on large libraries.
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 4cd470631e..bb9ecb3d1f 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -32,6 +32,8 @@ from datetime import datetime, UTC
from pathlib import Path
from typing import Optional
+from sqlalchemy.orm import defer
+
from ...constants import (
DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS,
DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS_JSON,
@@ -1974,21 +1976,29 @@ def get_collection_documents(collection_id):
{"success": False, "error": "Collection not found"}
), 404
- # Get documents through junction table
+ # Get documents through junction table. Compute "has text in DB"
+ # at the SQL level and defer the text_content column, so listing a
+ # collection doesn't pull every document's full text body into
+ # memory just to test it for truthiness (#4560).
+ has_text_col = (
+ Document.text_content.isnot(None)
+ & (Document.text_content != "")
+ ).label("has_text_db")
doc_links = (
- db_session.query(DocumentCollection, Document)
+ db_session.query(DocumentCollection, Document, has_text_col)
.join(Document)
+ .options(defer(Document.text_content))
.filter(DocumentCollection.collection_id == collection_id)
.all()
)
documents = []
- for link, doc in doc_links:
+ for link, doc, has_text_db in doc_links:
# Check if PDF file is stored
has_pdf = bool(
doc.file_path and doc.file_path not in FILE_PATH_SENTINELS
)
- has_text_db = bool(doc.text_content)
+ has_text_db = bool(has_text_db)
# Use title if available, otherwise filename
display_title = doc.title or doc.filename or "Untitled"
@@ -2198,6 +2208,11 @@ def _query_documents_to_index(db_session, collection_id, force_reindex):
query = (
db_session.query(DocumentCollection, Document)
.join(Document)
+ # Don't load the large text_content body: the indexing loop only
+ # reads doc.id/filename/title (index_document re-fetches by id in a
+ # worker thread), so loading every document's full text here just to
+ # iterate is what exhausts memory on big collections (#4560).
+ .options(defer(Document.text_content))
.filter(DocumentCollection.collection_id == collection_id)
)
diff --git a/src/local_deep_research/research_library/services/library_service.py b/src/local_deep_research/research_library/services/library_service.py
index 8e0e5a1e2b..ab160d051c 100644
--- a/src/local_deep_research/research_library/services/library_service.py
+++ b/src/local_deep_research/research_library/services/library_service.py
@@ -14,7 +14,7 @@ from urllib.parse import urlparse
from loguru import logger
from sqlalchemy import or_, func, case
-from sqlalchemy.orm import aliased
+from sqlalchemy.orm import aliased, defer
from ...constants import FILE_PATH_SENTINELS
from ...database.models.download_tracker import DownloadTracker
@@ -1153,10 +1153,15 @@ class LibraryService:
# and no DownloadTracker, so they don't belong in this routine
# (and the destructive `else` branch below would otherwise
# silently delete every uploaded document).
+ # Don't load the large text_content body: this sync loop only
+ # reads original_url/id/title (and may delete the row), so loading
+ # every completed document's full text would needlessly exhaust
+ # memory on a large library (#4560).
documents = (
session.query(Document)
.filter_by(status=DocumentStatus.COMPLETED)
.filter(Document.original_url.isnot(None))
+ .options(defer(Document.text_content))
.all()
)
diff --git a/tests/research_library/routes/test_rag_indexing_helpers.py b/tests/research_library/routes/test_rag_indexing_helpers.py
index 83b67ebcab..dd8f2981ff 100644
--- a/tests/research_library/routes/test_rag_indexing_helpers.py
+++ b/tests/research_library/routes/test_rag_indexing_helpers.py
@@ -95,6 +95,7 @@ class TestQueryDocumentsToIndex:
def _chainable_session(self, all_result):
db = Mock()
chain = db.query.return_value.join.return_value
+ chain.options.return_value = chain
chain.filter.return_value = chain
chain.all.return_value = all_result
return db, chain
@@ -139,6 +140,26 @@ class TestQueryDocumentsToIndex:
)
)
+ def test_does_not_eager_load_text_content(
+ self, library_session, mock_document, mock_collection
+ ):
+ """The indexing query must defer text_content. The loop only reads
+ doc.id/filename/title (index_document re-fetches by id), so eagerly
+ loading every document's full text body is what exhausts memory on a
+ large collection (#4560). Real-DB guard: a revert removing the
+ defer() option is output-identical and would otherwise pass."""
+ from sqlalchemy import inspect as sa_inspect
+
+ result = _query_documents_to_index(
+ library_session, mock_collection.id, force_reindex=True
+ )
+
+ assert len(result) == 1
+ _link, doc = result[0]
+ # text_content is deferred (not loaded); id is available.
+ assert "text_content" in sa_inspect(doc).unloaded
+ assert doc.id is not None
+
class TestResetCollectionForReindex:
def test_clears_chunks_indices_and_marks_unindexed(self):
diff --git a/tests/research_library/routes/test_rag_routes_background_coverage.py b/tests/research_library/routes/test_rag_routes_background_coverage.py
index 3a44bef245..2415391b24 100644
--- a/tests/research_library/routes/test_rag_routes_background_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_background_coverage.py
@@ -49,6 +49,7 @@ def _build_mock_query(all_result=None, first_result=None, count_result=0):
q.order_by.return_value = q
q.outerjoin.return_value = q
q.join.return_value = q
+ q.options.return_value = q
q.limit.return_value = q
q.offset.return_value = q
q.delete.return_value = 0
diff --git a/tests/research_library/routes/test_rag_routes_coverage.py b/tests/research_library/routes/test_rag_routes_coverage.py
index c9560bcb0c..480a43b233 100644
--- a/tests/research_library/routes/test_rag_routes_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_coverage.py
@@ -1366,8 +1366,11 @@ class TestGetCollectionDocuments:
elif call_count[0] == 2:
join_q = _build_mock_query()
q.join.return_value = join_q
+ join_q.options.return_value = join_q
join_q.filter.return_value = join_q
- join_q.all.return_value = [(mock_link, mock_doc)]
+ # 3-tuple: (link, doc, has_text_db) — has_text is now computed
+ # at the SQL level instead of read from doc.text_content.
+ join_q.all.return_value = [(mock_link, mock_doc, True)]
elif call_count[0] == 3:
q.filter.return_value = q
q.count.return_value = 1
@@ -1414,6 +1417,7 @@ class TestGetCollectionDocuments:
elif call_count[0] == 2:
join_q = _build_mock_query()
q.join.return_value = join_q
+ join_q.options.return_value = join_q
join_q.filter.return_value = join_q
join_q.all.return_value = []
elif call_count[0] == 3:
diff --git a/tests/research_library/routes/test_rag_routes_deep_coverage.py b/tests/research_library/routes/test_rag_routes_deep_coverage.py
index 148ac3bb8c..018e488aaf 100644
--- a/tests/research_library/routes/test_rag_routes_deep_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_deep_coverage.py
@@ -99,6 +99,7 @@ def _build_mock_query(all_result=None, first_result=None, count_result=0):
q.order_by.return_value = q
q.outerjoin.return_value = q
q.join.return_value = q
+ q.options.return_value = q
q.limit.return_value = q
q.offset.return_value = q
q.delete.return_value = 0
diff --git a/tests/research_library/routes/test_rag_routes_gaps_coverage.py b/tests/research_library/routes/test_rag_routes_gaps_coverage.py
index b58bbb4dd4..d5a77228d6 100644
--- a/tests/research_library/routes/test_rag_routes_gaps_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_gaps_coverage.py
@@ -60,6 +60,7 @@ def _build_mock_query(all_result=None, first_result=None, count_result=0):
q.order_by.return_value = q
q.outerjoin.return_value = q
q.join.return_value = q
+ q.options.return_value = q
q.limit.return_value = q
q.offset.return_value = q
return q
diff --git a/tests/research_library/routes/test_rag_routes_indexing_coverage.py b/tests/research_library/routes/test_rag_routes_indexing_coverage.py
index a5aa3ec002..cc9ec8793d 100644
--- a/tests/research_library/routes/test_rag_routes_indexing_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_indexing_coverage.py
@@ -79,6 +79,7 @@ def _build_mock_query(all_result=None, first_result=None, count_result=0):
q.order_by.return_value = q
q.outerjoin.return_value = q
q.join.return_value = q
+ q.options.return_value = q
q.limit.return_value = q
q.offset.return_value = q
q.delete.return_value = 0
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 36f57fe7f8..4a68770e78 100644
--- a/tests/research_library/routes/test_rag_routes_upload_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_upload_coverage.py
@@ -85,6 +85,7 @@ def _build_mock_query(all_result=None, first_result=None, count_result=0):
q.order_by.return_value = q
q.outerjoin.return_value = q
q.join.return_value = q
+ q.options.return_value = q
q.limit.return_value = q
q.offset.return_value = q
q.delete.return_value = 0
diff --git a/tests/research_library/services/test_library_service_crud_deep.py b/tests/research_library/services/test_library_service_crud_deep.py
index 0a0e34601c..7f272d8ac5 100644
--- a/tests/research_library/services/test_library_service_crud_deep.py
+++ b/tests/research_library/services/test_library_service_crud_deep.py
@@ -525,7 +525,7 @@ class TestSyncLibraryWithFilesystem:
"""No completed documents → all stats zero."""
service = _make_service()
mock_session = MagicMock()
- mock_session.query.return_value.filter_by.return_value.filter.return_value.all.return_value = []
+ mock_session.query.return_value.filter_by.return_value.filter.return_value.options.return_value.all.return_value = []
_mock_session_cm(mocker, mock_session)
result = service.sync_library_with_filesystem()
@@ -547,7 +547,7 @@ class TestSyncLibraryWithFilesystem:
mock_tracker = Mock()
mock_tracker.file_path = "pdfs/doc.pdf"
- mock_session.query.return_value.filter_by.return_value.filter.return_value.all.return_value = [
+ mock_session.query.return_value.filter_by.return_value.filter.return_value.options.return_value.all.return_value = [
mock_doc
]
@@ -562,7 +562,7 @@ class TestSyncLibraryWithFilesystem:
if call_count["n"] == 1:
# Document query
q = MagicMock()
- q.filter_by.return_value.filter.return_value.all.return_value = [
+ q.filter_by.return_value.filter.return_value.options.return_value.all.return_value = [
mock_doc
]
return q
@@ -601,7 +601,7 @@ class TestSyncLibraryWithFilesystem:
call_count["n"] += 1
if call_count["n"] == 1:
q = MagicMock()
- q.filter_by.return_value.filter.return_value.all.return_value = [
+ q.filter_by.return_value.filter.return_value.options.return_value.all.return_value = [
mock_doc
]
return q
@@ -643,7 +643,7 @@ class TestSyncLibraryWithFilesystem:
call_count["n"] += 1
if call_count["n"] == 1:
q = MagicMock()
- q.filter_by.return_value.filter.return_value.all.return_value = [
+ q.filter_by.return_value.filter.return_value.options.return_value.all.return_value = [
mock_doc
]
return q
@@ -683,7 +683,7 @@ class TestSyncLibraryWithFilesystem:
call_count["n"] += 1
if call_count["n"] == 1:
q = MagicMock()
- q.filter_by.return_value.filter.return_value.all.return_value = docs
+ q.filter_by.return_value.filter.return_value.options.return_value.all.return_value = docs
return q
idx = call_count["n"] - 2
tq = MagicMock()