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: reconcile orphan RAG chunks after login (#7889)

creedf9d16e62db6a
diff --git a/changelog.d/7473.bugfix.md b/changelog.d/7473.bugfix.md
new file mode 100644
index 0000000000..347b306d31
--- /dev/null
+++ b/changelog.d/7473.bugfix.md
@@ -0,0 +1 @@
+On login, retry cleanup of document chunks left behind by interrupted research deletion, including their index vectors when available, without touching chunks of existing documents.
diff --git a/src/local_deep_research/research_library/deletion/services/document_deletion.py b/src/local_deep_research/research_library/deletion/services/document_deletion.py
index fcb04253db..328741d6be 100644
--- a/src/local_deep_research/research_library/deletion/services/document_deletion.py
+++ b/src/local_deep_research/research_library/deletion/services/document_deletion.py
@@ -12,6 +12,7 @@ from contextlib import contextmanager
from typing import Any, Dict, Iterator, List, Tuple
from loguru import logger
+from sqlalchemy import exists
from ....constants import FILE_PATH_BLOB_DELETED
from ....database.models.library import (
@@ -102,7 +103,9 @@ class DocumentDeletionService:
self.username = username
def purge_deleted_research_documents(
- self, targets: List[Tuple[str, List[str]]]
+ self,
+ targets: List[Tuple[str, List[str]]],
+ db_password: str | None = None,
) -> None:
"""Purge vectors and residual chunks after research deletion commits."""
groups: Dict[str, set[str]] = {}
@@ -112,7 +115,12 @@ class DocumentDeletionService:
# surviving research by the cascade. Only a missing document may
# lose its RAG data; query committed state, not the old ownership.
try:
- with get_user_db_session(self.username) as session:
+ session_context = (
+ get_user_db_session(self.username, db_password)
+ if db_password is not None
+ else get_user_db_session(self.username)
+ )
+ with session_context as session:
if (
session.query(Document.id)
.filter_by(id=document_id)
@@ -140,7 +148,9 @@ class DocumentDeletionService:
with get_rag_service(
self.username,
collection_id=collection_id,
- db_password=capture_request_db_password(self.username),
+ db_password=db_password
+ if db_password is not None
+ else capture_request_db_password(self.username),
) as rag:
rag.purge_documents_vectors(
sorted(document_ids), collection_id
@@ -153,7 +163,12 @@ class DocumentDeletionService:
# unavailable. Its unresolvable vectors are collected on reconciliation.
if deleted_documents:
try:
- with get_user_db_session(self.username) as session:
+ session_context = (
+ get_user_db_session(self.username, db_password)
+ if db_password is not None
+ else get_user_db_session(self.username)
+ )
+ with session_context as session:
for document_id in deleted_documents:
CascadeHelper.delete_document_chunks(
session, document_id
@@ -164,6 +179,60 @@ class DocumentDeletionService:
"Could not sweep deleted research chunks"
)
+ def reconcile_orphaned_document_chunks(
+ self, db_password: str, batch_size: int = 25
+ ) -> int:
+ """Retry cleanup for deleted documents left behind by an interrupted purge.
+
+ Bound the scan by document ID, then include every collection for each
+ selected document before the existing purge sweeps all of its chunks.
+ A later login handles any remaining documents in the next batch.
+ """
+ with get_user_db_session(self.username, db_password) as session:
+ orphan_ids = [
+ document_id
+ for (document_id,) in session.query(DocumentChunk.source_id)
+ .filter(
+ DocumentChunk.source_type == "document",
+ DocumentChunk.source_id.is_not(None),
+ ~exists().where(Document.id == DocumentChunk.source_id),
+ )
+ .distinct()
+ .order_by(DocumentChunk.source_id)
+ .limit(batch_size)
+ .all()
+ ]
+ if not orphan_ids:
+ return 0
+ chunk_locations = (
+ session.query(
+ DocumentChunk.source_id, DocumentChunk.collection_name
+ )
+ .filter(
+ DocumentChunk.source_type == "document",
+ DocumentChunk.source_id.in_(orphan_ids),
+ )
+ .distinct()
+ .all()
+ )
+
+ collections: Dict[str, set[str]] = {
+ document_id: set() for document_id in orphan_ids
+ }
+ for document_id, collection_name in chunk_locations:
+ if collection_name.startswith("collection_"):
+ collections[document_id].add(
+ collection_name.removeprefix("collection_")
+ )
+ self.purge_deleted_research_documents(
+ [
+ (document_id, sorted(collections[document_id]))
+ for document_id in orphan_ids
+ ],
+ db_password=db_password,
+ )
+ return len(orphan_ids)
+
def delete_document(self, document_id: str) -> Dict[str, Any]:
"""Delete one document, serializing duplicate in-process requests."""
with _hold_document_delete_lock(self.username, document_id):
diff --git a/src/local_deep_research/web/routers/auth.py b/src/local_deep_research/web/routers/auth.py
index 656770fcd2..5883655a39 100644
--- a/src/local_deep_research/web/routers/auth.py
+++ b/src/local_deep_research/web/routers/auth.py
@@ -513,6 +513,27 @@ def _perform_post_login_tasks_body(
)
_log_step_duration("step 2 (library init)", step_start, username)
+ # Retry a bounded batch of document chunks left behind if a prior
+ # post-commit research deletion was interrupted. This runs after the
+ # login response in the existing worker, even when RAG indexing is off.
+ step_start = time.perf_counter()
+ try:
+ from ...research_library.deletion.services.document_deletion import (
+ DocumentDeletionService,
+ )
+
+ DocumentDeletionService(username).reconcile_orphaned_document_chunks(
+ password
+ )
+ except Exception:
+ logger.exception(
+ "Post-login orphan chunk reconciliation failed for {}",
+ _log_value_preview(username),
+ )
+ _log_step_duration(
+ "step 2a (orphan chunk reconciliation)", step_start, username
+ )
+
# 3. Update last_login in auth DB + notify news scheduler
step_start = time.perf_counter()
try:
diff --git a/tests/research_library/deletion/services/test_orphan_chunk_reconciliation_7473.py b/tests/research_library/deletion/services/test_orphan_chunk_reconciliation_7473.py
new file mode 100644
index 0000000000..97e7c4b33c
--- /dev/null
+++ b/tests/research_library/deletion/services/test_orphan_chunk_reconciliation_7473.py
@@ -0,0 +1,174 @@
+"""Recover chunk rows after a research deletion's post-commit purge is lost."""
+
+import hashlib
+from contextlib import contextmanager
+from unittest.mock import MagicMock
+
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import (
+ Document,
+ DocumentChunk,
+ DocumentStatus,
+ EmbeddingProvider,
+ SourceType,
+)
+from local_deep_research.research_library.deletion.services import (
+ document_deletion as deletion_module,
+)
+from local_deep_research.research_library.deletion.services.document_deletion import (
+ DocumentDeletionService,
+)
+from local_deep_research.research_library.services import rag_service_factory
+
+
+def _chunk(document_id, collection_id, ordinal):
+ text = f"{document_id}-{collection_id}-{ordinal}"
+ return DocumentChunk(
+ chunk_hash=hashlib.sha256(text.encode()).hexdigest(),
+ source_type="document",
+ source_id=document_id,
+ collection_name=f"collection_{collection_id}",
+ chunk_text=text,
+ chunk_index=ordinal,
+ start_char=0,
+ end_char=len(text),
+ word_count=1,
+ embedding_id=text,
+ embedding_model="test-model",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=2,
+ )
+
+
+def database(tmp_path, monkeypatch):
+ engine = create_engine(f"sqlite:///{tmp_path / 'orphans.db'}")
+ Base.metadata.create_all(engine)
+ Session = sessionmaker(bind=engine)
+ with Session() as session:
+ session.add(
+ SourceType(
+ id="document-source", name="document", display_name="Document"
+ )
+ )
+ session.add(
+ Document(
+ id="live",
+ source_type_id="document-source",
+ title="Live",
+ text_content="Live content",
+ document_hash=hashlib.sha256(b"Live content").hexdigest(),
+ file_size=12,
+ file_type="txt",
+ status=DocumentStatus.COMPLETED,
+ )
+ )
+ session.add_all(
+ [
+ _chunk("gone-a", "one", 0),
+ _chunk("gone-a", "two", 1),
+ _chunk("gone-b", "one", 0),
+ _chunk("live", "one", 0),
+ ]
+ )
+ session.commit()
+
+ @contextmanager
+ def user_session(username, password=None):
+ assert username == "alice"
+ assert password == "test-password" # gitleaks:allow
+ with Session() as session:
+ yield session
+
+ monkeypatch.setattr(deletion_module, "get_user_db_session", user_session)
+ rag = MagicMock()
+ rag_context = MagicMock()
+ rag_context.__enter__.return_value = rag
+ rag_context.__exit__.return_value = False
+ factory = MagicMock(return_value=rag_context)
+ monkeypatch.setattr(rag_service_factory, "get_rag_service", factory)
+ yield Session, factory, rag
+ engine.dispose()
+
+
+def _remaining(Session):
+ with Session() as session:
+ return sorted(
+ row.source_id for row in session.query(DocumentChunk).all()
+ )
+
+
+def test_login_reconciliation_retries_bounded_orphans_and_keeps_live_chunks(
+ database,
+):
+ Session, factory, rag = database
+ service = DocumentDeletionService("alice")
+
+ assert (
+ service.reconcile_orphaned_document_chunks(
+ "test-password", batch_size=1
+ )
+ == 1
+ )
+ assert _remaining(Session) == ["gone-b", "live"]
+ purged = {call.kwargs["collection_id"] for call in factory.call_args_list}
+ assert purged == {"one", "two"}
+ assert rag.purge_documents_vectors.call_count == 2
+
+ assert (
+ service.reconcile_orphaned_document_chunks(
+ "test-password", batch_size=1
+ )
+ == 1
+ )
+ assert _remaining(Session) == ["live"]
+ assert (
+ service.reconcile_orphaned_document_chunks(
+ "test-password", batch_size=1
+ )
+ == 0
+ )
+
+
+def test_failed_verification_leaves_orphan_for_next_login(
+ database, monkeypatch
+):
+ Session, factory, _rag = database
+ original_session = deletion_module.get_user_db_session
+ calls = 0
+
+ def fail_first_verification(*args, **kwargs):
+ nonlocal calls
+ calls += 1
+ if calls == 2:
+ raise RuntimeError("database locked during verification")
+ return original_session(*args, **kwargs)
+
+ monkeypatch.setattr(
+ deletion_module, "get_user_db_session", fail_first_verification
+ )
+ service = DocumentDeletionService("alice")
+
+ assert (
+ service.reconcile_orphaned_document_chunks(
+ "test-password", batch_size=1
+ )
+ == 1
+ )
+ assert _remaining(Session) == ["gone-a", "gone-a", "gone-b", "live"]
+ factory.assert_not_called()
+
+ monkeypatch.setattr(
+ deletion_module, "get_user_db_session", original_session
+ )
+ assert (
+ service.reconcile_orphaned_document_chunks(
+ "test-password", batch_size=1
+ )
+ == 1
+ )
+ assert _remaining(Session) == ["gone-b", "live"]