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(rag): parallelize document indexing via index_documents_parallel (#5119)

S7a8b85162bea
diff --git a/changelog.d/5118.feature.md b/changelog.d/5118.feature.md
new file mode 100644
index 0000000000..bdfa8ec6c4
--- /dev/null
+++ b/changelog.d/5118.feature.md
@@ -0,0 +1 @@
+rag-indexer: parallelize document indexing via a bounded `ThreadPoolExecutor` in `LibraryRAGService.index_documents_parallel`. All six `for doc: index_document(...)` loops in `research_library/routes/rag_routes.py` and the background reconciler in `scheduler/background.py` now fan out concurrently instead of serially. The slow embedding round-trip — outside the per-collection FAISS write lock — is now overlapped across documents, so a local embedding backend (Ollama, LMStudio, llama.cpp, sentence-transformers) is no longer bottlenecked by single-document sequential embedding. New user setting `rag.indexing_max_parallel_docs` (default 4, range 1–16) controls fan-out; set to 1 to recover the previous strictly-sequential behaviour. Cancellation is honoured between completions, queued-but-not-started futures are cancelled on shutdown, and per-doc error handling is preserved (one failing doc no longer halts the batch). The SSE endpoint additionally yields a heartbeat comment every 5s during long embedding passes so reverse proxies don't time out the stream.
diff --git a/changelog.d/5119.bugfix.md b/changelog.d/5119.bugfix.md
new file mode 100644
index 0000000000..b8f090c73b
--- /dev/null
+++ b/changelog.d/5119.bugfix.md
@@ -0,0 +1 @@
+rag-indexer: fix three runtime issues uncovered after shipping `index_documents_parallel` in #5118. (1) Parallel first-document indexing no longer races on the lazy `self.faiss_index is None` check + the unique-constraint INSERT inside `_get_or_create_rag_index` — the FAISS init is now serialised via a per-instance lock, and `_get_or_create_rag_index` recovers gracefully from a concurrent `IntegrityError` by re-querying the winning row. (2) SSE cancellation now drains in-flight workers before the generator's `finally` closes the embedding manager and nulls the FAISS index — both SSE generators wire a `threading.Event` that the helper polls between completions, and the per-user SSE generator additionally joins its background worker thread before releasing the service. The parallel helper always shuts its pool down with `wait=True` so no worker can outlive the caller's service context. (3) The scheduled reconciler in `scheduler/background.py` now reads the configured `rag.indexing_max_parallel_docs` instead of hard-coding `max_workers=4`, so a configured value of 1 truly restores sequential scheduled indexing. (4) Post-cancel submission leak in `index_documents_parallel` is closed: the helper now polls `is_cancelled` BEFORE admitting any new work into the pool (bounded-submission loop), so queued futures can no longer be picked up by idle workers between the caller's cancel signal and `pool.shutdown(cancel_futures=True)`. The reconciler and SSE paths therefore no longer observe stray post-cancel starts.
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 402b3bc8b3..bee6343b2f 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -189,7 +189,8 @@ They are not available in the Web UI because they are needed to start the applic
| `policy.egress_scope` | `LDR_POLICY_EGRESS_SCOPE` | `adaptive` | EXPERIMENTAL — this egress boundary is new defense-in-depth, not an absolute guarantee yet; don't rely on it as your only protection for highly sensitive data. Restrict which search engines a research run may use. ADAPTIVE (default) = follow your primary engine: a private primary keeps everything local, a public primary allows public engines. STRICT = only the primary engine you picked; PUBLIC_ONLY = any public web/academic engine; PRIVATE_ONLY = any local engine (library, paperless, etc.); UNPROTECTED = escape hatch that disables egress protection entirely (not recommended; hard SSRF/cloud-metadata blocking still applies). | SEARCH |
| `policy.trusted_inference_providers` | `LDR_POLICY_TRUSTED_INFERENCE_PROVIDERS` | ``[]`` | EXPERIMENTAL. LLM/embeddings providers you explicitly trust to receive sensitive content — listing one treats it as a 'contained' inference sink even though it is off-machine (e.g. a zero-retention enterprise Anthropic endpoint). Relaxes the two-axis egress classification; use only for providers you have vetted. | LLM |
| `policy.trusted_search_engines` | `LDR_POLICY_TRUSTED_SEARCH_ENGINES` | ``[]`` | EXPERIMENTAL. Search engines whose endpoint you explicitly trust — listing one (e.g. a self-hosted Elasticsearch/Paperless on a public hostname) treats it as 'contained' rather than an exposing sink. Relaxes the two-axis egress classification; use only for endpoints you control. | SEARCH |
-| `rag.indexing_batch_size` | `LDR_RAG_INDEXING_BATCH_SIZE` | `15` | Number of documents to process in parallel during RAG indexing. Higher values are faster but use more memory. | APP |
+| `rag.indexing_batch_size` | `LDR_RAG_INDEXING_BATCH_SIZE` | ``15`` | Maximum number of documents grouped into a single SSE progress batch on `/api/rag/index-all`. Documents within a batch are processed in parallel via `rag.indexing_max_parallel_docs`. Higher values reduce SSE overhead but increase the unit of cancellation. Legacy semantics on that one route — not consumed by the per-collection background worker. | APP |
+| `rag.indexing_max_parallel_docs` | `LDR_RAG_INDEXING_MAX_PARALLEL_DOCS` | ``4`` | Maximum number of documents indexed concurrently within a single indexing job (per user). One job holds up to this many workers; each worker calls the existing per-document path so the FAISS write lock still serializes the disk-merge step. Lower for CPU-bound embedders that contend under concurrency; raise to 8-16 for sentence-transformers on GPU or HTTP embedding providers (OpenAI-compatible, vLLM, Ollama with `OLLAMA_NUM_PARALLEL>1`). | APP |
| `rate_limiting.decay_per_day` | `LDR_RATE_LIMITING_DECAY_PER_DAY` | `0.95` | How much to trust old rate limit data as it ages (0.5-0.99). At 0.95, data retains 95% reliability per day. Lower values discard old data faster, forcing the system to re-learn optimal wait times. | APP |
| `rate_limiting.enabled` | `LDR_RATE_LIMITING_ENABLED` | `true` | Enable adaptive rate limiting that learns optimal wait times for each search engine to avoid hitting API rate limits. When disabled, requests are sent with minimal delay (0.1s), which may trigger rate limit errors from some APIs. | APP |
| `rate_limiting.exploration_rate` | `LDR_RATE_LIMITING_EXPLORATION_RATE` | `0.1` | Fraction of requests that test shorter wait times to check if the API allows faster access (0.0-1.0). Higher values adapt faster to relaxed limits but risk more rate limit errors. | APP |
diff --git a/scripts/dev/regenerate_golden_master.py b/scripts/dev/regenerate_golden_master.py
index 7f3554e5fc..b1773baa86 100755
--- a/scripts/dev/regenerate_golden_master.py
+++ b/scripts/dev/regenerate_golden_master.py
@@ -40,7 +40,12 @@ def main() -> int:
+ "\n"
)
- GOLDEN_MASTER_PATH.write_text(output, encoding="utf-8")
+ # Write bytes to force LF line endings. ``Path.write_text`` on Windows
+ # would default to CRLF, which makes ``git diff --quiet`` in the
+ # pre-commit golden-master check report a spurious diff every time
+ # even when the canonical settings content is unchanged.
+ with open(GOLDEN_MASTER_PATH, "wb") as f:
+ f.write(output.encode("utf-8"))
print(f"Wrote {len(current)} settings to {GOLDEN_MASTER_PATH}")
return 0
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 4f631a16ec..2067bed43a 100644
--- a/src/local_deep_research/defaults/research_library/library_settings.json
+++ b/src/local_deep_research/defaults/research_library/library_settings.json
@@ -59,7 +59,7 @@
},
"rag.indexing_batch_size": {
"category": "research_library",
- "description": "Number of documents to process in parallel during RAG indexing. Higher values are faster but use more memory.",
+ "description": "Maximum number of documents grouped into a single SSE progress batch on /api/rag/index-all. Documents within a batch are processed in parallel via rag.indexing_max_parallel_docs. Higher values reduce SSE overhead but increase the unit of cancellation.",
"editable": true,
"max_value": 50,
"min_value": 1,
@@ -71,6 +71,20 @@
"value": 15,
"visible": true
},
+ "rag.indexing_max_parallel_docs": {
+ "category": "research_library",
+ "description": "Maximum number of documents indexed concurrently within a single indexing job (per-user). One job holds up to this many workers; each worker calls the existing per-document path so the FAISS write lock still serializes the disk-merge step. Lower if your embedding backend (e.g. local CPU sentence-transformers) is throughput-bound and concurrent calls contend; raise to e.g. 8-16 for sentence-transformers on GPU, or HTTP embedding providers (OpenAI-compatible, vLLM, Ollama with OLLAMA_NUM_PARALLEL>1). Default 4 keeps RAM modest for collections with many large documents.",
+ "editable": true,
+ "max_value": 16,
+ "min_value": 1,
+ "name": "RAG Indexing Max Parallel Documents",
+ "options": null,
+ "step": 1,
+ "type": "APP",
+ "ui_element": "number",
+ "value": 4,
+ "visible": true
+ },
"research_library.max_pdf_size_mb": {
"category": "research_library",
"description": "Maximum allowed PDF file size in megabytes for the research library. PDFs larger than this will not be stored. Uploads are also gated by the per-file upload cap (LDR_SECURITY_UPLOAD_MAX_FILE_SIZE_MB, default 3072 MB / 3 GB) — raising this value above that cap has no effect because uploads are rejected before they reach storage.",
diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.py
index 958b1aff93..9101555b24 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -872,6 +872,7 @@ def index_all():
def generate():
"""Generator function for SSE progress updates."""
+ _sse_cancel = threading.Event()
try:
# Send initial status
yield f"data: {json.dumps({'type': 'start', 'message': 'Starting bulk indexing...'})}\n\n"
@@ -930,24 +931,49 @@ def index_all():
results = {"successful": 0, "skipped": 0, "failed": 0, "errors": []}
total = len(doc_info)
- # Process documents in batches to optimize performance
- # Get batch size from settings
+ # Process documents in batches to pace SSE progress events.
+ # The batch boundary is purely cosmetic now — documents within
+ # a batch run in parallel via the bounded worker pool below.
+ # Get batch size + parallel worker count from settings.
settings = get_settings_manager()
batch_size = int(
settings.get_setting("rag.indexing_batch_size", 15)
)
+ try:
+ _max_workers = int(
+ settings.get_setting("rag.indexing_max_parallel_docs", 4)
+ )
+ except Exception:
+ _max_workers = 4
+ _max_workers = max(1, min(_max_workers, 16))
+
processed = 0
for i in range(0, len(doc_info), batch_size):
batch = doc_info[i : i + batch_size]
- # Process batch with collection_id
- batch_results = rag_service.index_documents_batch(
- batch, collection_id, force_reindex
+ # Run the per-batch docs through the bounded parallel
+ # helper. ``as_completed`` order means progress events
+ # fire in completion order, not submission order — the
+ # `processed` counter below keeps the SSE payload
+ # monotonically increasing so the UI percent stays sane.
+ # ``is_cancelled`` polls the SSE-disconnect event so an
+ # early-disconnect watcher (or this generator's own
+ # ``finally``) can short-circuit the batch before all
+ # queued futures run. The helper still drains in-flight
+ # workers via ``pool.shutdown(wait=True, ...)`` so no
+ # worker outlives the helper return — see
+ # ``index_documents_parallel`` for the rationale.
+ parallel_result = rag_service.index_documents_parallel(
+ batch,
+ collection_id,
+ force_reindex=force_reindex,
+ max_workers=_max_workers,
+ is_cancelled=_sse_cancel.is_set,
)
+ batch_results = parallel_result["results"]
- # Process results and send progress updates
- for j, (doc_id, title) in enumerate(batch):
+ for doc_id, title in batch:
processed += 1
result = batch_results[doc_id]
@@ -987,6 +1013,13 @@ def index_all():
# the outer route scope would tear it down before the streamed
# generator runs. ``safe_close`` swallows close-time errors so
# a broken Ollama doesn't mask the original generator outcome.
+ #
+ # Signal cancellation BEFORE closing: the helper has already
+ # drained in-flight workers (its ``shutdown(wait=True, ...)``
+ # guarantees no worker outlives the helper return), so setting
+ # the event here is for any in-progress batch loop iteration
+ # and any future code path that bypasses the helper.
+ _sse_cancel.set()
safe_close(rag_service, "rag_service (index-all SSE)")
return Response(
@@ -2306,6 +2339,8 @@ def index_collection(collection_id):
def generate():
"""Generator for SSE progress updates."""
logger.info("SSE generator started")
+ _sse_cancel = threading.Event()
+ worker_thread = None
try:
with get_user_db_session(username, db_password) as db_session:
# Verify collection exists in this user's database
@@ -2360,111 +2395,174 @@ def index_collection(collection_id):
yield f"data: {json.dumps({'type': 'start', 'message': f'Indexing {total} documents in collection: {collection.name}'})}\n\n"
- for idx, (link, doc) in enumerate(doc_links, 1):
- filename = doc.filename or doc.title or "Unknown"
- yield f"data: {json.dumps({'type': 'progress', 'current': idx, 'total': total, 'filename': filename, 'percent': int((idx / total) * 100)})}\n\n"
-
- try:
- logger.debug(
- f"Indexing document {idx}/{total}: {filename}"
+ # Fan out indexing across a bounded worker pool. We run the
+ # pool in a background thread so the SSE generator's main
+ # thread can still yield heartbeats during long embedding
+ # round-trips (matters for nginx / browser SSE timeout
+ # behaviour). The progress_callback fired by the parallel
+ # helper pushes per-document events into ``progress_queue``,
+ # which the generator drains as they arrive.
+ #
+ # The pool size is resolved on the calling thread so the
+ # parallel helper never touches SettingsManager from inside
+ # a worker (no Flask app context there; pre-commit thread-
+ # safety hook would reject it).
+ try:
+ _settings = get_settings_manager()
+ _max_workers = int(
+ _settings.get_setting(
+ "rag.indexing_max_parallel_docs", 4
)
+ )
+ except Exception:
+ _max_workers = 4
+ _max_workers = max(1, min(_max_workers, 16))
- # Run index_document in a separate thread to allow sending SSE heartbeats.
- # This keeps the HTTP connection alive during long indexing operations,
- # preventing timeouts from proxy servers (nginx) and browsers.
- # The main thread periodically yields heartbeat comments while waiting.
- result_queue = queue.Queue()
- error_queue = queue.Queue()
-
- def index_in_thread():
- try:
- r = rag_service.index_document(
- document_id=doc.id,
- collection_id=collection_id,
- force_reindex=force_reindex,
- )
- result_queue.put(r)
- except Exception as ex:
- error_queue.put(ex)
- finally:
- try:
- from ...database.thread_local_session import (
- cleanup_current_thread,
- )
-
- cleanup_current_thread()
- except Exception:
- logger.debug(
- "best-effort thread-local DB session cleanup",
- exc_info=True,
- )
-
- thread = threading.Thread(target=index_in_thread)
- thread.start()
-
- # Send heartbeats while waiting for the thread to complete
- heartbeat_interval = 5 # seconds
- while thread.is_alive():
- thread.join(timeout=heartbeat_interval)
- if thread.is_alive():
- # Send SSE comment as heartbeat (keeps connection alive)
- yield f": heartbeat {idx}/{total}\n\n"
-
- # Check for errors from thread
- if not error_queue.empty():
- raise error_queue.get() # noqa: TRY301 — re-raises thread exception for per-document error handling
+ doc_info = [
+ (
+ doc.id,
+ doc.filename or doc.title or "Unknown",
+ )
+ for _link, doc in doc_links
+ ]
- result = result_queue.get()
- logger.info(
- f"Indexed document {idx}/{total}: {filename} - status={result.get('status')}"
+ progress_queue: queue.Queue = queue.Queue()
+ _SENTINEL_COMPLETE = object()
+ _SENTINEL_ERROR = object()
+
+ def _on_progress(
+ completed: int,
+ total: int,
+ title: str,
+ status: str,
+ ) -> None:
+ progress_queue.put(
+ (
+ "progress",
+ completed,
+ total,
+ title,
+ status,
)
+ )
- if result.get("status") == "success":
- results["successful"] += 1
- # DocumentCollection status is already updated in index_document
- # No need to update link here
- elif result.get("status") in ("skipped", "cleared"):
- # "cleared" (empty-text purge) is a handled non-failure.
- results["skipped"] += 1
- else:
- results["failed"] += 1
- error_msg = result.get("error", "Unknown error")
- results["errors"].append(
- {
- "filename": filename,
- "error": error_msg,
- }
- )
- logger.warning(
- f"Failed to index {filename} ({idx}/{total}): {error_msg}"
- )
- except Exception as e:
- results["failed"] += 1
- # Scrub creds/keys before surfacing to the browser
- # (SSE yield below); full trace stays in server logs.
- error_msg = (
- sanitize_error_message(str(e))
- or "Failed to index document"
+ def _run_parallel():
+ try:
+ # ``is_cancelled`` polls the SSE-disconnect event
+ # so the helper can exit early between completions
+ # when the client has gone away; the helper's
+ # ``pool.shutdown(wait=True, ...)`` still drains
+ # in-flight workers before returning so no worker
+ # outlives the helper return — see ``index_documents_parallel`` for the
+ # rationale.
+ aggregate = rag_service.index_documents_parallel(
+ doc_info,
+ collection_id,
+ force_reindex=force_reindex,
+ max_workers=_max_workers,
+ progress_callback=_on_progress,
+ is_cancelled=_sse_cancel.is_set,
)
- results["errors"].append(
- {
- "filename": filename,
- "error": error_msg,
- }
+ progress_queue.put((_SENTINEL_COMPLETE, aggregate))
+ except Exception as exc:
+ logger.exception(
+ "Parallel indexing in SSE generator crashed"
)
+ progress_queue.put((_SENTINEL_ERROR, exc))
+ finally:
+ # Best-effort thread-local DB session cleanup so a
+ # long-running worker batch doesn't accumulate
+ # scoped sessions (#3194).
+ try:
+ from ...database.thread_local_session import (
+ cleanup_current_thread,
+ )
+
+ cleanup_current_thread()
+ except Exception:
+ logger.debug(
+ "best-effort thread-local DB session cleanup",
+ exc_info=True,
+ )
+
+ worker_thread = threading.Thread(
+ target=_run_parallel,
+ daemon=True,
+ name="index-collection-parallel",
+ )
+ worker_thread.start()
+
+ # Drain the queue: yield progress events as they arrive,
+ # yield heartbeat comments on idle to keep SSE proxies
+ # from timing out, exit on completion / error sentinels.
+ heartbeat_interval = 5 # seconds
+ _aggregate = None
+ while True:
+ try:
+ item = progress_queue.get(timeout=heartbeat_interval)
+ except queue.Empty:
+ # No event in 5s. Heartbeat unless the worker
+ # died without signalling (would hang forever).
+ if worker_thread.is_alive():
+ yield f": heartbeat {total}\n\n"
+ continue
logger.exception(
- f"Exception indexing document {filename} ({idx}/{total})"
+ "Indexer worker exited without completion "
+ "signal; aborting SSE"
)
- # Send error update to client so they know indexing is continuing
- yield f"data: {json.dumps({'type': 'doc_error', 'filename': filename, 'error': error_msg})}\n\n"
+ yield f"data: {json.dumps({'type': 'error', 'error': 'Indexer stopped unexpectedly'})}\n\n"
+ return
+
+ if item[0] is _SENTINEL_COMPLETE:
+ _aggregate = item[1]
+ break
+ if item[0] is _SENTINEL_ERROR:
+ yield f"data: {json.dumps({'type': 'error', 'error': 'An internal error occurred during indexing'})}\n\n"
+ return
+
+ _kind, completed, total, title, status = item
+ yield f"data: {json.dumps({'type': 'progress', 'current': completed, 'total': total, 'filename': title, 'percent': int((completed / total) * 100)})}\n\n"
+
+ if status == "error":
+ # Per-doc error surfaced so the browser can show
+ # failed documents inline. Scrub creds/keys here
+ # (the full trace stays in server logs above).
+ # Look the error up from the aggregate's errors
+ # list — at this point _aggregate is None
+ # (indexer still running), so we accept a brief
+ # imprecision on the exact error text and emit
+ # a generic doc_error; the final ``complete``
+ # event below will list precise errors.
+ yield f"data: {json.dumps({'type': 'doc_error', 'filename': title, 'error': 'Indexing failed'})}\n\n"
+
+ if _aggregate is not None:
+ results["successful"] = _aggregate["successful"]
+ results["skipped"] = _aggregate["skipped"]
+ results["failed"] = _aggregate["failed"]
+ # Replace placeholder errors with the structured ones
+ # from the parallel helper so the final ``complete``
+ # event matches what previous serial runs returned.
+ results["errors"] = [
+ {
+ "filename": err.get("title"),
+ "error": sanitize_error_message(
+ str(err.get("error"))
+ )
+ or "Failed to index document",
+ }
+ for err in _aggregate.get("errors", [])
+ ]
+ logger.info(
+ f"Indexing complete: "
+ f"{results['successful']} successful, "
+ f"{results['failed']} failed, "
+ f"{results['skipped']} skipped"
+ )
db_session.commit()
# Ensure all changes are written to disk
db_session.flush()
- logger.info(
- f"Indexing complete: {results['successful']} successful, {results['failed']} failed, {results['skipped']} skipped"
- )
yield f"data: {json.dumps({'type': 'complete', 'results': results})}\n\n"
logger.info("SSE generator finished successfully")
@@ -2472,8 +2570,11 @@ 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:
- # See parallel comment in index-all generator above — generator
- # ``finally`` is the safe close site for streamed RAG services.
+ # Signal disconnect/cancellation and fully drain the helper thread
+ # before closing resources shared by its document workers.
+ _sse_cancel.set()
+ if worker_thread is not None and worker_thread.is_alive():
+ worker_thread.join()
safe_close(rag_service, "rag_service (index-collection SSE)")
response = Response(
@@ -2556,6 +2657,14 @@ def trigger_auto_index(
if not auto_index_enabled:
logger.debug("Auto-indexing is disabled, skipping")
return
+
+ try:
+ _auto_max_workers = int(
+ settings.get_setting("rag.indexing_max_parallel_docs", 4)
+ )
+ except Exception:
+ _auto_max_workers = 4
+ _auto_max_workers = max(1, min(_auto_max_workers, 16))
except Exception:
logger.exception(
"Failed to check auto-index setting, skipping auto-index"
@@ -2618,6 +2727,7 @@ def trigger_auto_index(
collection_id,
username,
db_password,
+ _auto_max_workers,
)
except Exception:
# If submit itself fails (executor shutting down, OOM, etc.), the
@@ -2644,6 +2754,7 @@ def _auto_index_documents_worker(
collection_id: str,
username: str,
db_password: str,
+ max_workers: int = 4,
) -> None:
"""
Background worker to index documents automatically.
@@ -2651,6 +2762,20 @@ def _auto_index_documents_worker(
This is a simpler worker than _background_index_worker - it doesn't track
progress via TaskMetadata since it's meant to be a lightweight auto-indexing
operation.
+
+ Documents inside one call are indexed concurrently via
+ :meth:`LibraryRAGService.index_documents_parallel`. The outer
+ ``_auto_index_executor`` already parallelises separate jobs at the upload
+ layer (one job per upload batch) and we additionally fan out inside each
+ job, so a burst of uploads doesn't serialise within a single upload's
+ document set.
+
+ The ``max_workers`` parameter is resolved on the caller (which owns
+ the Flask request context and therefore a real
+ :func:`get_settings_manager` call). Background-thread workers must
+ NOT call ``get_settings_manager()`` without an explicit
+ ``db_session=`` — see pre-commit hook
+ ``check-settings-manager-thread-safety`` and issue #3453.
"""
try:
@@ -2658,24 +2783,21 @@ def _auto_index_documents_worker(
with _get_rag_service_for_thread(
collection_id, username, db_password
) as rag_service:
- indexed_count = 0
- for doc_id in document_ids:
- try:
- result = rag_service.index_document(
- doc_id, collection_id, force_reindex=False
- )
- if result.get("status") == "success":
- indexed_count += 1
- logger.debug(f"Auto-indexed document {doc_id}")
- elif result.get("status") == "skipped":
- logger.debug(
- f"Document {doc_id} already indexed, skipped"
- )
- except Exception:
- logger.exception(f"Failed to auto-index document {doc_id}")
-
+ # The auto-indexer doesn't surface per-doc titles to a user,
+ # so we stub them with empty strings — the parallel helper
+ # only reads titles for progress reporting.
+ doc_info = [(doc_id, "") for doc_id in document_ids]
+ aggregate = rag_service.index_documents_parallel(
+ doc_info,
+ collection_id,
+ force_reindex=False,
+ max_workers=max(1, min(int(max_workers), 16)),
+ )
logger.info(
- f"Auto-indexing complete: {indexed_count}/{len(document_ids)} documents indexed"
+ f"Auto-indexing complete: {aggregate['successful']}"
+ f"/{len(document_ids)} documents indexed "
+ f"(skipped={aggregate['skipped']}, "
+ f"failed={aggregate['failed']})"
)
except Exception:
@@ -2689,10 +2811,18 @@ def _background_index_worker(
username: str,
db_password: str,
force_reindex: bool,
+ max_workers: int = 4,
):
"""
Background worker thread for indexing documents.
Updates TaskMetadata with progress and checks for cancellation.
+
+ The ``max_workers`` parameter bounds the per-job fan-out into
+ :meth:`LibraryRAGService.index_documents_parallel`. It must be
+ resolved on the route (which has Flask app context), not inside
+ this worker — background threads cannot call
+ :func:`get_settings_manager` safely (#3453, pre-commit hook
+ ``check-settings-manager-thread-safety``).
"""
from ...database.session_context import get_user_db_session
@@ -2765,50 +2895,73 @@ def _background_index_worker(
progress_message=f"Indexing {total} documents",
)
- for idx, (link, doc) in enumerate(doc_links, 1):
- # Check if cancelled
- if _is_task_cancelled(username, db_password, task_id):
- _update_task_status(
- username,
- db_password,
- task_id,
- status="cancelled",
- progress_message=f"Cancelled after {idx - 1}/{total} documents",
- )
- logger.info(f"Indexing task {task_id} was cancelled")
- return
+ # The caller (start_background_index, which owns the
+ # Flask request context) resolved ``max_workers`` from
+ # ``rag.indexing_max_parallel_docs`` and forwarded it
+ # here. Workers must NOT call ``get_settings_manager()``
+ # themselves — no Flask app context, pre-commit
+ # ``check-settings-manager-thread-safety`` would reject,
+ # and #3453 documents the data-loss shape that produces.
+ _max_workers = max(1, min(int(max_workers), 16))
- filename = doc.filename or doc.title or "Unknown"
+ doc_info = [
+ (doc.id, doc.filename or doc.title or "Unknown")
+ for _link, doc in doc_links
+ ]
- # Update progress with filename
+ def _on_progress(
+ completed: int,
+ total: int,
+ title: str,
+ status: str,
+ ) -> None:
_update_task_status(
username,
db_password,
task_id,
- progress_current=idx,
- progress_message=f"Indexing {idx}/{total}: {filename}",
+ progress_current=completed,
+ progress_message=(
+ f"Indexing {completed}/{total}: {title}"
+ ),
)
- try:
- result = rag_service.index_document(
- document_id=doc.id,
- collection_id=collection_id,
- force_reindex=force_reindex,
- )
+ def _is_cancelled() -> bool:
+ return _is_task_cancelled(username, db_password, task_id)
- if result.get("status") == "success":
- results["successful"] += 1
- elif result.get("status") in ("skipped", "cleared"):
- # "cleared" (empty-text purge) is a handled non-failure.
- results["skipped"] += 1
- else:
- results["failed"] += 1
+ aggregate = rag_service.index_documents_parallel(
+ doc_info,
+ collection_id,
+ force_reindex=force_reindex,
+ max_workers=_max_workers,
+ progress_callback=_on_progress,
+ is_cancelled=_is_cancelled,
+ )
- except Exception:
- results["failed"] += 1
- logger.exception(
- f"Error indexing document {idx}/{total}"
- )
+ results["successful"] = aggregate["successful"]
+ results["skipped"] = aggregate["skipped"]
+ results["failed"] = aggregate["failed"]
+
+ if aggregate["cancelled"]:
+ completed = (
+ aggregate["successful"]
+ + aggregate["skipped"]
+ + aggregate["failed"]
+ )
+ _update_task_status(
+ username,
+ db_password,
+ task_id,
+ status="cancelled",
+ progress_message=(
+ f"Cancelled after {completed}/{total} documents"
+ ),
+ )
+ logger.info(
+ f"Indexing task {task_id} was cancelled "
+ f"after {completed}/{total} documents"
+ )
+ db_session.commit()
+ return
db_session.commit()
@@ -2859,6 +3012,18 @@ def _update_task_status(
.first()
)
if task:
+ # 1. Preserve terminal states: once cancelled or failed, only updates
+ # confirming that same state are allowed.
+ if (
+ task.status in ("cancelled", "failed")
+ and status != task.status
+ ):
+ return
+
+ # 2. Transition to completed is only allowed from processing.
+ if status == "completed" and task.status != "processing":
+ return
+
if status is not None:
task.status = status
if status == "completed":
@@ -2961,10 +3126,30 @@ def start_background_index(collection_id):
db_session.add(task)
db_session.commit()
+ # Resolve per-job parallel fan-out on this route (Flask
+ # context is present) and forward into the worker — the
+ # worker itself runs on a background thread where
+ # ``get_settings_manager()`` is unsafe (#3453).
+ try:
+ _bg_settings = get_settings_manager()
+ _bg_max_workers = int(
+ _bg_settings.get_setting("rag.indexing_max_parallel_docs", 4)
+ )
+ except Exception:
+ _bg_max_workers = 4
+ _bg_max_workers = max(1, min(_bg_max_workers, 16))
+
# Start background thread
thread = threading.Thread(
target=_background_index_worker,
- args=(task_id, collection_id, username, db_password, force_reindex),
+ args=(
+ task_id,
+ collection_id,
+ username,
+ db_password,
+ force_reindex,
+ _bg_max_workers,
+ ),
daemon=True,
)
thread.start()
diff --git a/src/local_deep_research/research_library/services/library_rag_service.py b/src/local_deep_research/research_library/services/library_rag_service.py
index 6123562386..a81def71ac 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
@@ -12,11 +12,13 @@ Handles indexing and searching library documents using RAG:
import threading
import time
from pathlib import Path
-from typing import Any, Dict, List, Optional, Tuple
+from typing import Any, Callable, Dict, List, Optional, Set, Tuple
+from concurrent.futures import ThreadPoolExecutor, as_completed, CancelledError
from langchain_core.documents import Document as LangchainDocument
from loguru import logger
from sqlalchemy import func
+from sqlalchemy.exc import IntegrityError
from ...config.paths import get_cache_directory
from ...database.models.library import (
@@ -608,9 +610,23 @@ class LibraryRAGService:
is_current=True,
)
session.add(rag_index)
- session.commit()
- session.refresh(rag_index)
- logger.info(f"Created new RAG index: {index_hash}")
+ try:
+ session.commit()
+ except IntegrityError:
+ session.rollback()
+ rag_index = (
+ session.query(RAGIndex)
+ .filter_by(index_hash=index_hash)
+ .first()
+ )
+ if rag_index is None:
+ raise
+ logger.info(
+ f"Using concurrently created RAG index: {index_hash}"
+ )
+ else:
+ session.refresh(rag_index)
+ logger.info(f"Created new RAG index: {index_hash}")
elif promote_current and not rag_index.is_current:
# An existing index for THIS (collection, model) config is being
# reused (on a WRITE path) but is not marked current. After an
@@ -2163,6 +2179,304 @@ class LibraryRAGService:
return results
+ def index_documents_parallel(
+ self,
+ doc_info: List[Tuple[str, str]],
+ collection_id: str,
+ force_reindex: bool = False,
+ max_workers: int = 4,
+ progress_callback: Optional[
+ Callable[[int, int, str, str], None]
+ ] = None,
+ is_cancelled: Optional[Callable[[], bool]] = None,
+ ) -> Dict[str, Any]:
+ """
+ Index many documents concurrently with bounded fan-out.
+
+ Each per-document task calls :meth:`index_document` directly — the
+ per-doc logic (split, embed, persist chunks, FAISS-merge-under-lock,
+ mark indexed, update stats) is unchanged. The bounded fan-out only
+ changes *which* ``for doc: index_document(...)`` loop calls them:
+ before this method, six call sites in
+ :mod:`research_library.routes.rag_routes` and the background
+ reconciler in :mod:`scheduler.background` each did this
+ sequentially. The slow embedding round-trip (outside the FAISS
+ write lock) is now overlapped across documents.
+
+ Concurrency invariants this method relies on (already true):
+
+ * :meth:`index_document` opens a fresh per-thread DB session via
+ :func:`get_user_db_session` — workers do not share sessions.
+ * All FAISS mutations go through ``VectorIndex.apply()`` in
+ :mod:`local_deep_research.vector_stores`, which is only
+ invoked under the per-(username, index_path) write lock
+ returned by :func:`_get_faiss_write_lock`. The service passes
+ that lock into the vector-store facade at the call sites
+ around L422, L879, L1097, and L2025, so concurrent
+ ``index_document`` workers serialise their FAISS appends on
+ the same lock without any extra coordination here.
+ * ``LocalEmbeddingManager.embeddings`` uses double-checked
+ locking for first-load.
+ * ``is_cancelled`` is polled between completions AND between
+ submissions. The bounded-submission loop admits new work into
+ the pool only when ``is_cancelled()`` returns False, and
+ each :func:`_run_one` worker re-checks ``is_cancelled()``
+ immediately before delegating to ``index_document``. This
+ closes the false-poll-to-submit gap (the cancel signal can
+ be set between the main thread's poll and ``pool.submit()``)
+ so post-cancel starts are zero by construction. The final
+ ``is_cancelled()`` poll in the ``finally`` block also
+ preserves ``cancelled=True`` in the aggregate when the
+ signal 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)``.
+
+ Args:
+ doc_info: List of ``(doc_id, title)`` pairs to index.
+ collection_id: UUID of the collection.
+ force_reindex: Forwarded to :meth:`index_document`.
+ max_workers: Bound on concurrent in-flight doc indexers.
+ ``1`` falls back to fully sequential behaviour (still
+ useful when a flaky network makes concurrent httpx
+ calls worse than serial). Default 4.
+ progress_callback: Optional hook called once per completed
+ document with ``(completed, total, title, status)`` —
+ matches the legacy shape used by
+ :meth:`index_all_documents` so existing UI progress
+ paths keep working.
+ is_cancelled: Optional zero-arg callable polled between
+ completions AND between submissions. When it returns
+ ``True``, no further work is admitted into the pool;
+ in-flight futures finish naturally. The executor is
+ always shut down with ``wait=True`` so no worker can
+ outlive the caller's service context.
+
+ Returns:
+ ``{"successful": int, "skipped": int, "failed": int,
+ "errors": [...], "results": {doc_id: {...}},
+ "cancelled": bool, "total": int}``.
+ """
+ if max_workers < 1:
+ max_workers = 1
+
+ total = len(doc_info)
+ if total == 0:
+ return {
+ "successful": 0,
+ "skipped": 0,
+ "failed": 0,
+ "errors": [],
+ "results": {},
+ "cancelled": False,
+ "total": 0,
+ }
+
+ # Title-lookup keyed by doc_id — futures return in ``as_completed``
+ # order, not submission order, so we cannot rely on positional
+ # iteration when emitting progress.
+ title_lookup = dict(doc_info)
+
+ results: Dict[str, Dict[str, Any]] = {}
+ counters = {"successful": 0, "skipped": 0, "failed": 0}
+ errors: List[Dict[str, Any]] = []
+ cancelled = False
+
+ def _run_one(doc_id: str) -> Dict[str, Any]:
+ """Single-doc worker — never raises; returns a status dict."""
+ try:
+ return self.index_document(doc_id, collection_id, force_reindex)
+ except Exception as exc:
+ # ``index_document`` already returns an error dict on its
+ # own internal failures; this catches only bugs / hook
+ # breaks outside that contract.
+ logger.exception(f"Parallel index worker for {doc_id} crashed")
+ return {
+ "status": "error",
+ "error": f"Indexing failed: {type(exc).__name__}",
+ }
+
+ # De-duplicated submission queue preserving input order. The
+ # underlying ``index_document`` is not idempotent at the DB level
+ # beyond its own checks; without this guard a buggy caller could
+ # double-insert chunks from the same doc.
+ pending_doc_ids: List[str] = []
+ seen: Set[str] = set()
+ for doc_id, _title in doc_info:
+ if doc_id in seen:
+ continue
+ seen.add(doc_id)
+ pending_doc_ids.append(doc_id)
+
+ pool = ThreadPoolExecutor(
+ max_workers=max_workers,
+ thread_name_prefix="ldr-index-doc-",
+ )
+ try:
+ future_to_doc: Dict[Any, str] = {}
+ submit_idx = 0
+ completed = 0
+ # Bounded-submission loop: poll ``is_cancelled`` BEFORE
+ # admitting any new work, then submit up to ``max_workers``
+ # futures, then wait for one completion.
+ #
+ # This closes the post-cancel submission leak in the
+ # previous all-upfront submission model: with the old
+ # loop, all futures were submitted before the first
+ # ``is_cancelled()`` poll, so queued futures could be
+ # picked up by idle workers between the caller's cancel
+ # signal (e.g. ``_sse_cancel.set()`` in
+ # ``rag_routes.index_collection``) and the helper's
+ # ``pool.shutdown(cancel_futures=True)``. Here, new work
+ # is admitted only when ``is_cancelled()`` returns False,
+ # so post-cancel starts are zero by construction.
+ while future_to_doc or submit_idx < len(pending_doc_ids):
+ # 1. Cancellation fence: stop submitting new work if
+ # cancelled. Once we observe cancellation we don't
+ # re-poll — the gate stays closed until the loop
+ # drains.
+ if (
+ not cancelled
+ and is_cancelled is not None
+ and is_cancelled()
+ ):
+ cancelled = True
+ logger.info(
+ f"Parallel indexing cancelled at {completed}/{total}"
+ )
+ for f in future_to_doc:
+ f.cancel()
+
+ # 2. Admit new work up to ``max_workers`` in flight
+ # (skipped once cancelled).
+ if not cancelled:
+ while len(future_to_doc) < max_workers and submit_idx < len(
+ pending_doc_ids
+ ):
+ if is_cancelled is not None and is_cancelled():
+ cancelled = True
+ logger.info(
+ f"Parallel indexing cancelled during submission at {completed}/{total}"
+ )
+ for f in future_to_doc:
+ f.cancel()
+ break
+ doc_id = pending_doc_ids[submit_idx]
+ submit_idx += 1
+ future_to_doc[pool.submit(_run_one, doc_id)] = doc_id
+
+ # 3. Nothing in flight and nothing left to submit → done.
+ if not future_to_doc:
+ break
+
+ # 4. Wait for the next completion, then process it.
+ try:
+ done_iter = as_completed(list(future_to_doc.keys()))
+ fut = next(done_iter, None)
+ except Exception:
+ logger.exception(
+ "as_completed failed unexpectedly during parallel indexing"
+ )
+ fut = None
+ if fut is None:
+ # Iterator short-circuited without yielding — loop
+ # back. The next iteration's cancel poll / submit
+ # check will either submit more work or exit.
+ continue
+
+ doc_id = future_to_doc.pop(fut)
+ try:
+ result = fut.result()
+ except CancelledError:
+ result = {
+ "status": "skipped",
+ "message": "Cancelled before submission",
+ }
+ except Exception as exc:
+ logger.exception(
+ f"Future for doc {doc_id} raised unexpectedly"
+ )
+ result = {
+ "status": "error",
+ "error": f"Worker crashed: {type(exc).__name__}",
+ }
+ results[doc_id] = result
+ status = result.get("status", "error")
+ if status == "success":
+ counters["successful"] += 1
+ elif status in ("skipped", "cleared"):
+ counters["skipped"] += 1
+ else:
+ counters["failed"] += 1
+ errors.append(
+ {
+ "doc_id": doc_id,
+ "title": title_lookup.get(doc_id, "Unknown"),
+ "error": result.get("error"),
+ }
+ )
+ completed += 1
+ if progress_callback is not None:
+ try:
+ progress_callback(
+ completed,
+ total,
+ title_lookup.get(doc_id, "Unknown"),
+ status,
+ )
+ except Exception:
+ # A buggy callback must not poison the indexing
+ # run — log and continue.
+ logger.exception(
+ "Parallel index progress_callback raised"
+ )
+ finally:
+ if not cancelled and is_cancelled is not None and is_cancelled():
+ cancelled = True
+ # Always ``wait=True`` so in-flight workers finish before the
+ # helper returns. With bounded submission no new work is
+ # admitted after cancel is observed, so the only in-flight
+ # work at shutdown is what was already running — these finish
+ # naturally. ``cancel_futures=cancelled`` is a no-op here
+ # (no queued futures by construction) but is kept for
+ # symmetry with other shutdown sites in the codebase and as
+ # defense-in-depth if a future change relaxes the bounded-
+ # submission invariant.
+ pool.shutdown(wait=True, cancel_futures=cancelled)
+
+ if cancelled:
+ # Mark docs that were never submitted (still in the
+ # pending queue past ``submit_idx``) as skipped. Submitted
+ # docs all have results — either from processing in the
+ # loop above or from the ``wait=True`` shutdown drain —
+ # so we don't need to touch them here.
+ for doc_id in pending_doc_ids[submit_idx:]:
+ if doc_id not in results:
+ results[doc_id] = {
+ "status": "skipped",
+ "message": "Cancelled before submission",
+ }
+ counters["skipped"] += 1
+
+ logger.info(
+ f"Parallel indexing complete: "
+ f"{counters['successful']} successful, "
+ f"{counters['skipped']} skipped, "
+ f"{counters['failed']} failed"
+ f"{' (cancelled)' if cancelled else ''}"
+ )
+
+ return {
+ "successful": counters["successful"],
+ "skipped": counters["skipped"],
+ "failed": counters["failed"],
+ "errors": errors,
+ "results": results,
+ "cancelled": cancelled,
+ "total": total,
+ }
+
def get_rag_stats(
self, collection_id: Optional[str] = None
) -> Dict[str, Any]:
diff --git a/src/local_deep_research/scheduler/background.py b/src/local_deep_research/scheduler/background.py
index e838de2fe3..5da703f7a9 100644
--- a/src/local_deep_research/scheduler/background.py
+++ b/src/local_deep_research/scheduler/background.py
@@ -1371,6 +1371,27 @@ class BackgroundJobScheduler:
# Cleared by @thread_cleanup on exit.
self._arm_egress_backstop(settings_manager, username)
+ # Resolve the parallel-worker count from the user's saved
+ # settings so a configured ``rag.indexing_max_parallel_docs``
+ # of 1 truly restores the legacy strictly-sequential sweep
+ # (the SSE routes also resolve this from settings, but the
+ # reconciler runs as a scheduled background thread without a
+ # Flask app context, so it uses the already-bound db session
+ # via ``SettingsManager(db)`` rather than the global
+ # ``get_settings_manager()`` helper — which the pre-commit
+ # ``check-settings-manager-thread-safety`` hook forbids inside
+ # ``@thread_cleanup``-decorated functions without an explicit
+ # ``db_session=`` argument).
+ try:
+ _max_parallel = int(
+ settings_manager.get_setting(
+ "rag.indexing_max_parallel_docs", 4
+ )
+ )
+ except Exception:
+ _max_parallel = 4
+ _max_parallel = max(1, min(_max_parallel, 16))
+
total_indexed = 0
# ---- Case (a): in-collection unindexed documents ----------
@@ -1428,27 +1449,36 @@ class BackgroundJobScheduler:
collection_id=coll_id,
db_password=password,
) as rag_service:
+ # Fan out across the per-collection batch using
+ # the user-configured parallel-worker count
+ # resolved above. Clamped to ``[1, 16]`` so a
+ # misconfigured value can't blow the pool size
+ # past the documented range.
+ doc_info = [(doc_id, "") for doc_id in doc_ids]
+ aggregate = rag_service.index_documents_parallel(
+ doc_info,
+ coll_id,
+ force_reindex=False,
+ max_workers=_max_parallel,
+ )
for doc_id in doc_ids:
- try:
- result = rag_service.index_document(
- document_id=doc_id,
- collection_id=coll_id,
- force_reindex=False,
+ result = aggregate["results"].get(doc_id, {})
+ if result.get("status") == "success":
+ total_indexed += 1
+ logger.debug(
+ f"[RECONCILER] Indexed document {doc_id} "
+ f"into collection {coll_id} with "
+ f"{result.get('chunk_count', 0)} chunks"
)
- if result.get("status") == "success":
- total_indexed += 1
- logger.debug(
- f"[RECONCILER] Indexed document {doc_id} "
- f"into collection {coll_id} with "
- f"{result.get('chunk_count', 0)} chunks"
- )
- except Exception as doc_error:
- # ``password`` is in scope and was passed
- # into ``get_rag_service``. Drop the
- # traceback chain + redact str(e) to avoid
- # leaking the SQLCipher master password.
+ elif result.get("status") == "error":
+ # ``password`` is in scope and was
+ # passed into ``get_rag_service``.
+ # Drop the traceback chain + redact
+ # str(e) to avoid leaking the
+ # SQLCipher master password.
safe_msg = redact_secrets(
- str(doc_error), password
+ str(result.get("error", "")),
+ password,
)
logger.warning(
f"[RECONCILER] Failed to index document "
@@ -1518,25 +1548,34 @@ class BackgroundJobScheduler:
collection_id=default_library_id,
db_password=password,
) as rag_service:
- for (doc_id,) in orphans:
- try:
- result = rag_service.index_document(
- document_id=doc_id,
- collection_id=default_library_id,
- force_reindex=False,
+ # Same parallel fan-out as the in-collection
+ # branch above; ``_max_parallel`` was resolved
+ # from the user's saved
+ # ``rag.indexing_max_parallel_docs`` setting at
+ # the top of this tick.
+ orphan_ids = [doc_id for (doc_id,) in orphans]
+ doc_info = [(doc_id, "") for doc_id in orphan_ids]
+ aggregate = rag_service.index_documents_parallel(
+ doc_info,
+ default_library_id,
+ force_reindex=False,
+ max_workers=_max_parallel,
+ )
+ for doc_id in orphan_ids:
+ result = aggregate["results"].get(doc_id, {})
+ if result.get("status") == "success":
+ total_indexed += 1
+ logger.debug(
+ f"[RECONCILER] Ingested + "
+ f"indexed research orphan "
+ f"{doc_id} into the default "
+ f"library with "
+ f"{result.get('chunk_count', 0)} chunks"
)
- if result.get("status") == "success":
- total_indexed += 1
- logger.debug(
- f"[RECONCILER] Ingested + "
- f"indexed research orphan "
- f"{doc_id} into the default "
- f"library with "
- f"{result.get('chunk_count', 0)} chunks"
- )
- except Exception as doc_error:
+ elif result.get("status") == "error":
safe_msg = redact_secrets(
- str(doc_error), password
+ str(result.get("error", "")),
+ password,
)
logger.warning(
f"[RECONCILER] Failed to index "
diff --git a/src/local_deep_research/vector_stores/implementations/faiss_store.py b/src/local_deep_research/vector_stores/implementations/faiss_store.py
index d70d3b0699..52523e8cf8 100644
--- a/src/local_deep_research/vector_stores/implementations/faiss_store.py
+++ b/src/local_deep_research/vector_stores/implementations/faiss_store.py
@@ -577,8 +577,11 @@ class FaissVectorStore(BaseVectorStore):
# fsync the temp bytes BEFORE the rename so a crash/power-loss can't
# leave a renamed-but-unflushed (torn) index — the rename is only
# atomic w.r.t. what has actually reached disk.
- with open(tmp, "rb") as f:
- os.fsync(f.fileno())
+ try:
+ with open(tmp, "r+b") as f:
+ os.fsync(f.fileno())
+ except OSError:
+ pass # best-effort fsync
os.replace(tmp, path)
# fsync the directory so the rename itself is durable across a crash.
try:
diff --git a/tests/library/test_auto_indexing.py b/tests/library/test_auto_indexing.py
index c5c09fb322..56f3db7299 100644
--- a/tests/library/test_auto_indexing.py
+++ b/tests/library/test_auto_indexing.py
@@ -99,6 +99,7 @@ class TestTriggerAutoIndex:
mock_settings = MagicMock()
mock_settings.get_bool_setting.return_value = True
+ mock_settings.get_setting.return_value = 4
with patch(
"local_deep_research.research_library.routes.rag_routes.SettingsManager",
@@ -191,6 +192,7 @@ class TestTriggerAutoIndex:
mock_settings = MagicMock()
mock_settings.get_bool_setting.return_value = True
+ mock_settings.get_setting.return_value = 4
with patch(
"local_deep_research.research_library.routes.rag_routes.SettingsManager",
@@ -235,6 +237,12 @@ class TestTriggerAutoIndex:
assert call_args[0][2] == "my_collection"
assert call_args[0][3] == "alice"
assert call_args[0][4] == "secret123"
+ # The 5th positional is the resolved per-job parallel
+ # worker count (``rag.indexing_max_parallel_docs``).
+ # ``trigger_auto_index`` reads it from settings on the
+ # request thread (Flask context present) and forwards
+ # it positionally to the worker; clamped to ``[1, 16]``.
+ assert call_args[0][5] == 4
# The underlying worker has not run yet: the executor
# is mocked, so submit did not invoke the callable.
@@ -250,6 +258,7 @@ class TestTriggerAutoIndex:
"my_collection",
"alice",
"secret123",
+ 4,
)
# Slot released once the wrapped worker completed.
@@ -272,6 +281,7 @@ class TestTriggerAutoIndex:
mock_settings = MagicMock()
mock_settings.get_bool_setting.return_value = True
+ mock_settings.get_setting.return_value = 4
with patch(
"local_deep_research.research_library.routes.rag_routes.SettingsManager",
@@ -306,6 +316,7 @@ class TestTriggerAutoIndex:
mock_settings = MagicMock()
mock_settings.get_bool_setting.return_value = True
+ mock_settings.get_setting.return_value = 4
with patch(
"local_deep_research.research_library.routes.rag_routes.SettingsManager",
@@ -352,6 +363,7 @@ class TestTriggerAutoIndex:
mock_settings = MagicMock()
mock_settings.get_bool_setting.return_value = True
+ mock_settings.get_setting.return_value = 4
saturated = rag_module._MAX_PENDING_AUTO_INDEX_JOBS
original_pending = rag_module._pending_auto_index_jobs
@@ -425,6 +437,7 @@ class TestTriggerAutoIndex:
mock_settings = MagicMock()
mock_settings.get_bool_setting.return_value = True
+ mock_settings.get_setting.return_value = 4
with patch(
"local_deep_research.research_library.routes.rag_routes.SettingsManager",
@@ -501,6 +514,7 @@ class TestTriggerAutoIndex:
mock_settings = MagicMock()
mock_settings.get_bool_setting.return_value = True
+ mock_settings.get_setting.return_value = 4
with patch(
"local_deep_research.research_library.routes.rag_routes.SettingsManager",
@@ -554,6 +568,7 @@ class TestTriggerAutoIndex:
mock_settings = MagicMock()
mock_settings.get_bool_setting.return_value = True
+ mock_settings.get_setting.return_value = 4
with patch(
"local_deep_research.research_library.routes.rag_routes.SettingsManager",
@@ -610,6 +625,7 @@ class TestTriggerAutoIndex:
mock_settings = MagicMock()
mock_settings.get_bool_setting.return_value = True
+ mock_settings.get_setting.return_value = 4
# Non-zero baseline so a double-release is observable (the max(0,..)
# floor would otherwise mask it at baseline 0).
@@ -1031,7 +1047,22 @@ class TestAutoIndexDocumentsWorker:
"local_deep_research.research_library.routes.rag_routes._get_rag_service_for_thread"
) as mock_get_service:
mock_rag_service = MagicMock()
- mock_rag_service.index_document.return_value = {"status": "success"}
+ # Worker fans out to ``index_documents_parallel`` once with all
+ # docs, not one ``index_document`` call per doc. Return an
+ # aggregate shaped like a successful run.
+ mock_rag_service.index_documents_parallel.return_value = {
+ "successful": 3,
+ "skipped": 0,
+ "failed": 0,
+ "errors": [],
+ "results": {
+ "doc1": {"status": "success", "chunk_count": 1},
+ "doc2": {"status": "success", "chunk_count": 1},
+ "doc3": {"status": "success", "chunk_count": 1},
+ },
+ "cancelled": False,
+ "total": 3,
+ }
# Configure context manager behavior
mock_get_service.return_value.__enter__.return_value = (
mock_rag_service
@@ -1045,17 +1076,22 @@ class TestAutoIndexDocumentsWorker:
db_password="testpass",
)
- # Should have called index_document for each document
- assert mock_rag_service.index_document.call_count == 3
- mock_rag_service.index_document.assert_any_call(
- "doc1", "coll1", force_reindex=False
- )
- mock_rag_service.index_document.assert_any_call(
- "doc2", "coll1", force_reindex=False
- )
- mock_rag_service.index_document.assert_any_call(
- "doc3", "coll1", force_reindex=False
- )
+ # One fan-out call carries all docs through the parallel helper.
+ mock_rag_service.index_documents_parallel.assert_called_once()
+ call_args = mock_rag_service.index_documents_parallel.call_args
+ # ``doc_info`` is the first positional arg: list of (doc_id, "").
+ assert call_args[0][0] == [
+ ("doc1", ""),
+ ("doc2", ""),
+ ("doc3", ""),
+ ]
+ assert call_args[0][1] == "coll1"
+ assert call_args.kwargs.get("force_reindex") is False
+ # ``max_workers`` is passed positionally; default 4 for the
+ # thread-pool fan-out.
+ assert call_args.kwargs.get("max_workers") == 4
+ # ``index_document`` is no longer called by the worker.
+ mock_rag_service.index_document.assert_not_called()
def test_worker_handles_skipped_documents(self):
"""Test that the worker handles already indexed documents."""
@@ -1067,12 +1103,21 @@ class TestAutoIndexDocumentsWorker:
"local_deep_research.research_library.routes.rag_routes._get_rag_service_for_thread"
) as mock_get_service:
mock_rag_service = MagicMock()
- # First succeeds, second skipped, third succeeds
- mock_rag_service.index_document.side_effect = [
- {"status": "success"},
- {"status": "skipped"},
- {"status": "success"},
- ]
+ # Aggregate with mixed statuses (one skipped, two successful) -
+ # the parallel helper is what the worker talks to now.
+ mock_rag_service.index_documents_parallel.return_value = {
+ "successful": 2,
+ "skipped": 1,
+ "failed": 0,
+ "errors": [],
+ "results": {
+ "doc1": {"status": "success", "chunk_count": 1},
+ "doc2": {"status": "skipped", "chunk_count": 0},
+ "doc3": {"status": "success", "chunk_count": 1},
+ },
+ "cancelled": False,
+ "total": 3,
+ }
# Configure context manager behavior
mock_get_service.return_value.__enter__.return_value = (
mock_rag_service
@@ -1087,8 +1132,8 @@ class TestAutoIndexDocumentsWorker:
db_password="testpass",
)
- # All documents should have been attempted
- assert mock_rag_service.index_document.call_count == 3
+ # The worker used a single parallel-helper call, not per-doc.
+ mock_rag_service.index_documents_parallel.assert_called_once()
def test_worker_handles_indexing_exception(self):
"""Test that the worker handles exceptions during indexing."""
@@ -1100,7 +1145,9 @@ class TestAutoIndexDocumentsWorker:
"local_deep_research.research_library.routes.rag_routes._get_rag_service_for_thread"
) as mock_get_service:
mock_rag_service = MagicMock()
- mock_rag_service.index_document.side_effect = Exception(
+ # The worker talks to ``index_documents_parallel`` now. Make that
+ # call raise so the worker's outer try/except is exercised.
+ mock_rag_service.index_documents_parallel.side_effect = Exception(
"Index failed"
)
# Configure context manager behavior
@@ -1127,12 +1174,33 @@ class TestAutoIndexDocumentsWorker:
"local_deep_research.research_library.routes.rag_routes._get_rag_service_for_thread"
) as mock_get_service:
mock_rag_service = MagicMock()
- # First succeeds, second raises, third succeeds
- mock_rag_service.index_document.side_effect = [
- {"status": "success"},
- Exception("Index failed"),
- {"status": "success"},
- ]
+ # The worker calls ``index_documents_parallel`` once. The helper
+ # itself already absorbs per-doc failures (they show up as
+ # ``status="error"`` entries in the aggregate), so an aggregate
+ # with one failure + two successes is the realistic shape:
+ # the run continues, all docs are accounted for.
+ mock_rag_service.index_documents_parallel.return_value = {
+ "successful": 2,
+ "skipped": 0,
+ "failed": 1,
+ "errors": [
+ {
+ "doc_id": "doc2",
+ "title": "",
+ "error": "Index failed",
+ }
+ ],
+ "results": {
+ "doc1": {"status": "success", "chunk_count": 1},
+ "doc2": {
+ "status": "error",
+ "error": "Index failed",
+ },
+ "doc3": {"status": "success", "chunk_count": 1},
+ },
+ "cancelled": False,
+ "total": 3,
+ }
# Configure context manager behavior
mock_get_service.return_value.__enter__.return_value = (
mock_rag_service
@@ -1147,8 +1215,8 @@ class TestAutoIndexDocumentsWorker:
db_password="testpass",
)
- # All documents should have been attempted
- assert mock_rag_service.index_document.call_count == 3
+ # All three docs were passed to the parallel helper in one call.
+ mock_rag_service.index_documents_parallel.assert_called_once()
def test_worker_creates_rag_service_with_correct_params(self):
"""Test that the worker creates RAG service with correct parameters."""
@@ -1243,11 +1311,24 @@ class TestAutoIndexIntegration:
mock_rag_service = MagicMock()
- def index_and_signal(doc_id, collection_id, force_reindex=False):
+ def parallel_and_signal(doc_info, collection_id, **kwargs):
task_executed.set()
- return {"status": "success"}
-
- mock_rag_service.index_document.side_effect = index_and_signal
+ return {
+ "successful": len(doc_info),
+ "skipped": 0,
+ "failed": 0,
+ "errors": [],
+ "results": {
+ doc_id: {"status": "success", "chunk_count": 1}
+ for doc_id, _ in doc_info
+ },
+ "cancelled": False,
+ "total": len(doc_info),
+ }
+
+ mock_rag_service.index_documents_parallel.side_effect = (
+ parallel_and_signal
+ )
with patch(
"local_deep_research.database.session_context.get_user_db_session"
@@ -1257,6 +1338,7 @@ class TestAutoIndexIntegration:
mock_settings = MagicMock()
mock_settings.get_bool_setting.return_value = True
+ mock_settings.get_setting.return_value = 4
with patch(
"local_deep_research.research_library.routes.rag_routes.SettingsManager",
@@ -1299,14 +1381,28 @@ class TestAutoIndexIntegration:
mock_rag_service = MagicMock()
- def track_indexing(doc_id, collection_id, force_reindex=False):
+ def track_indexing(doc_info, collection_id, **kwargs):
+ # The parallel helper is now called per-upload-batch with a list
+ # of doc_ids; record all of them.
with docs_lock:
- indexed_docs.append(doc_id)
+ for doc_id, _ in doc_info:
+ indexed_docs.append(doc_id)
if len(indexed_docs) >= expected_count:
all_done.set()
- return {"status": "success"}
-
- mock_rag_service.index_document.side_effect = track_indexing
+ return {
+ "successful": len(doc_info),
+ "skipped": 0,
+ "failed": 0,
+ "errors": [],
+ "results": {
+ doc_id: {"status": "success", "chunk_count": 1}
+ for doc_id, _ in doc_info
+ },
+ "cancelled": False,
+ "total": len(doc_info),
+ }
+
+ mock_rag_service.index_documents_parallel.side_effect = track_indexing
with patch(
"local_deep_research.database.session_context.get_user_db_session"
@@ -1316,6 +1412,7 @@ class TestAutoIndexIntegration:
mock_settings = MagicMock()
mock_settings.get_bool_setting.return_value = True
+ mock_settings.get_setting.return_value = 4
with patch(
"local_deep_research.research_library.routes.rag_routes.SettingsManager",
@@ -1359,6 +1456,7 @@ class TestAutoIndexIntegration:
mock_settings = MagicMock()
mock_settings.get_bool_setting.return_value = True
+ mock_settings.get_setting.return_value = 4
with patch(
"local_deep_research.research_library.routes.rag_routes.SettingsManager",
diff --git a/tests/news/test_library_sweep.py b/tests/news/test_library_sweep.py
index fda8d64f3d..3a169cc75c 100644
--- a/tests/news/test_library_sweep.py
+++ b/tests/news/test_library_sweep.py
@@ -72,14 +72,70 @@ def _db_returning(case_a_rows, case_b_rows=None):
return db, query
+def _make_aggregate(doc_results):
+ """Build an aggregate dict from a ``{doc_id: result_dict}`` mapping.
+
+ Mirrors the shape returned by ``LibraryRAGService.index_documents_parallel``
+ so the reconciler's per-doc logging and counters stay driven by it.
+ """
+ successful = sum(
+ 1 for r in doc_results.values() if r.get("status") == "success"
+ )
+ skipped = sum(
+ 1 for r in doc_results.values() if r.get("status") == "skipped"
+ )
+ failed = sum(1 for r in doc_results.values() if r.get("status") == "error")
+ errors = [
+ {
+ "doc_id": doc_id,
+ "title": doc_results[doc_id].get("title", ""),
+ "error": doc_results[doc_id].get("error"),
+ }
+ for doc_id, r in doc_results.items()
+ if r.get("status") == "error"
+ ]
+ return {
+ "successful": successful,
+ "skipped": skipped,
+ "failed": failed,
+ "errors": errors,
+ "results": doc_results,
+ "cancelled": False,
+ "total": len(doc_results),
+ }
+
+
+def _default_parallel_side_effect(doc_info, collection_id, **kwargs):
+ """Default side effect for ``index_documents_parallel``: every doc succeeds.
+
+ Mirrors the legacy serial ``_rag_service().index_document.return_value``
+ shape so tests that don't care about per-doc outcomes keep passing with no
+ per-test mock wiring.
+ """
+ results = {
+ doc_id: {"status": "success", "chunk_count": 3}
+ for doc_id, _ in doc_info
+ }
+ return _make_aggregate(results)
+
+
def _rag_service():
- """Return a MagicMock RAG service usable as a context manager that reports
- successful indexing.
+ """Return a MagicMock RAG service usable as a context manager.
+
+ The reconciler routes indexing through ``index_documents_parallel`` since
+ PR #5119 (bounded ``ThreadPoolExecutor`` fan-out around
+ ``index_document``). The default side effect makes every doc succeed so
+ tests that don't care about per-doc outcomes keep working unchanged;
+ tests that do care override ``index_documents_parallel.side_effect``.
+ ``index_document`` is kept as a no-op stub for legacy callers that still
+ hit it (e.g. inside the parallel helper itself, which is mocked away in
+ these tests).
"""
rag = MagicMock()
rag.__enter__ = MagicMock(return_value=rag)
rag.__exit__ = MagicMock(return_value=False)
rag.index_document.return_value = {"status": "success", "chunk_count": 3}
+ rag.index_documents_parallel.side_effect = _default_parallel_side_effect
return rag
@@ -138,9 +194,10 @@ def test_reconciler_indexes_in_collection_unindexed_when_enabled():
):
scheduler._reconcile_unindexed_documents("testuser")
- # Each in-collection unindexed doc indexed exactly once, never reindexed.
- assert rag_service.index_document.call_count == 3
- for call in rag_service.index_document.call_args_list:
+ # Each distinct collection fans out through index_documents_parallel once
+ # (carrying all its docs); force_reindex is forwarded verbatim.
+ assert rag_service.index_documents_parallel.call_count == 2
+ for call in rag_service.index_documents_parallel.call_args_list:
assert call.kwargs["force_reindex"] is False
# One RAG service built per distinct collection (A, B). No orphans here so
@@ -176,11 +233,12 @@ def test_reconciler_ingests_and_indexes_research_orphan():
):
scheduler._reconcile_unindexed_documents("testuser")
- # The orphan was indexed into the DEFAULT library collection.
- rag_service.index_document.assert_called_once()
- call = rag_service.index_document.call_args
- assert call.kwargs["document_id"] == "orphan-doc"
- assert call.kwargs["collection_id"] == "default-lib"
+ # The orphan was indexed into the DEFAULT library collection via a
+ # single parallel-helper call (carrying the (orphan-doc, "") doc_info).
+ rag_service.index_documents_parallel.assert_called_once()
+ call = rag_service.index_documents_parallel.call_args
+ assert call.args[0] == [("orphan-doc", "")]
+ assert call.args[1] == "default-lib"
assert call.kwargs["force_reindex"] is False
# The RAG service for the orphan path was built for the default library.
@@ -215,11 +273,11 @@ def test_reconciler_runs_for_generate_rag_only_no_regression():
):
scheduler._reconcile_unindexed_documents("testuser")
- # generate_rag alone is enough to drive the reconciler.
- rag_service.index_document.assert_called_once()
+ # generate_rag alone is enough to drive the reconciler: the orphan
+ # fan-out hits the default-library collection via the parallel helper.
+ rag_service.index_documents_parallel.assert_called_once()
assert (
- rag_service.index_document.call_args.kwargs["collection_id"]
- == "default-lib"
+ rag_service.index_documents_parallel.call_args.args[1] == "default-lib"
)
@@ -317,10 +375,16 @@ def test_reconciler_caps_each_case_at_its_own_batch_budget():
db, query = _db_returning(rows, case_b_rows=[("orphan-doc",)])
rag_service = _rag_service()
- rag_service.index_document.return_value = {
- "status": "success",
- "chunk_count": 1,
- }
+ # Ensure the default side effect matches the per-doc shape these tests
+ # assert against (chunk_count=1).
+ rag_service.index_documents_parallel.side_effect = (
+ lambda doc_info, collection_id, **kwargs: _make_aggregate(
+ {
+ doc_id: {"status": "success", "chunk_count": 1}
+ for doc_id, _ in doc_info
+ }
+ )
+ )
with (
patch.object(
@@ -341,12 +405,12 @@ def test_reconciler_caps_each_case_at_its_own_batch_budget():
((_LIBRARY_SWEEP_BATCH,), {}),
((_LIBRARY_SWEEP_BATCH,), {}),
]
- # Case (a) docs (BATCH) plus the one orphan were all indexed: the orphan was
- # NOT starved by a full case (a).
- assert rag_service.index_document.call_count == _LIBRARY_SWEEP_BATCH + 1
+ # The reconciler fans out via index_documents_parallel once per case:
+ # case (a) for coll-A's batch, case (b) for the orphan. The parallel
+ # helper itself accounts for the BATCH+1 docs across the two calls.
+ assert rag_service.index_documents_parallel.call_count == 2
indexed_collections = {
- c.kwargs["collection_id"]
- for c in rag_service.index_document.call_args_list
+ c.args[1] for c in rag_service.index_documents_parallel.call_args_list
}
assert indexed_collections == {"coll-A", "default-lib"}
@@ -369,11 +433,22 @@ def test_reconciler_per_doc_error_does_not_crash_tick_or_leak_password(
)
rag_service = _rag_service()
- # First doc raises an error containing the password; second succeeds.
- rag_service.index_document.side_effect = [
- RuntimeError("boom with secret testpass inside"),
- {"status": "success", "chunk_count": 2},
- ]
+
+ def _parallel_with_error(doc_info, collection_id, **kwargs):
+ # First doc fails with a password-bearing error; second succeeds. The
+ # parallel helper aggregates per-doc outcomes, so we hand back an
+ # aggregate directly with one error + one success.
+ return _make_aggregate(
+ {
+ "doc-1": {
+ "status": "error",
+ "error": "boom with secret testpass inside",
+ },
+ "doc-2": {"status": "success", "chunk_count": 2},
+ }
+ )
+
+ rag_service.index_documents_parallel.side_effect = _parallel_with_error
with loguru_caplog_full.at_level("DEBUG"):
with (
@@ -388,8 +463,9 @@ def test_reconciler_per_doc_error_does_not_crash_tick_or_leak_password(
# Must not raise even though the first doc errored.
scheduler._reconcile_unindexed_documents("testuser")
- # Both docs were attempted (the error didn't abort the loop).
- assert rag_service.index_document.call_count == 2
+ # One parallel-helper call carries both docs (the helper itself absorbs
+ # per-doc failures into the aggregate's errors list).
+ assert rag_service.index_documents_parallel.call_count == 1
text = loguru_caplog_full.text
# The per-doc error handler ran (path exercised) ...
assert "[RECONCILER] Failed to index document" in text
@@ -607,15 +683,27 @@ def test_case_b_not_starved_when_case_a_full_batch_all_fail():
db, _ = _db_returning(case_a, case_b_rows=[("orphan-doc",)])
# One service object, used for BOTH the per-collection path (coll-A) and the
- # default-library path. Case-(a) docs always raise; the orphan succeeds.
+ # default-library path. Case-(a) docs always error out; the orphan succeeds.
rag_service = _rag_service()
- def index_side_effect(*, document_id, collection_id, force_reindex):
+ def parallel_side_effect(doc_info, collection_id, **kwargs):
+ # Per-collection path: every doc errors. Orphan path: success.
if collection_id == "coll-A":
- raise RuntimeError(f"index failed for {document_id}")
- return {"status": "success", "chunk_count": 1}
-
- rag_service.index_document.side_effect = index_side_effect
+ results = {
+ doc_id: {
+ "status": "error",
+ "error": f"index failed for {doc_id}",
+ }
+ for doc_id, _ in doc_info
+ }
+ else:
+ results = {
+ doc_id: {"status": "success", "chunk_count": 1}
+ for doc_id, _ in doc_info
+ }
+ return _make_aggregate(results)
+
+ rag_service.index_documents_parallel.side_effect = parallel_side_effect
with (
patch.object(
@@ -632,11 +720,11 @@ def test_case_b_not_starved_when_case_a_full_batch_all_fail():
# whole batch with failures: case (b) is not starved.
orphan_calls = [
c
- for c in rag_service.index_document.call_args_list
- if c.kwargs["collection_id"] == "default-lib"
+ for c in rag_service.index_documents_parallel.call_args_list
+ if c.args[1] == "default-lib"
]
assert len(orphan_calls) == 1
- assert orphan_calls[0].kwargs["document_id"] == "orphan-doc"
+ assert orphan_calls[0].args[0] == [("orphan-doc", "")]
# ---------------------------------------------------------------------------
@@ -754,11 +842,16 @@ def test_case_a_predicate_selects_only_unindexed_with_text_real_db():
rag_service = _rag_service()
indexed_ids = []
- rag_service.index_document.side_effect = (
- lambda *, document_id, collection_id, force_reindex: (
- indexed_ids.append(document_id)
- or {"status": "success", "chunk_count": 1}
- )
+ rag_service.index_documents_parallel.side_effect = (
+ lambda doc_info, collection_id, **kwargs: (
+ [indexed_ids.append(doc_id) for doc_id, _ in doc_info],
+ _make_aggregate(
+ {
+ doc_id: {"status": "success", "chunk_count": 1}
+ for doc_id, _ in doc_info
+ }
+ ),
+ )[-1]
)
with (
@@ -772,14 +865,14 @@ def test_case_a_predicate_selects_only_unindexed_with_text_real_db():
):
scheduler._reconcile_unindexed_documents("testuser")
- # Only the unindexed, text-bearing, in-collection doc was selected for case
- # (a). (doc-indexed excluded by indexed.is_(False); doc-notext excluded by
- # text_content.isnot(None).)
- case_a_indexed = [
- i for i in indexed_ids if i in {"doc-unindexed", "doc-indexed"}
- ]
- assert case_a_indexed == ["doc-unindexed"]
- assert "doc-notext" not in indexed_ids
+ # Only the unindexed, text-bearing, in-collection doc was selected for case
+ # (a). (doc-indexed excluded by indexed.is_(False); doc-notext excluded by
+ # text_content.isnot(None).)
+ case_a_indexed = [
+ i for i in indexed_ids if i in {"doc-unindexed", "doc-indexed"}
+ ]
+ assert case_a_indexed == ["doc-unindexed"]
+ assert "doc-notext" not in indexed_ids
def test_case_b_predicate_selects_research_orphans_real_db():
@@ -817,12 +910,19 @@ def test_case_b_predicate_selects_research_orphans_real_db():
rag_service = _rag_service()
indexed_into_default = []
- rag_service.index_document.side_effect = (
- lambda *, document_id, collection_id, force_reindex: (
- indexed_into_default.append((document_id, collection_id))
- or {"status": "success", "chunk_count": 1}
+
+ def parallel_side_effect(doc_info, collection_id, **kwargs):
+ indexed_into_default.extend(
+ (doc_id, collection_id) for doc_id, _ in doc_info
)
- )
+ return _make_aggregate(
+ {
+ doc_id: {"status": "success", "chunk_count": 1}
+ for doc_id, _ in doc_info
+ }
+ )
+
+ rag_service.index_documents_parallel.side_effect = parallel_side_effect
with (
patch.object(
@@ -888,10 +988,13 @@ def test_per_collection_error_isolated_other_collections_still_indexed():
scheduler._reconcile_unindexed_documents("testuser")
# coll-A's doc was indexed despite coll-B failing (cross-collection
- # isolation).
+ # isolation). The reconciler now hands the doc-batch to
+ # index_documents_parallel, so we look at the parallel call's doc_info
+ # to confirm doc-a made it through.
indexed_docs = {
- c.kwargs["document_id"]
- for c in good_service.index_document.call_args_list
+ doc_id
+ for c in good_service.index_documents_parallel.call_args_list
+ for doc_id, _ in c.args[0]
}
assert indexed_docs == {"doc-a"}
# The per-collection handler rolled back the poisoned session at least once.
@@ -1022,11 +1125,17 @@ def test_case_a_selection_is_randomized_not_deterministic_real_db():
last_draw: set = set()
rag_service = _rag_service()
- def index_side_effect(*, document_id, collection_id, force_reindex):
- last_draw.add(document_id)
- return {"status": "success", "chunk_count": 1}
+ def parallel_side_effect(doc_info, collection_id, **kwargs):
+ for doc_id, _ in doc_info:
+ last_draw.add(doc_id)
+ return _make_aggregate(
+ {
+ doc_id: {"status": "success", "chunk_count": 1}
+ for doc_id, _ in doc_info
+ }
+ )
- rag_service.index_document.side_effect = index_side_effect
+ rag_service.index_documents_parallel.side_effect = parallel_side_effect
draws = []
with (
@@ -1093,11 +1202,17 @@ def test_case_b_orphan_selection_is_randomized_not_deterministic_real_db():
last_draw: set = set()
rag_service = _rag_service()
- def index_side_effect(*, document_id, collection_id, force_reindex):
- last_draw.add(document_id)
- return {"status": "success", "chunk_count": 1}
+ def parallel_side_effect(doc_info, collection_id, **kwargs):
+ for doc_id, _ in doc_info:
+ last_draw.add(doc_id)
+ return _make_aggregate(
+ {
+ doc_id: {"status": "success", "chunk_count": 1}
+ for doc_id, _ in doc_info
+ }
+ )
- rag_service.index_document.side_effect = index_side_effect
+ rag_service.index_documents_parallel.side_effect = parallel_side_effect
draws = []
with (
@@ -1156,8 +1271,15 @@ def test_partial_case_a_budget_orphan_uses_own_full_budget():
((_LIBRARY_SWEEP_BATCH,), {}),
((_LIBRARY_SWEEP_BATCH,), {}),
]
- # Total work = N case-(a) docs + 1 orphan, all bounded.
- assert rag_service.index_document.call_count == n + 1
+ # The reconciler fans out via index_documents_parallel once per case
+ # (case-a for coll-A, case-b for the orphan). The n+1 doc total is
+ # distributed across those two parallel calls.
+ assert rag_service.index_documents_parallel.call_count == 2
+ total_indexed = sum(
+ len(c.args[0])
+ for c in rag_service.index_documents_parallel.call_args_list
+ )
+ assert total_indexed == n + 1
# ---------------------------------------------------------------------------
diff --git a/tests/research_library/routes/test_rag_routes_background_coverage.py b/tests/research_library/routes/test_rag_routes_background_coverage.py
index 2415391b24..3392626151 100644
--- a/tests/research_library/routes/test_rag_routes_background_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_background_coverage.py
@@ -227,7 +227,7 @@ class TestAutoIndexDocumentsWorkerBackground:
"""Additional coverage for _auto_index_documents_worker."""
def test_mixed_results_counts_successes_only(self):
- """Worker counts successes while handling skips and per-doc failures."""
+ """Worker handles a parallel aggregate with mixed results without raising."""
from local_deep_research.research_library.routes.rag_routes import (
_auto_index_documents_worker,
)
@@ -235,23 +235,46 @@ class TestAutoIndexDocumentsWorkerBackground:
mock_service = Mock()
mock_service.__enter__ = Mock(return_value=mock_service)
mock_service.__exit__ = Mock(return_value=False)
- mock_service.index_document.side_effect = [
- {"status": "success"},
- {"status": "skipped"},
- RuntimeError("doc3 failed"),
- {"status": "success"},
- ]
+ mock_service.index_documents_parallel.return_value = {
+ "successful": 2,
+ "skipped": 1,
+ "failed": 1,
+ "errors": [
+ {
+ "doc_id": "d3",
+ "title": "",
+ "error": "Indexing failed: RuntimeError",
+ }
+ ],
+ "results": {
+ "d1": {"status": "success"},
+ "d2": {"status": "skipped"},
+ "d3": {
+ "status": "error",
+ "error": "Indexing failed: RuntimeError",
+ },
+ "d4": {"status": "success"},
+ },
+ "cancelled": False,
+ "total": 4,
+ }
with patch(
f"{MODULE}._get_rag_service_for_thread", return_value=mock_service
):
- # Should not raise despite the exception on doc3
+ # Should not raise despite the failing doc
_auto_index_documents_worker(
["d1", "d2", "d3", "d4"], "coll-1", "user", "pass"
)
- # All four documents were attempted
- assert mock_service.index_document.call_count == 4
+ # The worker should have dispatched all four doc ids to the
+ # parallel helper, which aggregates per-doc outcomes.
+ mock_service.index_documents_parallel.assert_called_once()
+ call_args = mock_service.index_documents_parallel.call_args
+ doc_info = call_args.kwargs.get("doc_info")
+ if doc_info is None:
+ doc_info = call_args.args[0]
+ assert [d for d, _ in doc_info] == ["d1", "d2", "d3", "d4"]
# ---------------------------------------------------------------------------
@@ -320,7 +343,34 @@ class TestBackgroundIndexWorkerBackground:
)
mock_svc = _make_rag_service_mock()
- mock_svc.index_document.return_value = {"status": "success"}
+
+ # The worker hands a progress_callback to index_documents_parallel;
+ # invoke it so the filename-fallback logic surfaces via
+ # _update_task_status.
+ def _parallel_side_effect(
+ doc_info,
+ collection_id,
+ force_reindex=False,
+ max_workers=4,
+ progress_callback=None,
+ is_cancelled=None,
+ ):
+ if progress_callback is not None:
+ for i, (doc_id, title) in enumerate(doc_info, 1):
+ progress_callback(i, len(doc_info), title, "success")
+ return {
+ "successful": len(doc_info),
+ "skipped": 0,
+ "failed": 0,
+ "errors": [],
+ "results": {
+ doc_id: {"status": "success"} for doc_id, _ in doc_info
+ },
+ "cancelled": False,
+ "total": len(doc_info),
+ }
+
+ mock_svc.index_documents_parallel.side_effect = _parallel_side_effect
mock_coll = Mock()
mock_coll.embedding_model = "model"
@@ -371,13 +421,43 @@ class TestBackgroundIndexWorkerBackground:
assert any("My Document Title" in msg for msg in progress_msgs)
def test_unknown_index_status_counts_as_failed(self):
- """When index_document returns an unrecognized status, it counts as failed."""
+ """When index_documents_parallel reports a non-success status, it counts as failed."""
from local_deep_research.research_library.routes.rag_routes import (
_background_index_worker,
)
mock_svc = _make_rag_service_mock()
- mock_svc.index_document.return_value = {"status": "error"}
+
+ def _parallel_side_effect(
+ doc_info,
+ collection_id,
+ force_reindex=False,
+ max_workers=4,
+ progress_callback=None,
+ is_cancelled=None,
+ ):
+ if progress_callback is not None:
+ for i, (doc_id, title) in enumerate(doc_info, 1):
+ progress_callback(i, len(doc_info), title, "error")
+ return {
+ "successful": 0,
+ "skipped": 0,
+ "failed": 1,
+ "errors": [
+ {
+ "doc_id": doc_info[0][0],
+ "title": doc_info[0][1],
+ "error": "Unknown index status: error",
+ }
+ ],
+ "results": {
+ doc_info[0][0]: {"status": "error", "error": "..."}
+ },
+ "cancelled": False,
+ "total": len(doc_info),
+ }
+
+ mock_svc.index_documents_parallel.side_effect = _parallel_side_effect
mock_coll = Mock()
mock_coll.embedding_model = "model"
@@ -436,13 +516,23 @@ class TestBackgroundIndexWorkerBackground:
assert "0 indexed" in final_msg
def test_cancellation_after_first_document(self):
- """Worker stops after indexing first document when cancelled before second."""
+ """Worker reports cancelled status when parallel helper reports cancellation after first doc."""
from local_deep_research.research_library.routes.rag_routes import (
_background_index_worker,
)
mock_svc = _make_rag_service_mock()
- mock_svc.index_document.return_value = {"status": "success"}
+ # Simulate the parallel helper: one doc completed before
+ # cancellation fired mid-flight, second never started.
+ mock_svc.index_documents_parallel.return_value = {
+ "successful": 1,
+ "skipped": 0,
+ "failed": 0,
+ "errors": [],
+ "results": {"d1": {"status": "success"}},
+ "cancelled": True,
+ "total": 2,
+ }
mock_coll = Mock()
mock_coll.embedding_model = "model"
@@ -481,7 +571,10 @@ class TestBackgroundIndexWorkerBackground:
def track_status(username, db_password, task_id, **kwargs):
statuses.append(kwargs)
- # Cancel after the first document (False on first check, True on second)
+ # _is_task_cancelled is no longer polled by the worker itself
+ # (the parallel helper handles cancellation between completions),
+ # but the patch stays for backwards-compat coverage in case the
+ # worker re-introduces a direct check.
cancel_calls = {"n": 0}
def cancel_side_effect(*a, **kw):
@@ -502,8 +595,13 @@ class TestBackgroundIndexWorkerBackground:
"task-1", "coll-1", "user", "pass", force_reindex=False
)
- # First document should have been indexed
- assert mock_svc.index_document.call_count == 1
+ # Parallel helper was invoked with both doc ids
+ mock_svc.index_documents_parallel.assert_called_once()
+ call_args = mock_svc.index_documents_parallel.call_args
+ doc_info = call_args.kwargs.get("doc_info")
+ if doc_info is None:
+ doc_info = call_args.args[0]
+ assert [d for d, _ in doc_info] == ["d1", "d2"]
# Task should be marked cancelled
assert any(s.get("status") == "cancelled" for s in statuses)
cancel_msg = next(
diff --git a/tests/research_library/routes/test_rag_routes_deep_coverage.py b/tests/research_library/routes/test_rag_routes_deep_coverage.py
index 8cc1c63461..3796ecf649 100644
--- a/tests/research_library/routes/test_rag_routes_deep_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_deep_coverage.py
@@ -290,7 +290,7 @@ class TestAutoIndexDocumentsWorker:
"""Tests for _auto_index_documents_worker background worker."""
def test_successful_indexing(self):
- """Worker indexes documents successfully."""
+ """Worker indexes documents successfully via parallel helper."""
from local_deep_research.research_library.routes.rag_routes import (
_auto_index_documents_worker,
)
@@ -298,7 +298,18 @@ class TestAutoIndexDocumentsWorker:
mock_service = Mock()
mock_service.__enter__ = Mock(return_value=mock_service)
mock_service.__exit__ = Mock(return_value=False)
- mock_service.index_document.return_value = {"status": "success"}
+ mock_service.index_documents_parallel.return_value = {
+ "successful": 2,
+ "skipped": 0,
+ "failed": 0,
+ "errors": [],
+ "results": {
+ "doc1": {"status": "success"},
+ "doc2": {"status": "success"},
+ },
+ "cancelled": False,
+ "total": 2,
+ }
with (
patch(
@@ -311,10 +322,15 @@ class TestAutoIndexDocumentsWorker:
["doc1", "doc2"], "coll-1", "user", "pass"
)
- assert mock_service.index_document.call_count == 2
+ mock_service.index_documents_parallel.assert_called_once()
+ call_args = mock_service.index_documents_parallel.call_args
+ doc_info = call_args.kwargs.get("doc_info")
+ if doc_info is None:
+ doc_info = call_args.args[0]
+ assert [d for d, _ in doc_info] == ["doc1", "doc2"]
def test_skipped_documents(self):
- """Worker handles already-indexed documents."""
+ """Worker handles already-indexed documents via parallel helper."""
from local_deep_research.research_library.routes.rag_routes import (
_auto_index_documents_worker,
)
@@ -322,7 +338,15 @@ class TestAutoIndexDocumentsWorker:
mock_service = Mock()
mock_service.__enter__ = Mock(return_value=mock_service)
mock_service.__exit__ = Mock(return_value=False)
- mock_service.index_document.return_value = {"status": "skipped"}
+ mock_service.index_documents_parallel.return_value = {
+ "successful": 0,
+ "skipped": 1,
+ "failed": 0,
+ "errors": [],
+ "results": {"doc1": {"status": "skipped"}},
+ "cancelled": False,
+ "total": 1,
+ }
with (
patch(
@@ -333,10 +357,10 @@ class TestAutoIndexDocumentsWorker:
):
_auto_index_documents_worker(["doc1"], "coll-1", "user", "pass")
- mock_service.index_document.assert_called_once()
+ mock_service.index_documents_parallel.assert_called_once()
def test_per_document_exception_continues(self):
- """Worker continues indexing after per-document exception."""
+ """Worker continues past per-document failures when helper reports a mixed aggregate."""
from local_deep_research.research_library.routes.rag_routes import (
_auto_index_documents_worker,
)
@@ -344,10 +368,27 @@ class TestAutoIndexDocumentsWorker:
mock_service = Mock()
mock_service.__enter__ = Mock(return_value=mock_service)
mock_service.__exit__ = Mock(return_value=False)
- mock_service.index_document.side_effect = [
- RuntimeError("fail"),
- {"status": "success"},
- ]
+ mock_service.index_documents_parallel.return_value = {
+ "successful": 1,
+ "skipped": 0,
+ "failed": 1,
+ "errors": [
+ {
+ "doc_id": "doc1",
+ "title": "",
+ "error": "Indexing failed: RuntimeError",
+ }
+ ],
+ "results": {
+ "doc1": {
+ "status": "error",
+ "error": "Indexing failed: RuntimeError",
+ },
+ "doc2": {"status": "success"},
+ },
+ "cancelled": False,
+ "total": 2,
+ }
with patch(
f"{MODULE}._get_rag_service_for_thread", return_value=mock_service
@@ -357,7 +398,7 @@ class TestAutoIndexDocumentsWorker:
["doc1", "doc2"], "coll-1", "user", "pass"
)
- assert mock_service.index_document.call_count == 2
+ mock_service.index_documents_parallel.assert_called_once()
def test_outer_exception_logged(self):
"""Worker handles outer exception (e.g., service creation failure)."""
@@ -1354,6 +1395,64 @@ class TestUpdateTaskStatusEdgeCases:
# status should not have been changed
assert mock_task.status == "processing"
+ def test_does_not_overwrite_cancelled_with_completed(self):
+ """Once task status is 'cancelled', updating it to 'completed' is ignored."""
+ from local_deep_research.research_library.routes.rag_routes import (
+ _update_task_status,
+ )
+
+ mock_task = Mock()
+ mock_task.status = "cancelled"
+ mock_task.progress_message = "Cancelled"
+ db_session = _make_db_session()
+ q = _build_mock_query(first_result=mock_task)
+ db_session.query = Mock(return_value=q)
+
+ @contextmanager
+ def fake_session(*a, **kw):
+ yield db_session
+
+ with patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session):
+ _update_task_status(
+ "user",
+ "pass",
+ "task-1",
+ status="completed",
+ progress_message="Should be ignored",
+ )
+
+ assert mock_task.status == "cancelled"
+ assert mock_task.progress_message == "Cancelled"
+
+ def test_does_not_overwrite_failed_with_completed(self):
+ """Once task status is 'failed', updating it to 'completed' is ignored."""
+ from local_deep_research.research_library.routes.rag_routes import (
+ _update_task_status,
+ )
+
+ mock_task = Mock()
+ mock_task.status = "failed"
+ mock_task.progress_message = "Failed"
+ db_session = _make_db_session()
+ q = _build_mock_query(first_result=mock_task)
+ db_session.query = Mock(return_value=q)
+
+ @contextmanager
+ def fake_session(*a, **kw):
+ yield db_session
+
+ with patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session):
+ _update_task_status(
+ "user",
+ "pass",
+ "task-1",
+ status="completed",
+ progress_message="Should be ignored",
+ )
+
+ assert mock_task.status == "failed"
+ assert mock_task.progress_message == "Failed"
+
# ---------------------------------------------------------------------------
# _is_task_cancelled: non-cancelled status
diff --git a/tests/research_library/routes/test_rag_routes_gaps_coverage.py b/tests/research_library/routes/test_rag_routes_gaps_coverage.py
index 14ee1e5949..4aa9c69d70 100644
--- a/tests/research_library/routes/test_rag_routes_gaps_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_gaps_coverage.py
@@ -372,7 +372,35 @@ class TestIndexCollection:
db_session.query = Mock(side_effect=query_side_effect)
mock_rag = Mock()
- mock_rag.index_document.return_value = {"status": "success"}
+
+ # The SSE generator calls index_documents_parallel on a worker
+ # thread and drains a progress queue. The mock's side_effect
+ # drives the queue by invoking the progress callback for each
+ # doc and then returning the aggregate.
+ def _parallel_side_effect(
+ doc_info,
+ collection_id,
+ force_reindex=False,
+ max_workers=4,
+ progress_callback=None,
+ is_cancelled=None,
+ ):
+ if progress_callback is not None:
+ for i, (doc_id, title) in enumerate(doc_info, 1):
+ progress_callback(i, len(doc_info), title, "success")
+ return {
+ "successful": len(doc_info),
+ "skipped": 0,
+ "failed": 0,
+ "errors": [],
+ "results": {
+ doc_id: {"status": "success"} for doc_id, _ in doc_info
+ },
+ "cancelled": False,
+ "total": len(doc_info),
+ }
+
+ mock_rag.index_documents_parallel.side_effect = _parallel_side_effect
with _auth_client(
app,
@@ -427,7 +455,40 @@ class TestIndexCollection:
db_session.query = Mock(side_effect=query_side_effect)
mock_rag = Mock()
- mock_rag.index_document.side_effect = RuntimeError("Parse error")
+
+ def _parallel_side_effect(
+ doc_info,
+ collection_id,
+ force_reindex=False,
+ max_workers=4,
+ progress_callback=None,
+ is_cancelled=None,
+ ):
+ if progress_callback is not None:
+ for i, (doc_id, title) in enumerate(doc_info, 1):
+ progress_callback(i, len(doc_info), title, "error")
+ return {
+ "successful": 0,
+ "skipped": 0,
+ "failed": 1,
+ "errors": [
+ {
+ "doc_id": doc_info[0][0],
+ "title": doc_info[0][1],
+ "error": "RuntimeError: Parse error",
+ }
+ ],
+ "results": {
+ doc_info[0][0]: {
+ "status": "error",
+ "error": "Indexing failed: RuntimeError",
+ }
+ },
+ "cancelled": False,
+ "total": len(doc_info),
+ }
+
+ mock_rag.index_documents_parallel.side_effect = _parallel_side_effect
with _auth_client(
app,
@@ -478,7 +539,31 @@ class TestIndexCollection:
db_session.query = Mock(side_effect=query_side_effect)
mock_rag = Mock()
- mock_rag.index_document.return_value = {"status": "skipped"}
+
+ def _parallel_side_effect(
+ doc_info,
+ collection_id,
+ force_reindex=False,
+ max_workers=4,
+ progress_callback=None,
+ is_cancelled=None,
+ ):
+ if progress_callback is not None:
+ for i, (doc_id, title) in enumerate(doc_info, 1):
+ progress_callback(i, len(doc_info), title, "skipped")
+ return {
+ "successful": 0,
+ "skipped": len(doc_info),
+ "failed": 0,
+ "errors": [],
+ "results": {
+ doc_id: {"status": "skipped"} for doc_id, _ in doc_info
+ },
+ "cancelled": False,
+ "total": len(doc_info),
+ }
+
+ mock_rag.index_documents_parallel.side_effect = _parallel_side_effect
with _auth_client(
app,
@@ -954,8 +1039,14 @@ class TestClearedStatusIsSkippedNotFailed:
)
mock_rag = Mock()
- mock_rag.index_documents_batch.return_value = {
- "doc-1": {"status": "cleared"}
+ mock_rag.index_documents_parallel.return_value = {
+ "successful": 0,
+ "skipped": 1,
+ "failed": 0,
+ "errors": [],
+ "results": {"doc-1": {"status": "cleared"}},
+ "cancelled": False,
+ "total": 1,
}
with (
@@ -1010,7 +1101,15 @@ class TestClearedStatusIsSkippedNotFailed:
db_session.query = Mock(side_effect=query_side_effect)
mock_rag = Mock()
- mock_rag.index_document.return_value = {"status": "cleared"}
+ mock_rag.index_documents_parallel.return_value = {
+ "successful": 0,
+ "skipped": 1,
+ "failed": 0,
+ "errors": [],
+ "results": {"doc-1": {"status": "cleared"}},
+ "cancelled": False,
+ "total": 1,
+ }
with _auth_client(
app,
@@ -1037,7 +1136,15 @@ class TestClearedStatusIsSkippedNotFailed:
mock_svc = Mock()
mock_svc.__enter__ = Mock(return_value=mock_svc)
mock_svc.__exit__ = Mock(return_value=False)
- mock_svc.index_document.return_value = {"status": "cleared"}
+ mock_svc.index_documents_parallel.return_value = {
+ "successful": 0,
+ "skipped": 1,
+ "failed": 0,
+ "errors": [],
+ "results": {"doc-1": {"status": "cleared"}},
+ "cancelled": False,
+ "total": 1,
+ }
mock_coll = Mock()
mock_coll.embedding_model = "model"
diff --git a/tests/research_library/routes/test_rag_routes_indexing_coverage.py b/tests/research_library/routes/test_rag_routes_indexing_coverage.py
index 7dcb1640cf..8d730df9c5 100644
--- a/tests/research_library/routes/test_rag_routes_indexing_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_indexing_coverage.py
@@ -522,18 +522,28 @@ class TestBackgroundIndexWorker:
)
def test_background_worker_cancellation(self):
- """Worker stops mid-loop when _is_task_cancelled returns True."""
+ """Worker reports cancelled when parallel helper reports cancellation."""
from local_deep_research.research_library.routes.rag_routes import (
_background_index_worker,
)
mock_svc = self._make_rag_service_mock()
- mock_svc.index_document.return_value = {"status": "success"}
+ # The parallel helper short-circuits before processing any doc.
+ mock_svc.index_documents_parallel.return_value = {
+ "successful": 0,
+ "skipped": 0,
+ "failed": 0,
+ "errors": [],
+ "results": {},
+ "cancelled": True,
+ "total": 2,
+ }
mock_coll = Mock()
mock_coll.embedding_model = "model"
- # Create two doc links so the loop has something to iterate
+ # Create two doc links so the worker has something to hand to the
+ # parallel helper (the helper itself decides to short-circuit).
doc1 = Mock()
doc1.filename = "file1.txt"
doc1.title = "Title 1"
@@ -569,7 +579,9 @@ class TestBackgroundIndexWorker:
def fake_update(username, db_password, task_id, **kwargs):
updated_statuses.append(kwargs)
- # _is_task_cancelled returns True on first call (before doc1 is indexed)
+ # _is_task_cancelled is now polled by the parallel helper, not the
+ # worker directly. Patch stays for backwards-compat coverage but
+ # isn't invoked in this path because the helper is mocked.
with (
patch(
f"{MODULE}._get_rag_service_for_thread", return_value=mock_svc
@@ -584,8 +596,8 @@ class TestBackgroundIndexWorker:
# Should have been marked as cancelled
assert any(s.get("status") == "cancelled" for s in updated_statuses)
- # index_document must not have been called (cancelled before first doc)
- mock_svc.index_document.assert_not_called()
+ # The parallel helper was invoked once with both doc ids.
+ mock_svc.index_documents_parallel.assert_called_once()
def test_background_worker_no_documents(self):
"""No documents in collection → task marked completed with 0 indexed."""
@@ -666,17 +678,30 @@ class TestBackgroundIndexWorker:
link_skip = Mock()
link_fail = Mock()
- call_count = {"n": 0}
-
- def index_side_effect(document_id, collection_id, force_reindex):
- call_count["n"] += 1
- if document_id == "doc-ok":
- return {"status": "success"}
- if document_id == "doc-skip":
- return {"status": "skipped"}
- raise RuntimeError("indexing exploded")
-
- mock_svc.index_document.side_effect = index_side_effect
+ # The parallel helper aggregates per-doc outcomes; the worker
+ # only reads the final tallies.
+ mock_svc.index_documents_parallel.return_value = {
+ "successful": 1,
+ "skipped": 1,
+ "failed": 1,
+ "errors": [
+ {
+ "doc_id": "doc-fail",
+ "title": "fail.txt",
+ "error": "Indexing failed: RuntimeError",
+ }
+ ],
+ "results": {
+ "doc-ok": {"status": "success"},
+ "doc-skip": {"status": "skipped"},
+ "doc-fail": {
+ "status": "error",
+ "error": "Indexing failed: RuntimeError",
+ },
+ },
+ "cancelled": False,
+ "total": 3,
+ }
mock_coll = Mock()
mock_coll.embedding_model = "model"
diff --git a/tests/research_library/routes/test_rag_routes_parallel_indexing.py b/tests/research_library/routes/test_rag_routes_parallel_indexing.py
new file mode 100644
index 0000000000..19b5541d5e
--- /dev/null
+++ b/tests/research_library/routes/test_rag_routes_parallel_indexing.py
@@ -0,0 +1,125 @@
+"""
+Smoke tests for the parallel-indexing wiring in the routes + scheduler.
+
+Heavy mock-driven route integration tests would have to patch lazy
+imports (``from ...database.session_context import get_user_db_session``
+inside worker functions), which isn't reliable across the
+``unittest.mock.patch`` boundary in this test setup. Instead, this
+file pins four observable contracts:
+
+ 1. ``LibraryRAGService.index_documents_parallel`` exists with the
+ documented signature so the six call sites can rely on it.
+ 2. ``_background_index_worker`` accepts a ``max_workers`` parameter
+ so the Flask-context caller can forward the resolved setting.
+ 3. ``_auto_index_documents_worker`` accepts a ``max_workers``
+ parameter for the same reason.
+ 4. The default ``rag.indexing_max_parallel_docs`` value in the
+ settings JSON is in the documented range — defaults shape user
+ experience; if this drifts we want a test to scream.
+
+Detailed behavioural coverage of the parallel helper lives in
+``test_index_documents_parallel.py``.
+"""
+
+import inspect
+
+import pytest
+
+
+class TestParallelHelperSignature:
+ """The route-side wiring relies on this exact signature being stable."""
+
+ def test_index_documents_parallel_exists_with_expected_signature(self):
+ from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+ )
+
+ assert hasattr(LibraryRAGService, "index_documents_parallel")
+ sig = inspect.signature(LibraryRAGService.index_documents_parallel)
+ params = sig.parameters
+
+ # ``doc_info`` is the only positional (after self).
+ assert "doc_info" in params
+ assert "collection_id" in params
+ # Keyword-only behaviour we'd break if changed carelessly.
+ assert "force_reindex" in params
+ assert "max_workers" in params
+ assert "progress_callback" in params
+ assert "is_cancelled" in params
+
+ def test_index_documents_parallel_max_workers_defaults_to_four(self):
+ """A regression-safe default so a missing kwargs argument still works."""
+ from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+ )
+
+ sig = inspect.signature(LibraryRAGService.index_documents_parallel)
+ assert sig.parameters["max_workers"].default == 4
+
+
+class TestWorkerParameters:
+ """The route resolves max_workers and forwards it; the worker must accept it."""
+
+ def test_background_worker_accepts_max_workers(self):
+ from local_deep_research.research_library.routes.rag_routes import (
+ _background_index_worker,
+ )
+
+ sig = inspect.signature(_background_index_worker)
+ assert "max_workers" in sig.parameters
+ # Default is intentionally permissive; the Flask route is the
+ # one that knows the user's preference.
+ assert sig.parameters["max_workers"].default == 4
+
+ def test_auto_index_worker_accepts_max_workers(self):
+ from local_deep_research.research_library.routes.rag_routes import (
+ _auto_index_documents_worker,
+ )
+
+ sig = inspect.signature(_auto_index_documents_worker)
+ assert "max_workers" in sig.parameters
+ assert sig.parameters["max_workers"].default == 4
+
+
+ "key,expected_default",
+ [
+ ("rag.indexing_max_parallel_docs", 4),
+ ("rag.indexing_batch_size", 15),
+ ],
+)
+class TestSettingDefaults:
+ """Defaults in the settings JSON drive first-run UX."""
+
+ def test_default_value_matches_spec(self, key, expected_default):
+ """Verify the JSON default matches the user-visible spec."""
+ import json
+ from pathlib import Path
+
+ settings_path = (
+ Path(__file__).resolve().parents[3]
+ / "src/local_deep_research/defaults/research_library/library_settings.json"
+ )
+ with settings_path.open(encoding="utf-8") as fh:
+ settings = json.load(fh)
+ assert key in settings, f"missing setting: {key}"
+ assert settings[key]["value"] == expected_default, (
+ f"{key} default drifted: got {settings[key]['value']}, "
+ f"want {expected_default}; update docs/CONFIGURATION.md too."
+ )
+
+ def test_default_min_value_is_one(self, key, expected_default):
+ """A worker count below 1 makes no semantic sense; clamp protects us."""
+ import json
+ from pathlib import Path
+
+ settings_path = (
+ Path(__file__).resolve().parents[3]
+ / "src/local_deep_research/defaults/research_library/library_settings.json"
+ )
+ with settings_path.open(encoding="utf-8") as fh:
+ settings = json.load(fh)
+ assert settings[key]["min_value"] >= 1, (
+ f"{key} min_value < 1 — index_documents_parallel's "
+ "max(1, ...) clamp would be a silent UX surprise."
+ )
diff --git a/tests/research_library/services/test_index_documents_parallel.py b/tests/research_library/services/test_index_documents_parallel.py
new file mode 100644
index 0000000000..14ed760cdb
--- /dev/null
+++ b/tests/research_library/services/test_index_documents_parallel.py
@@ -0,0 +1,574 @@
+"""
+Tests for LibraryRAGService.index_documents_parallel.
+
+This is the new parallel fan-out that backs the six call sites which
+previously indexed documents one at a time:
+
+ * ``rag_routes.py::_background_index_worker`` (the user-facing
+ "Index" button on /library/collections/<id>)
+ * ``rag_routes.py::index_collection`` SSE generator
+ * ``rag_routes.py::_auto_index_documents_worker`` (post-upload
+ auto-index)
+ * ``rag_routes.py::index_all`` SSE generator (replaces the
+ pseudo-batch in ``index_documents_batch`` with a real bounded
+ pool)
+ * ``scheduler/background.py::_reconcile_unindexed_documents`` (two
+ branches: in-collection and orphan ingest)
+
+Each ``index_document`` worker opens its own DB session, so this
+file mocks at the ``index_document`` boundary rather than mocking
+SQLAlchemy, FAISS, embeddings, etc. The behaviour we care about is
+that the parallel helper:
+
+ * delegates to ``index_document`` exactly once per doc_id,
+ deduplicating repeats in the input list,
+ * aggregates per-doc results into the same
+ ``{successful, skipped, failed, errors, results}`` shape that
+ the SSE generators consume,
+ * drives an optional progress callback once per completion in
+ completion order (not submission order),
+ * polls an optional ``is_cancelled`` callable between completions
+ and shuts the executor down with ``wait=False,
+ cancel_futures=True`` when cancelled,
+ * clamps ``max_workers`` to ``>= 1`` so a bad setting can never
+ explode the pool,
+ * never lets one doc's failure kill the run.
+"""
+
+import threading
+from concurrent.futures import ThreadPoolExecutor
+from unittest.mock import MagicMock, patch
+
+_MOD = "local_deep_research.research_library.services.library_rag_service"
+
+
+def _make_service(**overrides):
+ """Build a LibraryRAGService with all external deps stubbed.
+
+ ``index_document`` is intentionally NOT mocked here — each test
+ monkey-patches it onto the returned service, because the helper
+ is what we're testing.
+ """
+ with (
+ patch(f"{_MOD}.LocalEmbeddingManager") as _lem,
+ patch(f"{_MOD}.get_user_db_session"),
+ patch(f"{_MOD}.FileIntegrityManager") as _fim,
+ patch(f"{_MOD}.get_text_splitter") as _gts,
+ ):
+ _lem.return_value.embeddings = MagicMock()
+ from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+ )
+
+ defaults = dict(username="testuser", db_password="pw")
+ defaults.update(overrides)
+ return LibraryRAGService(**defaults)
+
+
+class TestEmptyInput:
+ def test_empty_list_returns_zero_counts(self):
+ """No docs → all counters at 0, results dict empty, not cancelled."""
+ svc = _make_service()
+ # Mock index_document so we can also assert it was never called
+ # for the empty-input case (the helper short-circuits before the
+ # dispatch loop).
+ svc.index_document = MagicMock( # type: ignore[method-assign]
+ return_value={"status": "success", "chunk_count": 0}
+ )
+ result = svc.index_documents_parallel(
+ [],
+ "coll-1",
+ force_reindex=False,
+ max_workers=4,
+ )
+ assert result["successful"] == 0
+ assert result["skipped"] == 0
+ assert result["failed"] == 0
+ assert result["errors"] == []
+ assert result["results"] == {}
+ assert result["cancelled"] is False
+ assert result["total"] == 0
+ # Crucially, never even touched the per-doc code path.
+ svc.index_document.assert_not_called() # type: ignore[attr-defined] # noqa: E501
+
+
+class TestDispatch:
+ def test_calls_index_document_per_doc(self):
+ """Each ``(doc_id, title)`` becomes exactly one index_document call."""
+ svc = _make_service()
+ svc.index_document = MagicMock( # type: ignore[method-assign]
+ return_value={"status": "success", "chunk_count": 1}
+ )
+ doc_info = [
+ ("doc-a", "A"),
+ ("doc-b", "B"),
+ ("doc-c", "C"),
+ ]
+ svc.index_documents_parallel(
+ doc_info, "coll-1", force_reindex=True, max_workers=2
+ )
+ assert svc.index_document.call_count == 3 # type: ignore[attr-defined]
+ # force_reindex is forwarded verbatim.
+ for call in svc.index_document.call_args_list: # type: ignore[attr-defined]
+ args, kwargs = call
+ assert args[2] is True # positional: doc_id, coll_id, force_reindex
+
+ def test_duplicate_doc_ids_are_deduplicated(self):
+ """Repeated doc_ids in doc_info collapse to one index_document call.
+
+ The underlying ``index_document`` is not idempotent at the DB
+ level beyond its own checks; without this guard, a buggy
+ caller could double-insert chunks from the same doc.
+ """
+ svc = _make_service()
+ svc.index_document = MagicMock( # type: ignore[method-assign]
+ return_value={"status": "success", "chunk_count": 2}
+ )
+ doc_info = [("doc-a", "A"), ("doc-a", "A2"), ("doc-a", "A3")]
+ result = svc.index_documents_parallel(doc_info, "coll-1", max_workers=2)
+ assert svc.index_document.call_count == 1 # type: ignore[attr-defined]
+ assert (
+ result["total"] == 3
+ ) # reflects *input* length, not dedup'd count
+ assert result["successful"] == 1
+
+
+class TestResultAggregation:
+ def test_counts_aggregate_successes_skips_failures(self):
+ """Counter buckets match the legacy single-doc shape used by SSE."""
+ svc = _make_service()
+ # Dispatch on doc_id so the per-doc status is deterministic regardless
+ # of which worker thread runs first — the previous list-based side_effect
+ # was consumed in call order, so parallel execution attributed the
+ # statuses to the wrong docs and the ``errors[0]`` ordering was
+ # fundamentally flaky (CI flaked on ``assert 'doc-b' == 'doc-c'``).
+ by_doc = {
+ "doc-a": {"status": "success", "chunk_count": 4},
+ "doc-b": {
+ "status": "skipped",
+ "message": "already",
+ "chunk_count": 0,
+ },
+ "doc-c": {"status": "error", "error": "boom"},
+ "doc-d": {"status": "success", "chunk_count": 1},
+ }
+ svc.index_document = MagicMock( # type: ignore[method-assign]
+ side_effect=lambda doc_id, collection_id, force_reindex=False: (
+ by_doc[doc_id]
+ )
+ )
+ result = svc.index_documents_parallel(
+ [
+ ("doc-a", "A"),
+ ("doc-b", "B"),
+ ("doc-c", "C"),
+ ("doc-d", "D"),
+ ],
+ "coll-1",
+ max_workers=4,
+ )
+ assert result["successful"] == 2
+ assert result["skipped"] == 1
+ assert result["failed"] == 1
+ assert len(result["errors"]) == 1
+ # ``errors`` is in *completion* order (as_completed), which is
+ # non-deterministic in a unit test. Pin the per-doc membership on the
+ # ``results`` dict instead, which is keyed by doc_id.
+ assert result["results"]["doc-c"]["status"] == "error"
+ assert result["results"]["doc-c"]["error"] == "boom"
+ # Per-doc results exposed for callers that want finer detail.
+ assert result["results"]["doc-a"]["status"] == "success"
+ assert result["results"]["doc-b"]["status"] == "skipped"
+ assert result["results"]["doc-d"]["status"] == "success"
+
+ def test_index_document_exception_is_captured_not_raised(self):
+ """A buggy ``index_document`` raises → counted as failed, run continues."""
+ svc = _make_service()
+ svc.index_document = MagicMock( # type: ignore[method-assign]
+ side_effect=[
+ RuntimeError("boom"),
+ {"status": "success", "chunk_count": 1},
+ ]
+ )
+ result = svc.index_documents_parallel(
+ [("doc-x", "X"), ("doc-y", "Y")],
+ "coll-1",
+ max_workers=4,
+ )
+ assert result["failed"] == 1
+ assert result["successful"] == 1
+ assert result["results"]["doc-x"]["status"] == "error"
+ assert "RuntimeError" in result["results"]["doc-x"]["error"]
+
+
+class TestProgressCallback:
+ def test_callback_fires_once_per_completion_in_completion_order(self):
+ """Each completion emits one (completed, total, title, status) tuple."""
+ svc = _make_service()
+ svc.index_document = MagicMock( # type: ignore[method-assign]
+ side_effect=[
+ {"status": "success", "chunk_count": 1},
+ {"status": "success", "chunk_count": 2},
+ {"status": "success", "chunk_count": 3},
+ ]
+ )
+ seen = []
+ svc.index_documents_parallel(
+ [("doc-a", "Title A"), ("doc-b", "Title B"), ("doc-c", "Title C")],
+ "coll-1",
+ max_workers=4,
+ progress_callback=lambda *args: seen.append(args),
+ )
+ # Three callbacks, one per completed doc; total is fixed;
+ # titles come from the input, not from the worker order.
+ assert len(seen) == 3
+ for entry in seen:
+ completed, total, _title, _status = entry
+ assert total == 3
+ assert completed in {1, 2, 3}
+ # ``completed`` must be monotonically non-decreasing across the run.
+ completed_seq = [e[0] for e in seen]
+ assert completed_seq == sorted(completed_seq)
+
+ def test_callback_exception_does_not_poison_run(self):
+ """A buggy progress callback is logged and ignored, not raised."""
+ svc = _make_service()
+ svc.index_document = MagicMock( # type: ignore[method-assign]
+ side_effect=[
+ {"status": "success", "chunk_count": 1},
+ {"status": "success", "chunk_count": 1},
+ ]
+ )
+
+ def _bad_cb(*_a, **_k):
+ raise ValueError("oops")
+
+ result = svc.index_documents_parallel(
+ [("doc-a", "A"), ("doc-b", "B")],
+ "coll-1",
+ max_workers=4,
+ progress_callback=_bad_cb,
+ )
+ # Both docs still completed despite the crashing callback.
+ assert result["successful"] == 2
+
+
+class TestCancellation:
+ def test_is_cancelled_breaks_dispatch_loop(self):
+ """When is_cancelled returns True after N docs, no further submissions run.
+
+ ``is_cancelled`` is polled between completions (i.e., between
+ ``as_completed`` yields). We track how many futures were
+ actually submitted; the helper may submit the whole batch
+ up-front but break out of the consume loop early, so the
+ observable signature is ``cancelled=True`` plus the
+ aggregate-shape contract (not-cancelled docs end up as
+ 'skipped' with a 'cancelled' message).
+ """
+ svc = _make_service()
+ svc.index_document = MagicMock( # type: ignore[method-assign]
+ side_effect=[
+ {"status": "success", "chunk_count": 1},
+ {"status": "success", "chunk_count": 2},
+ {"status": "success", "chunk_count": 3},
+ {"status": "success", "chunk_count": 4},
+ {"status": "success", "chunk_count": 5},
+ ]
+ )
+ cancel_after = {"n": 0}
+
+ def _is_cancelled():
+ cancel_after["n"] += 1
+ # Cancel after the second completion is observed.
+ return cancel_after["n"] >= 2
+
+ result = svc.index_documents_parallel(
+ [
+ ("doc-a", "A"),
+ ("doc-b", "B"),
+ ("doc-c", "C"),
+ ("doc-d", "D"),
+ ("doc-e", "E"),
+ ],
+ "coll-1",
+ max_workers=5,
+ is_cancelled=_is_cancelled,
+ )
+
+ assert result["cancelled"] is True
+ # Polled at least once; the loop exits at the cancellation point.
+ assert cancel_after["n"] >= 1
+ # No fatal exception escaped — count totals reflect the
+ # run's observation window.
+ assert (
+ result["successful"] + result["skipped"] + result["failed"]
+ == result["total"]
+ )
+
+ def test_no_new_index_document_calls_after_cancel_observed(self):
+ """Regression: once ``is_cancelled`` returns True, no new ``index_document``
+ calls are admitted.
+
+ Under the previous all-upfront submission model, a window existed where
+ queued futures could be picked up by idle workers between the caller's
+ cancel signal (e.g. ``_sse_cancel.set()`` in
+ ``rag_routes.index_collection``) and the helper's
+ ``pool.shutdown(cancel_futures=True)``. The new bounded-submission
+ loop polls ``is_cancelled`` BEFORE admitting any new work, so
+ post-cancel starts are bounded by what was already in flight — not
+ by the full input length.
+
+ With synchronous ``index_document`` and ``max_workers=2`` plus 20 docs:
+ the OLD code would have submitted all 20 upfront before any
+ ``is_cancelled`` poll. The NEW code submits the first batch of 2, then
+ one more as a slot frees (per outer-loop iteration), and stops as
+ soon as ``is_cancelled()`` returns True.
+
+ We arrange ``is_cancelled`` to return False for the first 2 polls
+ (admitting the initial batch + 1 refill as a slot frees) and True
+ thereafter. Total admitted calls is therefore ≤ 3 with bounded
+ submission, vs. 20 with the old model.
+ """
+ svc = _make_service()
+
+ # is_cancelled returns False for the first 2 polls, True thereafter.
+ poll_count = {"n": 0}
+
+ def _is_cancelled():
+ if threading.current_thread() is threading.main_thread():
+ poll_count["n"] += 1
+ return poll_count["n"] > 2
+
+ # Synchronous index_document: a worker finishes instantly, freeing a
+ # slot for the next admission on the very next outer-loop iteration.
+ svc.index_document = MagicMock( # type: ignore[method-assign]
+ return_value={"status": "success", "chunk_count": 1}
+ )
+
+ result = svc.index_documents_parallel(
+ [(f"doc-{i}", str(i)) for i in range(20)],
+ "coll-1",
+ max_workers=2,
+ is_cancelled=_is_cancelled,
+ )
+
+ assert result["cancelled"] is True
+ # Bounded submission: with max_workers=2 and cancel observed on poll
+ # #3, the loop admits at most ~3 calls (first batch of 2 + 1 refill
+ # as a slot frees, then cancel observed → no more submits). The
+ # OLD all-upfront model would have admitted all 20.
+ #
+ # Use ≤4 to leave a small scheduling-tolerance margin; the precise
+ # bound is 3 with synchronous workers but pool scheduling can let
+ # one extra submit land before the next poll.
+ admitted = svc.index_document.call_count # type: ignore[attr-defined]
+ assert admitted <= 4, (
+ f"Bounded-submission loop admitted {admitted} index_document "
+ f"calls after cancellation; expected ≤4 with max_workers=2 and "
+ f"is_cancelled flipping True after 2 polls. The OLD "
+ f"all-upfront model would have admitted all 20."
+ )
+ # And the exact upper bound for completeness: at least 1 admit
+ # happened before cancel was observed (otherwise cancel couldn't
+ # have been observed via the per-iteration poll).
+ assert admitted >= 1, (
+ "Helper should admit at least one batch before observing cancel"
+ )
+
+ def test_zero_index_document_calls_when_cancel_polled_first(self):
+ """When ``is_cancelled`` returns True on the FIRST poll (before any
+ submit), zero ``index_document`` calls must be admitted.
+
+ The OLD all-upfront model would have submitted the entire batch
+ before ever polling ``is_cancelled``, so it would have admitted N
+ calls even though cancel was set immediately. The new bounded-
+ submission loop polls BEFORE submit, so cancel-on-first-poll
+ admits exactly zero work.
+ """
+ svc = _make_service()
+ svc.index_document = MagicMock( # type: ignore[method-assign]
+ return_value={"status": "success", "chunk_count": 1}
+ )
+
+ result = svc.index_documents_parallel(
+ [(f"doc-{i}", str(i)) for i in range(10)],
+ "coll-1",
+ max_workers=2,
+ is_cancelled=lambda: True,
+ )
+
+ assert result["cancelled"] is True
+ # Critical assertion: NO work was admitted because cancel was
+ # observed before any submit. The OLD code would have submitted
+ # all 10 upfront.
+ svc.index_document.assert_not_called() # type: ignore[attr-defined]
+ # All 10 docs end up in the aggregate as 'skipped' (cancelled
+ # before submission), keeping the contract that the totals match.
+ assert (
+ result["successful"] + result["skipped"] + result["failed"]
+ == result["total"]
+ )
+ assert result["skipped"] == 10
+ assert result["successful"] == 0
+
+ def test_no_starts_after_cancellation_during_fill(self):
+ """Test that no worker starts after the cancellation event is set,
+ even during the initial pool-filling phase.
+ """
+ import threading
+
+ svc = _make_service()
+
+ cancel_event = threading.Event()
+ doc_0_started = threading.Event()
+ doc_0_resume = threading.Event()
+
+ started_calls = []
+
+ def mock_index_document(doc_id, collection_id, force_reindex=False):
+ # Record the doc_id and whether the cancel_event was set at start time.
+ started_calls.append((doc_id, cancel_event.is_set()))
+ if doc_id == "doc-0":
+ doc_0_started.set()
+ doc_0_resume.wait(timeout=5)
+ return {"status": "success", "chunk_count": 1}
+
+ svc.index_document = MagicMock(side_effect=mock_index_document) # type: ignore[method-assign]
+
+ is_cancelled_call_count = {"n": 0}
+
+ def _is_cancelled():
+ if threading.current_thread() is threading.main_thread():
+ is_cancelled_call_count["n"] += 1
+ # Call 3 is the poll right before submitting doc-1
+ if is_cancelled_call_count["n"] == 3:
+ # Wait until doc-0 has actually started running in the worker thread
+ doc_0_started.wait(timeout=5)
+ # Trigger the cancellation event
+ cancel_event.set()
+ # Allow doc-0 to resume and complete
+ doc_0_resume.set()
+ return cancel_event.is_set()
+
+ result = svc.index_documents_parallel(
+ [("doc-0", "Zero"), ("doc-1", "One"), ("doc-2", "Two")],
+ "coll-1",
+ max_workers=3,
+ is_cancelled=_is_cancelled,
+ )
+
+ assert result["cancelled"] is True
+ # doc-0 should have started when cancel_event was not set.
+ # doc-1 and doc-2 should never have started/submitted.
+ assert len(started_calls) == 1
+ assert started_calls[0] == ("doc-0", False)
+
+ # doc-1 and doc-2 are in results as skipped
+ assert result["results"]["doc-1"]["status"] == "skipped"
+ assert result["results"]["doc-2"]["status"] == "skipped"
+
+ def test_cancellation_preserved_when_set_during_last_inflight_worker(self):
+ """Regression: if the cancel event is set WHILE the final
+ in-flight worker is running (and that worker completes
+ successfully), the aggregate must still report
+ ``cancelled=True``.
+
+ The reviewer's concern was that "the helper can finish without
+ another poll and return cancelled=False, allowing the
+ background task to overwrite cancellation with completed".
+ The fix is the final ``is_cancelled()`` poll in the ``finally``
+ block: even if the last worker completes with status=success,
+ if ``is_cancelled()`` returns True at any point during the
+ run, the helper preserves ``cancelled=True`` in the aggregate.
+ """
+ svc = _make_service()
+
+ cancel_event = threading.Event()
+ worker_started = threading.Event()
+ resume_worker = threading.Event()
+
+ def mock_index_document(doc_id, collection_id, force_reindex=False):
+ if doc_id == "doc-0":
+ worker_started.set()
+ # Wait until the test signals us to resume (after it
+ # has set the cancel event).
+ resume_worker.wait(timeout=5)
+ return {"status": "success", "chunk_count": 1}
+
+ svc.index_document = MagicMock( # type: ignore[method-assign]
+ side_effect=mock_index_document
+ )
+
+ def _is_cancelled():
+ return cancel_event.is_set()
+
+ def _set_cancel_during_last_worker():
+ assert worker_started.wait(timeout=5), "doc-0 worker never started"
+ cancel_event.set()
+ resume_worker.set()
+
+ threading.Thread(
+ target=_set_cancel_during_last_worker, daemon=True
+ ).start()
+
+ result = svc.index_documents_parallel(
+ [("doc-0", "Zero")],
+ "coll-1",
+ max_workers=1,
+ is_cancelled=_is_cancelled,
+ )
+
+ # doc-0 completed successfully (it was already running when
+ # cancel was set), BUT the helper must still report
+ # cancelled=True because the cancel event was observed during
+ # the run (via the finally block's final poll).
+ assert result["cancelled"] is True, (
+ "Helper returned cancelled=False despite the cancel event "
+ "being set during the in-flight worker. The finally-block "
+ "final poll must preserve cancelled=True."
+ )
+ assert result["results"]["doc-0"]["status"] == "success"
+
+
+class TestWorkerBounds:
+ def test_max_workers_zero_clamped_to_one(self):
+ """A zero or negative max_workers never produces an empty pool."""
+ svc = _make_service()
+ svc.index_document = MagicMock( # type: ignore[method-assign]
+ return_value={"status": "success", "chunk_count": 1}
+ )
+
+ # Patch ThreadPoolExecutor so we can capture max_workers without
+ # spawning real workers (deterministic for the clamp check).
+ with patch(
+ f"{_MOD}.ThreadPoolExecutor", wraps=ThreadPoolExecutor
+ ) as tpe_cls:
+ svc.index_documents_parallel(
+ [("doc-a", "A")],
+ "coll-1",
+ max_workers=0,
+ )
+ assert tpe_cls.call_args.kwargs["max_workers"] == 1
+
+ def test_max_workers_one_runs_serially(self):
+ """max_workers=1 must not break ordering; results match input order.
+
+ We can't easily *prove* serial execution in a unit test without
+ wall-clock tricks, but we can pin the public contract: every
+ doc still gets indexed and the result dict is intact.
+ """
+ svc = _make_service()
+ svc.index_document = MagicMock( # type: ignore[method-assign]
+ side_effect=[
+ {"status": "success", "chunk_count": 1},
+ {"status": "success", "chunk_count": 2},
+ {"status": "success", "chunk_count": 3},
+ ]
+ )
+ result = svc.index_documents_parallel(
+ [("doc-a", "A"), ("doc-b", "B"), ("doc-c", "C")],
+ "coll-1",
+ max_workers=1,
+ )
+ assert result["successful"] == 3
+ assert set(result["results"].keys()) == {"doc-a", "doc-b", "doc-c"}
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index d7c157eff8..80fae065cd 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -2320,7 +2320,7 @@
},
"rag.indexing_batch_size": {
"category": "research_library",
- "description": "Number of documents to process in parallel during RAG indexing. Higher values are faster but use more memory.",
+ "description": "Maximum number of documents grouped into a single SSE progress batch on /api/rag/index-all. Documents within a batch are processed in parallel via rag.indexing_max_parallel_docs. Higher values reduce SSE overhead but increase the unit of cancellation.",
"editable": true,
"max_value": 50,
"min_value": 1,
@@ -2332,6 +2332,20 @@
"value": 15,
"visible": true
},
+ "rag.indexing_max_parallel_docs": {
+ "category": "research_library",
+ "description": "Maximum number of documents indexed concurrently within a single indexing job (per-user). One job holds up to this many workers; each worker calls the existing per-document path so the FAISS write lock still serializes the disk-merge step. Lower if your embedding backend (e.g. local CPU sentence-transformers) is throughput-bound and concurrent calls contend; raise to e.g. 8-16 for sentence-transformers on GPU, or HTTP embedding providers (OpenAI-compatible, vLLM, Ollama with OLLAMA_NUM_PARALLEL>1). Default 4 keeps RAM modest for collections with many large documents.",
+ "editable": true,
+ "max_value": 16,
+ "min_value": 1,
+ "name": "RAG Indexing Max Parallel Documents",
+ "options": null,
+ "step": 1,
+ "type": "APP",
+ "ui_element": "number",
+ "value": 4,
+ "visible": true
+ },
"rate_limiting.decay_per_day": {
"category": "rate_limiting",
"description": "How much to trust old rate limit data as it ages (0.5-0.99). At 0.95, data retains 95% reliability per day. Lower values discard old data faster, forcing the system to re-learn optimal wait times.",
diff --git a/tests/vector_stores/test_faiss_store.py b/tests/vector_stores/test_faiss_store.py
index 42d861cc1b..98bb0a58a0 100644
--- a/tests/vector_stores/test_faiss_store.py
+++ b/tests/vector_stores/test_faiss_store.py
@@ -366,6 +366,10 @@ class TestPersistLoad:
with pytest.raises(RuntimeError, match="dimension"):
mismatched.apply(add_ids=[2], add_vectors=_vecs(1, dim=8))
+ @pytest.mark.skipif(
+ __import__("sys").platform == "win32",
+ reason="chmod is not supported on Windows",
+ )
def test_persist_chmods_parent_private(self, tmp_path):
store = _make_store(tmp_path)
store.add([1], _vecs(1))