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.

refactor: consolidate collection deletion logic into CollectionDeletionService

LearningCircuit3398305486af
diff --git a/src/local_deep_research/research_library/deletion/services/collection_deletion.py b/src/local_deep_research/research_library/deletion/services/collection_deletion.py
index 0dc0cf63f6..af50f95abe 100644
--- a/src/local_deep_research/research_library/deletion/services/collection_deletion.py
+++ b/src/local_deep_research/research_library/deletion/services/collection_deletion.py
@@ -35,11 +35,15 @@ class CollectionDeletionService:
"""
self.username = username
- def delete_collection(self, collection_id: str) -> Dict[str, Any]:
+ def delete_collection(
+ self, collection_id: str, delete_orphaned_documents: bool = True
+ ) -> Dict[str, Any]:
"""
Delete a collection and clean up all related data.
- Documents are preserved but unlinked from the collection.
+ By default, orphaned documents (not in any other collection) are deleted.
+ Set delete_orphaned_documents=False to preserve all documents.
+
The following are deleted:
- DocumentChunks for this collection
- FAISS index files
@@ -47,9 +51,12 @@ class CollectionDeletionService:
- CollectionFolder records (CASCADE)
- DocumentCollection links (CASCADE)
- RagDocumentStatus records (CASCADE)
+ - Orphaned documents (if delete_orphaned_documents=True)
Args:
collection_id: ID of the collection to delete
+ delete_orphaned_documents: If True, delete documents not in any
+ other collection after unlinking
Returns:
Dict with deletion details:
@@ -61,6 +68,7 @@ class CollectionDeletionService:
"documents_unlinked": int,
"indices_deleted": int,
"folders_deleted": int,
+ "orphaned_documents_deleted": int,
"error": str (if failed)
}
"""
@@ -84,14 +92,17 @@ class CollectionDeletionService:
"documents_unlinked": 0,
"indices_deleted": 0,
"folders_deleted": 0,
+ "orphaned_documents_deleted": 0,
}
- # 1. Count documents that will be unlinked
- result["documents_unlinked"] = (
- session.query(DocumentCollection)
+ # 1. Get document IDs BEFORE deleting links (for orphan check)
+ doc_ids_in_collection = [
+ dc.document_id
+ for dc in session.query(DocumentCollection)
.filter_by(collection_id=collection_id)
- .count()
- )
+ .all()
+ ]
+ result["documents_unlinked"] = len(doc_ids_in_collection)
# 2. Delete DocumentChunks for this collection
result["chunks_deleted"] = (
@@ -113,16 +124,46 @@ class CollectionDeletionService:
.count()
)
- # 5. Delete the collection (CASCADE handles DocumentCollection,
- # CollectionFolder, RagDocumentStatus)
+ # 5. Delete DocumentCollection links explicitly before collection
+ session.query(DocumentCollection).filter_by(
+ collection_id=collection_id
+ ).delete(synchronize_session=False)
+
+ # 6. Delete linked folders explicitly
+ session.query(CollectionFolder).filter_by(
+ collection_id=collection_id
+ ).delete(synchronize_session=False)
+
+ # 7. Delete the collection itself
session.delete(collection)
+
+ # 8. Delete orphaned documents if requested
+ if delete_orphaned_documents:
+ for doc_id in doc_ids_in_collection:
+ # Check if document is in any other collection
+ remaining = (
+ session.query(DocumentCollection)
+ .filter_by(document_id=doc_id)
+ .count()
+ )
+ if remaining == 0:
+ # Document is orphaned - delete it
+ CascadeHelper.delete_document_completely(
+ session, doc_id
+ )
+ result["orphaned_documents_deleted"] += 1
+ logger.info(
+ f"Deleted orphaned document {doc_id[:8]}..."
+ )
+
session.commit()
result["deleted"] = True
logger.info(
f"Deleted collection {collection_id[:8]}... "
- f"({collection.name}): {result['chunks_deleted']} chunks, "
- f"{result['documents_unlinked']} documents unlinked"
+ f"({result['collection_name']}): {result['chunks_deleted']} chunks, "
+ f"{result['documents_unlinked']} documents unlinked, "
+ f"{result['orphaned_documents_deleted']} orphaned deleted"
)
return result
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 23381f8dd9..0ca85b7c73 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -1269,93 +1269,34 @@ def update_collection(collection_id):
@rag_bp.route("/api/collections/<string:collection_id>", methods=["DELETE"])
@login_required
def delete_collection(collection_id):
- """Delete a collection and optionally its documents."""
- from ...database.models.library import (
- CollectionFolder,
- DocumentChunk,
+ """Delete a collection and its orphaned documents."""
+ from ..deletion.services.collection_deletion import (
+ CollectionDeletionService,
)
- from ...database.session_context import get_user_db_session
try:
username = session["username"]
- with get_user_db_session(username) as db_session:
- # No need to filter by username - each user has their own database
- collection = (
- db_session.query(Collection).filter_by(id=collection_id).first()
- )
-
- if not collection:
- return jsonify(
- {"success": False, "error": "Collection not found"}
- ), 404
-
- # 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)
- .filter_by(collection_name=collection_name)
- .delete()
- )
-
- # Delete junction table entries
- db_session.query(DocumentCollection).filter_by(
- collection_id=collection_id
- ).delete()
-
- # Delete linked folders
- db_session.query(CollectionFolder).filter_by(
- collection_id=collection_id
- ).delete()
-
- # Delete the collection itself
- db_session.delete(collection)
-
- # Check for orphaned documents and delete them
- from ..deletion.utils.cascade_helper import CascadeHelper
-
- 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
- CascadeHelper.delete_document_completely(db_session, doc_id)
- orphaned_deleted += 1
- logger.info(f"Deleted orphaned document {doc_id[:8]}...")
-
- db_session.commit()
-
- # Also remove from vector index if it exists
- try:
- rag_service = get_rag_service()
- rag_service.remove_collection_from_index(collection_name)
- except Exception as e:
- logger.warning(
- f"Could not remove collection from vector index: {e}"
- )
+ service = CollectionDeletionService(username)
+ result = service.delete_collection(
+ collection_id, delete_orphaned_documents=True
+ )
+ if result.get("deleted"):
return jsonify(
{
"success": True,
"message": "Collection deleted successfully",
- "deleted_chunks": deleted_chunks,
- "orphaned_documents_deleted": orphaned_deleted,
+ "deleted_chunks": result.get("chunks_deleted", 0),
+ "orphaned_documents_deleted": result.get(
+ "orphaned_documents_deleted", 0
+ ),
}
)
+ else:
+ error = result.get("error", "Unknown error")
+ status_code = 404 if "not found" in error.lower() else 400
+ return jsonify({"success": False, "error": error}), status_code
+
except Exception as e:
return handle_api_error("deleting collection", e)
diff --git a/tests/deletion/test_collection_deletion.py b/tests/deletion/test_collection_deletion.py
index 1e8795bd37..5355923671 100644
--- a/tests/deletion/test_collection_deletion.py
+++ b/tests/deletion/test_collection_deletion.py
@@ -365,3 +365,120 @@ class TestCollectionFolderCascade:
.first()
)
assert folder_after is None, "Folder should be deleted"
+
+
+class TestOrphanedDocumentDeletion:
+ """Tests for orphaned document deletion during collection deletion."""
+
+ def test_delete_collection_deletes_orphaned_documents(
+ self, test_session, test_collection, test_documents, source_type
+ ):
+ """Documents only in the deleted collection are deleted."""
+ collection_id = test_collection.id
+ doc_ids = [d.id for d in test_documents]
+
+ # Verify documents exist and are only in one collection
+ for doc_id in doc_ids:
+ link_count = (
+ test_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id)
+ .count()
+ )
+ assert link_count == 1, (
+ "Each doc should be in exactly one collection"
+ )
+
+ # Manually delete links first
+ test_session.query(DocumentCollection).filter_by(
+ collection_id=collection_id
+ ).delete(synchronize_session=False)
+
+ # Check for orphaned documents and delete them
+ orphaned_deleted = 0
+ for doc_id in doc_ids:
+ remaining = (
+ test_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id)
+ .count()
+ )
+ if remaining == 0:
+ # Delete document
+ doc = test_session.query(Document).get(doc_id)
+ if doc:
+ test_session.delete(doc)
+ orphaned_deleted += 1
+
+ # Delete collection
+ collection = test_session.query(Collection).get(collection_id)
+ test_session.delete(collection)
+ test_session.commit()
+
+ # Verify orphaned documents were deleted
+ assert orphaned_deleted == 3, (
+ "All 3 orphaned documents should be deleted"
+ )
+
+ for doc_id in doc_ids:
+ doc = test_session.query(Document).get(doc_id)
+ assert doc is None, (
+ f"Orphaned document {doc_id[:8]} should be deleted"
+ )
+
+ def test_delete_collection_preserves_shared_documents(
+ self, test_session, test_collection, test_documents, source_type
+ ):
+ """Documents in other collections are preserved."""
+ collection_id = test_collection.id
+ doc_ids = [d.id for d in test_documents]
+
+ # Create a second collection and link the first document to it
+ second_collection = Collection(
+ id=str(uuid.uuid4()),
+ name="Second Collection",
+ )
+ test_session.add(second_collection)
+ test_session.flush()
+
+ # Link first document to second collection
+ shared_doc_id = doc_ids[0]
+ link = DocumentCollection(
+ document_id=shared_doc_id,
+ collection_id=second_collection.id,
+ indexed=False,
+ chunk_count=0,
+ )
+ test_session.add(link)
+ test_session.commit()
+
+ # Delete links for first collection
+ test_session.query(DocumentCollection).filter_by(
+ collection_id=collection_id
+ ).delete(synchronize_session=False)
+
+ # Check orphaned docs
+ preserved_count = 0
+ deleted_count = 0
+ for doc_id in doc_ids:
+ remaining = (
+ test_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id)
+ .count()
+ )
+ if remaining == 0:
+ doc = test_session.query(Document).get(doc_id)
+ if doc:
+ test_session.delete(doc)
+ deleted_count += 1
+ else:
+ preserved_count += 1
+
+ # Delete first collection
+ collection = test_session.query(Collection).get(collection_id)
+ test_session.delete(collection)
+ test_session.commit()
+
+ # Verify shared document was preserved
+ shared_doc = test_session.query(Document).get(shared_doc_id)
+ assert shared_doc is not None, "Shared document should be preserved"
+ assert preserved_count == 1, "One document should be preserved"
+ assert deleted_count == 2, "Two orphaned documents should be deleted"