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(rag): update aggregate chunks on reindex (#5439)

Ziyang Guoc48329c6b990
diff --git a/changelog.d/+rag-index-chunk-delta.bugfix.md b/changelog.d/+rag-index-chunk-delta.bugfix.md
new file mode 100644
index 0000000000..0899e5f99a
--- /dev/null
+++ b/changelog.d/+rag-index-chunk-delta.bugfix.md
@@ -0,0 +1 @@
+Keep aggregate RAG chunk counts accurate when reindexing a document with a different number of chunks.
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.py
index d731f3fd7d..1b36c33cd0 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
@@ -1686,6 +1686,7 @@ class LibraryRAGService:
.filter_by(
document_id=document_id,
collection_id=collection_id,
+ rag_index_id=self.rag_index_record.id,
)
.first()
)
@@ -2023,11 +2024,16 @@ class LibraryRAGService:
existing_status = (
session.query(RagDocumentStatus)
.filter_by(
- document_id=document_id, collection_id=collection_id
+ document_id=document_id,
+ collection_id=collection_id,
+ rag_index_id=self.rag_index_record.id,
)
.first()
)
was_already_indexed = existing_status is not None
+ old_chunk_count = (
+ (existing_status.chunk_count or 0) if existing_status else 0
+ )
# Mark document as indexed using rag_document_status table
# Row existence = indexed, simple and clean
@@ -2062,18 +2068,25 @@ class LibraryRAGService:
"Also updated DocumentCollection.indexed for backward compatibility"
)
- # Update RAGIndex statistics (only if not already indexed)
+ # Keep the aggregate synchronized on both first index and
+ # replacement reindex. A replacement changes the per-document
+ # row above, so apply its new-old delta instead of skipping the
+ # aggregate update entirely.
rag_index_obj = (
session.query(RAGIndex)
.filter_by(id=self.rag_index_record.id)
.first()
)
- if rag_index_obj and not was_already_indexed:
- rag_index_obj.chunk_count += len(chunks)
- rag_index_obj.total_documents += 1
+ if rag_index_obj:
+ chunk_delta = len(chunks) - old_chunk_count
+ rag_index_obj.chunk_count += chunk_delta
+ if not was_already_indexed:
+ rag_index_obj.total_documents += 1
rag_index_obj.last_updated_at = datetime.now(UTC)
logger.info(
- f"Updated RAGIndex stats: chunk_count +{len(chunks)}, total_documents +1"
+ "Updated RAGIndex stats: "
+ f"chunk_count {chunk_delta:+d}, "
+ f"total_documents {'+1' if not was_already_indexed else '+0'}"
)
# Replace-on-reindex DB prune: no longer needed here —
diff --git a/tests/research_library/services/test_index_finalize_self_heal.py b/tests/research_library/services/test_index_finalize_self_heal.py
index e83e579919..b4c042d5bb 100644
--- a/tests/research_library/services/test_index_finalize_self_heal.py
+++ b/tests/research_library/services/test_index_finalize_self_heal.py
@@ -55,6 +55,7 @@ from local_deep_research.database.models.library import (
DocumentCollection,
DocumentStatus,
EmbeddingProvider,
+ RAGIndex,
RagDocumentStatus,
SourceType,
)
@@ -262,6 +263,57 @@ class TestIndexDocumentSelfHeal:
)
svc.close()
+ def test_force_reindex_updates_aggregate_chunk_delta(self, rag_env):
+ session = rag_env
+ source_type = self._source_type(session)
+
+ doc_id = uuid.uuid4().hex
+ coll_id = uuid.uuid4().hex
+ long_text = "\n\n".join(
+ f"Paragraph {i}: " + "alpha beta gamma " * 100 for i in range(30)
+ )
+ self._seed_document(
+ session,
+ source_type.id,
+ doc_id=doc_id,
+ coll_id=coll_id,
+ text=long_text,
+ title="Changing Notes",
+ )
+
+ svc = self._make_service("user-chunk-delta")
+ first = svc.index_document(doc_id, coll_id)
+ assert first["status"] == "success", first
+ old_count = first["chunk_count"]
+ assert old_count > 1
+
+ document = session.query(Document).filter_by(id=doc_id).one()
+ short_text = "A much shorter replacement document."
+ document.text_content = short_text
+ document.document_hash = hashlib.sha256(short_text.encode()).hexdigest()
+ session.commit()
+
+ second = svc.index_document(doc_id, coll_id, force_reindex=True)
+ assert second["status"] == "success", second
+ new_count = second["chunk_count"]
+ assert new_count < old_count
+
+ session.expire_all()
+ rag_index = (
+ session.query(RAGIndex)
+ .filter_by(collection_name=f"collection_{coll_id}", is_current=True)
+ .one()
+ )
+ status = (
+ session.query(RagDocumentStatus)
+ .filter_by(document_id=doc_id, collection_id=coll_id)
+ .one()
+ )
+ assert status.chunk_count == new_count
+ assert rag_index.chunk_count == new_count
+ assert rag_index.total_documents == 1
+ svc.close()
+
def test_control_without_backstop_stays_indexed_and_unsearchable(
self, rag_env, monkeypatch
):
diff --git a/tests/research_library/services/test_multi_model_switch_revert.py b/tests/research_library/services/test_multi_model_switch_revert.py
index 73e269f19a..5bc74e412b 100644
--- a/tests/research_library/services/test_multi_model_switch_revert.py
+++ b/tests/research_library/services/test_multi_model_switch_revert.py
@@ -48,6 +48,7 @@ from local_deep_research.database.models.library import (
DocumentChunk,
DocumentStatus,
RAGIndex,
+ RagDocumentStatus,
SourceType,
)
@@ -275,6 +276,15 @@ class TestMultiModelSwitchAndRevert:
row_b = current_rows_after_b[0]
assert row_b.embedding_model == "model-B"
assert row_b.index_hash != index_hash_a
+ status_b = (
+ session.query(RagDocumentStatus)
+ .filter_by(document_id=document_id, collection_id=collection_id)
+ .one()
+ )
+ assert status_b.rag_index_id == row_b.id
+ assert status_b.chunk_count == result_b1["chunk_count"]
+ assert row_b.chunk_count == result_b1["chunk_count"]
+ assert row_b.total_documents == 1
# A's row must now be demoted, but NOT deleted/mutated in its own config.
row_a_reloaded = session.query(RAGIndex).filter_by(id=row_a_id).first()