~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(rag): wire cancel indexing button to active SSE generator streams (#5223) (#5224)
S1378565f8cb3
diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.pyindex 9101555b24..55876aa75a 100644--- a/src/local_deep_research/research_library/routes/rag_routes.py+++ b/src/local_deep_research/research_library/routes/rag_routes.py@@ -30,7 +30,7 @@ import queuefrom concurrent.futures import ThreadPoolExecutorfrom datetime import datetime, UTCfrom pathlib import Path-from typing import Optional+from typing import Dict, Optional, Set, Tuplefrom sqlalchemy.orm import defer@@ -70,6 +70,14 @@ from ...constants import DEFAULT_SEARCH_TOOLrag_bp = Blueprint("rag", __name__, url_prefix="/library")+# Process-local registry tracking active SSE indexing streams for cancellation.+# Keyed by (username, collection_id) -> Set[threading.Event]+# NOTE: Process-local registry assumes single-process deployment (or sticky sessions).+# Multi-worker deployments (e.g. gunicorn with multiple workers without sticky sessions)+# would require cross-process signaling (e.g. DB-backed cancel flag or Redis pub/sub).+_active_sse_indexers: Dict[Tuple[str, str], Set[threading.Event]] = {}+_active_sse_indexers_lock = threading.Lock()+# NOTE: Routes use session["username"] (not .get()) intentionally.# @login_required guarantees the key exists; direct access fails fast# if the decorator is ever removed.@@ -2340,6 +2348,10 @@ def index_collection(collection_id):"""Generator for SSE progress updates."""logger.info("SSE generator started")_sse_cancel = threading.Event()+ with _active_sse_indexers_lock:+ _active_sse_indexers.setdefault(+ (username, collection_id), set()+ ).add(_sse_cancel)worker_thread = Nonetry:with get_user_db_session(username, db_password) as db_session:@@ -2570,9 +2582,17 @@ def index_collection(collection_id):logger.exception("Error in collection indexing")yield f"data: {json.dumps({'type': 'error', 'error': 'An internal error occurred during indexing'})}\n\n"finally:- # Signal disconnect/cancellation and fully drain the helper thread- # before closing resources shared by its document workers.+ # Signal disconnect/cancellation first so any in-flight checks notice it immediately,+ # then remove this specific stream's cancel event from the registry under lock._sse_cancel.set()+ with _active_sse_indexers_lock:+ events = _active_sse_indexers.get((username, collection_id))+ if events is not None:+ events.discard(_sse_cancel)+ if not events:+ _active_sse_indexers.pop(+ (username, collection_id), None+ )if worker_thread is not None and worker_thread.is_alive():worker_thread.join()safe_close(rag_service, "rag_service (index-collection SSE)")@@ -3288,6 +3308,18 @@ def cancel_indexing(collection_id):)try:+ # Signal active process-local SSE generator(s) if present+ sse_cancelled = False+ with _active_sse_indexers_lock:+ sse_events = _active_sse_indexers.get((username, collection_id))+ if sse_events:+ for sse_event in sse_events:+ sse_event.set()+ sse_cancelled = True+ logger.info(+ f"Signalled active SSE indexing event(s) for collection {collection_id}"+ )+with get_user_db_session(username, db_password) as db_session:# Find active indexing task for this collectiontask = (@@ -3299,38 +3331,42 @@ def cancel_indexing(collection_id):.first())- if not task:- return jsonify(- {- "success": False,- "error": "No active indexing task found",- }- ), 404+ matched_task = None+ if task:+ metadata = task.metadata_json or {}+ if metadata.get("collection_id") == collection_id:+ matched_task = task- # Check if it's for this collection- metadata = task.metadata_json or {}- if metadata.get("collection_id") != collection_id:+ if not matched_task and not sse_cancelled:+ if task:+ return jsonify(+ {+ "success": False,+ "error": "No active indexing task for this collection",+ }+ ), 404return jsonify({"success": False,- "error": "No active indexing task for this collection",+ "error": "No active indexing task found",}), 404- # Mark as cancelled - the worker thread will check this- task.status = "cancelled"- task.progress_message = "Cancellation requested..."- db_session.commit()+ if matched_task:+ # Mark as cancelled - the worker thread will check this+ matched_task.status = "cancelled"+ matched_task.progress_message = "Cancellation requested..."+ db_session.commit()- logger.info(- f"Cancelled indexing task {task.task_id} for collection {collection_id}"- )+ logger.info(+ f"Cancelled indexing task {matched_task.task_id} for collection {collection_id}"+ )return jsonify({"success": True,"message": "Cancellation requested",- "task_id": task.task_id,+ "task_id": matched_task.task_id if matched_task else None,})diff --git a/tests/research_library/routes/test_rag_routes_indexing_coverage.py b/tests/research_library/routes/test_rag_routes_indexing_coverage.pyindex 8d730df9c5..6d35be50b7 100644--- a/tests/research_library/routes/test_rag_routes_indexing_coverage.py+++ b/tests/research_library/routes/test_rag_routes_indexing_coverage.py@@ -909,7 +909,7 @@ class TestCancelIndexing:assert resp.status_code == 404data = resp.get_json()assert data["success"] is False- assert "No active indexing task" in data["error"]+ assert data["error"] == "No active indexing task found"def test_cancel_indexing_wrong_collection(self, app):"""Returns 404 when the active task belongs to a different collection."""@@ -941,4 +941,154 @@ class TestCancelIndexing:assert resp.status_code == 404data = resp.get_json()assert data["success"] is False- assert "this collection" in data["error"]+ assert data["error"] == "No active indexing task for this collection"++ def test_cancel_indexing_active_sse_stream(self, app):+ """Cancels an active SSE indexing stream via process-local registry."""+ import threading+ from local_deep_research.research_library.routes.rag_routes import (+ _active_sse_indexers,+ _active_sse_indexers_lock,+ )++ sse_cancel_event = threading.Event()+ with _active_sse_indexers_lock:+ _active_sse_indexers[("testuser", "coll-1")] = {sse_cancel_event}++ try:+ db_session = _make_db_session()+ q = _build_mock_query(first_result=None)+ db_session.query = Mock(return_value=q)++ mock_password_store = Mock()+ mock_password_store.get_session_password.return_value = None++ with _auth_client(+ app,+ mock_db_session=db_session,+ extra_patches=[+ patch(+ f"{_DB_PASS}.session_password_store",+ mock_password_store,+ ),+ ],+ ) as (client, ctx):+ resp = client.post(+ "/library/api/collections/coll-1/index/cancel"+ )++ assert resp.status_code == 200+ data = resp.get_json()+ assert data["success"] is True+ assert sse_cancel_event.is_set() is True+ finally:+ with _active_sse_indexers_lock:+ _active_sse_indexers.pop(("testuser", "coll-1"), None)++ def test_cancel_indexing_concurrent_sse_streams(self, app):+ """Cancels multiple active SSE indexing streams for the same collection without overwriting."""+ import threading+ from local_deep_research.research_library.routes.rag_routes import (+ _active_sse_indexers,+ _active_sse_indexers_lock,+ )++ event1 = threading.Event()+ event2 = threading.Event()+ with _active_sse_indexers_lock:+ _active_sse_indexers[("testuser", "coll-1")] = {event1, event2}++ try:+ db_session = _make_db_session()+ q = _build_mock_query(first_result=None)+ db_session.query = Mock(return_value=q)++ mock_password_store = Mock()+ mock_password_store.get_session_password.return_value = None++ with _auth_client(+ app,+ mock_db_session=db_session,+ extra_patches=[+ patch(+ f"{_DB_PASS}.session_password_store",+ mock_password_store,+ ),+ ],+ ) as (client, ctx):+ resp = client.post(+ "/library/api/collections/coll-1/index/cancel"+ )++ assert resp.status_code == 200+ assert event1.is_set() is True+ assert event2.is_set() is True+ finally:+ with _active_sse_indexers_lock:+ _active_sse_indexers.pop(("testuser", "coll-1"), None)++ def test_index_collection_sse_lifecycle_registration_and_cleanup(self, app):+ """Exercising the SSE generator verifies registration on start and cleanup in finally."""+ from local_deep_research.research_library.routes.rag_routes import (+ _active_sse_indexers,+ _active_sse_indexers_lock,+ )++ mock_svc = Mock()+ mock_svc.__enter__ = Mock(return_value=mock_svc)+ mock_svc.__exit__ = Mock(return_value=False)+ mock_svc.index_documents_parallel.return_value = {+ "successful": 0,+ "skipped": 0,+ "failed": 0,+ "errors": [],+ "results": {},+ "cancelled": False,+ "total": 0,+ }++ mock_coll = Mock()+ mock_coll.embedding_model = "model"++ db_session = _make_db_session()+ query_counter = {"n": 0}++ def query_side_effect(*models):+ query_counter["n"] += 1+ q = _build_mock_query()+ if query_counter["n"] == 1:+ q.first.return_value = mock_coll+ else:+ q.all.return_value = []+ return q++ db_session.query = Mock(side_effect=query_side_effect)++ mock_password_store = Mock()+ mock_password_store.get_session_password.return_value = None++ with (+ patch(f"{MODULE}.get_rag_service", return_value=mock_svc),+ patch(+ "local_deep_research.research_library.routes.rag_routes.safe_close"+ ),+ ):+ with _auth_client(+ app,+ mock_db_session=db_session,+ extra_patches=[+ patch(+ f"{_DB_PASS}.session_password_store",+ mock_password_store,+ ),+ ],+ ) as (client, ctx):+ response = client.get("/library/api/collections/coll-1/index")+ assert response.status_code == 200++ # Read generator chunk to trigger lifecycle+ _ = list(response.response)++ # After generator finishes, the registry entry should be popped+ with _active_sse_indexers_lock:+ assert ("testuser", "coll-1") not in _active_sse_indexers