~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(indexing,benchmark): abort in-flight embeddings and task LLM calls on cancel (#6744)
S6a0e02626c3c
diff --git a/changelog.d/+cancel-indexing-benchmark-inflight.bugfix.md b/changelog.d/+cancel-indexing-benchmark-inflight.bugfix.mdnew file mode 100644index 0000000000..dfd1417f26--- /dev/null+++ b/changelog.d/+cancel-indexing-benchmark-inflight.bugfix.md@@ -0,0 +1,7 @@+Cancelling a collection indexing run or a benchmark run now also aborts+the in-flight work, not just the queued work. Indexing embeds each+document in bounded batches with a cancel check between them, so a Stop+aborts after the current batch instead of embedding the whole document+first. Benchmark cancel sets the in-flight task's termination flag, so+its research and grading LLM calls abort mid-generation and the run+stops without counting the aborted task as failed.diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_service.py b/src/local_deep_research/benchmarks/web_api/benchmark_service.pyindex 8c406805ed..a5f9c49435 100644--- a/src/local_deep_research/benchmarks/web_api/benchmark_service.py+++ b/src/local_deep_research/benchmarks/web_api/benchmark_service.py@@ -12,6 +12,7 @@ from loguru import loggerfrom sqlalchemy.exc import SQLAlchemyErrorfrom ...api.research_functions import quick_summary+from ...exceptions import ResearchTerminatedExceptionfrom ...settings.manager import SnapshotSettingsContextfrom ...web.services.research_service import _global_research_semaphorefrom ...database.models.benchmark import (@@ -474,7 +475,9 @@ class BenchmarkService:)# Set up settings context for thread-local accesssettings_snapshot = benchmark_data.get("settings_snapshot", {})- username = benchmark_data.get("username", "benchmark_user")+ # ``or`` (not ``.get(..., default)``) so an explicit None still+ # falls back — symmetric with _run_key's normalization.+ username = benchmark_data.get("username") or "benchmark_user"# Create a settings context that threads can usesettings_context = SnapshotSettingsContext(@@ -505,7 +508,7 @@ class BenchmarkService:# Initialize task trackingtask_id = f"benchmark_{benchmark_run_id}_{int(datetime.now(UTC).timestamp())}"- username = benchmark_data.get("username", "benchmark_user")+ username = benchmark_data.get("username") or "benchmark_user"self.queue_tracker.add_task(task_id, username, "benchmark")self.queue_tracker.update_task_status(task_id, BenchmarkTaskStatus.PROCESSING@@ -538,22 +541,76 @@ class BenchmarkService:f"Benchmark {benchmark_run_id} processing task {i + 1}/{len(task_queue)}")try:- # Add username and password to task for metrics tracking- task["username"] = benchmark_data.get("username")+ # Add username and password to task for metrics tracking.+ # ``or`` keeps the fallback symmetric with _run_key: a+ # missing/None owner still maps to "benchmark_user" so+ # the publish below hits the same entry cancel reads.+ task["username"] = benchmark_data.get("username") or (+ "benchmark_user"+ )task["user_password"] = benchmark_data.get("user_password")# Acquire the global research semaphore so benchmark# tasks count against the server-wide concurrency limit_global_research_semaphore.acquire()try:+ # Re-check after the semaphore wait: Cancel may have+ # landed while blocked, when there was no tracking ID+ # to flag. Starting the task now would publish a fresh+ # ID the finished handshake cannot see and run to+ # completion after Cancel.+ if (+ run_key in self.active_runs+ and self.active_runs[run_key].get("status")+ == "cancelled"+ ):+ logger.info(+ f"Benchmark {benchmark_run_id} was cancelled "+ f"while waiting for capacity, skipping task "+ f"{i + 1}/{len(task_queue)}"+ )+ break# Process single taskresult = self._process_benchmark_task(task,search_config,evaluation_config,)+ except ResearchTerminatedException:+ # Cancel arrived mid-task: the in-flight LLM call+ # aborted via its termination flag (published as+ # current_tracking_id, see _process_benchmark_task).+ # Stop the run without counting the aborted task as+ # failed — the was_cancelled check below still marks+ # the run CANCELLED.+ logger.info(+ f"Benchmark {benchmark_run_id} task {i + 1} "+ f"aborted mid-task on cancel; stopping run"+ )+ breakfinally:_global_research_semaphore.release()+ # Drop the finished task's research scope and flag+ # so one task's cancellation state can never leak+ # into the next task's LLM calls.+ finished_entry = self.active_runs.get(run_key)+ finished_tid = (+ finished_entry.pop("current_tracking_id", None)+ if finished_entry is not None+ else None+ )+ if finished_tid:+ try:+ from ...web.research_state import (+ clear_termination_flag,+ )++ clear_termination_flag(finished_tid)+ except Exception:+ logger.debug(+ "Failed to clear benchmark task flag "+ "(non-critical)"+ )# Store result in memory for now (will be saved later)if "results" not in self.active_runs[run_key]:@@ -753,6 +810,52 @@ class BenchmarkService:f"Task {task['example_id']} assigned tracking_id: {tracking_id}")+ # Publish the in-flight research scope so cancel_benchmark can+ # abort this task's LLM calls mid-generation (not just between+ # tasks). quick_summary binds this id to its LLM (explicit+ # research_id) and thread context, and the grading phase below+ # re-arms the same scope — the termination flag then aborts the+ # current call within one streamed chunk. Cleared by the worker+ # loop after every task, so ids never outlive their task.+ # The key must match the worker loop's run_key: task["username"]+ # is set from benchmark_data (with the same "benchmark_user"+ # fallback) before this call, so web runs always hit. A direct+ # caller that bypasses the loop with a mismatched username+ # misses here instead of publishing to another user's same-id+ # run (BenchmarkRun.id is per-user) — log so the trap is visible.+ tracker_entry = self.active_runs.get(+ self._run_key(task.get("username"), task["benchmark_run_id"])+ )+ if tracker_entry is None:+ logger.warning(+ f"Benchmark {task['benchmark_run_id']} task "+ f"{task['example_id']} has no live run entry for "+ f"owner {task.get('username')!r}; skipping scope publish "+ f"(cancel will only stop between tasks)"+ )+ else:+ tracker_entry["current_tracking_id"] = tracking_id+ # Cooperative handoff: Cancel may have landed between the+ # worker's status checks and this publish, seeing no ID to+ # flag. If the run is already cancelled, arm the flag for the+ # just-published ID and abort before any LLM call starts, so+ # neither ordering loses the stop request.+ if tracker_entry.get("status") == "cancelled":+ try:+ from ...web.research_state import (+ set_termination_flag,+ )++ set_termination_flag(tracking_id)+ except Exception:+ logger.debug(+ "Failed to set benchmark termination flag "+ "(non-critical)"+ )+ raise ResearchTerminatedException( # noqa: TRY301+ "Benchmark cancelled before task started"+ )+# Format queryformatted_query = format_query(task["question"], task["dataset_type"]@@ -922,12 +1025,33 @@ class BenchmarkService:"extracted_answer": extracted_answer,}- eval_result = grade_single_result(- result_data,- task["dataset_type"],- evaluation_config,- settings_context.snapshot,+ # Re-arm the task's research scope around grading:+ # quick_summary cleared its own context on return, and the+ # grader LLM resolves cancellation from the thread context+ # (graders call get_llm without a research_id). The same+ # termination flag therefore aborts a long grading call+ # mid-stream too.+ from ...utilities.thread_context import (+ clear_search_context,+ set_search_context,+ )++ set_search_context(+ {+ "research_id": tracking_id,+ "research_query": task["question"],+ "username": task.get("username"),+ })+ try:+ eval_result = grade_single_result(+ result_data,+ task["dataset_type"],+ evaluation_config,+ settings_context.snapshot,+ )+ finally:+ clear_search_context()eval_time = time.time() - eval_start_timelogger.info(f"Task {task['example_id']} evaluation completed in {eval_time:.2f}s"@@ -1633,6 +1757,33 @@ class BenchmarkService:)if run is not None:run["status"] = "cancelled"+ # Abort the in-flight task's LLM calls mid-generation, not+ # just between tasks (see _process_benchmark_task): the+ # worker publishes each task's research scope here, and the+ # LLM wrapper aborts on the flag within one streamed chunk.+ # Scoped to the caller's own run via _run_key (above), and+ # the id is an unguessable per-task UUID besides.+ tracking_id = run.get("current_tracking_id")+ if tracking_id:+ try:+ from ...web.research_state import (+ clear_termination_flag,+ set_termination_flag,+ )++ set_termination_flag(tracking_id)+ # The worker pops the id then clears its flag in a+ # per-task finally. If it finished between our read+ # and set, we just created a stale process-global+ # flag for a fresh UUID that will never be reused+ # (cosmetic leak). Re-check and reclaim it.+ if run.get("current_tracking_id") != tracking_id:+ clear_termination_flag(tracking_id)+ except Exception:+ logger.debug(+ "Failed to set benchmark termination flag "+ "(non-critical)"+ )self.update_benchmark_status(benchmark_run_id, BenchmarkStatus.CANCELLED, username=usernamediff --git a/src/local_deep_research/research_library/services/library_rag_service.py b/src/local_deep_research/research_library/services/library_rag_service.pyindex 325c89d0f7..7f26532d50 100644--- a/src/local_deep_research/research_library/services/library_rag_service.py+++ b/src/local_deep_research/research_library/services/library_rag_service.py@@ -80,6 +80,14 @@ class _PreparedDocument:had_collection_link: Optional[bool] = None+# Texts per embed_documents() call while a cancellation scope is armed.+# Embeddings are per-text independent, so splitting changes nothing but+# adds cancel points between batches. Without a scope the single call+# below is kept exactly as today (zero behavior change for background /+# sequential paths that cannot be cancelled).+_EMBEDDING_CANCEL_BATCH_SIZE = 32++class _LazyEmbeddings(Embeddings):"""Embeddings proxy that defers backend construction until first use.@@ -1728,8 +1736,45 @@ class LibraryRAGService:with _hold_faiss_write_lock(self.username, str(index_path)) as lock:yield lock+ def _embed_texts_cancellable(+ self,+ texts: List[str],+ is_cancelled: Optional[Callable[[], bool]] = None,+ ) -> Optional[List[List[float]]]:+ """Embed texts, honouring cancellation between batches.++ Returns the full vector list, or ``None`` when ``is_cancelled()``+ fired before or during embedding — the caller must abandon the+ document (nothing was persisted yet at the prepare stage). The+ in-flight batch finishes naturally: an HTTP round-trip or a local+ forward pass cannot be safely interrupted mid-array, so batching+ bounds the uncancellable tail to one batch instead of the whole+ document.+ """+ embeddings = self.embedding_manager.embeddings+ if is_cancelled is None or len(texts) <= _EMBEDDING_CANCEL_BATCH_SIZE:+ if is_cancelled is not None and is_cancelled():+ return None+ return embeddings.embed_documents(texts)+ vectors: List[List[float]] = []+ for start in range(0, len(texts), _EMBEDDING_CANCEL_BATCH_SIZE):+ if is_cancelled():+ return None+ vectors.extend(+ embeddings.embed_documents(+ texts[start : start + _EMBEDDING_CANCEL_BATCH_SIZE]+ )+ )+ if is_cancelled():+ return None+ return vectors+def _prepare_document(- self, document_id: str, collection_id: str, force_reindex: bool+ self,+ document_id: str,+ collection_id: str,+ force_reindex: bool,+ is_cancelled: Optional[Callable[[], bool]] = None,) -> Dict[str, Any]:"""Load, split, and embed without mutating collection state."""with get_user_db_session(self.username, self.db_password) as session:@@ -1797,10 +1842,20 @@ class LibraryRAGService:)for i, chunk in enumerate(chunks)]+ vectors_list = self._embed_texts_cancellable(+ [chunk.text for chunk in chunk_inputs], is_cancelled+ )+ if vectors_list is None:+ logger.info(+ f"Embedding cancelled for document {document_id} "+ f"({len(chunk_inputs)} chunks)"+ )+ return {+ "status": "cancelled",+ "message": "Cancelled during embedding",+ }vectors = np.asarray(- self.embedding_manager.embeddings.embed_documents(- [chunk.text for chunk in chunk_inputs]- ),+ vectors_list,dtype="float32",)logger.info(@@ -3193,10 +3248,15 @@ class LibraryRAGService:``is_cancelled()`` poll in the ``finally`` block alsopreserves ``cancelled=True`` in the aggregate when thesignal lands while the last in-flight worker is running.- * In-flight embedding round-trips cannot be interrupted (Python- has no safe way to kill a SentenceTransformer forward pass- mid-array) — they finish naturally before the helper returns- via ``pool.shutdown(wait=True)``.+ * In-flight embedding batches cannot be interrupted (Python+ has no safe way to kill an HTTP round-trip or a+ SentenceTransformer forward pass mid-array) — but+ ``_prepare_document`` embeds in bounded batches+ (``_EMBEDDING_CANCEL_BATCH_SIZE``) with an ``is_cancelled()``+ check between them, so the uncancellable tail is one batch,+ not the whole document. The helper returns via+ ``pool.shutdown(wait=True)`` after in-flight batches finish+ naturally.Args:doc_info: List of ``(doc_id, title)`` pairs to index.@@ -3300,7 +3360,7 @@ class LibraryRAGService:):return self._index_one(doc_id, collection_id, force_reindex)prepared_result = self._prepare_document(- doc_id, collection_id, force_reindex+ doc_id, collection_id, force_reindex, is_cancelled)if prepared_result.get("status") == "needs_serial_write":return self.index_document(@@ -3433,6 +3493,14 @@ class LibraryRAGService:counters["successful"] += 1elif status in ("skipped", "cleared"):counters["skipped"] += 1+ elif status == "cancelled":+ # A worker observed the cancel signal mid-document+ # (see _prepare_document). Count it as skipped — same+ # as "Cancelled before submission" below — and flip+ # the aggregate even if the main-thread polls have not+ # observed the signal yet.+ counters["skipped"] += 1+ cancelled = Trueelse:counters["failed"] += 1errors.append(diff --git a/tests/benchmarks/test_benchmark_cancellation.py b/tests/benchmarks/test_benchmark_cancellation.pynew file mode 100644index 0000000000..402b9bd503--- /dev/null+++ b/tests/benchmarks/test_benchmark_cancellation.py@@ -0,0 +1,330 @@+"""Mid-task abort of benchmark runs on cancel.++The worker loop already stopped *between* tasks on cancel, but the+in-flight task's research + grading LLM calls ran to completion. Each+task publishes its research scope (``current_tracking_id``) so+``cancel_benchmark`` can abort the current LLM call mid-generation via+the termination flag, and the loop breaks on+``ResearchTerminatedException`` instead of crashing or counting a+failure.+"""++import uuid+from types import SimpleNamespace+from unittest.mock import Mock++import pytest+++def _task():+ return {+ "task_index": 0,+ "example_id": "ex-1",+ "dataset_type": "simpleqa",+ "question": "What is 2+2?",+ "correct_answer": "4",+ "benchmark_run_id": 7,+ "username": "u",+ "user_password": "pw",+ }+++class TestCancelBenchmarkFlagsInFlightTask:+ def test_cancel_sets_flag_for_published_tracking_id(self):+ from local_deep_research.benchmarks.web_api.benchmark_service import (+ BenchmarkService,+ )+ from local_deep_research.web.research_state import (+ cleanup_research,+ is_termination_requested,+ )++ service = BenchmarkService(socket_service=Mock())+ tracking_id = f"bench-tid-{uuid.uuid4().hex[:12]}"+ run_key = BenchmarkService._run_key("u", 7)+ service.active_runs[run_key] = {+ "status": "running",+ "current_tracking_id": tracking_id,+ }+ service.update_benchmark_status = lambda *a, **k: None+ try:+ assert service.cancel_benchmark(7, "u") is True+ assert service.active_runs[run_key]["status"] == "cancelled"+ assert is_termination_requested(tracking_id)+ finally:+ cleanup_research(tracking_id)+ service.active_runs.pop(run_key, None)++ def test_cancel_without_inflight_task_still_succeeds(self):+ from local_deep_research.benchmarks.web_api.benchmark_service import (+ BenchmarkService,+ )++ service = BenchmarkService(socket_service=Mock())+ run_key = BenchmarkService._run_key("u", 7)+ service.active_runs[run_key] = {"status": "running"}+ service.update_benchmark_status = lambda *a, **k: None+ try:+ assert service.cancel_benchmark(7, "u") is True+ assert service.active_runs[run_key]["status"] == "cancelled"+ finally:+ service.active_runs.pop(run_key, None)+++class TestTaskPublishesScope:+ def test_tracking_id_published_and_grading_scoped(self, monkeypatch):+ from local_deep_research.benchmarks.web_api import (+ benchmark_service as mod,+ )+ from local_deep_research.utilities.thread_context import (+ get_search_context,+ )+ from local_deep_research.web.research_state import cleanup_research++ seen = {}++ def _fake_quick_summary(**kwargs):+ return {+ "summary": "R",+ "findings": [],+ "iterations": 1,+ "questions": {},+ "formatted_findings": "",+ "sources": [],+ }++ def _fake_grade(result_data, dataset_type, config, snapshot):+ ctx = get_search_context() or {}+ seen["grading_scope"] = ctx.get("research_id")+ return {"is_correct": True, "graded_confidence": "90"}++ monkeypatch.setattr(mod, "quick_summary", _fake_quick_summary)+ monkeypatch.setattr(+ mod,+ "format_query",+ lambda question, dataset_type: question,+ )+ monkeypatch.setattr(+ mod,+ "extract_answer_from_response",+ lambda response, dataset_type: {+ "extracted_answer": "R",+ "confidence": "100",+ },+ )+ monkeypatch.setattr(mod, "grade_single_result", _fake_grade)+ monkeypatch.setattr(+ "local_deep_research.config.thread_settings.get_settings_context",+ lambda: SimpleNamespace(snapshot={}),+ )++ service = mod.BenchmarkService(socket_service=Mock())+ run_key = mod.BenchmarkService._run_key("u", 7)+ service.active_runs[run_key] = {"status": "running", "data": {}}+ try:+ result = service._process_benchmark_task(+ _task(), {"iterations": 1}, {}+ )+ published = service.active_runs[run_key].get("current_tracking_id")+ assert published+ assert result.get("research_id") == published+ # Grading ran under the same research scope, so a cancel+ # flag aborts the grader LLM call too.+ assert seen.get("grading_scope") == published+ finally:+ tid = service.active_runs[run_key].get("current_tracking_id")+ service.active_runs.pop(run_key, None)+ if tid:+ cleanup_research(tid)++ def test_terminated_exception_propagates_for_loop_handler(+ self, monkeypatch+ ):+ """The worker loop breaks on this; it must never become a failed task."""+ from local_deep_research.benchmarks.web_api import (+ benchmark_service as mod,+ )+ from local_deep_research.exceptions import ResearchTerminatedException++ def _raise(**kwargs):+ raise ResearchTerminatedException("cancelled")++ monkeypatch.setattr(mod, "quick_summary", _raise)+ monkeypatch.setattr(+ mod,+ "format_query",+ lambda question, dataset_type: question,+ )+ monkeypatch.setattr(+ "local_deep_research.config.thread_settings.get_settings_context",+ lambda: SimpleNamespace(snapshot={}),+ )++ service = mod.BenchmarkService(socket_service=Mock())+ run_key = mod.BenchmarkService._run_key("u", 7)+ service.active_runs[run_key] = {"status": "running", "data": {}}+ try:+ with pytest.raises(ResearchTerminatedException):+ service._process_benchmark_task(_task(), {}, {})+ finally:+ tid = service.active_runs[run_key].get("current_tracking_id")+ service.active_runs.pop(run_key, None)+ if tid:+ from local_deep_research.web.research_state import (+ cleanup_research,+ )++ cleanup_research(tid)+++class TestCancelDuringSemaphoreWait:+ """Cancel arriving while the worker is blocked on capacity.++ The loop used to check ``status`` only before the semaphore wait and+ published ``current_tracking_id`` only afterwards, so a Cancel during+ the wait had no ID to flag and the next task ran to completion.+ """++ def test_cancel_while_blocked_starts_no_task(self, monkeypatch):+ import threading++ from local_deep_research.benchmarks.web_api import (+ benchmark_service as mod,+ )++ service = mod.BenchmarkService(socket_service=Mock())+ service.update_benchmark_status = lambda *a, **k: None+ service._sync_results_to_database = lambda *a, **k: None+ run_key = mod.BenchmarkService._run_key("u", 7)+ service.active_runs[run_key] = {+ "data": {+ "username": "u",+ "user_password": "pw",+ "datasets_config": {},+ "search_config": {},+ "evaluation_config": {},+ "settings_snapshot": {},+ },+ "status": "running",+ "results": [],+ }+ task = _task()+ monkeypatch.setattr(+ service,+ "_create_task_queue",+ lambda *a, **k: [dict(task)],+ )+ started = []+ monkeypatch.setattr(+ service,+ "_process_benchmark_task",+ lambda *a, **k: started.append(True) or {},+ )++ acquire_entered = threading.Event()+ real_sem = threading.Semaphore(0)++ class _SignallingSemaphore:+ def acquire(self, *a, **k):+ acquire_entered.set()+ return real_sem.acquire(*a, **k)++ def release(self, *a, **k):+ return real_sem.release(*a, **k)++ monkeypatch.setattr(+ mod, "_global_research_semaphore", _SignallingSemaphore()+ )++ worker = threading.Thread(+ target=service._run_benchmark_thread, args=("u", 7), daemon=True+ )+ worker.start()+ try:+ assert acquire_entered.wait(timeout=10), "worker never blocked"+ # Cancel lands while no tracking ID is published yet.+ assert service.cancel_benchmark(7, "u") is True+ assert "current_tracking_id" not in service.active_runs[run_key]+ # Release capacity: the worker must notice the cancel and skip.+ real_sem.release()+ worker.join(timeout=30)+ assert not worker.is_alive()+ assert started == []+ from local_deep_research.benchmarks.web_api.benchmark_service import (+ BenchmarkStatus,+ )++ assert (+ service.active_runs[run_key]["completion_info"]["status"]+ == BenchmarkStatus.CANCELLED+ )+ finally:+ if worker.is_alive():+ real_sem.release()+ worker.join(timeout=10)+ service.active_runs.pop(run_key, None)++ def test_publish_after_cancel_aborts_before_llm_calls(self, monkeypatch):+ """Cancel between the status check and the scope publish must not run.++ The worker publishes ``current_tracking_id`` inside+ ``_process_benchmark_task``; a Cancel that landed just before the+ publish sees no ID to flag. The publish must cooperate by arming the+ new ID and aborting before any LLM call starts.+ """+ from local_deep_research.benchmarks.web_api import (+ benchmark_service as mod,+ )+ from local_deep_research.exceptions import ResearchTerminatedException+ from local_deep_research.web.research_state import (+ cleanup_research,+ is_termination_requested,+ )++ calls = {"research": 0, "grade": 0}++ def _fake_quick_summary(**kwargs):+ calls["research"] += 1+ return {"summary": "R", "sources": []}++ def _fake_grade(*a, **k):+ calls["grade"] += 1+ return {"is_correct": True}++ monkeypatch.setattr(mod, "quick_summary", _fake_quick_summary)+ monkeypatch.setattr(mod, "grade_single_result", _fake_grade)+ monkeypatch.setattr(+ mod,+ "format_query",+ lambda question, dataset_type: question,+ )+ monkeypatch.setattr(+ mod,+ "extract_answer_from_response",+ lambda response, dataset_type: {+ "extracted_answer": "R",+ "confidence": "100",+ },+ )+ monkeypatch.setattr(+ "local_deep_research.config.thread_settings.get_settings_context",+ lambda: SimpleNamespace(snapshot={}),+ )++ service = mod.BenchmarkService(socket_service=Mock())+ run_key = mod.BenchmarkService._run_key("u", 7)+ service.active_runs[run_key] = {"status": "cancelled", "data": {}}+ try:+ with pytest.raises(ResearchTerminatedException):+ service._process_benchmark_task(_task(), {}, {})+ assert calls == {"research": 0, "grade": 0}+ published = service.active_runs[run_key].get("current_tracking_id")+ assert published+ # The just-published scope is flagged so any racing LLM call+ # aborts too.+ assert is_termination_requested(published)+ finally:+ tid = service.active_runs[run_key].get("current_tracking_id")+ service.active_runs.pop(run_key, None)+ if tid:+ cleanup_research(tid)diff --git a/tests/research_library/services/test_index_documents_parallel.py b/tests/research_library/services/test_index_documents_parallel.pyindex b23d56db2c..4b140b438e 100644--- a/tests/research_library/services/test_index_documents_parallel.py+++ b/tests/research_library/services/test_index_documents_parallel.py@@ -218,7 +218,7 @@ class TestPreparedPipeline:write_peak = 0write_threads = []- def prepare(doc_id, collection_id, force_reindex):+ def prepare(doc_id, collection_id, force_reindex, is_cancelled=None):nonlocal prep_active, prep_peakwith prep_lock:prep_active += 1diff --git a/tests/research_library/test_indexing_cancellation.py b/tests/research_library/test_indexing_cancellation.pynew file mode 100644index 0000000000..0d159f37a0--- /dev/null+++ b/tests/research_library/test_indexing_cancellation.py@@ -0,0 +1,132 @@+"""Cancellation of in-flight collection-indexing embeddings.++``index_documents_parallel`` polls ``is_cancelled`` between documents, but+a single document's ``embed_documents`` call used to run to completion no+matter when Stop arrived. ``_embed_texts_cancellable`` embeds in bounded+batches with a cancel check between them, so the uncancellable tail is+one batch instead of the whole document.+"""++from types import SimpleNamespace+++def _stub_service(calls):+ from local_deep_research.research_library.services.library_rag_service import (+ LibraryRAGService,+ )++ class _FakeEmbeddings:+ def embed_documents(self, texts):+ calls.append(list(texts))+ return [[float(len(t))] for t in texts]++ stub = SimpleNamespace(+ embedding_manager=SimpleNamespace(embeddings=_FakeEmbeddings())+ )+ return LibraryRAGService, stub+++class TestNoScopeKeepsSingleCall:+ def test_large_doc_without_scope_is_one_call(self):+ """Background/sequential paths (no cancel scope) behave as before."""+ LibraryRAGService, stub = _stub_service(calls := [])+ texts = [f"chunk-{i}" for i in range(70)]+ vectors = LibraryRAGService._embed_texts_cancellable(stub, texts, None)+ assert vectors is not None and len(vectors) == 70+ assert calls == [texts]+ # Order preserved.+ assert [v[0] for v in vectors] == [float(len(t)) for t in texts]+++class TestBatchedScope:+ def test_batches_concatenate_in_order(self):+ LibraryRAGService, stub = _stub_service(calls := [])+ texts = [f"chunk-{i}" for i in range(70)]+ vectors = LibraryRAGService._embed_texts_cancellable(+ stub, texts, lambda: False+ )+ assert vectors is not None and len(vectors) == 70+ assert [len(batch) for batch in calls] == [32, 32, 6]+ assert [v[0] for v in vectors] == [float(len(t)) for t in texts]++ def test_small_doc_is_one_call_with_scope(self):+ LibraryRAGService, stub = _stub_service(calls := [])+ texts = [f"chunk-{i}" for i in range(10)]+ vectors = LibraryRAGService._embed_texts_cancellable(+ stub, texts, lambda: False+ )+ assert vectors is not None and len(vectors) == 10+ assert calls == [texts]+++class TestCancelAbortsEmbedding:+ def test_pre_cancelled_makes_no_calls(self):+ LibraryRAGService, stub = _stub_service(calls := [])+ texts = [f"chunk-{i}" for i in range(70)]+ assert (+ LibraryRAGService._embed_texts_cancellable(+ stub, texts, lambda: True+ )+ is None+ )+ assert calls == []++ def test_cancel_mid_batches_aborts_after_current_batch(self):+ LibraryRAGService, stub = _stub_service(calls := [])+ texts = [f"chunk-{i}" for i in range(70)]+ # Cancel lands after the first batch finished.+ state = {"batches": 0}++ def _is_cancelled():+ return state["batches"] >= 1++ orig = stub.embedding_manager.embeddings.embed_documents++ def _counting(texts_batch):+ try:+ return orig(texts_batch)+ finally:+ state["batches"] += 1++ stub.embedding_manager.embeddings.embed_documents = _counting+ try:+ assert (+ LibraryRAGService._embed_texts_cancellable(+ stub, texts, _is_cancelled+ )+ is None+ )+ finally:+ stub.embedding_manager.embeddings.embed_documents = orig+ assert len(calls) == 1+ assert len(calls[0]) == 32++ def test_cancel_after_last_batch_discards_vectors(self):+ """A cancel racing the final batch must not persist vectors."""+ LibraryRAGService, stub = _stub_service(calls := [])+ texts = [f"chunk-{i}" for i in range(70)]+ state = {"calls": 0}++ def _is_cancelled():+ # False between batches, True at the trailing check.+ return state["calls"] >= 3++ orig = stub.embedding_manager.embeddings.embed_documents++ def _counting(texts_batch):+ try:+ return orig(texts_batch)+ finally:+ state["calls"] += 1++ stub.embedding_manager.embeddings.embed_documents = _counting+ try:+ assert (+ LibraryRAGService._embed_texts_cancellable(+ stub, texts, _is_cancelled+ )+ is None+ )+ finally:+ stub.embedding_manager.embeddings.embed_documents = orig+ assert len(calls) == 3diff --git a/tests/web/test_research_state_accessor_gaps.py b/tests/web/test_research_state_accessor_gaps.pyindex 7812ab1f3c..d99d071b8e 100644--- a/tests/web/test_research_state_accessor_gaps.py+++ b/tests/web/test_research_state_accessor_gaps.py@@ -24,7 +24,8 @@ everywhere. What is recovered here is the residue it does not pin:registry test builds already carries a ``log`` list, so thecreate-the-list-if-missing half never executes there.* **``clear_termination_flag``** — pinned in the registry file only as- *having no production call sites*; nothing asserts it actually clears.+ *having two deliberate benchmark-task call sites*; nothing asserts it+ actually clears.* The remaining ``.get(..., default)`` fallbacks on entries built withoutthe canonical keys (``settings``/``thread``/``progress`` absent), and``get_active_research_count``'s exact count.@@ -147,10 +148,10 @@ def test_append_research_log_creates_the_log_list_when_it_is_missing():def test_clear_termination_flag_actually_clears_and_is_per_id():- """``clear_termination_flag`` has no production caller today, and the- registry file pins only that fact — not that the function works. It- is the obvious thing for a future patch to reach for, so what it does- is worth an assertion."""+ """``clear_termination_flag`` has two deliberate benchmark-task callers,+ and the registry file pins only that fact — not that the function+ works. It is the obvious thing for a future patch to reach for, so+ what it does is worth an assertion."""doomed, bystander = _rid(), _rid()assert research_state.is_termination_requested(doomed) is Falsediff --git a/tests/web/test_research_state_registry.py b/tests/web/test_research_state_registry.pyindex 3136224bca..fc191da5ca 100644--- a/tests/web/test_research_state_registry.py+++ b/tests/web/test_research_state_registry.py@@ -707,10 +707,13 @@ def test_a_termination_flag_for_an_unregistered_id_is_never_reclaimed():"""A flag can outlive -- and be set without -- any research.``set_termination_flag`` writes unconditionally; it does not require- the id to be active. ``cleanup_research`` is the only production- path that pops ``_termination_flags`` (``clear_termination_flag``- has zero production call sites, asserted below), and it runs from- the *worker's* teardown. So a flag set for an id whose worker never+ the id to be active. ``cleanup_research`` is the production path that+ pops ``_termination_flags`` for research runs (plus deliberate+ benchmark-task exceptions: the benchmark worker reclaims each+ finished task's per-task UUID scope, and ``cancel_benchmark``+ reclaims the same scope on its cancel-vs-finish race — see+ ``test_clear_termination_flag_call_sites_are_pinned``), and it runs+ from the *worker's* teardown. So a flag set for an id whose worker neverstarts stays in the process-global dict for the lifetime of theprocess.@@ -748,21 +751,46 @@ def test_a_termination_flag_for_an_unregistered_id_is_never_reclaimed():)-def test_clear_termination_flag_has_no_production_call_sites():- """The only explicit un-set is dead code.-- Pinned because it is the reason the leak above has no escape hatch:- a future reader looking for "where do we clear this" will find an- accessor that is never called.+def test_clear_termination_flag_call_sites_are_pinned():+ """Exactly two deliberate production callers exist.++ The flag-leak test above documents that *research* flags are only+ reclaimed by the worker's own ``cleanup_research`` teardown.+ Benchmark tasks are the deliberate exception: each task runs under+ a fresh per-task UUID scope (see+ ``benchmark_service._process_benchmark_task``), and both callers+ below operate only on that scope:++ * ``_run_benchmark_thread`` clears it in a per-task ``finally``+ so one finished task's cancellation state can never leak into+ the next task's LLM calls;+ * ``cancel_benchmark`` reclaims it only on the cancel-vs-finish+ race -- if the worker popped the scope between cancel's read+ and ``set_termination_flag``, cancel just created a stale+ process-global flag for a fresh UUID that will never be reused,+ so it re-checks ``current_tracking_id`` and clears it back.++ The fresh-uuid-per-scope shape is what makes this safe --+ re-deriving (not just extending) this list is required if it ever+ changes, because a further caller needs the same argument or it+ reintroduces cross-run kills."""sites, _ = _census()callers = [- site for site in sites if site.accessor == "clear_termination_flag"+ (site.module, site.qualname)+ for site in sites+ if site.accessor == "clear_termination_flag"]- assert callers == [], (- "clear_termination_flag now has call sites; the flag-leak test "- f"above needs re-deriving: {callers}"- )+ assert callers == [+ (+ "benchmarks/web_api/benchmark_service.py",+ "_run_benchmark_thread",+ ),+ (+ "benchmarks/web_api/benchmark_service.py",+ "cancel_benchmark",+ ),+ ], f"clear_termination_flag call sites changed: {callers}"def test_accessors_with_no_production_call_sites_are_pinned():@@ -777,7 +805,6 @@ def test_accessors_with_no_production_call_sites_are_pinned():called = {site.accessor for site in sites}unused = sorted(ACCESSORS - called)assert unused == [- "clear_termination_flag","get_active_research_count","iter_active_research","remove_active_research",