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.

feat: add comprehensive delete functionality with modular architecture

LearningCircuit8d39ecc33a21
diff --git a/src/local_deep_research/defaults/research_library/library_settings.json b/src/local_deep_research/defaults/research_library/library_settings.json
index 83d7c6268a..dd661783a0 100644
--- a/src/local_deep_research/defaults/research_library/library_settings.json
+++ b/src/local_deep_research/defaults/research_library/library_settings.json
@@ -123,5 +123,19 @@
"value": "none",
"visible": true,
"env_var": "RESEARCH_LIBRARY_UPLOAD_PDF_STORAGE"
+ },
+ "research_library.confirm_deletions": {
+ "category": "research_library",
+ "description": "Show confirmation dialogs before delete operations. Recommended to keep enabled to prevent accidental data loss.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Confirm Deletions",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "checkbox",
+ "value": true,
+ "visible": true
}
}
diff --git a/src/local_deep_research/research_library/__init__.py b/src/local_deep_research/research_library/__init__.py
index 031a06d589..ca24b474fe 100644
--- a/src/local_deep_research/research_library/__init__.py
+++ b/src/local_deep_research/research_library/__init__.py
@@ -13,6 +13,7 @@ from .services.library_service import LibraryService
from .services.library_rag_service import LibraryRAGService
from .routes.library_routes import library_bp
from .routes.rag_routes import rag_bp
+from .deletion.routes import delete_bp
__all__ = [
"DownloadService",
@@ -20,4 +21,5 @@ __all__ = [
"LibraryRAGService",
"library_bp",
"rag_bp",
+ "delete_bp",
]
diff --git a/src/local_deep_research/research_library/deletion/__init__.py b/src/local_deep_research/research_library/deletion/__init__.py
new file mode 100644
index 0000000000..388ddd9126
--- /dev/null
+++ b/src/local_deep_research/research_library/deletion/__init__.py
@@ -0,0 +1,25 @@
+"""
+Deletion module for research library.
+
+Provides clean separation of delete functionality:
+- Document deletion with proper cascade cleanup
+- Blob-only deletion (remove PDF, keep text)
+- Collection deletion with cleanup
+- Bulk delete operations
+
+All delete operations ensure:
+- Proper cleanup of related records (DocumentChunk has no FK constraint)
+- FAISS index cleanup
+- Filesystem file cleanup (if applicable)
+- Clear return values for UI feedback
+"""
+
+from .services.document_deletion import DocumentDeletionService
+from .services.collection_deletion import CollectionDeletionService
+from .services.bulk_deletion import BulkDeletionService
+
+__all__ = [
+ "DocumentDeletionService",
+ "CollectionDeletionService",
+ "BulkDeletionService",
+]
diff --git a/src/local_deep_research/research_library/deletion/routes/__init__.py b/src/local_deep_research/research_library/deletion/routes/__init__.py
new file mode 100644
index 0000000000..deaedf09f6
--- /dev/null
+++ b/src/local_deep_research/research_library/deletion/routes/__init__.py
@@ -0,0 +1,5 @@
+"""Delete routes blueprint for research library."""
+
+from .delete_routes import delete_bp
+
+__all__ = ["delete_bp"]
diff --git a/src/local_deep_research/research_library/deletion/routes/delete_routes.py b/src/local_deep_research/research_library/deletion/routes/delete_routes.py
new file mode 100644
index 0000000000..aff2866084
--- /dev/null
+++ b/src/local_deep_research/research_library/deletion/routes/delete_routes.py
@@ -0,0 +1,413 @@
+"""
+Delete API Routes
+
+Provides endpoints for delete operations:
+- Delete document
+- Delete document blob only
+- Delete documents in bulk
+- Delete blobs in bulk
+- Remove document from collection
+- Delete collection
+- Delete collection index only
+"""
+
+from flask import Blueprint, jsonify, request, session
+
+
+from ....web.auth.decorators import login_required
+from ...utils import handle_api_error
+from ..services.document_deletion import DocumentDeletionService
+from ..services.collection_deletion import CollectionDeletionService
+from ..services.bulk_deletion import BulkDeletionService
+
+
+delete_bp = Blueprint("delete", __name__, url_prefix="/library/api")
+
+
+# =============================================================================
+# Document Delete Endpoints
+# =============================================================================
+
+
+@delete_bp.route("/document/<string:document_id>", methods=["DELETE"])
+@login_required
+def delete_document(document_id):
+ """
+ Delete a document and all related data.
+
+ Tooltip: "Permanently delete this document, including PDF and text content.
+ This cannot be undone."
+
+ Returns:
+ JSON with deletion details including chunks deleted, blob size freed
+ """
+ try:
+ username = session["username"]
+ service = DocumentDeletionService(username)
+ result = service.delete_document(document_id)
+
+ if result.get("deleted"):
+ return jsonify({"success": True, **result})
+ else:
+ return jsonify({"success": False, **result}), 404
+
+ except Exception as e:
+ return handle_api_error("deleting document", e)
+
+
+@delete_bp.route("/document/<string:document_id>/blob", methods=["DELETE"])
+@login_required
+def delete_document_blob(document_id):
+ """
+ Delete PDF binary but keep document metadata and text content.
+
+ Tooltip: "Remove the PDF file to save space. Text content will be
+ preserved for searching."
+
+ Returns:
+ JSON with bytes freed
+ """
+ try:
+ username = session["username"]
+ service = DocumentDeletionService(username)
+ result = service.delete_blob_only(document_id)
+
+ if result.get("deleted"):
+ return jsonify({"success": True, **result})
+ else:
+ error_code = (
+ 404 if "not found" in result.get("error", "").lower() else 400
+ )
+ return jsonify({"success": False, **result}), error_code
+
+ except Exception as e:
+ return handle_api_error("deleting document blob", e)
+
+
+@delete_bp.route("/document/<string:document_id>/preview", methods=["GET"])
+@login_required
+def get_document_deletion_preview(document_id):
+ """
+ Get a preview of what will be deleted.
+
+ Returns information about the document to help user confirm deletion.
+ """
+ try:
+ username = session["username"]
+ service = DocumentDeletionService(username)
+ result = service.get_deletion_preview(document_id)
+
+ if result.get("found"):
+ return jsonify({"success": True, **result})
+ else:
+ return jsonify(
+ {"success": False, "error": "Document not found"}
+ ), 404
+
+ except Exception as e:
+ return handle_api_error("getting document preview", e)
+
+
+# =============================================================================
+# Collection Document Endpoints
+# =============================================================================
+
+
+@delete_bp.route(
+ "/collection/<string:collection_id>/document/<string:document_id>",
+ methods=["DELETE"],
+)
+@login_required
+def remove_document_from_collection(collection_id, document_id):
+ """
+ Remove document from a collection.
+
+ If the document is not in any other collection, it will be deleted.
+
+ Tooltip: "Remove from this collection. If not in any other collection,
+ the document will be deleted."
+
+ Returns:
+ JSON with unlink status and whether document was deleted
+ """
+ try:
+ username = session["username"]
+ service = DocumentDeletionService(username)
+ result = service.remove_from_collection(document_id, collection_id)
+
+ if result.get("unlinked"):
+ return jsonify({"success": True, **result})
+ else:
+ return jsonify({"success": False, **result}), 404
+
+ except Exception as e:
+ return handle_api_error("removing document from collection", e)
+
+
+# =============================================================================
+# Collection Delete Endpoints
+# =============================================================================
+
+
+@delete_bp.route("/collections/<string:collection_id>", methods=["DELETE"])
+@login_required
+def delete_collection(collection_id):
+ """
+ Delete a collection and clean up all related data.
+
+ Documents are preserved but unlinked. RAG index and chunks are deleted.
+
+ Tooltip: "Delete this collection. Documents will remain in the library
+ but will be unlinked from this collection."
+
+ Returns:
+ JSON with deletion details
+ """
+ try:
+ username = session["username"]
+ service = CollectionDeletionService(username)
+ result = service.delete_collection(collection_id)
+
+ if result.get("deleted"):
+ return jsonify({"success": True, **result})
+ else:
+ return jsonify({"success": False, **result}), 404
+
+ except Exception as e:
+ return handle_api_error("deleting collection", e)
+
+
+@delete_bp.route(
+ "/collections/<string:collection_id>/index", methods=["DELETE"]
+)
+@login_required
+def delete_collection_index(collection_id):
+ """
+ Delete only the RAG index for a collection, keeping the collection itself.
+
+ Useful for rebuilding an index from scratch.
+
+ Returns:
+ JSON with deletion details
+ """
+ try:
+ username = session["username"]
+ service = CollectionDeletionService(username)
+ result = service.delete_collection_index_only(collection_id)
+
+ if result.get("deleted"):
+ return jsonify({"success": True, **result})
+ else:
+ return jsonify({"success": False, **result}), 404
+
+ except Exception as e:
+ return handle_api_error("deleting collection index", e)
+
+
+@delete_bp.route("/collections/<string:collection_id>/preview", methods=["GET"])
+@login_required
+def get_collection_deletion_preview(collection_id):
+ """
+ Get a preview of what will be deleted.
+
+ Returns information about the collection to help user confirm deletion.
+ """
+ try:
+ username = session["username"]
+ service = CollectionDeletionService(username)
+ result = service.get_deletion_preview(collection_id)
+
+ if result.get("found"):
+ return jsonify({"success": True, **result})
+ else:
+ return jsonify(
+ {"success": False, "error": "Collection not found"}
+ ), 404
+
+ except Exception as e:
+ return handle_api_error("getting collection preview", e)
+
+
+# =============================================================================
+# Bulk Delete Endpoints
+# =============================================================================
+
+
+@delete_bp.route("/documents/bulk", methods=["DELETE"])
+@login_required
+def delete_documents_bulk():
+ """
+ Delete multiple documents at once.
+
+ Tooltip: "Permanently delete all selected documents and their associated data."
+
+ Request body:
+ {"document_ids": ["id1", "id2", ...]}
+
+ Returns:
+ JSON with bulk deletion results
+ """
+ try:
+ data = request.get_json()
+ if not data or "document_ids" not in data:
+ return jsonify(
+ {
+ "success": False,
+ "error": "document_ids required in request body",
+ }
+ ), 400
+
+ document_ids = data["document_ids"]
+ if not isinstance(document_ids, list) or not document_ids:
+ return jsonify(
+ {
+ "success": False,
+ "error": "document_ids must be a non-empty list",
+ }
+ ), 400
+
+ username = session["username"]
+ service = BulkDeletionService(username)
+ result = service.delete_documents(document_ids)
+
+ return jsonify({"success": True, **result})
+
+ except Exception as e:
+ return handle_api_error("bulk deleting documents", e)
+
+
+@delete_bp.route("/documents/blobs", methods=["DELETE"])
+@login_required
+def delete_documents_blobs_bulk():
+ """
+ Delete PDF binaries for multiple documents.
+
+ Tooltip: "Remove PDF files from selected documents to free up database space.
+ Text content is preserved."
+
+ Request body:
+ {"document_ids": ["id1", "id2", ...]}
+
+ Returns:
+ JSON with bulk blob deletion results
+ """
+ try:
+ data = request.get_json()
+ if not data or "document_ids" not in data:
+ return jsonify(
+ {
+ "success": False,
+ "error": "document_ids required in request body",
+ }
+ ), 400
+
+ document_ids = data["document_ids"]
+ if not isinstance(document_ids, list) or not document_ids:
+ return jsonify(
+ {
+ "success": False,
+ "error": "document_ids must be a non-empty list",
+ }
+ ), 400
+
+ username = session["username"]
+ service = BulkDeletionService(username)
+ result = service.delete_blobs(document_ids)
+
+ return jsonify({"success": True, **result})
+
+ except Exception as e:
+ return handle_api_error("bulk deleting blobs", e)
+
+
+@delete_bp.route(
+ "/collection/<string:collection_id>/documents/bulk", methods=["DELETE"]
+)
+@login_required
+def remove_documents_from_collection_bulk(collection_id):
+ """
+ Remove multiple documents from a collection.
+
+ Documents that are not in any other collection will be deleted.
+
+ Request body:
+ {"document_ids": ["id1", "id2", ...]}
+
+ Returns:
+ JSON with bulk removal results
+ """
+ try:
+ data = request.get_json()
+ if not data or "document_ids" not in data:
+ return jsonify(
+ {
+ "success": False,
+ "error": "document_ids required in request body",
+ }
+ ), 400
+
+ document_ids = data["document_ids"]
+ if not isinstance(document_ids, list) or not document_ids:
+ return jsonify(
+ {
+ "success": False,
+ "error": "document_ids must be a non-empty list",
+ }
+ ), 400
+
+ username = session["username"]
+ service = BulkDeletionService(username)
+ result = service.remove_documents_from_collection(
+ document_ids, collection_id
+ )
+
+ return jsonify({"success": True, **result})
+
+ except Exception as e:
+ return handle_api_error("bulk removing documents from collection", e)
+
+
+@delete_bp.route("/documents/preview", methods=["POST"])
+@login_required
+def get_bulk_deletion_preview():
+ """
+ Get a preview of what will be affected by a bulk operation.
+
+ Request body:
+ {
+ "document_ids": ["id1", "id2", ...],
+ "operation": "delete" or "delete_blobs"
+ }
+
+ Returns:
+ JSON with preview information
+ """
+ try:
+ data = request.get_json()
+ if not data or "document_ids" not in data:
+ return jsonify(
+ {
+ "success": False,
+ "error": "document_ids required in request body",
+ }
+ ), 400
+
+ document_ids = data["document_ids"]
+ operation = data.get("operation", "delete")
+
+ if not isinstance(document_ids, list) or not document_ids:
+ return jsonify(
+ {
+ "success": False,
+ "error": "document_ids must be a non-empty list",
+ }
+ ), 400
+
+ username = session["username"]
+ service = BulkDeletionService(username)
+ result = service.get_bulk_preview(document_ids, operation)
+
+ return jsonify({"success": True, **result})
+
+ except Exception as e:
+ return handle_api_error("getting bulk preview", e)
diff --git a/src/local_deep_research/research_library/deletion/services/__init__.py b/src/local_deep_research/research_library/deletion/services/__init__.py
new file mode 100644
index 0000000000..0a613c1107
--- /dev/null
+++ b/src/local_deep_research/research_library/deletion/services/__init__.py
@@ -0,0 +1,11 @@
+"""Deletion services for research library."""
+
+from .document_deletion import DocumentDeletionService
+from .collection_deletion import CollectionDeletionService
+from .bulk_deletion import BulkDeletionService
+
+__all__ = [
+ "DocumentDeletionService",
+ "CollectionDeletionService",
+ "BulkDeletionService",
+]
diff --git a/src/local_deep_research/research_library/deletion/services/bulk_deletion.py b/src/local_deep_research/research_library/deletion/services/bulk_deletion.py
new file mode 100644
index 0000000000..3b1f6231cf
--- /dev/null
+++ b/src/local_deep_research/research_library/deletion/services/bulk_deletion.py
@@ -0,0 +1,297 @@
+"""
+Bulk deletion service.
+
+Handles bulk operations:
+- Delete multiple documents
+- Delete blobs for multiple documents
+- Remove multiple documents from a collection
+"""
+
+from typing import Dict, Any, List
+
+from loguru import logger
+
+from .document_deletion import DocumentDeletionService
+
+
+class BulkDeletionService:
+ """Service for bulk deletion operations."""
+
+ def __init__(self, username: str):
+ """
+ Initialize bulk deletion service.
+
+ Args:
+ username: Username for database session
+ """
+ self.username = username
+ self._document_service = DocumentDeletionService(username)
+
+ def delete_documents(self, document_ids: List[str]) -> Dict[str, Any]:
+ """
+ Delete multiple documents.
+
+ Args:
+ document_ids: List of document IDs to delete
+
+ Returns:
+ Dict with bulk deletion results:
+ {
+ "total": int,
+ "deleted": int,
+ "failed": int,
+ "total_chunks_deleted": int,
+ "total_bytes_freed": int,
+ "results": List[Dict],
+ "errors": List[Dict]
+ }
+ """
+ result = {
+ "total": len(document_ids),
+ "deleted": 0,
+ "failed": 0,
+ "total_chunks_deleted": 0,
+ "total_bytes_freed": 0,
+ "results": [],
+ "errors": [],
+ }
+
+ for document_id in document_ids:
+ delete_result = self._document_service.delete_document(document_id)
+
+ if delete_result.get("deleted"):
+ result["deleted"] += 1
+ result["total_chunks_deleted"] += delete_result.get(
+ "chunks_deleted", 0
+ )
+ result["total_bytes_freed"] += delete_result.get("blob_size", 0)
+ result["results"].append(
+ {
+ "document_id": document_id,
+ "title": delete_result.get("title", "Unknown"),
+ "chunks_deleted": delete_result.get(
+ "chunks_deleted", 0
+ ),
+ "blob_size": delete_result.get("blob_size", 0),
+ }
+ )
+ else:
+ result["failed"] += 1
+ result["errors"].append(
+ {
+ "document_id": document_id,
+ "error": delete_result.get("error", "Unknown error"),
+ }
+ )
+
+ logger.info(
+ f"Bulk delete: {result['deleted']}/{result['total']} documents, "
+ f"{result['total_chunks_deleted']} chunks, "
+ f"{result['total_bytes_freed']} bytes"
+ )
+
+ return result
+
+ def delete_blobs(self, document_ids: List[str]) -> Dict[str, Any]:
+ """
+ Delete PDF binaries for multiple documents, keeping text content.
+
+ Args:
+ document_ids: List of document IDs to delete blobs for
+
+ Returns:
+ Dict with bulk blob deletion results:
+ {
+ "total": int,
+ "deleted": int,
+ "skipped": int,
+ "failed": int,
+ "total_bytes_freed": int,
+ "results": List[Dict],
+ "errors": List[Dict]
+ }
+ """
+ result = {
+ "total": len(document_ids),
+ "deleted": 0,
+ "skipped": 0,
+ "failed": 0,
+ "total_bytes_freed": 0,
+ "results": [],
+ "errors": [],
+ }
+
+ for document_id in document_ids:
+ delete_result = self._document_service.delete_blob_only(document_id)
+
+ if delete_result.get("deleted"):
+ result["deleted"] += 1
+ result["total_bytes_freed"] += delete_result.get(
+ "bytes_freed", 0
+ )
+ result["results"].append(
+ {
+ "document_id": document_id,
+ "bytes_freed": delete_result.get("bytes_freed", 0),
+ }
+ )
+ elif "no stored PDF" in delete_result.get("error", "").lower():
+ result["skipped"] += 1
+ else:
+ result["failed"] += 1
+ result["errors"].append(
+ {
+ "document_id": document_id,
+ "error": delete_result.get("error", "Unknown error"),
+ }
+ )
+
+ logger.info(
+ f"Bulk blob delete: {result['deleted']}/{result['total']} blobs, "
+ f"{result['total_bytes_freed']} bytes freed"
+ )
+
+ return result
+
+ def remove_documents_from_collection(
+ self,
+ document_ids: List[str],
+ collection_id: str,
+ ) -> Dict[str, Any]:
+ """
+ Remove multiple documents from a collection.
+
+ Documents that are not in any other collection will be deleted.
+
+ Args:
+ document_ids: List of document IDs to remove
+ collection_id: ID of the collection
+
+ Returns:
+ Dict with bulk removal results:
+ {
+ "total": int,
+ "unlinked": int,
+ "deleted": int,
+ "failed": int,
+ "total_chunks_deleted": int,
+ "results": List[Dict],
+ "errors": List[Dict]
+ }
+ """
+ result = {
+ "total": len(document_ids),
+ "unlinked": 0,
+ "deleted": 0,
+ "failed": 0,
+ "total_chunks_deleted": 0,
+ "results": [],
+ "errors": [],
+ }
+
+ for document_id in document_ids:
+ remove_result = self._document_service.remove_from_collection(
+ document_id, collection_id
+ )
+
+ if remove_result.get("unlinked"):
+ result["unlinked"] += 1
+ result["total_chunks_deleted"] += remove_result.get(
+ "chunks_deleted", 0
+ )
+ if remove_result.get("document_deleted"):
+ result["deleted"] += 1
+ result["results"].append(
+ {
+ "document_id": document_id,
+ "document_deleted": remove_result.get(
+ "document_deleted", False
+ ),
+ "chunks_deleted": remove_result.get(
+ "chunks_deleted", 0
+ ),
+ }
+ )
+ else:
+ result["failed"] += 1
+ result["errors"].append(
+ {
+ "document_id": document_id,
+ "error": remove_result.get("error", "Unknown error"),
+ }
+ )
+
+ logger.info(
+ f"Bulk remove from collection: {result['unlinked']}/{result['total']} "
+ f"unlinked, {result['deleted']} deleted, "
+ f"{result['total_chunks_deleted']} chunks"
+ )
+
+ return result
+
+ def get_bulk_preview(
+ self,
+ document_ids: List[str],
+ operation: str = "delete",
+ ) -> Dict[str, Any]:
+ """
+ Get a preview of what will be affected by a bulk operation.
+
+ Args:
+ document_ids: List of document IDs
+ operation: Type of operation ("delete", "delete_blobs")
+
+ Returns:
+ Dict with preview information
+ """
+ from ....database.models.library import Document, DocumentChunk
+ from ....database.session_context import get_user_db_session
+ from ..utils.cascade_helper import CascadeHelper
+
+ result = {
+ "total_documents": len(document_ids),
+ "found_documents": 0,
+ "total_blob_size": 0,
+ "documents_with_blobs": 0,
+ "total_chunks": 0,
+ "documents": [],
+ }
+
+ with get_user_db_session(self.username) as session:
+ for document_id in document_ids:
+ document = session.query(Document).get(document_id)
+ if not document:
+ continue
+
+ result["found_documents"] += 1
+ blob_size = CascadeHelper.get_document_blob_size(
+ session, document_id
+ )
+
+ if blob_size > 0:
+ result["documents_with_blobs"] += 1
+ result["total_blob_size"] += blob_size
+
+ chunks = (
+ session.query(DocumentChunk)
+ .filter(
+ DocumentChunk.source_id == document_id,
+ DocumentChunk.source_type == "document",
+ )
+ .count()
+ )
+ result["total_chunks"] += chunks
+
+ result["documents"].append(
+ {
+ "id": document_id,
+ "title": document.title
+ or document.filename
+ or "Untitled",
+ "has_blob": blob_size > 0,
+ "blob_size": blob_size,
+ "chunks_count": chunks,
+ }
+ )
+
+ return result
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
new file mode 100644
index 0000000000..0dc0cf63f6
--- /dev/null
+++ b/src/local_deep_research/research_library/deletion/services/collection_deletion.py
@@ -0,0 +1,286 @@
+"""
+Collection deletion service.
+
+Handles:
+- Full collection deletion with proper cleanup
+- Documents are preserved but unlinked
+- RAG index and chunks are deleted
+"""
+
+from typing import Dict, Any
+
+from loguru import logger
+
+from ....database.models.library import (
+ Collection,
+ DocumentCollection,
+ DocumentChunk,
+ CollectionFolder,
+ RAGIndex,
+ RagDocumentStatus,
+)
+from ....database.session_context import get_user_db_session
+from ..utils.cascade_helper import CascadeHelper
+
+
+class CollectionDeletionService:
+ """Service for collection deletion operations."""
+
+ def __init__(self, username: str):
+ """
+ Initialize collection deletion service.
+
+ Args:
+ username: Username for database session
+ """
+ self.username = username
+
+ def delete_collection(self, collection_id: str) -> Dict[str, Any]:
+ """
+ Delete a collection and clean up all related data.
+
+ Documents are preserved but unlinked from the collection.
+ The following are deleted:
+ - DocumentChunks for this collection
+ - FAISS index files
+ - RAGIndex records
+ - CollectionFolder records (CASCADE)
+ - DocumentCollection links (CASCADE)
+ - RagDocumentStatus records (CASCADE)
+
+ Args:
+ collection_id: ID of the collection to delete
+
+ Returns:
+ Dict with deletion details:
+ {
+ "deleted": True/False,
+ "collection_id": str,
+ "collection_name": str,
+ "chunks_deleted": int,
+ "documents_unlinked": int,
+ "indices_deleted": int,
+ "folders_deleted": int,
+ "error": str (if failed)
+ }
+ """
+ with get_user_db_session(self.username) as session:
+ try:
+ # Get collection
+ collection = session.query(Collection).get(collection_id)
+ if not collection:
+ return {
+ "deleted": False,
+ "collection_id": collection_id,
+ "error": "Collection not found",
+ }
+
+ collection_name = f"collection_{collection_id}"
+ result = {
+ "deleted": False,
+ "collection_id": collection_id,
+ "collection_name": collection.name,
+ "chunks_deleted": 0,
+ "documents_unlinked": 0,
+ "indices_deleted": 0,
+ "folders_deleted": 0,
+ }
+
+ # 1. Count documents that will be unlinked
+ result["documents_unlinked"] = (
+ session.query(DocumentCollection)
+ .filter_by(collection_id=collection_id)
+ .count()
+ )
+
+ # 2. Delete DocumentChunks for this collection
+ result["chunks_deleted"] = (
+ CascadeHelper.delete_collection_chunks(
+ session, collection_name
+ )
+ )
+
+ # 3. Delete RAGIndex records and FAISS files
+ rag_result = CascadeHelper.delete_rag_indices_for_collection(
+ session, collection_name
+ )
+ result["indices_deleted"] = rag_result["deleted_indices"]
+
+ # 4. Count folders before deletion
+ result["folders_deleted"] = (
+ session.query(CollectionFolder)
+ .filter_by(collection_id=collection_id)
+ .count()
+ )
+
+ # 5. Delete the collection (CASCADE handles DocumentCollection,
+ # CollectionFolder, RagDocumentStatus)
+ session.delete(collection)
+ 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"
+ )
+
+ return result
+
+ except Exception as e:
+ logger.exception(f"Failed to delete collection {collection_id}")
+ session.rollback()
+ return {
+ "deleted": False,
+ "collection_id": collection_id,
+ "error": str(e),
+ }
+
+ def delete_collection_index_only(
+ self, collection_id: str
+ ) -> Dict[str, Any]:
+ """
+ Delete only the RAG index for a collection, keeping the collection itself.
+
+ This is useful for rebuilding an index from scratch.
+
+ Args:
+ collection_id: ID of the collection
+
+ Returns:
+ Dict with deletion details
+ """
+ with get_user_db_session(self.username) as session:
+ try:
+ # Verify collection exists
+ collection = session.query(Collection).get(collection_id)
+ if not collection:
+ return {
+ "deleted": False,
+ "collection_id": collection_id,
+ "error": "Collection not found",
+ }
+
+ collection_name = f"collection_{collection_id}"
+ result = {
+ "deleted": False,
+ "collection_id": collection_id,
+ "chunks_deleted": 0,
+ "indices_deleted": 0,
+ "documents_reset": 0,
+ }
+
+ # 1. Delete DocumentChunks
+ result["chunks_deleted"] = (
+ CascadeHelper.delete_collection_chunks(
+ session, collection_name
+ )
+ )
+
+ # 2. Delete RAGIndex records and FAISS files
+ rag_result = CascadeHelper.delete_rag_indices_for_collection(
+ session, collection_name
+ )
+ result["indices_deleted"] = rag_result["deleted_indices"]
+
+ # 3. Reset DocumentCollection indexed status
+ result["documents_reset"] = (
+ session.query(DocumentCollection)
+ .filter_by(collection_id=collection_id)
+ .update({"indexed": False, "chunk_count": 0})
+ )
+
+ # 4. Delete RagDocumentStatus for this collection
+ session.query(RagDocumentStatus).filter_by(
+ collection_id=collection_id
+ ).delete(synchronize_session=False)
+
+ # 5. Reset collection embedding info
+ collection.embedding_model = None
+ collection.embedding_model_type = None
+ collection.embedding_dimension = None
+ collection.chunk_size = None
+ collection.chunk_overlap = None
+
+ session.commit()
+ result["deleted"] = True
+
+ logger.info(
+ f"Deleted index for collection {collection_id[:8]}...: "
+ f"{result['chunks_deleted']} chunks, "
+ f"{result['documents_reset']} documents reset"
+ )
+
+ return result
+
+ except Exception as e:
+ logger.exception(
+ f"Failed to delete index for collection {collection_id}"
+ )
+ session.rollback()
+ return {
+ "deleted": False,
+ "collection_id": collection_id,
+ "error": str(e),
+ }
+
+ def get_deletion_preview(self, collection_id: str) -> Dict[str, Any]:
+ """
+ Get a preview of what will be deleted.
+
+ Useful for showing the user what will happen before confirming.
+
+ Args:
+ collection_id: ID of the collection
+
+ Returns:
+ Dict with preview information
+ """
+ with get_user_db_session(self.username) as session:
+ collection = session.query(Collection).get(collection_id)
+ if not collection:
+ return {"found": False, "collection_id": collection_id}
+
+ collection_name = f"collection_{collection_id}"
+
+ # Count documents
+ documents_count = (
+ session.query(DocumentCollection)
+ .filter_by(collection_id=collection_id)
+ .count()
+ )
+
+ # Count chunks
+ chunks_count = (
+ session.query(DocumentChunk)
+ .filter_by(collection_name=collection_name)
+ .count()
+ )
+
+ # Count folders
+ folders_count = (
+ session.query(CollectionFolder)
+ .filter_by(collection_id=collection_id)
+ .count()
+ )
+
+ # Check for RAG index
+ has_index = (
+ session.query(RAGIndex)
+ .filter_by(collection_name=collection_name)
+ .first()
+ is not None
+ )
+
+ return {
+ "found": True,
+ "collection_id": collection_id,
+ "name": collection.name,
+ "description": collection.description,
+ "is_default": collection.is_default,
+ "documents_count": documents_count,
+ "chunks_count": chunks_count,
+ "folders_count": folders_count,
+ "has_rag_index": has_index,
+ "embedding_model": collection.embedding_model,
+ }
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
new file mode 100644
index 0000000000..cbc7b6e3b5
--- /dev/null
+++ b/src/local_deep_research/research_library/deletion/services/document_deletion.py
@@ -0,0 +1,434 @@
+"""
+Document deletion service.
+
+Handles:
+- Full document deletion with proper cascade cleanup
+- Blob-only deletion (remove PDF, keep text)
+- Remove from collection (unlink or delete if orphaned)
+"""
+
+from typing import Dict, Any
+
+from loguru import logger
+
+from ....database.models.library import (
+ Document,
+ DocumentChunk,
+ DocumentCollection,
+)
+from ....database.session_context import get_user_db_session
+from ..utils.cascade_helper import CascadeHelper
+
+
+class DocumentDeletionService:
+ """Service for document deletion operations."""
+
+ def __init__(self, username: str):
+ """
+ Initialize document deletion service.
+
+ Args:
+ username: Username for database session
+ """
+ self.username = username
+
+ def delete_document(self, document_id: str) -> Dict[str, Any]:
+ """
+ Delete a document and ALL related data.
+
+ This method ensures complete cleanup:
+ - DocumentChunks (no FK constraint, manual cleanup required)
+ - DocumentBlob (CASCADE handles, but we track for stats)
+ - Filesystem files
+ - FAISS index entries
+ - DownloadTracker update
+ - DocumentCollection links (CASCADE)
+ - RagDocumentStatus (CASCADE)
+
+ Args:
+ document_id: ID of the document to delete
+
+ Returns:
+ Dict with deletion details:
+ {
+ "deleted": True/False,
+ "document_id": str,
+ "title": str,
+ "blob_deleted": bool,
+ "blob_size": int,
+ "chunks_deleted": int,
+ "collections_unlinked": int,
+ "error": str (if failed)
+ }
+ """
+ with get_user_db_session(self.username) as session:
+ try:
+ # Get document
+ document = session.query(Document).get(document_id)
+ if not document:
+ return {
+ "deleted": False,
+ "document_id": document_id,
+ "error": "Document not found",
+ }
+
+ title = document.title or document.filename or "Untitled"
+ result = {
+ "deleted": False,
+ "document_id": document_id,
+ "title": title,
+ "blob_deleted": False,
+ "blob_size": 0,
+ "chunks_deleted": 0,
+ "collections_unlinked": 0,
+ "file_deleted": False,
+ }
+
+ # 1. Get collections before deletion for chunk cleanup
+ collections = CascadeHelper.get_document_collections(
+ session, document_id
+ )
+ result["collections_unlinked"] = len(collections)
+
+ # 2. Delete DocumentChunks for ALL collections this document is in
+ total_chunks_deleted = 0
+ for collection_id in collections:
+ collection_name = f"collection_{collection_id}"
+ chunks_deleted = CascadeHelper.delete_document_chunks(
+ session, document_id, collection_name
+ )
+ total_chunks_deleted += chunks_deleted
+ result["chunks_deleted"] = total_chunks_deleted
+
+ # 3. Get blob size before deletion (for stats)
+ result["blob_size"] = CascadeHelper.get_document_blob_size(
+ session, document_id
+ )
+ result["blob_deleted"] = result["blob_size"] > 0
+
+ # 4. Delete filesystem file if exists
+ if document.storage_mode == "filesystem" and document.file_path:
+ from ...utils import get_absolute_path_from_settings
+
+ try:
+ file_path = get_absolute_path_from_settings(
+ document.file_path
+ )
+ result["file_deleted"] = (
+ CascadeHelper.delete_filesystem_file(str(file_path))
+ )
+ except Exception:
+ logger.exception("Failed to delete filesystem file")
+
+ # 5. Update DownloadTracker
+ CascadeHelper.update_download_tracker(session, document)
+
+ # 6. Delete the document (CASCADE handles Blob, DocumentCollection,
+ # RagDocumentStatus)
+ session.delete(document)
+ session.commit()
+
+ result["deleted"] = True
+ logger.info(
+ f"Deleted document {document_id[:8]}... ({title}): "
+ f"{total_chunks_deleted} chunks, "
+ f"{result['blob_size']} bytes blob"
+ )
+
+ return result
+
+ except Exception as e:
+ logger.exception(f"Failed to delete document {document_id}")
+ session.rollback()
+ return {
+ "deleted": False,
+ "document_id": document_id,
+ "error": str(e),
+ }
+
+ def delete_blob_only(self, document_id: str) -> Dict[str, Any]:
+ """
+ Delete PDF binary but keep document metadata and text content.
+
+ This saves database space while preserving searchability.
+
+ Args:
+ document_id: ID of the document
+
+ Returns:
+ Dict with deletion details:
+ {
+ "deleted": True/False,
+ "document_id": str,
+ "bytes_freed": int,
+ "storage_mode_updated": bool,
+ "error": str (if failed)
+ }
+ """
+ with get_user_db_session(self.username) as session:
+ try:
+ # Get document
+ document = session.query(Document).get(document_id)
+ if not document:
+ return {
+ "deleted": False,
+ "document_id": document_id,
+ "bytes_freed": 0,
+ "error": "Document not found",
+ }
+
+ result = {
+ "deleted": False,
+ "document_id": document_id,
+ "bytes_freed": 0,
+ "storage_mode_updated": False,
+ }
+
+ # Handle based on storage mode
+ if document.storage_mode == "database":
+ # Delete blob from database
+ result["bytes_freed"] = CascadeHelper.delete_document_blob(
+ session, document_id
+ )
+
+ elif document.storage_mode == "filesystem":
+ # Delete filesystem file
+ from ...utils import get_absolute_path_from_settings
+
+ if document.file_path:
+ try:
+ file_path = get_absolute_path_from_settings(
+ document.file_path
+ )
+ if file_path.exists():
+ result["bytes_freed"] = file_path.stat().st_size
+ CascadeHelper.delete_filesystem_file(
+ str(file_path)
+ )
+ except Exception:
+ logger.exception("Failed to delete filesystem file")
+
+ else:
+ # No blob to delete
+ return {
+ "deleted": False,
+ "document_id": document_id,
+ "bytes_freed": 0,
+ "error": "Document has no stored PDF (storage_mode is 'none')",
+ }
+
+ # Update document to indicate blob is deleted
+ document.storage_mode = "none"
+ document.file_path = "blob_deleted"
+ result["storage_mode_updated"] = True
+
+ session.commit()
+ result["deleted"] = True
+
+ logger.info(
+ f"Deleted blob for document {document_id[:8]}...: "
+ f"{result['bytes_freed']} bytes freed"
+ )
+
+ return result
+
+ except Exception as e:
+ logger.exception(
+ f"Failed to delete blob for document {document_id}"
+ )
+ session.rollback()
+ return {
+ "deleted": False,
+ "document_id": document_id,
+ "bytes_freed": 0,
+ "error": str(e),
+ }
+
+ def remove_from_collection(
+ self,
+ document_id: str,
+ collection_id: str,
+ ) -> Dict[str, Any]:
+ """
+ Remove document from a collection.
+
+ If the document is not in any other collection after removal,
+ it will be completely deleted.
+
+ Args:
+ document_id: ID of the document
+ collection_id: ID of the collection
+
+ Returns:
+ Dict with operation details:
+ {
+ "unlinked": True/False,
+ "document_deleted": bool,
+ "document_id": str,
+ "collection_id": str,
+ "chunks_deleted": int,
+ "error": str (if failed)
+ }
+ """
+ with get_user_db_session(self.username) as session:
+ try:
+ # Verify document exists
+ document = session.query(Document).get(document_id)
+ if not document:
+ return {
+ "unlinked": False,
+ "document_deleted": False,
+ "document_id": document_id,
+ "collection_id": collection_id,
+ "error": "Document not found",
+ }
+
+ # Verify collection exists and document is in it
+ doc_collection = (
+ session.query(DocumentCollection)
+ .filter_by(
+ document_id=document_id, collection_id=collection_id
+ )
+ .first()
+ )
+
+ if not doc_collection:
+ return {
+ "unlinked": False,
+ "document_deleted": False,
+ "document_id": document_id,
+ "collection_id": collection_id,
+ "error": "Document not in this collection",
+ }
+
+ result = {
+ "unlinked": False,
+ "document_deleted": False,
+ "document_id": document_id,
+ "collection_id": collection_id,
+ "chunks_deleted": 0,
+ }
+
+ # Delete chunks for this document in this collection
+ collection_name = f"collection_{collection_id}"
+ result["chunks_deleted"] = CascadeHelper.delete_document_chunks(
+ session, document_id, collection_name
+ )
+
+ # Remove the link
+ session.delete(doc_collection)
+ session.flush()
+
+ # Check if document is in any other collection
+ remaining_count = CascadeHelper.count_document_in_collections(
+ session, document_id
+ )
+
+ if remaining_count == 0:
+ # Document is orphaned - delete it completely
+ # Note: We're already in a session, so we need to do this
+ # directly rather than calling delete_document()
+ logger.info(
+ f"Document {document_id[:8]}... is orphaned, deleting"
+ )
+
+ # Delete remaining chunks (shouldn't be any, but be safe)
+ session.query(DocumentChunk).filter(
+ DocumentChunk.source_id == document_id,
+ DocumentChunk.source_type == "document",
+ ).delete(synchronize_session=False)
+
+ # Update DownloadTracker
+ CascadeHelper.update_download_tracker(session, document)
+
+ # Delete filesystem file if applicable
+ if (
+ document.storage_mode == "filesystem"
+ and document.file_path
+ ):
+ from ...utils import get_absolute_path_from_settings
+
+ try:
+ file_path = get_absolute_path_from_settings(
+ document.file_path
+ )
+ CascadeHelper.delete_filesystem_file(str(file_path))
+ except Exception:
+ logger.exception("Failed to delete filesystem file")
+
+ # Delete document (CASCADE handles blob, RagDocumentStatus)
+ session.delete(document)
+ result["document_deleted"] = True
+
+ session.commit()
+ result["unlinked"] = True
+
+ logger.info(
+ f"Removed document {document_id[:8]}... from collection "
+ f"{collection_id[:8]}... "
+ f"(deleted={result['document_deleted']})"
+ )
+
+ return result
+
+ except Exception as e:
+ logger.exception(
+ f"Failed to remove document {document_id} "
+ f"from collection {collection_id}"
+ )
+ session.rollback()
+ return {
+ "unlinked": False,
+ "document_deleted": False,
+ "document_id": document_id,
+ "collection_id": collection_id,
+ "error": str(e),
+ }
+
+ def get_deletion_preview(self, document_id: str) -> Dict[str, Any]:
+ """
+ Get a preview of what will be deleted.
+
+ Useful for showing the user what will happen before confirming.
+
+ Args:
+ document_id: ID of the document
+
+ Returns:
+ Dict with preview information
+ """
+ with get_user_db_session(self.username) as session:
+ document = session.query(Document).get(document_id)
+ if not document:
+ return {"found": False, "document_id": document_id}
+
+ collections = CascadeHelper.get_document_collections(
+ session, document_id
+ )
+
+ # Count chunks
+ total_chunks = (
+ session.query(DocumentChunk)
+ .filter(
+ DocumentChunk.source_id == document_id,
+ DocumentChunk.source_type == "document",
+ )
+ .count()
+ )
+
+ blob_size = CascadeHelper.get_document_blob_size(
+ session, document_id
+ )
+
+ return {
+ "found": True,
+ "document_id": document_id,
+ "title": document.title or document.filename or "Untitled",
+ "file_type": document.file_type,
+ "storage_mode": document.storage_mode,
+ "has_blob": blob_size > 0,
+ "blob_size": blob_size,
+ "has_text": bool(document.text_content),
+ "collections_count": len(collections),
+ "chunks_count": total_chunks,
+ }
diff --git a/src/local_deep_research/research_library/deletion/utils/__init__.py b/src/local_deep_research/research_library/deletion/utils/__init__.py
new file mode 100644
index 0000000000..a97480502f
--- /dev/null
+++ b/src/local_deep_research/research_library/deletion/utils/__init__.py
@@ -0,0 +1,5 @@
+"""Utility functions for deletion operations."""
+
+from .cascade_helper import CascadeHelper
+
+__all__ = ["CascadeHelper"]
diff --git a/src/local_deep_research/research_library/deletion/utils/cascade_helper.py b/src/local_deep_research/research_library/deletion/utils/cascade_helper.py
new file mode 100644
index 0000000000..22dcb98c32
--- /dev/null
+++ b/src/local_deep_research/research_library/deletion/utils/cascade_helper.py
@@ -0,0 +1,369 @@
+"""
+Cascade helper for deletion operations.
+
+Handles cleanup of related records that don't have proper FK constraints:
+- DocumentChunk (source_id has no FK constraint)
+- FAISS index files
+- Filesystem files
+"""
+
+from pathlib import Path
+from typing import Dict, List, Optional, Any
+
+from loguru import logger
+from sqlalchemy.orm import Session
+
+from ....database.models.library import (
+ Document,
+ DocumentBlob,
+ DocumentChunk,
+ DocumentCollection,
+ RAGIndex,
+)
+from ....database.models.download_tracker import DownloadTracker
+
+
+class CascadeHelper:
+ """Helper class for cleaning up related records during deletion."""
+
+ @staticmethod
+ def delete_document_chunks(
+ session: Session,
+ document_id: str,
+ collection_name: Optional[str] = None,
+ ) -> int:
+ """
+ Delete DocumentChunks for a document.
+
+ Since DocumentChunk.source_id has no FK constraint, we must manually
+ clean up chunks when deleting a document.
+
+ Args:
+ session: Database session
+ document_id: The document ID to delete chunks for
+ collection_name: Optional collection name to limit deletion scope
+
+ Returns:
+ Number of chunks deleted
+ """
+ query = session.query(DocumentChunk).filter(
+ DocumentChunk.source_id == document_id,
+ DocumentChunk.source_type == "document",
+ )
+
+ if collection_name:
+ query = query.filter(
+ DocumentChunk.collection_name == collection_name
+ )
+
+ count = query.delete(synchronize_session=False)
+ logger.debug(
+ f"Deleted {count} chunks for document {document_id[:8]}..."
+ + (f" in collection {collection_name}" if collection_name else "")
+ )
+ return count
+
+ @staticmethod
+ def delete_collection_chunks(
+ session: Session,
+ collection_name: str,
+ ) -> int:
+ """
+ Delete all DocumentChunks for a collection.
+
+ Args:
+ session: Database session
+ collection_name: The collection name (e.g., "collection_<uuid>")
+
+ Returns:
+ Number of chunks deleted
+ """
+ count = (
+ session.query(DocumentChunk)
+ .filter_by(collection_name=collection_name)
+ .delete(synchronize_session=False)
+ )
+ logger.debug(f"Deleted {count} chunks for collection {collection_name}")
+ return count
+
+ @staticmethod
+ def get_document_blob_size(session: Session, document_id: str) -> int:
+ """
+ Get the size of a document's blob in bytes.
+
+ Args:
+ session: Database session
+ document_id: The document ID
+
+ Returns:
+ Size in bytes, or 0 if no blob exists
+ """
+ blob = (
+ session.query(DocumentBlob)
+ .filter_by(document_id=document_id)
+ .first()
+ )
+ if blob and blob.pdf_binary:
+ return len(blob.pdf_binary)
+ return 0
+
+ @staticmethod
+ def delete_document_blob(session: Session, document_id: str) -> int:
+ """
+ Delete a document's blob record.
+
+ Note: This is typically handled by CASCADE, but can be called explicitly
+ for blob-only deletion.
+
+ Args:
+ session: Database session
+ document_id: The document ID
+
+ Returns:
+ Size of deleted blob in bytes
+ """
+ blob = (
+ session.query(DocumentBlob)
+ .filter_by(document_id=document_id)
+ .first()
+ )
+ if blob:
+ size = len(blob.pdf_binary) if blob.pdf_binary else 0
+ session.delete(blob)
+ logger.debug(
+ f"Deleted blob for document {document_id[:8]}... ({size} bytes)"
+ )
+ return size
+ return 0
+
+ @staticmethod
+ def delete_filesystem_file(file_path: Optional[str]) -> bool:
+ """
+ Delete a file from the filesystem.
+
+ Args:
+ file_path: Path to the file (can be relative or absolute)
+
+ Returns:
+ True if file was deleted, False otherwise
+ """
+ if not file_path:
+ return False
+
+ # Skip special path markers
+ if file_path in (
+ "metadata_only",
+ "text_only_not_stored",
+ "blob_deleted",
+ ):
+ return False
+
+ try:
+ path = Path(file_path)
+ if path.exists():
+ path.unlink()
+ logger.debug(f"Deleted filesystem file: {file_path}")
+ return True
+ except Exception:
+ logger.exception(f"Failed to delete filesystem file: {file_path}")
+ return False
+
+ @staticmethod
+ def delete_faiss_index_files(index_path: Optional[str]) -> bool:
+ """
+ Delete FAISS index files.
+
+ FAISS stores indices as .faiss and .pkl files.
+
+ Args:
+ index_path: Path to the FAISS index file (without extension)
+
+ Returns:
+ True if files were deleted, False otherwise
+ """
+ if not index_path:
+ return False
+
+ try:
+ path = Path(index_path)
+ deleted_any = False
+
+ # FAISS index file
+ faiss_file = path.with_suffix(".faiss")
+ if faiss_file.exists():
+ faiss_file.unlink()
+ logger.debug(f"Deleted FAISS index file: {faiss_file}")
+ deleted_any = True
+
+ # Pickle file for metadata
+ pkl_file = path.with_suffix(".pkl")
+ if pkl_file.exists():
+ pkl_file.unlink()
+ logger.debug(f"Deleted FAISS pkl file: {pkl_file}")
+ deleted_any = True
+
+ return deleted_any
+ except Exception:
+ logger.exception(f"Failed to delete FAISS files for: {index_path}")
+ return False
+
+ @staticmethod
+ def delete_rag_indices_for_collection(
+ session: Session,
+ collection_name: str,
+ ) -> Dict[str, Any]:
+ """
+ Delete RAGIndex records and their FAISS files for a collection.
+
+ Args:
+ session: Database session
+ collection_name: The collection name (e.g., "collection_<uuid>")
+
+ Returns:
+ Dict with deletion results
+ """
+ indices = (
+ session.query(RAGIndex)
+ .filter_by(collection_name=collection_name)
+ .all()
+ )
+
+ deleted_indices = 0
+ deleted_files = 0
+
+ for index in indices:
+ # Delete FAISS files
+ if CascadeHelper.delete_faiss_index_files(index.index_path):
+ deleted_files += 1
+
+ session.delete(index)
+ deleted_indices += 1
+
+ logger.debug(
+ f"Deleted {deleted_indices} RAGIndex records and {deleted_files} "
+ f"FAISS files for collection {collection_name}"
+ )
+
+ return {
+ "deleted_indices": deleted_indices,
+ "deleted_files": deleted_files,
+ }
+
+ @staticmethod
+ def update_download_tracker(
+ session: Session,
+ document: Document,
+ ) -> bool:
+ """
+ Update DownloadTracker when a document is deleted.
+
+ The FK has SET NULL, but we also need to update is_downloaded flag.
+
+ Args:
+ session: Database session
+ document: The document being deleted
+
+ Returns:
+ True if tracker was updated
+ """
+ if not document.original_url:
+ return False
+
+ # Get URL hash using the same method as library_service
+ from ...utils import get_url_hash
+
+ try:
+ url_hash = get_url_hash(document.original_url)
+ tracker = (
+ session.query(DownloadTracker)
+ .filter_by(url_hash=url_hash)
+ .first()
+ )
+
+ if tracker:
+ tracker.is_downloaded = False
+ tracker.file_path = None
+ logger.debug(
+ f"Updated DownloadTracker for document {document.id[:8]}..."
+ )
+ return True
+ except Exception:
+ logger.exception("Failed to update DownloadTracker")
+ return False
+
+ @staticmethod
+ def count_document_in_collections(
+ session: Session,
+ document_id: str,
+ ) -> int:
+ """
+ Count how many collections a document is in.
+
+ Args:
+ session: Database session
+ document_id: The document ID
+
+ Returns:
+ Number of collections the document is in
+ """
+ return (
+ session.query(DocumentCollection)
+ .filter_by(document_id=document_id)
+ .count()
+ )
+
+ @staticmethod
+ def get_document_collections(
+ session: Session,
+ document_id: str,
+ ) -> List[str]:
+ """
+ Get all collection IDs a document belongs to.
+
+ Args:
+ session: Database session
+ document_id: The document ID
+
+ Returns:
+ List of collection IDs
+ """
+ doc_collections = (
+ session.query(DocumentCollection.collection_id)
+ .filter_by(document_id=document_id)
+ .all()
+ )
+ return [dc.collection_id for dc in doc_collections]
+
+ @staticmethod
+ def remove_from_faiss_index(
+ username: str,
+ collection_name: str,
+ chunk_ids: List[str],
+ ) -> bool:
+ """
+ Remove specific chunks from a FAISS index.
+
+ Args:
+ username: Username for RAG service
+ collection_name: Collection name
+ chunk_ids: List of chunk IDs to remove
+
+ Returns:
+ True if successful
+ """
+ try:
+ from ..services.library_rag_service import LibraryRAGService
+
+ rag_service = LibraryRAGService(
+ username=username,
+ collection_name=collection_name,
+ )
+
+ # This uses the existing remove functionality
+ if hasattr(rag_service, "faiss_index") and rag_service.faiss_index:
+ if hasattr(rag_service.faiss_index, "delete"):
+ rag_service.faiss_index.delete(chunk_ids)
+ return True
+ except Exception:
+ logger.exception("Failed to remove chunks from FAISS index")
+ return False
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index c6d3c6cf9d..efa92b61ee 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -514,7 +514,7 @@ def register_blueprints(app):
app.register_blueprint(api_blueprint) # Already has url_prefix='/api/v1'
# Register Research Library blueprint
- from ..research_library import library_bp, rag_bp
+ from ..research_library import library_bp, rag_bp, delete_bp
app.register_blueprint(library_bp) # Already has url_prefix='/library'
logger.info("Research Library routes registered successfully")
@@ -523,6 +523,10 @@ def register_blueprints(app):
app.register_blueprint(rag_bp) # Already has url_prefix='/library'
logger.info("RAG Management routes registered successfully")
+ # Register Deletion Management blueprint
+ app.register_blueprint(delete_bp) # Already has url_prefix='/library/api'
+ logger.info("Deletion Management routes registered successfully")
+
# Register Document Scheduler blueprint
from ..research_scheduler.routes import scheduler_bp
diff --git a/src/local_deep_research/web/static/css/collection_details.css b/src/local_deep_research/web/static/css/collection_details.css
index 58d7194ef7..fe1668d6eb 100644
--- a/src/local_deep_research/web/static/css/collection_details.css
+++ b/src/local_deep_research/web/static/css/collection_details.css
@@ -418,6 +418,47 @@
position: relative;
overflow: hidden;
cursor: pointer;
+ display: flex;
+ align-items: center;
+ gap: 15px;
+}
+
+.ldr-document-item .ldr-document-info {
+ flex: 1;
+}
+
+.ldr-document-item .ldr-document-actions {
+ display: flex;
+ gap: 8px;
+ flex-shrink: 0;
+}
+
+.ldr-document-item .ldr-document-actions button {
+ background: transparent;
+ border: 1px solid #cbd5e0;
+ color: #718096;
+ padding: 8px 12px;
+ border-radius: 8px;
+ cursor: pointer;
+ transition: all 0.2s ease;
+ font-size: 14px;
+}
+
+.ldr-document-item .ldr-document-actions button:hover {
+ background: #edf2f7;
+ color: #2d3748;
+}
+
+.ldr-document-item .ldr-document-actions .ldr-btn-delete-doc:hover {
+ background: rgba(220, 53, 69, 0.15);
+ border-color: #dc3545;
+ color: #dc3545;
+}
+
+.ldr-document-item .ldr-document-actions .ldr-btn-remove-from-collection:hover {
+ background: rgba(255, 193, 7, 0.15);
+ border-color: #ffc107;
+ color: #d69e00;
}
.ldr-document-item .ldr-document-title {
@@ -700,6 +741,16 @@
color: #cbd5e0;
}
+ .ldr-document-item .ldr-document-actions button {
+ border-color: #4a5568;
+ color: #a0aec0;
+ }
+
+ .ldr-document-item .ldr-document-actions button:hover {
+ background: #4a5568;
+ color: #f7fafc;
+ }
+
.ldr-progress-bar {
background: #4a5568;
}
diff --git a/src/local_deep_research/web/static/js/collection_details.js b/src/local_deep_research/web/static/js/collection_details.js
index da73aeee11..1e081d83ec 100644
--- a/src/local_deep_research/web/static/js/collection_details.js
+++ b/src/local_deep_research/web/static/js/collection_details.js
@@ -172,25 +172,37 @@ function renderDocuments() {
noDocsMessage.style.display = 'none';
container.innerHTML = filteredDocs.map(doc => `
- <a href="/library/document/${doc.id}" class="ldr-document-item ${doc.indexed ? 'indexed' : 'unindexed'}" style="text-decoration: none; color: inherit; display: block;">
- <div class="document-info">
- <div class="ldr-document-title">
- ${escapeHtml(doc.filename)}
- ${doc.has_pdf ? '<i class="fas fa-file-pdf" style="color: #dc3545; margin-left: 8px;" title="PDF stored"></i>' : ''}
- ${doc.has_text_db ? '<i class="fas fa-file-alt" style="color: #28a745; margin-left: 8px;" title="Text content available"></i>' : ''}
- ${doc.in_other_collections ? `<i class="fas fa-link" style="color: #667eea; margin-left: 8px;" title="In ${doc.other_collections_count + 1} collections"></i>` : ''}
- </div>
- <div class="ldr-document-meta">
- ${doc.file_size ? `Size: ${formatBytes(doc.file_size)} • ` : ''}
- ${doc.source_type && doc.source_type !== 'unknown' ? `<span class="badge badge-info">${doc.source_type.replace('_', ' ')}</span> • ` : ''}
- ${doc.indexed ?
- `<span class="badge badge-success">Indexed (${doc.chunk_count} chunks)</span>` :
- '<span class="badge badge-warning">Not indexed</span>'
- }
- ${doc.last_indexed_at ? ` • Last indexed: ${new Date(doc.last_indexed_at).toLocaleString()}` : ''}
+ <div class="ldr-document-item ${doc.indexed ? 'indexed' : 'unindexed'}">
+ <a href="/library/document/${doc.id}" class="document-link" style="text-decoration: none; color: inherit; display: block; flex: 1;">
+ <div class="ldr-document-info">
+ <div class="ldr-document-title">
+ ${escapeHtml(doc.filename)}
+ ${doc.has_pdf ? '<i class="fas fa-file-pdf" style="color: #dc3545; margin-left: 8px;" title="PDF stored"></i>' : ''}
+ ${doc.has_text_db ? '<i class="fas fa-file-alt" style="color: #28a745; margin-left: 8px;" title="Text content available"></i>' : ''}
+ ${doc.in_other_collections ? `<i class="fas fa-link" style="color: #667eea; margin-left: 8px;" title="In ${doc.other_collections_count + 1} collections"></i>` : ''}
+ </div>
+ <div class="ldr-document-meta">
+ ${doc.file_size ? `Size: ${formatBytes(doc.file_size)} • ` : ''}
+ ${doc.source_type && doc.source_type !== 'unknown' ? `<span class="badge badge-info">${doc.source_type.replace('_', ' ')}</span> • ` : ''}
+ ${doc.indexed ?
+ `<span class="badge badge-success">Indexed (${doc.chunk_count} chunks)</span>` :
+ '<span class="badge badge-warning">Not indexed</span>'
+ }
+ ${doc.last_indexed_at ? ` • Last indexed: ${new Date(doc.last_indexed_at).toLocaleString()}` : ''}
+ </div>
</div>
+ </a>
+ <div class="ldr-document-actions">
+ <button class="ldr-btn-remove-from-collection" onclick="event.stopPropagation(); removeDocumentFromCollection('${doc.id}')"
+ title="Remove from collection. ${doc.in_other_collections ? 'Document exists in other collections.' : 'Document will be deleted (not in other collections).'}">
+ <i class="fas fa-unlink"></i>
+ </button>
+ <button class="ldr-btn-delete-doc" onclick="event.stopPropagation(); deleteDocumentCompletely('${doc.id}')"
+ title="Permanently delete this document, including PDF and text content. This cannot be undone.">
+ <i class="fas fa-trash"></i>
+ </button>
</div>
- </a>
+ </div>
`).join('');
}
@@ -380,3 +392,83 @@ function showSuccess(message) {
function showError(message) {
alert('Error: ' + message);
}
+
+/**
+ * Remove document from this collection
+ * If not in other collections, the document will be deleted
+ */
+async function removeDocumentFromCollection(documentId) {
+ // Check if DeleteManager is available
+ if (typeof DeleteManager !== 'undefined' && DeleteManager.removeFromCollection) {
+ DeleteManager.removeFromCollection(documentId, COLLECTION_ID, {
+ onSuccess: () => loadCollectionDetails()
+ });
+ } else {
+ // Fallback to simple confirm
+ if (!confirm('Remove this document from the collection? If not in other collections, it will be deleted.')) {
+ return;
+ }
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
+ const response = await fetch(`/library/api/collection/${COLLECTION_ID}/document/${documentId}`, {
+ method: 'DELETE',
+ headers: {
+ 'X-CSRFToken': csrfToken
+ }
+ });
+
+ const data = await response.json();
+ if (data.success) {
+ const message = data.document_deleted
+ ? 'Document removed and deleted (not in other collections)'
+ : 'Document removed from collection';
+ showSuccess(message);
+ loadCollectionDetails();
+ } else {
+ showError('Failed to remove document: ' + data.error);
+ }
+ } catch (error) {
+ console.error('Error removing document:', error);
+ showError('Failed to remove document');
+ }
+ }
+}
+
+/**
+ * Delete document completely (from all collections)
+ */
+async function deleteDocumentCompletely(documentId) {
+ // Check if DeleteManager is available
+ if (typeof DeleteManager !== 'undefined' && DeleteManager.deleteDocument) {
+ DeleteManager.deleteDocument(documentId, {
+ onSuccess: () => loadCollectionDetails()
+ });
+ } else {
+ // Fallback to simple confirm
+ if (!confirm('Permanently delete this document? This cannot be undone.')) {
+ return;
+ }
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
+ const response = await fetch(`/library/api/document/${documentId}`, {
+ method: 'DELETE',
+ headers: {
+ 'X-CSRFToken': csrfToken
+ }
+ });
+
+ const data = await response.json();
+ if (data.success) {
+ showSuccess('Document deleted successfully');
+ loadCollectionDetails();
+ } else {
+ showError('Failed to delete document: ' + data.error);
+ }
+ } catch (error) {
+ console.error('Error deleting document:', error);
+ showError('Failed to delete document');
+ }
+ }
+}
diff --git a/src/local_deep_research/web/static/js/deletion/confirmation_modal.js b/src/local_deep_research/web/static/js/deletion/confirmation_modal.js
new file mode 100644
index 0000000000..549fd6a663
--- /dev/null
+++ b/src/local_deep_research/web/static/js/deletion/confirmation_modal.js
@@ -0,0 +1,271 @@
+/**
+ * Delete Confirmation Modal Handler
+ *
+ * Provides a consistent interface for showing delete confirmation dialogs.
+ * Respects the user's "confirm_deletions" setting.
+ *
+ * Note: This module does not handle external URLs - only UI interactions.
+ * URLValidator is not needed here as no URL assignments occur.
+ */
+
+// Store the current confirmation callback
+let currentConfirmCallback = null;
+let currentCancelCallback = null;
+
+/**
+ * Delete action configurations with tooltips
+ */
+const DELETE_ACTIONS = {
+ deleteDocument: {
+ tooltip: "Permanently delete this document, including PDF and text content. This cannot be undone.",
+ title: "Delete Document?",
+ message: "This will permanently delete the document and all associated data.",
+ buttonText: "Delete Document",
+ dangerous: true
+ },
+ deleteBlob: {
+ tooltip: "Remove the PDF file to save space. Text content will be preserved for searching.",
+ title: "Remove PDF?",
+ message: "The PDF will be deleted but extracted text remains searchable.",
+ buttonText: "Remove PDF",
+ dangerous: false
+ },
+ removeFromCollection: {
+ tooltip: "Remove from this collection. If not in any other collection, the document will be deleted.",
+ title: "Remove from Collection?",
+ message: "Document will be removed from this collection.",
+ buttonText: "Remove",
+ dangerous: false
+ },
+ deleteCollection: {
+ tooltip: "Delete this collection. Documents will remain in the library but will be unlinked from this collection.",
+ title: "Delete Collection?",
+ message: "All documents will be unlinked. RAG index will be deleted.",
+ buttonText: "Delete Collection",
+ dangerous: true
+ },
+ bulkDeleteDocuments: {
+ tooltip: "Permanently delete all selected documents and their associated data.",
+ title: "Delete Selected Documents?",
+ message: "This will permanently delete all selected documents.",
+ buttonText: "Delete All",
+ dangerous: true
+ },
+ bulkDeleteBlobs: {
+ tooltip: "Remove PDF files from selected documents to free up database space. Text content is preserved.",
+ title: "Remove PDFs from Selected?",
+ message: "PDF files will be removed from selected documents. Text content is preserved.",
+ buttonText: "Remove PDFs",
+ dangerous: false
+ }
+};
+
+/**
+ * Initialize the confirmation modal
+ */
+function initDeleteConfirmModal() {
+ const modal = document.getElementById('deleteConfirmModal');
+ if (!modal) {
+ console.warn('Delete confirmation modal not found in DOM');
+ return;
+ }
+
+ // Set up confirm button handler
+ const confirmBtn = document.getElementById('deleteConfirmBtn');
+ if (confirmBtn) {
+ confirmBtn.addEventListener('click', function() {
+ if (currentConfirmCallback) {
+ currentConfirmCallback();
+ }
+ hideDeleteModal();
+ });
+ }
+
+ // Set up cancel handlers
+ modal.addEventListener('hidden.bs.modal', function() {
+ if (currentCancelCallback) {
+ currentCancelCallback();
+ }
+ currentConfirmCallback = null;
+ currentCancelCallback = null;
+ });
+}
+
+/**
+ * Show the delete confirmation modal
+ *
+ * @param {Object} options - Configuration options
+ * @param {string} options.action - The action type (e.g., 'deleteDocument')
+ * @param {string} options.title - Custom title (overrides action default)
+ * @param {string} options.message - Custom message (overrides action default)
+ * @param {Array<string>} options.details - List of items that will be deleted
+ * @param {string} options.warning - Custom warning message
+ * @param {string} options.buttonText - Custom button text
+ * @param {Function} options.onConfirm - Callback when confirmed
+ * @param {Function} options.onCancel - Callback when cancelled
+ * @returns {Promise<boolean>} - Resolves to true if confirmed, false if cancelled
+ */
+function showDeleteConfirmation(options) {
+ return new Promise((resolve) => {
+ const actionConfig = DELETE_ACTIONS[options.action] || {};
+
+ // Set modal content
+ const titleEl = document.getElementById('deleteModalTitle');
+ const messageEl = document.getElementById('deleteModalMessage');
+ const detailsEl = document.getElementById('deleteModalDetails');
+ const detailsListEl = document.getElementById('deleteDetailsList');
+ const warningEl = document.getElementById('deleteModalWarning');
+ const warningTextEl = document.getElementById('deleteWarningText');
+ const confirmBtnTextEl = document.getElementById('deleteConfirmBtnText');
+
+ // Set title
+ if (titleEl) {
+ titleEl.textContent = options.title || actionConfig.title || 'Confirm Delete';
+ }
+
+ // Set message
+ if (messageEl) {
+ messageEl.textContent = options.message || actionConfig.message || 'Are you sure you want to delete this item?';
+ }
+
+ // Set details
+ if (detailsEl && detailsListEl) {
+ if (options.details && options.details.length > 0) {
+ detailsListEl.innerHTML = options.details.map(d => `<li>${escapeHtml(d)}</li>`).join('');
+ detailsEl.style.display = 'block';
+ } else {
+ detailsEl.style.display = 'none';
+ }
+ }
+
+ // Set warning
+ if (warningEl && warningTextEl) {
+ const showWarning = options.warning || actionConfig.dangerous;
+ if (showWarning) {
+ warningTextEl.textContent = options.warning || 'This action cannot be undone.';
+ warningEl.style.display = 'block';
+ } else {
+ warningEl.style.display = 'none';
+ }
+ }
+
+ // Set button text
+ if (confirmBtnTextEl) {
+ confirmBtnTextEl.textContent = options.buttonText || actionConfig.buttonText || 'Delete';
+ }
+
+ // Set callbacks
+ currentConfirmCallback = () => {
+ if (options.onConfirm) options.onConfirm();
+ resolve(true);
+ };
+ currentCancelCallback = () => {
+ if (options.onCancel) options.onCancel();
+ resolve(false);
+ };
+
+ // Show modal
+ const modal = document.getElementById('deleteConfirmModal');
+ if (modal) {
+ const bsModal = new bootstrap.Modal(modal);
+ bsModal.show();
+ } else {
+ // Fallback to native confirm
+ const confirmed = confirm(
+ (options.title || actionConfig.title || 'Confirm Delete') + '\n\n' +
+ (options.message || actionConfig.message || 'Are you sure?')
+ );
+ if (confirmed) {
+ if (options.onConfirm) options.onConfirm();
+ resolve(true);
+ } else {
+ if (options.onCancel) options.onCancel();
+ resolve(false);
+ }
+ }
+ });
+}
+
+/**
+ * Hide the delete confirmation modal
+ */
+function hideDeleteModal() {
+ const modal = document.getElementById('deleteConfirmModal');
+ if (modal) {
+ const bsModal = bootstrap.Modal.getInstance(modal);
+ if (bsModal) {
+ bsModal.hide();
+ }
+ }
+}
+
+/**
+ * Escape HTML to prevent XSS
+ */
+function escapeHtml(text) {
+ const div = document.createElement('div');
+ div.textContent = text;
+ return div.innerHTML;
+}
+
+/**
+ * Get tooltip text for an action
+ *
+ * @param {string} action - The action type
+ * @returns {string} - Tooltip text
+ */
+function getDeleteTooltip(action) {
+ const config = DELETE_ACTIONS[action];
+ return config ? config.tooltip : 'Delete this item';
+}
+
+/**
+ * Check if confirmations are enabled
+ *
+ * @returns {Promise<boolean>} - True if confirmations are enabled
+ */
+async function areConfirmationsEnabled() {
+ try {
+ const response = await fetch('/api/v1/settings/research_library.confirm_deletions');
+ if (response.ok) {
+ const data = await response.json();
+ return data.value !== false;
+ }
+ } catch (e) {
+ console.warn('Could not check confirmation setting:', e);
+ }
+ return true; // Default to showing confirmations
+}
+
+/**
+ * Show confirmation if enabled, otherwise run directly
+ *
+ * @param {Object} options - Options for showDeleteConfirmation
+ * @param {Function} action - The action to perform
+ */
+async function confirmAndRun(options, action) {
+ const confirmationsEnabled = await areConfirmationsEnabled();
+
+ if (confirmationsEnabled) {
+ const confirmed = await showDeleteConfirmation(options);
+ if (confirmed) {
+ action();
+ }
+ } else {
+ action();
+ }
+}
+
+// Initialize when DOM is ready
+document.addEventListener('DOMContentLoaded', initDeleteConfirmModal);
+
+// Export for use in other modules
+if (typeof window !== 'undefined') {
+ window.DeleteConfirmation = {
+ show: showDeleteConfirmation,
+ hide: hideDeleteModal,
+ getTooltip: getDeleteTooltip,
+ confirmAndRun: confirmAndRun,
+ ACTIONS: DELETE_ACTIONS
+ };
+}
diff --git a/src/local_deep_research/web/static/js/deletion/delete_manager.js b/src/local_deep_research/web/static/js/deletion/delete_manager.js
new file mode 100644
index 0000000000..e72580b55f
--- /dev/null
+++ b/src/local_deep_research/web/static/js/deletion/delete_manager.js
@@ -0,0 +1,652 @@
+/**
+ * Delete Manager
+ *
+ * Handles all delete operations for the library:
+ * - Document deletion
+ * - Blob-only deletion
+ * - Collection deletion
+ * - Bulk operations
+ * - Remove from collection
+ *
+ * Note: This module only uses internal API endpoints (no external URLs).
+ * URLValidator is not needed here as all fetch() calls are to internal paths.
+ */
+
+// API Endpoints
+const DELETE_API = {
+ DOCUMENT: '/library/api/document/',
+ DOCUMENT_BLOB: '/library/api/document/{id}/blob',
+ DOCUMENT_PREVIEW: '/library/api/document/{id}/preview',
+ COLLECTION: '/library/api/collections/',
+ COLLECTION_INDEX: '/library/api/collections/{id}/index',
+ COLLECTION_PREVIEW: '/library/api/collections/{id}/preview',
+ COLLECTION_DOCUMENT: '/library/api/collection/{collectionId}/document/{documentId}',
+ BULK_DOCUMENTS: '/library/api/documents/bulk',
+ BULK_BLOBS: '/library/api/documents/blobs',
+ BULK_COLLECTION_DOCUMENTS: '/library/api/collection/{collectionId}/documents/bulk',
+ BULK_PREVIEW: '/library/api/documents/preview'
+};
+
+/**
+ * Get CSRF token from meta tag
+ */
+function getCsrfToken() {
+ const meta = document.querySelector('meta[name="csrf-token"]');
+ return meta ? meta.getAttribute('content') : '';
+}
+
+/**
+ * Make a DELETE request to the API
+ */
+async function deleteRequest(url, body = null) {
+ const options = {
+ method: 'DELETE',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': getCsrfToken()
+ }
+ };
+
+ if (body) {
+ options.body = JSON.stringify(body);
+ }
+
+ const response = await fetch(url, options);
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error(data.error || `Request failed with status ${response.status}`);
+ }
+
+ return data;
+}
+
+/**
+ * Make a GET request to the API
+ */
+async function getRequest(url) {
+ const response = await fetch(url, {
+ method: 'GET',
+ headers: {
+ 'X-CSRFToken': getCsrfToken()
+ }
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error(data.error || `Request failed with status ${response.status}`);
+ }
+
+ return data;
+}
+
+/**
+ * Make a POST request to the API
+ */
+async function postRequest(url, body) {
+ const response = await fetch(url, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': getCsrfToken()
+ },
+ body: JSON.stringify(body)
+ });
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error(data.error || `Request failed with status ${response.status}`);
+ }
+
+ return data;
+}
+
+/**
+ * Format bytes to human readable size
+ */
+function formatBytes(bytes) {
+ if (bytes === 0) return '0 Bytes';
+ const k = 1024;
+ const sizes = ['Bytes', 'KB', 'MB', 'GB'];
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
+}
+
+// =============================================================================
+// Document Operations
+// =============================================================================
+
+/**
+ * Delete a document completely
+ *
+ * @param {string} documentId - The document ID
+ * @param {Object} options - Options
+ * @param {boolean} options.skipConfirm - Skip confirmation dialog
+ * @param {Function} options.onSuccess - Callback on success
+ * @param {Function} options.onError - Callback on error
+ */
+async function deleteDocument(documentId, options = {}) {
+ const confirmOptions = {
+ action: 'deleteDocument',
+ onConfirm: async () => {
+ try {
+ const result = await deleteRequest(DELETE_API.DOCUMENT + documentId);
+
+ if (result.success) {
+ showNotification('success', 'Document deleted successfully');
+
+ if (options.onSuccess) {
+ options.onSuccess(result);
+ }
+ } else {
+ throw new Error(result.error || 'Delete failed');
+ }
+ } catch (error) {
+ console.error('Error deleting document:', error);
+ showNotification('error', 'Failed to delete document: ' + error.message);
+
+ if (options.onError) {
+ options.onError(error);
+ }
+ }
+ }
+ };
+
+ if (options.skipConfirm) {
+ confirmOptions.onConfirm();
+ } else {
+ // Get preview for better confirmation message
+ try {
+ const preview = await getRequest(DELETE_API.DOCUMENT_PREVIEW.replace('{id}', documentId));
+ if (preview.success) {
+ confirmOptions.title = `Delete "${preview.title}"?`;
+ confirmOptions.details = [];
+ if (preview.has_blob) {
+ confirmOptions.details.push(`PDF file (${formatBytes(preview.blob_size)})`);
+ }
+ if (preview.has_text) {
+ confirmOptions.details.push('Extracted text content');
+ }
+ if (preview.chunks_count > 0) {
+ confirmOptions.details.push(`${preview.chunks_count} RAG index chunks`);
+ }
+ if (preview.collections_count > 0) {
+ confirmOptions.details.push(`Links to ${preview.collections_count} collection(s)`);
+ }
+ }
+ } catch (e) {
+ console.warn('Could not get deletion preview:', e);
+ }
+
+ await window.DeleteConfirmation.confirmAndRun(confirmOptions, confirmOptions.onConfirm);
+ }
+}
+
+/**
+ * Delete only the PDF blob, keeping text content
+ *
+ * @param {string} documentId - The document ID
+ * @param {Object} options - Options
+ */
+async function deleteDocumentBlob(documentId, options = {}) {
+ const confirmOptions = {
+ action: 'deleteBlob',
+ onConfirm: async () => {
+ try {
+ const result = await deleteRequest(
+ DELETE_API.DOCUMENT_BLOB.replace('{id}', documentId)
+ );
+
+ if (result.success) {
+ showNotification('success', `PDF removed (${formatBytes(result.bytes_freed)} freed)`);
+
+ if (options.onSuccess) {
+ options.onSuccess(result);
+ }
+ } else {
+ throw new Error(result.error || 'Delete failed');
+ }
+ } catch (error) {
+ console.error('Error deleting blob:', error);
+ showNotification('error', 'Failed to remove PDF: ' + error.message);
+
+ if (options.onError) {
+ options.onError(error);
+ }
+ }
+ }
+ };
+
+ if (options.skipConfirm) {
+ confirmOptions.onConfirm();
+ } else {
+ await window.DeleteConfirmation.confirmAndRun(confirmOptions, confirmOptions.onConfirm);
+ }
+}
+
+/**
+ * Remove document from a collection
+ *
+ * @param {string} documentId - The document ID
+ * @param {string} collectionId - The collection ID
+ * @param {Object} options - Options
+ */
+async function removeFromCollection(documentId, collectionId, options = {}) {
+ const confirmOptions = {
+ action: 'removeFromCollection',
+ message: 'Document will be removed from this collection. If it\'s not in any other collection, it will be permanently deleted.',
+ onConfirm: async () => {
+ try {
+ const url = DELETE_API.COLLECTION_DOCUMENT
+ .replace('{collectionId}', collectionId)
+ .replace('{documentId}', documentId);
+
+ const result = await deleteRequest(url);
+
+ if (result.success) {
+ const message = result.document_deleted
+ ? 'Document removed and deleted (not in other collections)'
+ : 'Document removed from collection';
+ showNotification('success', message);
+
+ if (options.onSuccess) {
+ options.onSuccess(result);
+ }
+ } else {
+ throw new Error(result.error || 'Remove failed');
+ }
+ } catch (error) {
+ console.error('Error removing from collection:', error);
+ showNotification('error', 'Failed to remove: ' + error.message);
+
+ if (options.onError) {
+ options.onError(error);
+ }
+ }
+ }
+ };
+
+ if (options.skipConfirm) {
+ confirmOptions.onConfirm();
+ } else {
+ await window.DeleteConfirmation.confirmAndRun(confirmOptions, confirmOptions.onConfirm);
+ }
+}
+
+// =============================================================================
+// Collection Operations
+// =============================================================================
+
+/**
+ * Delete a collection
+ *
+ * @param {string} collectionId - The collection ID
+ * @param {Object} options - Options
+ */
+async function deleteCollection(collectionId, options = {}) {
+ const confirmOptions = {
+ action: 'deleteCollection',
+ onConfirm: async () => {
+ try {
+ const result = await deleteRequest(DELETE_API.COLLECTION + collectionId);
+
+ if (result.success) {
+ showNotification('success',
+ `Collection deleted (${result.documents_unlinked} documents unlinked, ${result.chunks_deleted} chunks removed)`
+ );
+
+ if (options.onSuccess) {
+ options.onSuccess(result);
+ }
+ } else {
+ throw new Error(result.error || 'Delete failed');
+ }
+ } catch (error) {
+ console.error('Error deleting collection:', error);
+ showNotification('error', 'Failed to delete collection: ' + error.message);
+
+ if (options.onError) {
+ options.onError(error);
+ }
+ }
+ }
+ };
+
+ if (options.skipConfirm) {
+ confirmOptions.onConfirm();
+ } else {
+ // Get preview for better confirmation message
+ try {
+ const preview = await getRequest(
+ DELETE_API.COLLECTION_PREVIEW.replace('{id}', collectionId)
+ );
+ if (preview.success) {
+ confirmOptions.title = `Delete "${preview.name}"?`;
+ confirmOptions.details = [];
+ if (preview.documents_count > 0) {
+ confirmOptions.details.push(`${preview.documents_count} document(s) will be unlinked`);
+ }
+ if (preview.chunks_count > 0) {
+ confirmOptions.details.push(`${preview.chunks_count} RAG index chunks`);
+ }
+ if (preview.folders_count > 0) {
+ confirmOptions.details.push(`${preview.folders_count} linked folder(s)`);
+ }
+ }
+ } catch (e) {
+ console.warn('Could not get deletion preview:', e);
+ }
+
+ await window.DeleteConfirmation.confirmAndRun(confirmOptions, confirmOptions.onConfirm);
+ }
+}
+
+/**
+ * Delete only the RAG index for a collection
+ *
+ * @param {string} collectionId - The collection ID
+ * @param {Object} options - Options
+ */
+async function deleteCollectionIndex(collectionId, options = {}) {
+ const confirmOptions = {
+ action: 'deleteCollection',
+ title: 'Delete RAG Index?',
+ message: 'This will delete the RAG index for this collection. You can rebuild it later.',
+ buttonText: 'Delete Index',
+ onConfirm: async () => {
+ try {
+ const result = await deleteRequest(
+ DELETE_API.COLLECTION_INDEX.replace('{id}', collectionId)
+ );
+
+ if (result.success) {
+ showNotification('success',
+ `Index deleted (${result.chunks_deleted} chunks removed)`
+ );
+
+ if (options.onSuccess) {
+ options.onSuccess(result);
+ }
+ } else {
+ throw new Error(result.error || 'Delete failed');
+ }
+ } catch (error) {
+ console.error('Error deleting index:', error);
+ showNotification('error', 'Failed to delete index: ' + error.message);
+
+ if (options.onError) {
+ options.onError(error);
+ }
+ }
+ }
+ };
+
+ if (options.skipConfirm) {
+ confirmOptions.onConfirm();
+ } else {
+ await window.DeleteConfirmation.confirmAndRun(confirmOptions, confirmOptions.onConfirm);
+ }
+}
+
+// =============================================================================
+// Bulk Operations
+// =============================================================================
+
+/**
+ * Delete multiple documents
+ *
+ * @param {Array<string>} documentIds - Array of document IDs
+ * @param {Object} options - Options
+ */
+async function bulkDeleteDocuments(documentIds, options = {}) {
+ const confirmOptions = {
+ action: 'bulkDeleteDocuments',
+ title: `Delete ${documentIds.length} Documents?`,
+ message: `This will permanently delete ${documentIds.length} document(s) and all associated data.`,
+ onConfirm: async () => {
+ try {
+ const result = await deleteRequest(DELETE_API.BULK_DOCUMENTS, {
+ document_ids: documentIds
+ });
+
+ if (result.success) {
+ showNotification('success',
+ `Deleted ${result.deleted}/${result.total} documents (${formatBytes(result.total_bytes_freed)} freed)`
+ );
+
+ if (options.onSuccess) {
+ options.onSuccess(result);
+ }
+ } else {
+ throw new Error(result.error || 'Bulk delete failed');
+ }
+ } catch (error) {
+ console.error('Error in bulk delete:', error);
+ showNotification('error', 'Bulk delete failed: ' + error.message);
+
+ if (options.onError) {
+ options.onError(error);
+ }
+ }
+ }
+ };
+
+ if (options.skipConfirm) {
+ confirmOptions.onConfirm();
+ } else {
+ // Get preview for better confirmation message
+ try {
+ const preview = await postRequest(DELETE_API.BULK_PREVIEW, {
+ document_ids: documentIds,
+ operation: 'delete'
+ });
+ if (preview.success) {
+ confirmOptions.details = [];
+ if (preview.documents_with_blobs > 0) {
+ confirmOptions.details.push(`${preview.documents_with_blobs} PDF file(s) (${formatBytes(preview.total_blob_size)})`);
+ }
+ if (preview.total_chunks > 0) {
+ confirmOptions.details.push(`${preview.total_chunks} RAG index chunks`);
+ }
+ }
+ } catch (e) {
+ console.warn('Could not get bulk preview:', e);
+ }
+
+ await window.DeleteConfirmation.confirmAndRun(confirmOptions, confirmOptions.onConfirm);
+ }
+}
+
+/**
+ * Delete blobs for multiple documents
+ *
+ * @param {Array<string>} documentIds - Array of document IDs
+ * @param {Object} options - Options
+ */
+async function bulkDeleteBlobs(documentIds, options = {}) {
+ const confirmOptions = {
+ action: 'bulkDeleteBlobs',
+ title: `Remove PDFs from ${documentIds.length} Documents?`,
+ message: 'PDF files will be removed but text content is preserved for searching.',
+ onConfirm: async () => {
+ try {
+ const result = await deleteRequest(DELETE_API.BULK_BLOBS, {
+ document_ids: documentIds
+ });
+
+ if (result.success) {
+ showNotification('success',
+ `Removed ${result.deleted} PDF(s) (${formatBytes(result.total_bytes_freed)} freed)`
+ );
+
+ if (options.onSuccess) {
+ options.onSuccess(result);
+ }
+ } else {
+ throw new Error(result.error || 'Bulk blob delete failed');
+ }
+ } catch (error) {
+ console.error('Error in bulk blob delete:', error);
+ showNotification('error', 'Failed to remove PDFs: ' + error.message);
+
+ if (options.onError) {
+ options.onError(error);
+ }
+ }
+ }
+ };
+
+ if (options.skipConfirm) {
+ confirmOptions.onConfirm();
+ } else {
+ // Get preview
+ try {
+ const preview = await postRequest(DELETE_API.BULK_PREVIEW, {
+ document_ids: documentIds,
+ operation: 'delete_blobs'
+ });
+ if (preview.success && preview.documents_with_blobs > 0) {
+ confirmOptions.details = [
+ `${preview.documents_with_blobs} PDF file(s)`,
+ `${formatBytes(preview.total_blob_size)} will be freed`
+ ];
+ }
+ } catch (e) {
+ console.warn('Could not get bulk preview:', e);
+ }
+
+ await window.DeleteConfirmation.confirmAndRun(confirmOptions, confirmOptions.onConfirm);
+ }
+}
+
+/**
+ * Remove multiple documents from a collection
+ *
+ * @param {Array<string>} documentIds - Array of document IDs
+ * @param {string} collectionId - The collection ID
+ * @param {Object} options - Options
+ */
+async function bulkRemoveFromCollection(documentIds, collectionId, options = {}) {
+ const confirmOptions = {
+ action: 'removeFromCollection',
+ title: `Remove ${documentIds.length} Documents?`,
+ message: 'Documents will be removed from this collection. Documents not in other collections will be deleted.',
+ onConfirm: async () => {
+ try {
+ const url = DELETE_API.BULK_COLLECTION_DOCUMENTS.replace('{collectionId}', collectionId);
+ const result = await deleteRequest(url, {
+ document_ids: documentIds
+ });
+
+ if (result.success) {
+ const message = result.deleted > 0
+ ? `Removed ${result.unlinked} (${result.deleted} deleted, not in other collections)`
+ : `Removed ${result.unlinked} document(s) from collection`;
+ showNotification('success', message);
+
+ if (options.onSuccess) {
+ options.onSuccess(result);
+ }
+ } else {
+ throw new Error(result.error || 'Bulk remove failed');
+ }
+ } catch (error) {
+ console.error('Error in bulk remove:', error);
+ showNotification('error', 'Failed to remove documents: ' + error.message);
+
+ if (options.onError) {
+ options.onError(error);
+ }
+ }
+ }
+ };
+
+ if (options.skipConfirm) {
+ confirmOptions.onConfirm();
+ } else {
+ await window.DeleteConfirmation.confirmAndRun(confirmOptions, confirmOptions.onConfirm);
+ }
+}
+
+// =============================================================================
+// Notification Helper
+// =============================================================================
+
+/**
+ * Show a notification message
+ *
+ * @param {string} type - 'success', 'error', 'warning', 'info'
+ * @param {string} message - The message to display
+ */
+function showNotification(type, message) {
+ // Check if there's a global notification function
+ if (typeof window.showToast === 'function') {
+ window.showToast(message, type);
+ return;
+ }
+
+ // Check for Bootstrap toast
+ if (typeof bootstrap !== 'undefined' && typeof bootstrap.Toast !== 'undefined') {
+ // Create toast element
+ const toastContainer = document.querySelector('.ldr-toast-container') ||
+ createToastContainer();
+
+ const toastEl = document.createElement('div');
+ toastEl.className = `toast align-items-center text-white bg-${type === 'error' ? 'danger' : type}`;
+ toastEl.setAttribute('role', 'alert');
+ toastEl.innerHTML = `
+ <div class="d-flex">
+ <div class="toast-body">${message}</div>
+ <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
+ </div>
+ `;
+
+ toastContainer.appendChild(toastEl);
+ const toast = new bootstrap.Toast(toastEl, { delay: 5000 });
+ toast.show();
+
+ toastEl.addEventListener('hidden.bs.toast', () => toastEl.remove());
+ return;
+ }
+
+ // Fallback to console
+ console.log(`[${type.toUpperCase()}] ${message}`);
+}
+
+/**
+ * Create toast container if not exists
+ */
+function createToastContainer() {
+ const container = document.createElement('div');
+ container.className = 'ldr-toast-container position-fixed bottom-0 end-0 p-3';
+ container.style.zIndex = '11000';
+ document.body.appendChild(container);
+ return container;
+}
+
+// =============================================================================
+// Export
+// =============================================================================
+
+// Export for use in other modules
+if (typeof window !== 'undefined') {
+ window.DeleteManager = {
+ // Document operations
+ deleteDocument,
+ deleteDocumentBlob,
+ removeFromCollection,
+
+ // Collection operations
+ deleteCollection,
+ deleteCollectionIndex,
+
+ // Bulk operations
+ bulkDeleteDocuments,
+ bulkDeleteBlobs,
+ bulkRemoveFromCollection,
+
+ // Utilities
+ formatBytes,
+ showNotification
+ };
+}
diff --git a/src/local_deep_research/web/templates/components/delete_confirmation_modal.html b/src/local_deep_research/web/templates/components/delete_confirmation_modal.html
new file mode 100644
index 0000000000..fa4cee854e
--- /dev/null
+++ b/src/local_deep_research/web/templates/components/delete_confirmation_modal.html
@@ -0,0 +1,66 @@
+<!-- Delete Confirmation Modal -->
+<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-labelledby="deleteConfirmModalLabel" aria-hidden="true" style="z-index: 10000;">
+ <div class="modal-dialog">
+ <div class="modal-content">
+ <div class="modal-header bg-danger text-white">
+ <h5 class="modal-title" id="deleteConfirmModalLabel">
+ <i class="fas fa-exclamation-triangle me-2"></i>
+ <span id="deleteModalTitle">Confirm Delete</span>
+ </h5>
+ <button type="button" class="btn-close ldr-btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
+ </div>
+ <div class="modal-body">
+ <p id="deleteModalMessage" class="mb-3">Are you sure you want to delete this item?</p>
+
+ <!-- Dynamic details section -->
+ <div id="deleteModalDetails" class="alert alert-warning" style="display: none;">
+ <strong>This will delete:</strong>
+ <ul id="deleteDetailsList" class="mb-0 mt-2"></ul>
+ </div>
+
+ <!-- Warning section for dangerous operations -->
+ <div id="deleteModalWarning" class="alert alert-danger" style="display: none;">
+ <i class="fas fa-exclamation-circle me-2"></i>
+ <span id="deleteWarningText">This action cannot be undone.</span>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
+ <i class="fas fa-times me-1"></i> Cancel
+ </button>
+ <button type="button" class="btn btn-danger" id="deleteConfirmBtn">
+ <i class="fas fa-trash me-1"></i> <span id="deleteConfirmBtnText">Delete</span>
+ </button>
+ </div>
+ </div>
+ </div>
+</div>
+
+<style>
+/* Delete confirmation modal specific styles */
+#deleteConfirmModal .modal-header.bg-danger {
+ background: linear-gradient(135deg, #dc3545 0%, #c82333 100%) !important;
+}
+
+#deleteConfirmModal .ldr-btn-close-white {
+ filter: brightness(0) invert(1);
+}
+
+#deleteModalDetails ul {
+ padding-left: 1.5rem;
+}
+
+#deleteModalDetails li {
+ margin-bottom: 0.25rem;
+}
+
+/* Animation for the delete button on hover */
+#deleteConfirmBtn:hover {
+ transform: scale(1.02);
+ box-shadow: 0 2px 8px rgba(220, 53, 69, 0.4);
+}
+
+#deleteConfirmBtn {
+ transition: all 0.2s ease;
+}
+</style>
diff --git a/src/local_deep_research/web/templates/pages/collection_details.html b/src/local_deep_research/web/templates/pages/collection_details.html
index 4c6fe63626..7d1f939d9a 100644
--- a/src/local_deep_research/web/templates/pages/collection_details.html
+++ b/src/local_deep_research/web/templates/pages/collection_details.html
@@ -183,9 +183,14 @@
</div>
</div>
+<!-- Delete Confirmation Modal -->
+{% include "components/delete_confirmation_modal.html" %}
+
<!-- Pass collection_id to JavaScript -->
<script>
const COLLECTION_ID = "{{ collection_id }}";
</script>
+<script src="/static/js/deletion/confirmation_modal.js"></script>
+<script src="/static/js/deletion/delete_manager.js"></script>
<script src="/static/js/collection_details.js"></script>
{% endblock %}
diff --git a/src/local_deep_research/web/templates/pages/library.html b/src/local_deep_research/web/templates/pages/library.html
index d98d3c7c45..3f24601c08 100644
--- a/src/local_deep_research/web/templates/pages/library.html
+++ b/src/local_deep_research/web/templates/pages/library.html
@@ -246,6 +246,18 @@
{% endif %}
<span class="tag">{{ doc.domain|truncate(20) }}</span>
</div>
+ <div class="doc-actions" onclick="event.stopPropagation()">
+ {% if doc.has_pdf %}
+ <button class="btn-delete-blob" onclick="DeleteManager.deleteDocumentBlob('{{ doc.id }}', {onSuccess: () => location.reload()})"
+ title="Remove PDF only (keep text). Text content will be preserved for searching.">
+ <i class="fas fa-file-pdf"></i><i class="fas fa-times" style="font-size: 0.6em; margin-left: -2px;"></i>
+ </button>
+ {% endif %}
+ <button class="btn-delete-doc" onclick="DeleteManager.deleteDocument('{{ doc.id }}', {onSuccess: () => location.reload()})"
+ title="Permanently delete this document, including PDF and text content. This cannot be undone.">
+ <i class="fas fa-trash"></i>
+ </button>
+ </div>
</div>
</div>
{% endfor %}
@@ -806,6 +818,9 @@
padding: 10px 15px;
background: var(--bg-secondary, #1a1a1a);
border-top: 1px solid var(--border-color, #333);
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
}
.doc-tags {
@@ -814,6 +829,39 @@
flex-wrap: wrap;
}
+.doc-actions {
+ display: flex;
+ gap: 8px;
+}
+
+.doc-actions button {
+ background: transparent;
+ border: 1px solid var(--border-color, #444);
+ color: var(--text-secondary, #999);
+ padding: 4px 8px;
+ border-radius: 4px;
+ cursor: pointer;
+ transition: all 0.2s ease;
+ font-size: 12px;
+}
+
+.doc-actions button:hover {
+ background: var(--bg-tertiary, #333);
+ color: var(--text-primary, #e4e4e4);
+}
+
+.doc-actions .btn-delete-doc:hover {
+ background: rgba(220, 53, 69, 0.2);
+ border-color: #dc3545;
+ color: #dc3545;
+}
+
+.doc-actions .btn-delete-blob:hover {
+ background: rgba(255, 193, 7, 0.2);
+ border-color: #ffc107;
+ color: #ffc107;
+}
+
.tag {
padding: 2px 8px;
background: var(--bg-tertiary, #333);
@@ -1770,4 +1818,11 @@ document.querySelectorAll('.view-toggle button').forEach(btn => {
});
});
</script>
+
+<!-- Delete Confirmation Modal -->
+{% include "components/delete_confirmation_modal.html" %}
+
+<!-- Deletion JS Module -->
+<script src="/static/js/deletion/confirmation_modal.js"></script>
+<script src="/static/js/deletion/delete_manager.js"></script>
{% endblock %}
diff --git a/tests/deletion/__init__.py b/tests/deletion/__init__.py
new file mode 100644
index 0000000000..2fe852224b
--- /dev/null
+++ b/tests/deletion/__init__.py
@@ -0,0 +1 @@
+"""Tests for the deletion module."""
diff --git a/tests/deletion/test_cascade_integration.py b/tests/deletion/test_cascade_integration.py
new file mode 100644
index 0000000000..db4dce0ef0
--- /dev/null
+++ b/tests/deletion/test_cascade_integration.py
@@ -0,0 +1,535 @@
+"""
+Integration tests for delete cascade behavior.
+
+Tests end-to-end deletion scenarios verifying proper cleanup
+of all related records across the database.
+"""
+
+import pytest
+import uuid
+
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models.library import (
+ Document,
+ DocumentBlob,
+ DocumentChunk,
+ DocumentCollection,
+ Collection,
+ CollectionFolder,
+ SourceType,
+ RAGIndex,
+ EmbeddingProvider,
+)
+from local_deep_research.database.models.base import Base
+
+
+def test_engine():
+ """Create an in-memory SQLite database for testing."""
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ return engine
+
+
+def test_session(test_engine):
+ """Create a session for testing."""
+ Session = sessionmaker(bind=test_engine)
+ session = Session()
+ yield session
+ session.close()
+
+
+def source_type(test_session):
+ """Create a source type for testing."""
+ st = SourceType(
+ id=str(uuid.uuid4()),
+ name="user_upload",
+ display_name="User Upload",
+ )
+ test_session.add(st)
+ test_session.commit()
+ return st
+
+
+def create_full_document(
+ session, source_type, collection, with_blob=True, with_chunks=True
+):
+ """
+ Create a document with all related records:
+ - DocumentBlob (optional)
+ - DocumentCollection link
+ - DocumentChunks (optional)
+ - RagDocumentStatus
+ """
+ doc_id = str(uuid.uuid4())
+ collection_name = f"collection_{collection.id}"
+
+ # Create document
+ doc = Document(
+ id=doc_id,
+ source_type_id=source_type.id,
+ document_hash=f"hash_{doc_id[:8]}",
+ file_size=1024,
+ file_type="pdf",
+ title=f"Document {doc_id[:8]}",
+ filename=f"doc_{doc_id[:8]}.pdf",
+ storage_mode="database" if with_blob else "none",
+ text_content="Test document content for full cascade test.",
+ )
+ session.add(doc)
+ session.flush()
+
+ # Create blob
+ if with_blob:
+ blob = DocumentBlob(
+ document_id=doc_id,
+ pdf_binary=b"PDF content " * 100,
+ blob_hash=f"blob_hash_{doc_id[:8]}",
+ )
+ session.add(blob)
+
+ # Create collection link
+ doc_collection = DocumentCollection(
+ document_id=doc_id,
+ collection_id=collection.id,
+ indexed=with_chunks,
+ chunk_count=3 if with_chunks else 0,
+ )
+ session.add(doc_collection)
+
+ # Create chunks
+ chunks = []
+ if with_chunks:
+ for i in range(3):
+ chunk = DocumentChunk(
+ chunk_hash=f"chunk_{doc_id[:8]}_{i}_{uuid.uuid4().hex[:6]}",
+ source_type="document",
+ source_id=doc_id,
+ collection_name=collection_name,
+ chunk_text=f"Chunk {i} of document {doc_id[:8]}",
+ chunk_index=i,
+ start_char=i * 100,
+ end_char=(i + 1) * 100,
+ word_count=10,
+ embedding_id=str(uuid.uuid4()),
+ embedding_model="all-MiniLM-L6-v2",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ )
+ session.add(chunk)
+ chunks.append(chunk)
+
+ session.commit()
+ return doc, chunks
+
+
+class TestFullDocumentCascade:
+ """
+ Integration tests for complete document deletion cascade.
+
+ Create document with:
+ - DocumentBlob
+ - DocumentCollection (multiple)
+ - DocumentChunk (multiple)
+ - RagDocumentStatus
+
+ Delete document, verify ALL related records cleaned up.
+ """
+
+ def test_document_delete_full_cascade(self, test_session, source_type):
+ """Complete cascade cleanup when deleting a document."""
+ # Create two collections
+ collection1 = Collection(
+ id=str(uuid.uuid4()),
+ name="Collection 1",
+ )
+ collection2 = Collection(
+ id=str(uuid.uuid4()),
+ name="Collection 2",
+ )
+ test_session.add_all([collection1, collection2])
+ test_session.commit()
+
+ # Create document with blob
+ doc_id = str(uuid.uuid4())
+ doc = Document(
+ id=doc_id,
+ source_type_id=source_type.id,
+ document_hash=f"hash_{doc_id[:8]}",
+ file_size=2048,
+ file_type="pdf",
+ title="Full Cascade Test Document",
+ storage_mode="database",
+ text_content="Content for cascade test.",
+ )
+ test_session.add(doc)
+ test_session.flush()
+
+ # Add blob
+ blob = DocumentBlob(
+ document_id=doc_id,
+ pdf_binary=b"PDF content for cascade test" * 50,
+ )
+ test_session.add(blob)
+
+ # Add to both collections
+ for coll in [collection1, collection2]:
+ link = DocumentCollection(
+ document_id=doc_id,
+ collection_id=coll.id,
+ indexed=True,
+ chunk_count=2,
+ )
+ test_session.add(link)
+
+ # Add chunks for both collections
+ for coll in [collection1, collection2]:
+ collection_name = f"collection_{coll.id}"
+ for i in range(2):
+ chunk = DocumentChunk(
+ chunk_hash=f"chunk_{coll.id[:8]}_{i}_{uuid.uuid4().hex[:6]}",
+ source_type="document",
+ source_id=doc_id,
+ collection_name=collection_name,
+ chunk_text=f"Chunk {i} in {coll.name}",
+ chunk_index=i,
+ start_char=i * 50,
+ end_char=(i + 1) * 50,
+ word_count=5,
+ embedding_id=str(uuid.uuid4()),
+ embedding_model="test-model",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ )
+ test_session.add(chunk)
+
+ test_session.commit()
+
+ # Verify everything exists
+ assert test_session.query(Document).get(doc_id) is not None
+ assert (
+ test_session.query(DocumentBlob)
+ .filter_by(document_id=doc_id)
+ .first()
+ is not None
+ )
+ assert (
+ test_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id)
+ .count()
+ == 2
+ )
+ assert (
+ test_session.query(DocumentChunk)
+ .filter_by(source_id=doc_id, source_type="document")
+ .count()
+ == 4
+ )
+
+ # === PERFORM DELETION ===
+ # Step 1: Delete chunks (no FK, manual cleanup required)
+ test_session.query(DocumentChunk).filter(
+ DocumentChunk.source_id == doc_id,
+ DocumentChunk.source_type == "document",
+ ).delete(synchronize_session=False)
+
+ # Step 2: Delete document (CASCADE handles blob and collection links)
+ document = test_session.query(Document).get(doc_id)
+ test_session.delete(document)
+ test_session.commit()
+
+ # === VERIFY COMPLETE CLEANUP ===
+ assert test_session.query(Document).get(doc_id) is None, (
+ "Document deleted"
+ )
+ assert (
+ test_session.query(DocumentBlob)
+ .filter_by(document_id=doc_id)
+ .first()
+ is None
+ ), "Blob deleted (CASCADE)"
+ assert (
+ test_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id)
+ .count()
+ == 0
+ ), "Collection links deleted (CASCADE)"
+ assert (
+ test_session.query(DocumentChunk)
+ .filter_by(source_id=doc_id, source_type="document")
+ .count()
+ == 0
+ ), "Chunks deleted (manual)"
+
+ # Collections should still exist
+ assert test_session.query(Collection).get(collection1.id) is not None
+ assert test_session.query(Collection).get(collection2.id) is not None
+
+
+class TestFullCollectionCascade:
+ """
+ Integration tests for complete collection deletion cascade.
+
+ Create collection with:
+ - Multiple documents
+ - DocumentChunks
+ - CollectionFolder
+ - RAGIndex
+
+ Delete collection, verify cleanup but documents preserved.
+ """
+
+ def test_collection_delete_full_cascade(self, test_session, source_type):
+ """Complete cascade cleanup when deleting a collection."""
+ # Create collection with all features
+ collection = Collection(
+ id=str(uuid.uuid4()),
+ name="Full Featured Collection",
+ embedding_model="all-MiniLM-L6-v2",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=384,
+ )
+ test_session.add(collection)
+ test_session.flush()
+
+ collection_name = f"collection_{collection.id}"
+
+ # Add folder
+ folder = CollectionFolder(
+ collection_id=collection.id,
+ folder_path="/tmp/test_collection_folder",
+ recursive=True,
+ file_count=5,
+ )
+ test_session.add(folder)
+
+ # Add RAG index
+ rag_index = RAGIndex(
+ collection_name=collection_name,
+ embedding_model="all-MiniLM-L6-v2",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=384,
+ index_path=f"/tmp/{collection_name}/index",
+ index_hash=f"index_hash_{collection.id[:8]}",
+ chunk_size=500,
+ chunk_overlap=50,
+ chunk_count=10,
+ total_documents=2,
+ )
+ test_session.add(rag_index)
+
+ # Create documents
+ doc_ids = []
+ for i in range(2):
+ doc_id = str(uuid.uuid4())
+ doc = Document(
+ id=doc_id,
+ source_type_id=source_type.id,
+ document_hash=f"doc_hash_{doc_id[:8]}",
+ file_size=512 * (i + 1),
+ file_type="pdf",
+ title=f"Collection Doc {i + 1}",
+ text_content=f"Content {i + 1}",
+ )
+ test_session.add(doc)
+ test_session.flush()
+
+ link = DocumentCollection(
+ document_id=doc_id,
+ collection_id=collection.id,
+ indexed=True,
+ chunk_count=5,
+ )
+ test_session.add(link)
+
+ # Add chunks
+ for j in range(5):
+ chunk = DocumentChunk(
+ chunk_hash=f"chunk_{doc_id[:6]}_{j}_{uuid.uuid4().hex[:4]}",
+ source_type="document",
+ source_id=doc_id,
+ collection_name=collection_name,
+ chunk_text=f"Chunk {j} of doc {i + 1}",
+ chunk_index=j,
+ start_char=j * 20,
+ end_char=(j + 1) * 20,
+ word_count=3,
+ embedding_id=str(uuid.uuid4()),
+ embedding_model="all-MiniLM-L6-v2",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ )
+ test_session.add(chunk)
+
+ doc_ids.append(doc_id)
+
+ test_session.commit()
+
+ # Verify everything exists
+ assert test_session.query(Collection).get(collection.id) is not None
+ assert (
+ test_session.query(CollectionFolder)
+ .filter_by(collection_id=collection.id)
+ .first()
+ is not None
+ )
+ assert (
+ test_session.query(RAGIndex)
+ .filter_by(collection_name=collection_name)
+ .first()
+ is not None
+ )
+ assert (
+ test_session.query(DocumentCollection)
+ .filter_by(collection_id=collection.id)
+ .count()
+ == 2
+ )
+ assert (
+ test_session.query(DocumentChunk)
+ .filter_by(collection_name=collection_name)
+ .count()
+ == 10
+ )
+
+ # === PERFORM DELETION ===
+ # Step 1: Delete chunks (no FK, manual cleanup)
+ test_session.query(DocumentChunk).filter_by(
+ collection_name=collection_name
+ ).delete(synchronize_session=False)
+
+ # Step 2: Delete RAG index
+ test_session.query(RAGIndex).filter_by(
+ collection_name=collection_name
+ ).delete(synchronize_session=False)
+
+ # Step 3: Delete collection (CASCADE handles folders, links)
+ coll = test_session.query(Collection).get(collection.id)
+ test_session.delete(coll)
+ test_session.commit()
+
+ # === VERIFY CLEANUP ===
+ assert test_session.query(Collection).get(collection.id) is None, (
+ "Collection deleted"
+ )
+ assert (
+ test_session.query(CollectionFolder)
+ .filter_by(collection_id=collection.id)
+ .first()
+ is None
+ ), "Folder deleted (CASCADE)"
+ assert (
+ test_session.query(RAGIndex)
+ .filter_by(collection_name=collection_name)
+ .first()
+ is None
+ ), "RAG index deleted"
+ assert (
+ test_session.query(DocumentCollection)
+ .filter_by(collection_id=collection.id)
+ .count()
+ == 0
+ ), "Links deleted (CASCADE)"
+ assert (
+ test_session.query(DocumentChunk)
+ .filter_by(collection_name=collection_name)
+ .count()
+ == 0
+ ), "Chunks deleted"
+
+ # Documents should still exist!
+ for doc_id in doc_ids:
+ doc = test_session.query(Document).get(doc_id)
+ assert doc is not None, f"Document {doc_id[:8]} preserved"
+
+
+class TestOrphanDetection:
+ """Tests to verify no orphaned records after deletions."""
+
+ def test_no_orphaned_chunks_after_document_delete(
+ self, test_session, source_type
+ ):
+ """Verify no orphaned chunks remain after proper document deletion."""
+ collection = Collection(id=str(uuid.uuid4()), name="Test")
+ test_session.add(collection)
+ test_session.commit()
+
+ doc, chunks = create_full_document(
+ test_session, source_type, collection, with_chunks=True
+ )
+ doc_id = doc.id
+
+ # Proper deletion: chunks first, then document
+ test_session.query(DocumentChunk).filter(
+ DocumentChunk.source_id == doc_id,
+ DocumentChunk.source_type == "document",
+ ).delete(synchronize_session=False)
+
+ test_session.delete(doc)
+ test_session.commit()
+
+ # Check for orphans
+ orphaned_chunks = (
+ test_session.query(DocumentChunk)
+ .filter_by(source_id=doc_id, source_type="document")
+ .all()
+ )
+ assert len(orphaned_chunks) == 0, "No orphaned chunks should exist"
+
+ def test_no_orphaned_blobs_after_document_delete(
+ self, test_session, source_type
+ ):
+ """Verify no orphaned blobs remain after document deletion."""
+ collection = Collection(id=str(uuid.uuid4()), name="Test")
+ test_session.add(collection)
+ test_session.commit()
+
+ doc, _ = create_full_document(
+ test_session,
+ source_type,
+ collection,
+ with_blob=True,
+ with_chunks=False,
+ )
+ doc_id = doc.id
+
+ # Delete document (CASCADE should handle blob)
+ test_session.delete(doc)
+ test_session.commit()
+
+ # Check for orphan blobs
+ orphaned_blob = (
+ test_session.query(DocumentBlob)
+ .filter_by(document_id=doc_id)
+ .first()
+ )
+ assert orphaned_blob is None, "No orphaned blob should exist"
+
+ def test_no_orphaned_links_after_collection_delete(
+ self, test_session, source_type
+ ):
+ """Verify no orphaned DocumentCollection links after collection deletion."""
+ collection = Collection(id=str(uuid.uuid4()), name="Test")
+ test_session.add(collection)
+ test_session.commit()
+
+ doc, _ = create_full_document(
+ test_session, source_type, collection, with_chunks=False
+ )
+ collection_id = collection.id
+
+ # Delete collection
+ test_session.delete(collection)
+ test_session.commit()
+
+ # Check for orphan links
+ orphaned_links = (
+ test_session.query(DocumentCollection)
+ .filter_by(collection_id=collection_id)
+ .all()
+ )
+ assert len(orphaned_links) == 0, "No orphaned links should exist"
+
+ # Document should still exist
+ assert test_session.query(Document).get(doc.id) is not None
diff --git a/tests/deletion/test_collection_deletion.py b/tests/deletion/test_collection_deletion.py
new file mode 100644
index 0000000000..1e8795bd37
--- /dev/null
+++ b/tests/deletion/test_collection_deletion.py
@@ -0,0 +1,367 @@
+"""
+Tests for collection deletion functionality.
+
+Tests the CollectionDeletionService methods:
+- delete_collection
+- delete_collection_index_only
+"""
+
+import pytest
+import uuid
+
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models.library import (
+ Document,
+ DocumentChunk,
+ DocumentCollection,
+ Collection,
+ CollectionFolder,
+ SourceType,
+ RAGIndex,
+ EmbeddingProvider,
+)
+from local_deep_research.database.models.base import Base
+
+
+def test_engine():
+ """Create an in-memory SQLite database for testing."""
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ return engine
+
+
+def test_session(test_engine):
+ """Create a session for testing."""
+ Session = sessionmaker(bind=test_engine)
+ session = Session()
+ yield session
+ session.close()
+
+
+def source_type(test_session):
+ """Create a source type for testing."""
+ st = SourceType(
+ id=str(uuid.uuid4()),
+ name="user_upload",
+ display_name="User Upload",
+ )
+ test_session.add(st)
+ test_session.commit()
+ return st
+
+
+def test_collection(test_session):
+ """Create a test collection with embedding settings."""
+ collection = Collection(
+ id=str(uuid.uuid4()),
+ name="Test Collection",
+ description="A test collection",
+ embedding_model="all-MiniLM-L6-v2",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=384,
+ chunk_size=500,
+ chunk_overlap=50,
+ )
+ test_session.add(collection)
+ test_session.commit()
+ return collection
+
+
+def test_documents(test_session, source_type, test_collection):
+ """Create multiple test documents in a collection."""
+ docs = []
+ for i in range(3):
+ doc_id = str(uuid.uuid4())
+ doc = Document(
+ id=doc_id,
+ source_type_id=source_type.id,
+ document_hash=f"hash_{doc_id[:8]}",
+ file_size=1024 * (i + 1),
+ file_type="pdf",
+ title=f"Test Document {i + 1}",
+ filename=f"test{i + 1}.pdf",
+ text_content=f"Content of document {i + 1}",
+ )
+ test_session.add(doc)
+ test_session.flush()
+
+ # Add to collection
+ doc_collection = DocumentCollection(
+ document_id=doc_id,
+ collection_id=test_collection.id,
+ indexed=True,
+ chunk_count=5,
+ )
+ test_session.add(doc_collection)
+ docs.append(doc)
+
+ test_session.commit()
+ return docs
+
+
+def test_chunks(test_session, test_collection, test_documents):
+ """Create chunks for the test documents."""
+ collection_name = f"collection_{test_collection.id}"
+ chunks = []
+
+ for doc in test_documents:
+ for i in range(2):
+ chunk = DocumentChunk(
+ chunk_hash=f"chunk_{doc.id[:8]}_{i}_{uuid.uuid4().hex[:8]}",
+ source_type="document",
+ source_id=doc.id,
+ collection_name=collection_name,
+ chunk_text=f"Chunk {i} of {doc.title}",
+ chunk_index=i,
+ start_char=i * 100,
+ end_char=(i + 1) * 100,
+ word_count=10,
+ embedding_id=str(uuid.uuid4()),
+ embedding_model="all-MiniLM-L6-v2",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ )
+ test_session.add(chunk)
+ chunks.append(chunk)
+
+ test_session.commit()
+ return chunks
+
+
+def test_rag_index(test_session, test_collection):
+ """Create a RAG index for the collection."""
+ collection_name = f"collection_{test_collection.id}"
+ rag_index = RAGIndex(
+ collection_name=collection_name,
+ embedding_model="all-MiniLM-L6-v2",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=384,
+ index_path=f"/tmp/test_index_{test_collection.id}",
+ index_hash=f"hash_{test_collection.id[:8]}",
+ chunk_size=500,
+ chunk_overlap=50,
+ chunk_count=6,
+ total_documents=3,
+ )
+ test_session.add(rag_index)
+ test_session.commit()
+ return rag_index
+
+
+class TestCollectionDeletion:
+ """Unit tests for collection deletion."""
+
+ def test_delete_collection_preserves_documents(
+ self, test_session, test_collection, test_documents
+ ):
+ """Documents remain after collection deletion."""
+ collection_id = test_collection.id
+ doc_ids = [d.id for d in test_documents]
+
+ # Delete collection
+ collection = test_session.query(Collection).get(collection_id)
+ test_session.delete(collection)
+ test_session.commit()
+
+ # Verify documents still exist
+ for doc_id in doc_ids:
+ doc = test_session.query(Document).get(doc_id)
+ assert doc is not None, f"Document {doc_id[:8]} should still exist"
+
+ def test_delete_collection_removes_links(
+ self, test_session, test_collection, test_documents
+ ):
+ """DocumentCollection links are deleted with collection."""
+ collection_id = test_collection.id
+
+ # Verify links exist
+ links_before = (
+ test_session.query(DocumentCollection)
+ .filter_by(collection_id=collection_id)
+ .count()
+ )
+ assert links_before == 3, "Should have 3 document links"
+
+ # Delete collection
+ collection = test_session.query(Collection).get(collection_id)
+ test_session.delete(collection)
+ test_session.commit()
+
+ # Verify links are deleted (CASCADE)
+ links_after = (
+ test_session.query(DocumentCollection)
+ .filter_by(collection_id=collection_id)
+ .count()
+ )
+ assert links_after == 0, "Document links should be deleted"
+
+ def test_delete_collection_removes_chunks(
+ self, test_session, test_collection, test_documents, test_chunks
+ ):
+ """DocumentChunks for collection are deleted."""
+ collection_id = test_collection.id
+ collection_name = f"collection_{collection_id}"
+
+ # Verify chunks exist
+ chunks_before = (
+ test_session.query(DocumentChunk)
+ .filter_by(collection_name=collection_name)
+ .count()
+ )
+ assert chunks_before == 6, "Should have 6 chunks (2 per document)"
+
+ # Manually delete chunks (no FK, must be explicit)
+ deleted = (
+ test_session.query(DocumentChunk)
+ .filter_by(collection_name=collection_name)
+ .delete(synchronize_session=False)
+ )
+ assert deleted == 6
+
+ # Delete collection
+ collection = test_session.query(Collection).get(collection_id)
+ test_session.delete(collection)
+ test_session.commit()
+
+ # Verify all cleaned up
+ chunks_after = (
+ test_session.query(DocumentChunk)
+ .filter_by(collection_name=collection_name)
+ .count()
+ )
+ assert chunks_after == 0
+
+ def test_delete_collection_removes_rag_index(
+ self, test_session, test_collection, test_rag_index
+ ):
+ """RAGIndex records are deleted with collection."""
+ collection_id = test_collection.id
+ collection_name = f"collection_{collection_id}"
+
+ # Verify RAG index exists
+ index_before = (
+ test_session.query(RAGIndex)
+ .filter_by(collection_name=collection_name)
+ .first()
+ )
+ assert index_before is not None, "RAG index should exist"
+
+ # Manually delete RAG index (should be done by service)
+ test_session.delete(index_before)
+
+ # Delete collection
+ collection = test_session.query(Collection).get(collection_id)
+ test_session.delete(collection)
+ test_session.commit()
+
+ # Verify RAG index is deleted
+ index_after = (
+ test_session.query(RAGIndex)
+ .filter_by(collection_name=collection_name)
+ .first()
+ )
+ assert index_after is None
+
+
+class TestCollectionIndexDeletion:
+ """Tests for deleting only the collection index."""
+
+ def test_delete_index_keeps_collection(
+ self, test_session, test_collection, test_chunks, test_rag_index
+ ):
+ """Collection remains after index deletion."""
+ collection_id = test_collection.id
+ collection_name = f"collection_{collection_id}"
+
+ # Delete chunks
+ test_session.query(DocumentChunk).filter_by(
+ collection_name=collection_name
+ ).delete(synchronize_session=False)
+
+ # Delete RAG index
+ test_session.delete(test_rag_index)
+ test_session.commit()
+
+ # Verify collection still exists
+ collection = test_session.query(Collection).get(collection_id)
+ assert collection is not None, "Collection should still exist"
+
+ def test_delete_index_resets_document_status(
+ self, test_session, test_collection, test_documents, test_chunks
+ ):
+ """DocumentCollection indexed status is reset."""
+ collection_id = test_collection.id
+ collection_name = f"collection_{collection_id}"
+
+ # Delete chunks
+ test_session.query(DocumentChunk).filter_by(
+ collection_name=collection_name
+ ).delete(synchronize_session=False)
+
+ # Reset document indexed status
+ updated = (
+ test_session.query(DocumentCollection)
+ .filter_by(collection_id=collection_id)
+ .update({"indexed": False, "chunk_count": 0})
+ )
+ assert updated == 3, "Should update 3 document links"
+
+ test_session.commit()
+
+ # Verify status is reset
+ links = (
+ test_session.query(DocumentCollection)
+ .filter_by(collection_id=collection_id)
+ .all()
+ )
+ for link in links:
+ assert link.indexed is False, "Should be marked as not indexed"
+ assert link.chunk_count == 0, "Chunk count should be 0"
+
+
+class TestCollectionFolderCascade:
+ """Tests for CollectionFolder cascade deletion."""
+
+ def test_delete_collection_removes_folders(
+ self, test_session, test_collection
+ ):
+ """CollectionFolders are deleted with collection."""
+ collection_id = test_collection.id
+
+ # Add a folder to the collection
+ folder = CollectionFolder(
+ collection_id=collection_id,
+ folder_path="/tmp/test_folder",
+ recursive=True,
+ )
+ test_session.add(folder)
+ test_session.commit()
+
+ # Verify folder exists
+ folder_before = (
+ test_session.query(CollectionFolder)
+ .filter_by(collection_id=collection_id)
+ .first()
+ )
+ assert folder_before is not None, "Folder should exist"
+
+ # Delete collection
+ collection = test_session.query(Collection).get(collection_id)
+ test_session.delete(collection)
+ test_session.commit()
+
+ # Verify folder is deleted (CASCADE)
+ folder_after = (
+ test_session.query(CollectionFolder)
+ .filter_by(collection_id=collection_id)
+ .first()
+ )
+ assert folder_after is None, "Folder should be deleted"
diff --git a/tests/deletion/test_document_deletion.py b/tests/deletion/test_document_deletion.py
new file mode 100644
index 0000000000..39fe6347c6
--- /dev/null
+++ b/tests/deletion/test_document_deletion.py
@@ -0,0 +1,407 @@
+"""
+Tests for document deletion functionality.
+
+Tests the DocumentDeletionService methods:
+- delete_document
+- delete_blob_only
+- remove_from_collection
+"""
+
+import pytest
+import uuid
+
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models.library import (
+ Document,
+ DocumentBlob,
+ DocumentChunk,
+ DocumentCollection,
+ Collection,
+ SourceType,
+)
+from local_deep_research.database.models.base import Base
+
+
+def test_engine():
+ """Create an in-memory SQLite database for testing."""
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ return engine
+
+
+def test_session(test_engine):
+ """Create a session for testing."""
+ Session = sessionmaker(bind=test_engine)
+ session = Session()
+ yield session
+ session.close()
+
+
+def source_type(test_session):
+ """Create a source type for testing."""
+ st = SourceType(
+ id=str(uuid.uuid4()),
+ name="user_upload",
+ display_name="User Upload",
+ )
+ test_session.add(st)
+ test_session.commit()
+ return st
+
+
+def test_collection(test_session):
+ """Create a test collection."""
+ collection = Collection(
+ id=str(uuid.uuid4()),
+ name="Test Collection",
+ description="A test collection",
+ )
+ test_session.add(collection)
+ test_session.commit()
+ return collection
+
+
+def test_document(test_session, source_type, test_collection):
+ """Create a test document with blob and collection link."""
+ doc_id = str(uuid.uuid4())
+ doc = Document(
+ id=doc_id,
+ source_type_id=source_type.id,
+ document_hash=f"hash_{doc_id[:8]}",
+ file_size=1024,
+ file_type="pdf",
+ title="Test Document",
+ filename="test.pdf",
+ storage_mode="database",
+ text_content="This is test content.",
+ )
+ test_session.add(doc)
+ test_session.flush()
+
+ # Add blob
+ blob = DocumentBlob(
+ document_id=doc_id,
+ pdf_binary=b"fake pdf content",
+ blob_hash="fake_hash",
+ )
+ test_session.add(blob)
+
+ # Add to collection
+ doc_collection = DocumentCollection(
+ document_id=doc_id,
+ collection_id=test_collection.id,
+ indexed=False,
+ )
+ test_session.add(doc_collection)
+
+ test_session.commit()
+ return doc
+
+
+class TestDocumentDeletionService:
+ """Unit tests for DocumentDeletionService."""
+
+ def test_delete_document_removes_blob(self, test_session, test_document):
+ """Verify DocumentBlob is deleted with document."""
+ doc_id = test_document.id
+
+ # Verify blob exists before deletion
+ blob_before = (
+ test_session.query(DocumentBlob)
+ .filter_by(document_id=doc_id)
+ .first()
+ )
+ assert blob_before is not None, "Blob should exist before deletion"
+
+ # Delete document (manually simulating service behavior)
+ doc = test_session.query(Document).get(doc_id)
+ test_session.delete(doc)
+ test_session.commit()
+
+ # Verify blob is deleted (CASCADE should handle this)
+ blob_after = (
+ test_session.query(DocumentBlob)
+ .filter_by(document_id=doc_id)
+ .first()
+ )
+ assert blob_after is None, "Blob should be deleted with document"
+
+ def test_delete_document_removes_collection_links(
+ self, test_session, test_document, test_collection
+ ):
+ """Verify DocumentCollection links are deleted."""
+ doc_id = test_document.id
+
+ # Verify link exists before deletion
+ link_before = (
+ test_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id)
+ .first()
+ )
+ assert link_before is not None, "Collection link should exist"
+
+ # Delete document
+ doc = test_session.query(Document).get(doc_id)
+ test_session.delete(doc)
+ test_session.commit()
+
+ # Verify link is deleted
+ link_after = (
+ test_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id)
+ .first()
+ )
+ assert link_after is None, "Collection link should be deleted"
+
+ def test_delete_blob_keeps_document(self, test_session, test_document):
+ """Verify document metadata and text_content preserved after blob deletion."""
+ doc_id = test_document.id
+
+ # Delete only the blob
+ blob = (
+ test_session.query(DocumentBlob)
+ .filter_by(document_id=doc_id)
+ .first()
+ )
+ test_session.delete(blob)
+ test_session.commit()
+
+ # Verify document still exists with text
+ doc = test_session.query(Document).get(doc_id)
+ assert doc is not None, "Document should still exist"
+ assert doc.text_content is not None, "Text content should be preserved"
+ assert doc.title == "Test Document", "Title should be preserved"
+
+ def test_remove_from_collection_deletes_orphan(
+ self, test_session, test_document, test_collection
+ ):
+ """Document in single collection: deleted completely."""
+ doc_id = test_document.id
+
+ # Remove the collection link (simulate remove_from_collection)
+ link = (
+ test_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id, collection_id=test_collection.id)
+ .first()
+ )
+ test_session.delete(link)
+ test_session.flush()
+
+ # Check if document is in any collection
+ remaining = (
+ test_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id)
+ .count()
+ )
+ assert remaining == 0, "Document should not be in any collection"
+
+ # If orphaned, delete document
+ if remaining == 0:
+ doc = test_session.query(Document).get(doc_id)
+ test_session.delete(doc)
+ test_session.commit()
+
+ # Verify document is deleted
+ doc_after = test_session.query(Document).get(doc_id)
+ assert doc_after is None, "Orphaned document should be deleted"
+
+ def test_remove_from_collection_keeps_if_in_other(
+ self, test_session, test_document, test_collection
+ ):
+ """Document in multiple collections: only unlinked."""
+ doc_id = test_document.id
+
+ # Create another collection and link document to it
+ other_collection = Collection(
+ id=str(uuid.uuid4()),
+ name="Other Collection",
+ )
+ test_session.add(other_collection)
+ test_session.flush()
+
+ other_link = DocumentCollection(
+ document_id=doc_id,
+ collection_id=other_collection.id,
+ indexed=False,
+ )
+ test_session.add(other_link)
+ test_session.commit()
+
+ # Remove from first collection
+ link = (
+ test_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id, collection_id=test_collection.id)
+ .first()
+ )
+ test_session.delete(link)
+ test_session.commit()
+
+ # Document should still exist (in other collection)
+ doc = test_session.query(Document).get(doc_id)
+ assert doc is not None, "Document should exist (in other collection)"
+
+ # Document should only be in other collection
+ links = (
+ test_session.query(DocumentCollection)
+ .filter_by(document_id=doc_id)
+ .all()
+ )
+ assert len(links) == 1, "Document should be in exactly one collection"
+ assert links[0].collection_id == other_collection.id
+
+
+class TestBlobDeletion:
+ """Unit tests for blob-only deletion."""
+
+ def test_delete_blob_updates_storage_mode(
+ self, test_session, test_document
+ ):
+ """Verify storage_mode set to 'none' after blob deletion."""
+ doc_id = test_document.id
+
+ # Delete blob and update storage mode
+ blob = (
+ test_session.query(DocumentBlob)
+ .filter_by(document_id=doc_id)
+ .first()
+ )
+ test_session.delete(blob)
+
+ doc = test_session.query(Document).get(doc_id)
+ doc.storage_mode = "none"
+ doc.file_path = "blob_deleted"
+ test_session.commit()
+
+ # Verify update
+ doc_after = test_session.query(Document).get(doc_id)
+ assert doc_after.storage_mode == "none"
+ assert doc_after.file_path == "blob_deleted"
+
+ def test_delete_blob_frees_bytes(self, test_session, test_document):
+ """Verify bytes freed calculation is correct."""
+ doc_id = test_document.id
+
+ # Get blob size
+ blob = (
+ test_session.query(DocumentBlob)
+ .filter_by(document_id=doc_id)
+ .first()
+ )
+ blob_size = len(blob.pdf_binary) if blob.pdf_binary else 0
+ assert blob_size > 0, "Blob should have content"
+
+ # Delete blob
+ test_session.delete(blob)
+ test_session.commit()
+
+ # Verify blob is deleted
+ blob_after = (
+ test_session.query(DocumentBlob)
+ .filter_by(document_id=doc_id)
+ .first()
+ )
+ assert blob_after is None
+
+
+class TestDocumentChunkCleanup:
+ """Tests for DocumentChunk cleanup (no FK constraint)."""
+
+ def test_chunks_require_manual_cleanup(
+ self, test_session, test_document, test_collection
+ ):
+ """Verify DocumentChunks must be manually deleted (no FK)."""
+ doc_id = test_document.id
+ collection_name = f"collection_{test_collection.id}"
+
+ # Create some chunks for the document
+ for i in range(3):
+ chunk = DocumentChunk(
+ chunk_hash=f"chunk_hash_{i}_{uuid.uuid4().hex[:8]}",
+ source_type="document",
+ source_id=doc_id,
+ collection_name=collection_name,
+ chunk_text=f"Test chunk {i} content",
+ chunk_index=i,
+ start_char=i * 100,
+ end_char=(i + 1) * 100,
+ word_count=10,
+ embedding_id=str(uuid.uuid4()),
+ embedding_model="test-model",
+ embedding_model_type="sentence_transformers",
+ )
+ test_session.add(chunk)
+ test_session.commit()
+
+ # Verify chunks exist
+ chunks_before = (
+ test_session.query(DocumentChunk)
+ .filter_by(source_id=doc_id, source_type="document")
+ .count()
+ )
+ assert chunks_before == 3, "Should have 3 chunks"
+
+ # Delete document WITHOUT manually deleting chunks first
+ doc = test_session.query(Document).get(doc_id)
+ test_session.delete(doc)
+ test_session.commit()
+
+ # Chunks should still exist (no FK constraint!)
+ chunks_after = (
+ test_session.query(DocumentChunk)
+ .filter_by(source_id=doc_id, source_type="document")
+ .count()
+ )
+ # This shows the orphan problem - chunks remain after document deletion
+ assert chunks_after == 3, "Chunks remain orphaned (no FK)"
+
+ def test_manual_chunk_deletion(
+ self, test_session, test_document, test_collection
+ ):
+ """Verify manual chunk deletion works."""
+ doc_id = test_document.id
+ collection_name = f"collection_{test_collection.id}"
+
+ # Create a chunk
+ chunk = DocumentChunk(
+ chunk_hash=f"chunk_hash_{uuid.uuid4().hex[:8]}",
+ source_type="document",
+ source_id=doc_id,
+ collection_name=collection_name,
+ chunk_text="Test chunk content",
+ chunk_index=0,
+ start_char=0,
+ end_char=100,
+ word_count=10,
+ embedding_id=str(uuid.uuid4()),
+ embedding_model="test-model",
+ embedding_model_type="sentence_transformers",
+ )
+ test_session.add(chunk)
+ test_session.commit()
+
+ # Manually delete chunks before document
+ deleted = (
+ test_session.query(DocumentChunk)
+ .filter(
+ DocumentChunk.source_id == doc_id,
+ DocumentChunk.source_type == "document",
+ )
+ .delete(synchronize_session=False)
+ )
+ assert deleted == 1, "Should delete 1 chunk"
+
+ # Now delete document
+ doc = test_session.query(Document).get(doc_id)
+ test_session.delete(doc)
+ test_session.commit()
+
+ # Verify all cleaned up
+ doc_after = test_session.query(Document).get(doc_id)
+ assert doc_after is None