~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): cancel the requested collection index task (#6906)
LearningCircuit5b3ddadacdef
diff --git a/changelog.d/+cancel-collection-index.bugfix.md b/changelog.d/+cancel-collection-index.bugfix.mdnew file mode 100644index 0000000000..f3958f9da0--- /dev/null+++ b/changelog.d/+cancel-collection-index.bugfix.md@@ -0,0 +1 @@+Cancel the requested collection’s indexing task even when another collection is indexing at the same time.diff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.pyindex 9a1e3c7ca0..92725f21aa 100644--- a/src/local_deep_research/web/routers/rag.py+++ b/src/local_deep_research/web/routers/rag.py@@ -5001,23 +5001,29 @@ def cancel_indexing(with get_user_db_session(username, db_password) as db_session:# Find active indexing task for this collection- task = (+ tasks = (db_session.query(TaskMetadata).filter(TaskMetadata.task_type == "indexing",TaskMetadata.status == "processing",)- .first()+ .all())- matched_task = None- if task:- metadata = task.metadata_json or {}- if metadata.get("collection_id") == collection_id:- matched_task = task+ # Another collection's earlier task must not hide this one.+ # Match the same collection metadata used by index/start.+ matched_task = next(+ (+ task+ for task in tasks+ if (task.metadata_json or {}).get("collection_id")+ == collection_id+ ),+ None,+ )if not matched_task and not sse_cancelled:- if task:+ if tasks:return JSONResponse({"success": False,diff --git a/tests/research_library/routes/test_rag_routes_cancel_and_worker_wiring.py b/tests/research_library/routes/test_rag_routes_cancel_and_worker_wiring.pyindex 81932c8322..9a002ba071 100644--- a/tests/research_library/routes/test_rag_routes_cancel_and_worker_wiring.py+++ b/tests/research_library/routes/test_rag_routes_cancel_and_worker_wiring.py@@ -220,7 +220,7 @@ class TestCancelIndexingSSEWiring:db_session = _make_db_session(query_side_effect=lambda *a: _build_mock_query(- first_result=existing_task+ all_result=[existing_task]))@@ -262,7 +262,7 @@ class TestCancelIndexingStatusWriteFailures:task.metadata_json = {"collection_id": "coll-1"}db_session = _make_db_session(- query_side_effect=lambda *a: _build_mock_query(first_result=task)+ query_side_effect=lambda *a: _build_mock_query(all_result=[task]))password_store = Mock()diff --git a/tests/research_library/routes/test_rag_routes_coverage_main_port.py b/tests/research_library/routes/test_rag_routes_coverage_main_port.pyindex c4a055ba29..00576f6a10 100644--- a/tests/research_library/routes/test_rag_routes_coverage_main_port.py+++ b/tests/research_library/routes/test_rag_routes_coverage_main_port.py@@ -2741,7 +2741,7 @@ class TestCancelIndexing:db_session = _make_db_session()db_session.query = Mock(- return_value=_build_mock_query(first_result=task)+ return_value=_build_mock_query(first_result=task, all_result=[task]))password_store = Mock()@@ -2774,7 +2774,7 @@ class TestCancelIndexing:db_session = _make_db_session()db_session.query = Mock(- return_value=_build_mock_query(first_result=task)+ return_value=_build_mock_query(first_result=task, all_result=[task]))password_store = Mock()diff --git a/tests/research_library/routes/test_rag_routes_deep_main_port.py b/tests/research_library/routes/test_rag_routes_deep_main_port.pyindex b63d7b0c4b..50165ca188 100644--- a/tests/research_library/routes/test_rag_routes_deep_main_port.py+++ b/tests/research_library/routes/test_rag_routes_deep_main_port.py@@ -1163,13 +1163,16 @@ class TestCancelIndexingNullMetadata:"""An in-progress task whose ``metadata_json`` is NULL must not bematched to this collection -- and the ``or {}`` guard must survive:without it ``None.get(...)`` raises and the route 500s instead of- 404-ing. ``TestCancelIndexingSSEWiring::test_wrong_collection_task_+ 404-ing. The row is served through ``.all()``, the call the lookup+ scans, and the "for this collection" message proves it was examined+ (an empty scan answers "No active indexing task found").+ ``TestCancelIndexingSSEWiring::test_wrong_collection_task_returns_404`` uses a populated dict, so it cannot see this."""from local_deep_research.web.routers.rag import cancel_indexingtask = Mock(task_id="task-1", status="processing", metadata_json=None)db_session = _make_db_session(- query_side_effect=lambda *a: _build_mock_query(first_result=task)+ query_side_effect=lambda *a: _build_mock_query(all_result=[task]))with _patched(@@ -1184,6 +1187,9 @@ class TestCancelIndexingNullMetadata:)assert resp.status_code == 404+ assert json.loads(resp.body)["error"] == (+ "No active indexing task for this collection"+ )# ---------------------------------------------------------------------------diff --git a/tests/research_library/test_library_pipeline_contracts.py b/tests/research_library/test_library_pipeline_contracts.pyindex 2d5f7e2ed1..ed668bcbeb 100644--- a/tests/research_library/test_library_pipeline_contracts.py+++ b/tests/research_library/test_library_pipeline_contracts.py@@ -1256,24 +1256,6 @@ class TestIndexingTaskStatus:)assert after.json()["status"] == "cancelled", after.json()- @pytest.mark.xfail(- strict=True,- reason=(- "cancel_indexing() picks ONE row -- "- "query(TaskMetadata).filter(task_type=='indexing', "- "status=='processing').first() -- with no collection filter and "- "no ORDER BY, and only then checks whether that row's "- "metadata_json['collection_id'] is the requested collection. With "- "two collections indexing at once, cancelling the one that is not "- "first (rowid order under SQLite) answers 404 'No active indexing "- "task for this collection' while index/status still reports "- "processing and index/start still answers 409 -- the collection "- "can neither be re-indexed nor released. start_background_index() "- "had exactly this .first() bug and was fixed by scanning .all(); "- "the same fix was never applied to cancel. Fix: filter/scan all "- "processing indexing tasks for the matching collection_id."- ),- )def test_cancel_is_scoped_to_the_requested_collection(self, fresh_client):client = fresh_client("libpipe_cancel2")first_coll = _new_collection(client, "cancel-first")diff --git a/tests/test_known_defect_pattern_sweep.py b/tests/test_known_defect_pattern_sweep.pyindex 2f11055c60..10fb2ec2dc 100644--- a/tests/test_known_defect_pattern_sweep.py+++ b/tests/test_known_defect_pattern_sweep.py@@ -1586,8 +1586,8 @@ def by_token(session, token, expected_state):return None"""-P4_KNOWN = ("src/local_deep_research/web/routers/rag.py", "cancel_indexing")-P4_EXPECTED = {P4_KNOWN}+P4_REPAIRED = ("src/local_deep_research/web/routers/rag.py", "cancel_indexing")+P4_EXPECTED: set[tuple[str, str]] = set()def test_p4_positive_control():@@ -1608,10 +1608,10 @@ def test_p4_examines_a_floor_of_sites():assert stats["unique_pinned_skipped"] >= 150, stats-def test_p4_known_live_instance_is_refound():+def test_p4_cancel_indexing_no_longer_selects_an_arbitrary_task():sites, _ = scan_pattern_4(modules())- assert P4_KNOWN in keys(sites), report(- "pattern 4: rag.py::cancel_indexing must still be flagged", sites+ assert P4_REPAIRED not in keys(sites), report(+ "pattern 4: rag.py::cancel_indexing must remain repaired", sites)diff --git a/tests/web/routers/test_rag_indexing_pipeline.py b/tests/web/routers/test_rag_indexing_pipeline.pyindex b07d226505..51ddc80c08 100644--- a/tests/web/routers/test_rag_indexing_pipeline.py+++ b/tests/web/routers/test_rag_indexing_pipeline.py@@ -44,11 +44,10 @@ passing controls beside them so the harness cannot mask a failure:admission gate checks both streaming workers and background tasks beforea second run can reach the destructive reset helper.-Plus a cancellation gap: ``cancel_indexing`` scans in-progress tasks with-``.first()`` (``start_background_index`` was fixed to ``.all()`` for-exactly this reason), so an unrelated collection's task shadows this-collection's and cancellation silently 404s while the worker keeps-running.+Plus a cancellation guard: ``cancel_indexing`` scans ALL in-progress tasks+(``.all()``, as ``start_background_index`` does) instead of ``.first()``, so+an unrelated collection's task cannot shadow this collection's and make+cancellation 404 while the worker keeps running.NOT covered here (already covered elsewhere, deliberately not duplicated):SSE framing/heartbeats, the disconnect drain-thread, the cancel-event@@ -1476,10 +1475,7 @@ class TestConcurrentIndexingOfOneCollection:class TestCancelIndexingTaskLookup:- """``start_background_index`` scans ALL in-progress indexing tasks- (``.all()``) precisely because ``.first()`` misses a match when another- collection's task sorts first. ``cancel_indexing`` still uses- ``.first()``."""+ """Unrelated in-progress tasks must not hide the requested collection."""@staticmethoddef _cancel(collection_id):@@ -1507,22 +1503,6 @@ class TestCancelIndexingTaskLookup:session.query(TaskMetadata).filter_by(task_id="task-mine").one()).status == "cancelled"- @pytest.mark.xfail(- strict=True,- reason=(- "cancel_indexing selects in-progress indexing tasks with "- ".first() and only THEN compares metadata_json['collection_id']. "- "With any other collection mid-index, that single row is the "- "other collection's, so this collection's active task is never "- "matched: the endpoint answers 404 'No active indexing task for "- "this collection' while its worker keeps embedding. This is the "- "same defect start_background_index was fixed for (its comment "- "spells it out: 'The old query did .first() and then checked -- "- "so it missed collision when another collection's task happened "- "to sort first'). Fix by scanning .all() and filtering on "- "collection_id, as start_background_index now does."- ),- )def test_an_unrelated_task_does_not_shadow_this_collections_cancel(self, world, seeded):@@ -1535,6 +1515,12 @@ class TestCancelIndexingTaskLookup:result = self._cancel(collection_id)session.expire_all()+ assert isinstance(result, dict)+ assert result["success"] is True+ assert result["task_id"] == "task-mine"+ assert (+ session.query(TaskMetadata).filter_by(task_id="task-other").one()+ ).status == "processing"mine = session.query(TaskMetadata).filter_by(task_id="task-mine").one()assert getattr(result, "status_code", None) != 404, ("cancel_indexing 404s for a collection that DOES have an active "