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): keep index aggregates scoped across model switches (#8209)

creed5d9b90a93bce
diff --git a/changelog.d/+5528-rag-switch-aggregate-accounting.bugfix.md b/changelog.d/+5528-rag-switch-aggregate-accounting.bugfix.md
new file mode 100644
index 0000000000..fde40d12ef
--- /dev/null
+++ b/changelog.d/+5528-rag-switch-aggregate-accounting.bugfix.md
@@ -0,0 +1 @@
+Keep per-index RAG document and chunk totals accurate when a document is reindexed under a different embedding model, including existing inflated totals when an index is promoted again.
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 9bcfcb80fe..c769dbcda8 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
@@ -1175,6 +1175,36 @@ class LibraryRAGService:
# other caller until an actual indexing run switches over.
promoted = promote_current and not rag_index.is_current
if promoted:
+ # A previous model switch may have left aggregates inflated while
+ # the one status row per document moved to another index. Repair
+ # all configurations once on promotion, then use O(1) deltas for
+ # the documents written under the newly current configuration.
+ index_rows = (
+ db_session.query(RAGIndex)
+ .filter_by(collection_name=collection_name)
+ .all()
+ )
+ totals = {
+ index_id: (documents, chunks or 0)
+ for index_id, documents, chunks in (
+ db_session.query(
+ RagDocumentStatus.rag_index_id,
+ func.count(),
+ func.sum(RagDocumentStatus.chunk_count),
+ )
+ .filter(
+ RagDocumentStatus.rag_index_id.in_(
+ [row.id for row in index_rows]
+ )
+ )
+ .group_by(RagDocumentStatus.rag_index_id)
+ .all()
+ )
+ }
+ for row in index_rows:
+ row.total_documents, row.chunk_count = totals.get(
+ row.id, (0, 0)
+ )
db_session.query(RAGIndex).filter(
RAGIndex.collection_name == collection_name,
RAGIndex.is_current.is_(True),
@@ -2445,11 +2475,13 @@ class LibraryRAGService:
.filter_by(
document_id=document_id,
collection_id=collection_id,
- rag_index_id=self.rag_index_record.id,
)
.first()
)
- old_chunks = existing.chunk_count if existing else 0
+ prior_index_id = existing.rag_index_id if existing else None
+ prior_chunks = existing.chunk_count if existing else 0
+ same_index = prior_index_id == self.rag_index_record.id
+ old_chunks = prior_chunks if same_index else 0
session.merge(
RagDocumentStatus(
document_id=document_id,
@@ -2501,9 +2533,19 @@ class LibraryRAGService:
)
if rag_index:
rag_index.chunk_count += len(chunks) - old_chunks
- if existing is None:
+ if not same_index:
rag_index.total_documents += 1
rag_index.last_updated_at = timestamp
+ if prior_index_id is not None and not same_index:
+ prior_index = session.get(RAGIndex, prior_index_id)
+ if prior_index is not None:
+ prior_index.chunk_count = max(
+ 0, (prior_index.chunk_count or 0) - prior_chunks
+ )
+ prior_index.total_documents = max(
+ 0, (prior_index.total_documents or 0) - 1
+ )
+ prior_index.last_updated_at = timestamp
session.commit()
logger.info(
f"Persisted prepared document {document_id}: "
@@ -3098,13 +3140,18 @@ class LibraryRAGService:
.filter_by(
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
+ prior_index_id = (
+ existing_status.rag_index_id if existing_status else None
+ )
+ prior_chunk_count = (
+ existing_status.chunk_count if existing_status else 0
+ )
+ was_already_indexed = prior_index_id == self.rag_index_record.id
old_chunk_count = (
- (existing_status.chunk_count or 0) if existing_status else 0
+ prior_chunk_count if was_already_indexed else 0
)
# Mark document as indexed using rag_document_status table
@@ -3184,6 +3231,17 @@ class LibraryRAGService:
f"chunk_count {chunk_delta:+d}, "
f"total_documents {'+1' if not was_already_indexed else '+0'}"
)
+ if prior_index_id is not None and not was_already_indexed:
+ prior_index = session.get(RAGIndex, prior_index_id)
+ if prior_index is not None:
+ prior_index.chunk_count = max(
+ 0,
+ (prior_index.chunk_count or 0) - prior_chunk_count,
+ )
+ prior_index.total_documents = max(
+ 0, (prior_index.total_documents or 0) - 1
+ )
+ prior_index.last_updated_at = timestamp
# Flush ORM changes to database before commit
session.flush()
diff --git a/tests/research_library/services/test_index_documents_parallel.py b/tests/research_library/services/test_index_documents_parallel.py
index 12552c12ee..cc83a65915 100644
--- a/tests/research_library/services/test_index_documents_parallel.py
+++ b/tests/research_library/services/test_index_documents_parallel.py
@@ -968,6 +968,7 @@ class TestWritePreparedDocumentReindexDelta:
mock_existing = MagicMock()
mock_existing.chunk_count = 5 # 5 old chunks
+ mock_existing.rag_index_id = 1
mock_rag_index = MagicMock()
mock_rag_index.chunk_count = 10 # 10 total chunks currently in index
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 a1e07c8928..411fbe3210 100644
--- a/tests/research_library/services/test_multi_model_switch_revert.py
+++ b/tests/research_library/services/test_multi_model_switch_revert.py
@@ -194,6 +194,128 @@ def _current_rows(session, collection_name):
class TestMultiModelSwitchAndRevert:
+ def test_switching_a_to_b_to_a_keeps_each_index_aggregate_scoped(
+ self, shared_world, seeded_doc
+ ):
+ session = shared_world
+ collection_id, document_id = seeded_doc
+ svc_a, _ = _make_service("switchuser", "pw", "model-A", dim=8)
+ svc_b, _ = _make_service("switchuser", "pw", "model-B", dim=4)
+
+ try:
+ first_a = svc_a.index_document(document_id, collection_id)
+ assert first_a["status"] == "success", first_a
+ index_a = (
+ session.query(RAGIndex)
+ .filter_by(
+ collection_name=f"collection_{collection_id}",
+ embedding_model="model-A",
+ )
+ .one()
+ )
+ assert (index_a.chunk_count, index_a.total_documents) == (
+ first_a["chunk_count"],
+ 1,
+ )
+
+ first_b = svc_b.index_document(
+ document_id, collection_id, force_reindex=True
+ )
+ assert first_b["status"] == "success", first_b
+ index_b = (
+ session.query(RAGIndex)
+ .filter_by(
+ collection_name=f"collection_{collection_id}",
+ embedding_model="model-B",
+ )
+ .one()
+ )
+ assert (index_a.chunk_count, index_a.total_documents) == (0, 0)
+ assert (index_b.chunk_count, index_b.total_documents) == (
+ first_b["chunk_count"],
+ 1,
+ )
+
+ # Existing installations can already carry inflated counters.
+ # Re-promoting A must repair them from the canonical status rows.
+ index_a.chunk_count = 99
+ index_a.total_documents = 9
+ session.commit()
+
+ second_a = svc_a.index_document(
+ document_id, collection_id, force_reindex=True
+ )
+ assert second_a["status"] == "success", second_a
+ assert (index_a.chunk_count, index_a.total_documents) == (
+ second_a["chunk_count"],
+ 1,
+ )
+ assert (index_b.chunk_count, index_b.total_documents) == (0, 0)
+ status = (
+ session.query(RagDocumentStatus)
+ .filter_by(document_id=document_id, collection_id=collection_id)
+ .one()
+ )
+ assert status.rag_index_id == index_a.id
+ finally:
+ svc_a.close()
+ svc_b.close()
+
+ def test_prepared_write_transfers_aggregate_between_models(
+ self, shared_world, seeded_doc
+ ):
+ session = shared_world
+ collection_id, document_id = seeded_doc
+ svc_a, _ = _make_service("switchuser", "pw", "model-A", dim=8)
+ svc_b, _ = _make_service("switchuser", "pw", "model-B", dim=4)
+
+ try:
+ first_a = svc_a.index_document(document_id, collection_id)
+ assert first_a["status"] == "success", first_a
+ index_a = (
+ session.query(RAGIndex)
+ .filter_by(
+ collection_name=f"collection_{collection_id}",
+ embedding_model="model-A",
+ )
+ .one()
+ )
+
+ prepared_b = svc_b._prepare_document(
+ document_id, collection_id, force_reindex=True
+ )
+ assert prepared_b["status"] == "prepared", prepared_b
+ written_b = svc_b._write_prepared_document(prepared_b["prepared"])
+ assert written_b["status"] == "success", written_b
+ index_b = (
+ session.query(RAGIndex)
+ .filter_by(
+ collection_name=f"collection_{collection_id}",
+ embedding_model="model-B",
+ )
+ .one()
+ )
+ assert (index_a.chunk_count, index_a.total_documents) == (0, 0)
+ assert (index_b.chunk_count, index_b.total_documents) == (
+ written_b["chunk_count"],
+ 1,
+ )
+
+ prepared_a = svc_a._prepare_document(
+ document_id, collection_id, force_reindex=True
+ )
+ assert prepared_a["status"] == "prepared", prepared_a
+ written_a = svc_a._write_prepared_document(prepared_a["prepared"])
+ assert written_a["status"] == "success", written_a
+ assert (index_a.chunk_count, index_a.total_documents) == (
+ written_a["chunk_count"],
+ 1,
+ )
+ assert (index_b.chunk_count, index_b.total_documents) == (0, 0)
+ finally:
+ svc_a.close()
+ svc_b.close()
+
def test_switch_to_new_model_then_revert_resolves_and_repromotes_original(
self, shared_world, seeded_doc
):