DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(rag): stop a stalled LlamaIndex worker leaking progress into the next job (#1478)
ZQR1101e0dc389a2d8b
diff --git a/deeptutor/services/rag/pipelines/llamaindex/pipeline.py b/deeptutor/services/rag/pipelines/llamaindex/pipeline.pyindex 4e99a4093..68b13562c 100644--- a/deeptutor/services/rag/pipelines/llamaindex/pipeline.py+++ b/deeptutor/services/rag/pipelines/llamaindex/pipeline.py@@ -37,6 +37,17 @@ DEFAULT_KB_BASE_DIR = str(get_runtime_data_root() / "knowledge_bases")# is treated as stalled (see _run_with_stall_guard)._INDEX_STALL_TIMEOUT_SECONDS = 600.0# How often the stall guard checks the progress heartbeat.+# Which indexing run currently owns the shared embedding-progress callback+# slot. ``set_progress_callback`` writes to the process-global LlamaIndex+# ``Settings.embed_model`` (one slot), and a run that stalls leaves its sync+# embedding worker running in a thread Python cannot interrupt. That worker+# keeps calling the stored callback long after the run ended, so without an+# ownership check the stale worker's batch events land in the *next* job that+# grabbed the slot — the "infinite Embedding batches / reset to 1/N" leak+# (#1478). The stall guard stamps each run with a fresh owner and its+# ``_heartbeat`` refuses to forward progress once ``owner`` no longer matches.+_ACTIVE_PROGRESS_OWNER: Optional[str] = None+_INDEX_STALL_POLL_SECONDS = 5.0SignatureProvider = Callable[[], EmbeddingSignature | None]@@ -79,9 +90,22 @@ async def _run_with_stall_guard(if stall_timeout is None:stall_timeout = _INDEX_STALL_TIMEOUT_SECONDS+ # Stamp this run as the current owner of the shared progress slot. The+ # ``_heartbeat`` wrapper refuses to forward progress once a newer run has+ # taken ownership (or we have finished), so a worker thread left running+ # by a stall can no longer write its batch events into the next job+ # (#1478 — the "infinite Embedding batches / reset to 1/N" leak).+ owner = f"{time.monotonic_ns()}"+ global _ACTIVE_PROGRESS_OWNER+ _ACTIVE_PROGRESS_OWNER = owner+last_progress = {"at": time.monotonic()}def _heartbeat(*args: Any, **kwargs: Any) -> None:+ if _ACTIVE_PROGRESS_OWNER != owner:+ # A concurrent or previous run owns the slot now; this worker is+ # either stale or displaced. Do not feed its progress elsewhere.+ returnlast_progress["at"] = time.monotonic()if progress_callback is not None:progress_callback(*args, **kwargs)@@ -95,21 +119,27 @@ async def _run_with_stall_guard(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."- )+ try:+ 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."+ )+ finally:+ # Release ownership of the progress slot exactly when this run still+ # holds it — never clobber a newer run that has already taken over.+ if _ACTIVE_PROGRESS_OWNER == owner:+ _ACTIVE_PROGRESS_OWNER = Noneclass LlamaIndexPipeline:diff --git a/tests/services/rag/test_llamaindex_pipeline_stall.py b/tests/services/rag/test_llamaindex_pipeline_stall.pyindex 15b531b15..6783b43fa 100644--- a/tests/services/rag/test_llamaindex_pipeline_stall.py+++ b/tests/services/rag/test_llamaindex_pipeline_stall.py@@ -204,3 +204,82 @@ async def test_initialize_succeeds_when_indexing_completes(monkeypatch.setattr(storage_module, "create_index", lambda *a, **k: 7)assert await pipeline.initialize("kb", ["doc.pdf"]) is True+++async def test_finished_job_progress_callback_stops_leaking_into_next_turn(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A worker left running after a run finishes must no longer write+ progress into the shared slot.++ The stall guard leaves the sync embedding worker alive when it raises.+ Without an ownership check, that stale worker keeps calling the stored+ callback and its batches land in whatever job grabs the slot next —+ the "Embedding batches reset / keep going after N/N" leak (#1478).+ """+ 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_cb(batch_num: int, total_batches: int) -> None:+ events.append((batch_num, total_batches))++ def quick() -> str:+ captured["cb"](1, 1)+ return "done"++ assert (+ await pipeline_module._run_with_stall_guard(+ quick, progress_callback=user_cb, stall_timeout=1.0+ )+ == "done"+ )++ # The finished run's ownership has been released; a stale worker must not emit.+ captured["cb"](9, 9)+ assert events == [(1, 1)]+++async def test_stale_wrapper_from_finished_run_is_suppressed_after_ownership_changes(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A stale worker from a finished run must not leak once a newer run owns+ the progress slot.++ This drives the ownership handoff directly (release + a simulated B taking+ the slot) rather than racing two executors, pinning the invariant that+ matters: once this run no longer owns the slot, its wrapper is a no-op, so+ a worker thread left running by a stall can never feed batch events into+ the next job (#1478).+ """+ 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_a: list[tuple[int, int]] = []++ def quick_a() -> str:+ captured["cb"](1, 1)+ return "done-a"++ assert (+ await pipeline_module._run_with_stall_guard(+ quick_a,+ progress_callback=lambda b, t: events_a.append((b, t)),+ stall_timeout=1.0,+ )+ == "done-a"+ )+ stale_a_cb = captured["cb"]+ # This run released the slot; a newer job takes ownership of it.+ assert pipeline_module._ACTIVE_PROGRESS_OWNER is None+ pipeline_module._ACTIVE_PROGRESS_OWNER = "job-b-owner"++ stale_a_cb(9, 9)++ assert events_a == [(1, 1)]+ pipeline_module._ACTIVE_PROGRESS_OWNER = None