Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(llamaindex): fail bounded when indexing stalls (#953)

0xTidalBore8d6a6e3a5930
diff --git a/deeptutor/services/rag/pipelines/llamaindex/pipeline.py b/deeptutor/services/rag/pipelines/llamaindex/pipeline.py
index 58526bf8e..4e99a4093 100644
--- a/deeptutor/services/rag/pipelines/llamaindex/pipeline.py
+++ b/deeptutor/services/rag/pipelines/llamaindex/pipeline.py
@@ -6,6 +6,7 @@ import asyncio
import json
import logging
from pathlib import Path
+import time
import traceback
from typing import Any, Callable, Dict, List, Optional
@@ -32,9 +33,85 @@ from .errors import search_error_result
DEFAULT_KB_BASE_DIR = str(get_runtime_data_root() / "knowledge_bases")
+# How long an indexing step may run without reporting any progress before it
+# is treated as stalled (see _run_with_stall_guard).
+_INDEX_STALL_TIMEOUT_SECONDS = 600.0
+# How often the stall guard checks the progress heartbeat.
+_INDEX_STALL_POLL_SECONDS = 5.0
+
SignatureProvider = Callable[[], EmbeddingSignature | None]
+class IndexingStallError(RuntimeError):
+ """Raised when an indexing operation makes no progress for too long."""
+
+
+async def _run_with_stall_guard(
+ fn: Callable[[], Any],
+ *,
+ progress_callback: Optional[Callable[..., Any]] = None,
+ stall_timeout: Optional[float] = None,
+) -> Any:
+ """Run a synchronous indexing step in the executor, failing if it stalls.
+
+ Indexing steps (chunking + embedding) run in a worker thread via
+ ``run_in_executor``. A provider that accepts a request but never
+ completes it (e.g. a blackholed keep-alive connection) can block that
+ thread indefinitely: per-request HTTP timeouts only bound a single
+ attempt, and provider retries extend the wait far beyond any reasonable
+ budget. Instead of hanging forever, watch the embedding progress
+ heartbeat and fail with a clear error once no progress has been reported
+ for ``stall_timeout`` seconds.
+
+ The sync function keeps running in its thread after a stall is raised —
+ Python cannot interrupt arbitrary synchronous code — but the API call
+ fails fast with an actionable message instead of waiting forever.
+
+ ``set_progress_callback`` writes to the process-global LlamaIndex
+ ``Settings`` embed model, which holds exactly one callback. A second
+ indexing job started while this one runs therefore displaces our
+ heartbeat, so we re-arm it on every poll tick: missing a few
+ notifications for one tick is harmless, whereas never seeing our own
+ progress again would kill a perfectly healthy job. The guard is
+ consciously biased this way — it can be slow to notice a genuine stall
+ while another job indexes, and never fails a job that is making progress.
+ """
+ if stall_timeout is None:
+ stall_timeout = _INDEX_STALL_TIMEOUT_SECONDS
+
+ last_progress = {"at": time.monotonic()}
+
+ def _heartbeat(*args: Any, **kwargs: Any) -> None:
+ last_progress["at"] = time.monotonic()
+ if progress_callback is not None:
+ progress_callback(*args, **kwargs)
+
+ set_progress_callback(_heartbeat)
+ future = asyncio.get_running_loop().run_in_executor(None, fn)
+
+ def _consume_terminal_exception(fut: "asyncio.Future[Any]") -> None:
+ # The stalled thread may finish after we raise; retrieve its exception
+ # so it is not reported as "exception was never retrieved".
+ if not fut.cancelled():
+ fut.exception()
+
+ while True:
+ done, _ = await asyncio.wait({future}, timeout=_INDEX_STALL_POLL_SECONDS)
+ if done:
+ return future.result()
+ # Reclaim the shared callback slot in case a concurrent job took it.
+ set_progress_callback(_heartbeat)
+ stalled_for = time.monotonic() - last_progress["at"]
+ if stalled_for > stall_timeout:
+ future.add_done_callback(_consume_terminal_exception)
+ raise IndexingStallError(
+ f"Indexing made no progress for {stalled_for:.0f}s while "
+ "embedding documents. The embedding provider may be accepting "
+ "requests without completing them; check the embedding "
+ "endpoint and retry."
+ )
+
+
class LlamaIndexPipeline:
"""Pipeline that indexes and retrieves KB content via LlamaIndex."""
@@ -99,15 +176,11 @@ class LlamaIndexPipeline:
f"(chunking + embedding)..."
)
- if progress_callback:
- set_progress_callback(progress_callback)
-
- loop = asyncio.get_running_loop()
- await loop.run_in_executor(
- None,
+ await _run_with_stall_guard(
lambda: storage.create_index(
documents, storage_dir, show_progress=should_show_progress()
),
+ progress_callback=progress_callback,
)
self.logger.info(f"Index persisted to {storage_dir}")
@@ -240,8 +313,6 @@ class LlamaIndexPipeline:
try:
await self._verify_embedding_connectivity()
- if progress_callback:
- set_progress_callback(progress_callback)
documents = await self.document_loader.load(
file_paths, image_progress_callback=image_progress_callback
@@ -250,15 +321,13 @@ class LlamaIndexPipeline:
self.logger.warning("No valid documents to add")
return False
- loop = asyncio.get_running_loop()
-
if plan.existing_storage is not None:
self.logger.info(f"Loading existing index from {plan.existing_storage}...")
- num_added = await loop.run_in_executor(
- None,
+ num_added = await _run_with_stall_guard(
lambda: storage.insert_documents(
plan.existing_storage, plan.storage_dir, documents
),
+ progress_callback=progress_callback,
)
self.logger.info(f"Added {num_added} documents to existing index")
if signature is not None and plan.storage_dir != plan.existing_storage:
@@ -266,11 +335,11 @@ class LlamaIndexPipeline:
else:
self.logger.info(f"Creating new index with {len(documents)} documents...")
plan.storage_dir.mkdir(parents=True, exist_ok=True)
- num_added = await loop.run_in_executor(
- None,
+ num_added = await _run_with_stall_guard(
lambda: storage.create_index(
documents, plan.storage_dir, show_progress=should_show_progress()
),
+ progress_callback=progress_callback,
)
self.logger.info(f"Created new index with {num_added} documents")
if signature is not None:
diff --git a/tests/services/rag/test_llamaindex_pipeline_stall.py b/tests/services/rag/test_llamaindex_pipeline_stall.py
new file mode 100644
index 000000000..15b531b15
--- /dev/null
+++ b/tests/services/rag/test_llamaindex_pipeline_stall.py
@@ -0,0 +1,206 @@
+"""Regression tests for bounded LlamaIndex indexing (issue #946).
+
+Indexing steps run in a sync executor thread. An embedding provider that
+accepts a request but never completes it (e.g. a blackholed keep-alive
+connection) can stall the executor future forever: HTTP timeouts only bound
+a single attempt, and provider retries extend the wait far past any
+reasonable request budget. These tests pin the stall guard that fails such
+operations with a clear error instead of hanging indefinitely.
+"""
+
+from __future__ import annotations
+
+import time
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+
+def _llamaindex_modules() -> tuple[Any, Any, Any]:
+ """Import the pipeline modules lazily, matching sibling test files."""
+ from deeptutor.services.rag.pipelines.llamaindex import pipeline as pipeline_module
+ from deeptutor.services.rag.pipelines.llamaindex import storage as storage_module
+ from deeptutor.services.rag.pipelines.llamaindex.pipeline import LlamaIndexPipeline
+
+ return pipeline_module, storage_module, LlamaIndexPipeline
+
+
+async def _async_noop(*args, **kwargs) -> None:
+ """Async stand-in for connectivity checks that need no provider call."""
+
+
+def _make_pipeline(tmp_path, monkeypatch: pytest.MonkeyPatch) -> Any:
+ """Build a pipeline with provider calls neutralized for fast tests."""
+ pipeline_module, _storage_module, LlamaIndexPipeline = _llamaindex_modules()
+ monkeypatch.setattr(pipeline_module, "_INDEX_STALL_POLL_SECONDS", 0.05)
+ monkeypatch.setattr(pipeline_module, "_INDEX_STALL_TIMEOUT_SECONDS", 0.3)
+ monkeypatch.setattr(LlamaIndexPipeline, "_configure_settings", lambda self: None)
+ monkeypatch.setattr(LlamaIndexPipeline, "_verify_embedding_connectivity", _async_noop)
+
+ async def _fake_load(file_paths, **kwargs):
+ del file_paths, kwargs
+ return [SimpleNamespace(text="hello world")]
+
+ monkeypatch.setattr(
+ pipeline_module, "LlamaIndexDocumentLoader", lambda logger: SimpleNamespace(load=_fake_load)
+ )
+ return LlamaIndexPipeline(kb_base_dir=str(tmp_path), signature_provider=lambda: None)
+
+
+async def test_stall_guard_raises_when_no_progress_is_reported(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """An executor step that never reports progress must fail bounded."""
+ pipeline_module, _, _ = _llamaindex_modules()
+ monkeypatch.setattr(pipeline_module, "_INDEX_STALL_POLL_SECONDS", 0.05)
+
+ def never_finishes():
+ time.sleep(5)
+
+ started = time.monotonic()
+ with pytest.raises(pipeline_module.IndexingStallError, match="no progress"):
+ await pipeline_module._run_with_stall_guard(
+ never_finishes, progress_callback=None, stall_timeout=0.2
+ )
+ assert time.monotonic() - started < 10
+
+
+async def test_stall_guard_returns_when_progress_keeps_flowing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A slow-but-moving step must not be mistaken for a stall."""
+ pipeline_module, _, _ = _llamaindex_modules()
+ monkeypatch.setattr(pipeline_module, "_INDEX_STALL_POLL_SECONDS", 0.05)
+ captured: dict = {}
+ monkeypatch.setattr(pipeline_module, "set_progress_callback", lambda cb: captured.update(cb=cb))
+
+ def slow_but_moving():
+ end = time.monotonic() + 0.6
+ while time.monotonic() < end:
+ captured["cb"](1, 1)
+ time.sleep(0.05)
+ return "done"
+
+ assert (
+ await pipeline_module._run_with_stall_guard(
+ slow_but_moving, progress_callback=None, stall_timeout=0.3
+ )
+ == "done"
+ )
+
+
+async def test_stall_guard_survives_a_concurrent_job_taking_the_callback_slot(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A second indexing job must not make this one look stalled.
+
+ ``set_progress_callback`` writes to the process-global LlamaIndex
+ ``Settings`` embed model, which holds exactly one callback. A concurrent
+ job overwrites ours, so without re-arming on each poll tick we would stop
+ observing progress we are still making and kill a perfectly healthy job
+ with a false ``IndexingStallError``.
+ """
+ pipeline_module, _, _ = _llamaindex_modules()
+ monkeypatch.setattr(pipeline_module, "_INDEX_STALL_POLL_SECONDS", 0.05)
+ slot: dict = {}
+ monkeypatch.setattr(pipeline_module, "set_progress_callback", lambda cb: slot.update(cb=cb))
+
+ def displaced_then_moving():
+ # A concurrent indexing job claims the single shared slot.
+ slot["cb"] = lambda *args, **kwargs: None
+ end = time.monotonic() + 0.6
+ while time.monotonic() < end:
+ # Batches notify whoever currently owns the slot.
+ slot["cb"](1, 1)
+ time.sleep(0.05)
+ return "done"
+
+ assert (
+ await pipeline_module._run_with_stall_guard(
+ displaced_then_moving, progress_callback=None, stall_timeout=0.3
+ )
+ == "done"
+ )
+
+
+async def test_stall_guard_forwards_user_progress_callback(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The user-facing progress callback must keep receiving batch events."""
+ pipeline_module, _, _ = _llamaindex_modules()
+ monkeypatch.setattr(pipeline_module, "_INDEX_STALL_POLL_SECONDS", 0.05)
+ captured: dict = {}
+ monkeypatch.setattr(pipeline_module, "set_progress_callback", lambda cb: captured.update(cb=cb))
+ events: list[tuple[int, int]] = []
+
+ def user_callback(batch_num, total_batches):
+ events.append((batch_num, total_batches))
+
+ def reports_once():
+ captured["cb"](2, 10)
+ return "ok"
+
+ assert (
+ await pipeline_module._run_with_stall_guard(
+ reports_once, progress_callback=user_callback, stall_timeout=1.0
+ )
+ == "ok"
+ )
+ assert events == [(2, 10)]
+
+
+async def test_initialize_fails_bounded_when_indexing_stalls(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """initialize() must raise IndexingStallError instead of hanging forever."""
+ pipeline_module, storage_module, _ = _llamaindex_modules()
+ pipeline = _make_pipeline(tmp_path, monkeypatch)
+
+ def _blocking_create_index(*args, **kwargs):
+ del args, kwargs
+ time.sleep(5)
+
+ monkeypatch.setattr(storage_module, "create_index", _blocking_create_index)
+
+ started = time.monotonic()
+ with pytest.raises(pipeline_module.IndexingStallError, match="no progress"):
+ await pipeline.initialize("kb", ["doc.pdf"])
+ assert time.monotonic() - started < 10
+
+
+async def test_add_documents_fails_bounded_when_new_index_stalls(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """add_documents() new-index path must also fail bounded on a stall."""
+ pipeline_module, storage_module, _ = _llamaindex_modules()
+ pipeline = _make_pipeline(tmp_path, monkeypatch)
+
+ def _blocking_create_index(*args, **kwargs):
+ del args, kwargs
+ time.sleep(5)
+
+ monkeypatch.setattr(storage_module, "create_index", _blocking_create_index)
+
+ started = time.monotonic()
+ with pytest.raises(pipeline_module.IndexingStallError, match="no progress"):
+ await pipeline.add_documents("kb", ["doc.pdf"])
+ assert time.monotonic() - started < 10
+
+
+async def test_initialize_succeeds_when_indexing_completes(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The happy path must be unaffected by the stall guard."""
+ _pipeline_module, storage_module, _ = _llamaindex_modules()
+ pipeline = _make_pipeline(tmp_path, monkeypatch)
+ monkeypatch.setattr(storage_module, "create_index", lambda *a, **k: 7)
+
+ assert await pipeline.initialize("kb", ["doc.pdf"]) is True