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): dedup collection indexing across SSE route and background worker (#4502)

LearningCircuit77c9c10e96f3
diff --git a/changelog.d/+fix-rag-collection-indexing-drift.bugfix.md b/changelog.d/+fix-rag-collection-indexing-drift.bugfix.md
new file mode 100644
index 0000000000..16a12776e1
--- /dev/null
+++ b/changelog.d/+fix-rag-collection-indexing-drift.bugfix.md
@@ -0,0 +1,8 @@
+Collection indexing now behaves identically whether started via the streaming
+(SSE) route or the background worker. The two paths had duplicated and drifted:
+the background worker did not persist a collection's ``embedding_dimension`` (so
+collections indexed in the background lost it), and the SSE route skipped the
+force-reindex cleanup that clears old chunks and FAISS indices (so a streamed
+force-reindex could leave stale, mixed-model vectors behind). The shared
+embedding-metadata, force-reindex cleanup, and document-query logic is now
+factored into single helpers used by both paths.
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 3ba78fef32..2ec1757f8d 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -2005,6 +2005,122 @@ def get_collection_documents(collection_id):
return handle_api_error("getting collection documents", e)
+# =============================================================================
+# Shared collection-indexing helpers
+#
+# Both the SSE route (index_collection) and the background worker
+# (_background_index_worker) index a collection. These helpers hold the logic
+# that must stay identical between the two paths so it cannot drift again — the
+# embedding metadata to persist, the force-reindex cleanup, and the query for
+# documents to index. The two callers differ only in how they report progress
+# (SSE stream vs TaskMetadata) and so keep their own loops.
+# =============================================================================
+
+
+def _store_collection_embedding_metadata(collection, rag_service):
+ """Persist the embedding/index configuration used to index a collection.
+
+ Run on first index or force-reindex. Includes the embedding dimension,
+ probed from the provider; previously the background worker omitted it, so
+ collections indexed that way lost ``embedding_dimension``. Does not commit —
+ the caller owns the transaction.
+ """
+ embedding_dim = None
+ try:
+ # Try to get dimension from the embedding manager's provider
+ if hasattr(rag_service.embedding_manager, "provider"):
+ provider = rag_service.embedding_manager.provider
+ if hasattr(provider, "embedding_dimension"):
+ embedding_dim = provider.embedding_dimension
+ except Exception:
+ logger.warning("Could not get embedding dimension")
+
+ collection.embedding_model = rag_service.embedding_model
+ collection.embedding_model_type = EmbeddingProvider(
+ rag_service.embedding_provider
+ )
+ collection.embedding_dimension = embedding_dim
+ collection.chunk_size = rag_service.chunk_size
+ collection.chunk_overlap = rag_service.chunk_overlap
+ # Advanced settings
+ collection.splitter_type = rag_service.splitter_type
+ collection.text_separators = rag_service.text_separators
+ collection.distance_metric = rag_service.distance_metric
+ # Ensure normalize_vectors is a proper boolean for the database
+ collection.normalize_vectors = bool(rag_service.normalize_vectors)
+ collection.index_type = rag_service.index_type
+ logger.info(
+ f"Stored embedding metadata for collection: provider={rag_service.embedding_provider}"
+ )
+
+
+def _reset_collection_for_reindex(db_session, collection_id):
+ """Clear old chunks, FAISS indices, and indexed-state before a force rebuild.
+
+ Prevents mixed-model vectors / stale chunks when re-indexing (e.g. if a
+ previous run was cancelled midway). Shared so a force-reindex behaves the
+ same whether started via the SSE route or the background worker. Does not
+ commit — the caller owns the transaction.
+ """
+ # Import stays function-local: hoisting it would pull in the whole
+ # deletion package (deletion/__init__ imports its services) at
+ # route-module import time for a path only exercised on force-reindex.
+ from ..deletion.utils.cascade_helper import CascadeHelper
+
+ collection_name = f"collection_{collection_id}"
+
+ # Delete all old document chunks from DB
+ deleted_chunks = CascadeHelper.delete_collection_chunks(
+ db_session, collection_name
+ )
+ logger.info(
+ f"Cleared {deleted_chunks} old chunks for collection {collection_id}"
+ )
+
+ # Delete old FAISS index files (.faiss + .pkl) and RAGIndex records.
+ # RagDocumentStatus rows cascade-delete via FK ondelete="CASCADE".
+ rag_result = CascadeHelper.delete_rag_indices_for_collection(
+ db_session, collection_name
+ )
+ logger.info(
+ f"Cleared old RAG indices for collection {collection_id}: {rag_result}"
+ )
+
+ # Mark all documents as unindexed
+ db_session.query(DocumentCollection).filter_by(
+ collection_id=collection_id
+ ).update(
+ {
+ DocumentCollection.indexed: False,
+ DocumentCollection.chunk_count: 0,
+ }
+ )
+ logger.info(f"Reset indexing state for collection {collection_id}")
+
+
+def _query_documents_to_index(db_session, collection_id, force_reindex):
+ """Return the ``(DocumentCollection, Document)`` pairs to index.
+
+ When not force-reindexing, only un-indexed documents are returned.
+ """
+ query = (
+ db_session.query(DocumentCollection, Document)
+ .join(Document)
+ .filter(DocumentCollection.collection_id == collection_id)
+ )
+
+ if not force_reindex:
+ # IMPORTANT: DO NOT CHANGE THIS LINE! DO NOT REMOVE THIS COMMENT!
+ # We MUST use `== False` instead of `not DocumentCollection.indexed`
+ # The Python `not` operator does NOT work correctly in SQLAlchemy filters.
+ # Using `not` will cause the query to return NO results (zero documents).
+ # SQLAlchemy requires explicit comparison: `== False` or `== True`
+ # This has been fixed multiple times - DO NOT change it back to `not`!
+ query = query.filter(DocumentCollection.indexed == False) # noqa: E712
+
+ return query.all()
+
+
@rag_bp.route("/api/collections/<string:collection_id>/index", methods=["GET"])
@login_required
def index_collection(collection_id):
@@ -2049,57 +2165,22 @@ def index_collection(collection_id):
# Store embedding metadata on first index or force reindex
if collection.embedding_model is None or force_reindex:
- # Get embedding dimension from the embedding manager
- embedding_dim = None
- try:
- # Try to get dimension from the embedding manager's provider
- if hasattr(rag_service.embedding_manager, "provider"):
- provider = rag_service.embedding_manager.provider
- if hasattr(provider, "embedding_dimension"):
- embedding_dim = provider.embedding_dimension
- except Exception:
- logger.warning("Could not get embedding dimension")
-
- # Store the embedding configuration used for this collection
- collection.embedding_model = rag_service.embedding_model
- collection.embedding_model_type = EmbeddingProvider(
- rag_service.embedding_provider
- )
- collection.embedding_dimension = embedding_dim
- collection.chunk_size = rag_service.chunk_size
- collection.chunk_overlap = rag_service.chunk_overlap
- # Store advanced settings
- collection.splitter_type = rag_service.splitter_type
- collection.text_separators = rag_service.text_separators
- collection.distance_metric = rag_service.distance_metric
- # Ensure normalize_vectors is a proper boolean for database
- collection.normalize_vectors = bool(
- rag_service.normalize_vectors
+ _store_collection_embedding_metadata(
+ collection, rag_service
)
- collection.index_type = rag_service.index_type
db_session.commit()
- logger.info(
- f"Stored embedding metadata for collection: provider={rag_service.embedding_provider}"
- )
+
+ # Clean up old index data for a fresh rebuild (prevents stale /
+ # mixed-model vectors). Shared with the background worker.
+ if force_reindex:
+ _reset_collection_for_reindex(db_session, collection_id)
+ db_session.commit()
# Get documents to index
- query = (
- db_session.query(DocumentCollection, Document)
- .join(Document)
- .filter(DocumentCollection.collection_id == collection_id)
+ doc_links = _query_documents_to_index(
+ db_session, collection_id, force_reindex
)
- if not force_reindex:
- # IMPORTANT: DO NOT CHANGE THIS LINE! DO NOT REMOVE THIS COMMENT!
- # We MUST use `== False` instead of `not DocumentCollection.indexed`
- # The Python `not` operator does NOT work correctly in SQLAlchemy filters.
- # Using `not` will cause the query to return NO results (zero documents).
- # SQLAlchemy requires explicit comparison: `== False` or `== True`
- # This has been fixed multiple times - DO NOT change it back to `not`!
- query = query.filter(DocumentCollection.indexed == False) # noqa: E712
-
- doc_links = query.all()
-
if not doc_links:
logger.info("No documents to index in collection")
yield f"data: {json.dumps({'type': 'complete', 'results': {'successful': 0, 'skipped': 0, 'failed': 0, 'message': 'No documents to index'}})}\n\n"
@@ -2410,74 +2491,23 @@ def _background_index_worker(
# Store embedding metadata on first index or force reindex
if collection.embedding_model is None or force_reindex:
- collection.embedding_model = rag_service.embedding_model
- collection.embedding_model_type = EmbeddingProvider(
- rag_service.embedding_provider
+ _store_collection_embedding_metadata(
+ collection, rag_service
)
- collection.chunk_size = rag_service.chunk_size
- collection.chunk_overlap = rag_service.chunk_overlap
- collection.splitter_type = rag_service.splitter_type
- collection.text_separators = rag_service.text_separators
- collection.distance_metric = rag_service.distance_metric
- collection.normalize_vectors = bool(
- rag_service.normalize_vectors
- )
- collection.index_type = rag_service.index_type
db_session.commit()
# Clean up old index data for a fresh rebuild.
# This prevents mixed-model vectors if cancelled midway
# and ensures accurate stats during partial reindex.
if force_reindex:
- from ..deletion.utils.cascade_helper import CascadeHelper
-
- collection_name = f"collection_{collection_id}"
-
- # Delete all old document chunks from DB
- deleted_chunks = CascadeHelper.delete_collection_chunks(
- db_session, collection_name
- )
- logger.info(
- f"Cleared {deleted_chunks} old chunks for collection {collection_id}"
- )
-
- # Delete old FAISS index files (.faiss + .pkl) and RAGIndex records
- # RagDocumentStatus rows cascade-delete via FK ondelete="CASCADE"
- rag_result = (
- CascadeHelper.delete_rag_indices_for_collection(
- db_session, collection_name
- )
- )
- logger.info(
- f"Cleared old RAG indices for collection {collection_id}: {rag_result}"
- )
-
- # Mark all documents as unindexed
- db_session.query(DocumentCollection).filter_by(
- collection_id=collection_id
- ).update(
- {
- DocumentCollection.indexed: False,
- DocumentCollection.chunk_count: 0,
- }
- )
+ _reset_collection_for_reindex(db_session, collection_id)
db_session.commit()
- logger.info(
- f"Reset indexing state for collection {collection_id}"
- )
# Get documents to index
- query = (
- db_session.query(DocumentCollection, Document)
- .join(Document)
- .filter(DocumentCollection.collection_id == collection_id)
+ doc_links = _query_documents_to_index(
+ db_session, collection_id, force_reindex
)
- if not force_reindex:
- query = query.filter(DocumentCollection.indexed == False) # noqa: E712
-
- doc_links = query.all()
-
if not doc_links:
_update_task_status(
username,
diff --git a/tests/research_library/routes/test_rag_indexing_helpers.py b/tests/research_library/routes/test_rag_indexing_helpers.py
new file mode 100644
index 0000000000..68155d0acb
--- /dev/null
+++ b/tests/research_library/routes/test_rag_indexing_helpers.py
@@ -0,0 +1,131 @@
+"""Unit tests for the shared collection-indexing helpers in rag_routes.
+
+These helpers were extracted so the SSE route (index_collection) and the
+background worker (_background_index_worker) share identical metadata,
+force-reindex cleanup, and document-query logic. The key regression they fix:
+the background worker previously did NOT store ``embedding_dimension``, so
+collections indexed that way lost it.
+"""
+
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+from local_deep_research.database.models.library import EmbeddingProvider
+from local_deep_research.research_library.routes.rag_routes import (
+ _store_collection_embedding_metadata,
+ _reset_collection_for_reindex,
+ _query_documents_to_index,
+)
+
+MODULE = "local_deep_research.research_library.routes.rag_routes"
+
+
+def _mock_rag_service(embedding_dimension=768, provider_has_dim=True):
+ if provider_has_dim:
+ provider = SimpleNamespace(embedding_dimension=embedding_dimension)
+ else:
+ provider = SimpleNamespace() # no embedding_dimension attribute
+ return SimpleNamespace(
+ embedding_manager=SimpleNamespace(provider=provider),
+ embedding_model="nomic-embed-text",
+ embedding_provider="ollama",
+ chunk_size=512,
+ chunk_overlap=50,
+ splitter_type="recursive",
+ text_separators=["\n\n", "\n"],
+ distance_metric="cosine",
+ normalize_vectors=1, # truthy non-bool, helper must coerce to bool
+ index_type="flat",
+ )
+
+
+class TestStoreCollectionEmbeddingMetadata:
+ def test_stores_embedding_dimension_and_all_fields(self):
+ collection = Mock()
+ rag = _mock_rag_service(embedding_dimension=768)
+
+ _store_collection_embedding_metadata(collection, rag)
+
+ # The regression this fixes: dimension is persisted.
+ assert collection.embedding_dimension == 768
+ assert collection.embedding_model == "nomic-embed-text"
+ assert collection.embedding_model_type == EmbeddingProvider.OLLAMA
+ assert collection.chunk_size == 512
+ assert collection.chunk_overlap == 50
+ assert collection.splitter_type == "recursive"
+ assert collection.text_separators == ["\n\n", "\n"]
+ assert collection.distance_metric == "cosine"
+ assert collection.index_type == "flat"
+
+ def test_normalize_vectors_coerced_to_bool(self):
+ collection = Mock()
+ rag = _mock_rag_service()
+ _store_collection_embedding_metadata(collection, rag)
+ assert collection.normalize_vectors is True
+
+ def test_missing_provider_dimension_yields_none(self):
+ collection = Mock()
+ rag = _mock_rag_service(provider_has_dim=False)
+ _store_collection_embedding_metadata(collection, rag)
+ assert collection.embedding_dimension is None
+ # Other fields are still stored.
+ assert collection.embedding_model == "nomic-embed-text"
+
+ # Note: "does not commit" needs no test here — the helper takes no session
+ # at all, so transaction ownership is enforced by its signature.
+
+
+class TestQueryDocumentsToIndex:
+ def _chainable_session(self, all_result):
+ db = Mock()
+ chain = db.query.return_value.join.return_value
+ chain.filter.return_value = chain
+ chain.all.return_value = all_result
+ return db, chain
+
+ def test_incremental_filters_on_unindexed(self):
+ db, chain = self._chainable_session(["doc"])
+ result = _query_documents_to_index(db, "cid", force_reindex=False)
+ assert result == ["doc"]
+ # collection_id filter + indexed==False filter
+ assert chain.filter.call_count == 2
+
+ def test_force_reindex_skips_indexed_filter(self):
+ db, chain = self._chainable_session(["a", "b"])
+ result = _query_documents_to_index(db, "cid", force_reindex=True)
+ assert result == ["a", "b"]
+ # only the collection_id filter
+ assert chain.filter.call_count == 1
+
+
+class TestResetCollectionForReindex:
+ def test_clears_chunks_indices_and_marks_unindexed(self):
+ db = Mock()
+ with patch(
+ "local_deep_research.research_library.deletion.utils."
+ "cascade_helper.CascadeHelper"
+ ) as cascade:
+ cascade.delete_collection_chunks.return_value = 12
+ cascade.delete_rag_indices_for_collection.return_value = {
+ "deleted": 1
+ }
+
+ _reset_collection_for_reindex(db, "cid")
+
+ cascade.delete_collection_chunks.assert_called_once_with(
+ db, "collection_cid"
+ )
+ cascade.delete_rag_indices_for_collection.assert_called_once_with(
+ db, "collection_cid"
+ )
+ # Marks documents unindexed
+ db.query.return_value.filter_by.return_value.update.assert_called_once()
+
+ def test_does_not_commit(self):
+ db = Mock()
+ with patch(
+ "local_deep_research.research_library.deletion.utils."
+ "cascade_helper.CascadeHelper"
+ ):
+ _reset_collection_for_reindex(db, "cid")
+ db.commit.assert_not_called()