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: delete orphaned documents when collection is deleted

LearningCircuit6724f5a6899d
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 fe7e2dc77e..d96043cefa 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -1273,6 +1273,8 @@ def delete_collection(collection_id):
from ...database.models.library import (
CollectionFolder,
DocumentChunk,
+ Document,
+ DocumentBlob,
)
from ...database.session_context import get_user_db_session
@@ -1292,6 +1294,14 @@ def delete_collection(collection_id):
# Get collection name for deleting chunks
collection_name = f"collection_{collection.id}"
+ # Get document IDs in this collection BEFORE deleting links
+ doc_ids_in_collection = [
+ dc.document_id
+ for dc in db_session.query(DocumentCollection)
+ .filter_by(collection_id=collection_id)
+ .all()
+ ]
+
# Delete associated document chunks from vector store
deleted_chunks = (
db_session.query(DocumentChunk)
@@ -1311,6 +1321,28 @@ def delete_collection(collection_id):
# Delete the collection itself
db_session.delete(collection)
+
+ # Check for orphaned documents and delete them
+ orphaned_deleted = 0
+ for doc_id in doc_ids_in_collection:
+ # Check if document is in any other collection
+ remaining = (
+ db_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id)
+ .count()
+ )
+ if remaining == 0:
+ # Document is orphaned - delete it using query deletes
+ # to avoid ORM cascade issues with DocumentBlob
+ db_session.query(DocumentBlob).filter_by(
+ document_id=doc_id
+ ).delete(synchronize_session=False)
+ db_session.query(Document).filter_by(id=doc_id).delete(
+ synchronize_session=False
+ )
+ orphaned_deleted += 1
+ logger.info(f"Deleted orphaned document {doc_id[:8]}...")
+
db_session.commit()
# Also remove from vector index if it exists
@@ -1327,6 +1359,7 @@ def delete_collection(collection_id):
"success": True,
"message": "Collection deleted successfully",
"deleted_chunks": deleted_chunks,
+ "orphaned_documents_deleted": orphaned_deleted,
}
)
except Exception as e: