DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix: converge LightRAG transport failures and cancellation (#940)
NoxsMedia7411315b6b6d
diff --git a/deeptutor/services/llm/error_mapping.py b/deeptutor/services/llm/error_mapping.pyindex 0e8d2b5cc..890ffe0c9 100644--- a/deeptutor/services/llm/error_mapping.py+++ b/deeptutor/services/llm/error_mapping.py@@ -6,7 +6,10 @@ from __future__ import annotationsfrom collections.abc import Callablefrom dataclasses import dataclass+from datetime import datetime, timezone+from email.utils import parsedate_to_datetimeimport logging+import math# Import unified exceptions from exceptions.pyfrom .exceptions import (@@ -51,6 +54,60 @@ def _class_named(*names: str) -> ErrorClassifier:return _classifier+def retry_after_seconds(+ exc: Exception,+ *,+ now: datetime | None = None,+) -> float | None:+ """Extract a numeric or HTTP-date Retry-After value from an exception."""+ value = getattr(exc, "retry_after", None)+ if value is None:+ response = getattr(exc, "response", None)+ headers = getattr(response, "headers", None)+ get_header = getattr(headers, "get", None)+ if callable(get_header):+ value = get_header("Retry-After")+ if value is None:+ value = get_header("retry-after")++ if isinstance(value, bool) or value is None:+ return None+ if isinstance(value, (int, float)):+ seconds = float(value)+ elif isinstance(value, str):+ normalized = value.strip()+ if not normalized:+ return None+ try:+ seconds = float(normalized)+ except ValueError:+ try:+ retry_at = parsedate_to_datetime(normalized)+ except (TypeError, ValueError, OverflowError):+ return None+ if retry_at.tzinfo is None:+ retry_at = retry_at.replace(tzinfo=timezone.utc)+ current_time = now or datetime.now(timezone.utc)+ if current_time.tzinfo is None:+ current_time = current_time.replace(tzinfo=timezone.utc)+ return max(0.0, (retry_at - current_time).total_seconds())+ else:+ return None++ if not math.isfinite(seconds) or seconds < 0:+ return None+ return seconds+++def _rate_limit_error(exc: Exception, provider: str | None) -> LLMRateLimitError:+ """Map rate-limit errors without discarding their server retry hint."""+ return LLMRateLimitError(+ str(exc),+ retry_after=retry_after_seconds(exc),+ provider=provider,+ )++_GLOBAL_RULES: list[MappingRule] = [MappingRule(classifier=_class_named("AuthenticationError", "AuthenticationStatusError"),@@ -58,11 +115,11 @@ _GLOBAL_RULES: list[MappingRule] = [),MappingRule(classifier=_class_named("RateLimitError"),- factory=lambda exc, provider: LLMRateLimitError(str(exc), provider=provider),+ factory=_rate_limit_error,),MappingRule(classifier=_message_contains("rate limit", "429", "quota"),- factory=lambda exc, provider: LLMRateLimitError(str(exc), provider=provider),+ factory=_rate_limit_error,),MappingRule(classifier=_message_contains("context length", "maximum context"),@@ -73,12 +130,17 @@ _GLOBAL_RULES: list[MappingRule] = [def map_error(exc: Exception, provider: str | None = None) -> LLMError:"""Map provider-specific errors to unified internal exceptions."""+ if isinstance(exc, LLMError):+ if exc.provider is None:+ exc.provider = provider+ return exc+# Heuristic check for status codes before rulesstatus_code = getattr(exc, "status_code", None)if status_code == 401:return LLMAuthenticationError(str(exc), provider=provider)if status_code == 429:- return LLMRateLimitError(str(exc), provider=provider)+ return _rate_limit_error(exc, provider)for rule in _GLOBAL_RULES:if rule.classifier(exc):diff --git a/deeptutor/services/llm/factory.py b/deeptutor/services/llm/factory.pyindex f0b9734f6..adc5e65b6 100644--- a/deeptutor/services/llm/factory.py+++ b/deeptutor/services/llm/factory.py@@ -346,6 +346,7 @@ async def complete(max_retries: int = DEFAULT_MAX_RETRIES,retry_delay: float = DEFAULT_RETRY_DELAY,exponential_backoff: bool = DEFAULT_EXPONENTIAL_BACKOFF,+ allow_image_fallback: bool | None = None,**kwargs: Any,) -> str:caller_extra_headers = kwargs.pop("extra_headers", None)@@ -378,6 +379,11 @@ async def complete(extra_kwargs = _sanitize_call_kwargs(binding=capability_binding, model=config.model, kwargs=kwargs)+ image_fallback_enabled = (+ not supports_vision(capability_binding, config.model)+ if allow_image_fallback is None+ else allow_image_fallback+ )try:response = await provider.chat_with_retry(@@ -385,7 +391,7 @@ async def complete(model=config.model,reasoning_effort=config.reasoning_effort,retry_delays=retry_delays,- allow_image_fallback=not supports_vision(capability_binding, config.model),+ allow_image_fallback=image_fallback_enabled,**extra_kwargs,)except Exception as exc:@@ -410,6 +416,7 @@ async def stream(max_retries: int = DEFAULT_MAX_RETRIES,retry_delay: float = DEFAULT_RETRY_DELAY,exponential_backoff: bool = DEFAULT_EXPONENTIAL_BACKOFF,+ allow_image_fallback: bool | None = None,**kwargs: Any,) -> AsyncGenerator[str, None]:caller_extra_headers = kwargs.pop("extra_headers", None)@@ -448,6 +455,11 @@ async def stream(extra_kwargs = _sanitize_call_kwargs(binding=capability_binding, model=config.model, kwargs=kwargs)+ image_fallback_enabled = (+ not supports_vision(capability_binding, config.model)+ if allow_image_fallback is None+ else allow_image_fallback+ )queue: asyncio.Queue[str | BaseException | None] = asyncio.Queue()saw_output = False@@ -485,7 +497,7 @@ async def stream(on_content_delta=_on_content_delta,on_reasoning_delta=_on_reasoning_delta,retry_delays=retry_delays,- allow_image_fallback=not supports_vision(capability_binding, config.model),+ allow_image_fallback=image_fallback_enabled,**extra_kwargs,)if in_think_block:diff --git a/deeptutor/services/llm/provider_core/openai_codex_provider.py b/deeptutor/services/llm/provider_core/openai_codex_provider.pyindex d4bdd17c6..13daefd80 100644--- a/deeptutor/services/llm/provider_core/openai_codex_provider.py+++ b/deeptutor/services/llm/provider_core/openai_codex_provider.py@@ -13,6 +13,7 @@ from loguru import loggerfrom deeptutor.services.codex_auth import CodexAuthError, get_codex_oauth_servicefrom deeptutor.services.codex_auth.constants import CODEX_DEFAULT_MODEL_ID, CODEX_RESPONSES_URLfrom deeptutor.services.codex_auth.contracts import CodexToken+from deeptutor.services.llm.exceptions import LLMProviderTransportErrorfrom deeptutor.services.llm.openai_http_client import disable_ssl_verify_enabledfrom deeptutor.services.llm.provider_core.base import LLMProvider, LLMResponse, ToolCallRequestfrom deeptutor.services.llm.provider_core.openai_responses import (@@ -20,6 +21,7 @@ from deeptutor.services.llm.provider_core.openai_responses import (convert_messages,convert_tools,)+from deeptutor.services.llm.request_compat import is_transient_transport_errorDEFAULT_ORIGINATOR = "DeepTutor"@@ -125,7 +127,12 @@ class OpenAICodexProvider(LLMProvider):content=f"Error calling Codex: {exc.public_message}",finish_reason="error",)- except Exception:+ except Exception as exc:+ if is_transient_transport_error(exc):+ # Preserve a structured retry signal without exposing the+ # URL, proxy, response body, or token-bearing request.+ logger.warning("Codex transport request failed: {}", type(exc).__name__)+ raise LLMProviderTransportError("Codex transport request failed.") from exc# The user-facing text stays generic so upstream payloads never# leak, but an operator still needs the real cause in the log.logger.exception("Codex request failed")diff --git a/deeptutor/services/llm/request_compat.py b/deeptutor/services/llm/request_compat.pyindex 087ff302f..29550c788 100644--- a/deeptutor/services/llm/request_compat.py+++ b/deeptutor/services/llm/request_compat.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport httpx-from .exceptions import LLMTimeoutError+from .exceptions import LLMProviderTransportError, LLMTimeoutErrordef _exception_chain(exc: Exception):@@ -102,7 +102,13 @@ def is_transient_transport_error(exc: Exception) -> bool:for current in _exception_chain(exc):if isinstance(current,- (httpx.TransportError, LLMTimeoutError, TimeoutError, ConnectionError),+ (+ httpx.TransportError,+ LLMProviderTransportError,+ LLMTimeoutError,+ TimeoutError,+ ConnectionError,+ ),):return Trueerror_type = type(current)diff --git a/deeptutor/services/rag/pipelines/lightrag/config.py b/deeptutor/services/rag/pipelines/lightrag/config.pyindex 1b7e15faf..2d8aed5fd 100644--- a/deeptutor/services/rag/pipelines/lightrag/config.py+++ b/deeptutor/services/rag/pipelines/lightrag/config.py@@ -22,15 +22,20 @@ Decoupling notes:from __future__ import annotations+import asyncio+from collections.abc import Awaitable, Callableimport importlib.utilimport logging-from typing import TYPE_CHECKING+import re+from typing import TYPE_CHECKING, TypeVarif TYPE_CHECKING:from .worker import OwnerLoopBridgelogger = logging.getLogger(__name__)+_T = TypeVar("_T")+# LightRAG's native retrieval modes. ``hybrid`` (KG + vector) is the safest# general default and matches the shared per-KB ``search_mode`` default.SUPPORTED_MODES = ("naive", "local", "global", "hybrid", "mix")@@ -39,6 +44,18 @@ DEFAULT_MODE = "hybrid"# Conservative cap for the embedding wrapper when the model doesn't advertise one._DEFAULT_MAX_TOKEN_SIZE = 8192+# Keep retries at the LightRAG adapter boundary so RAG-Anything receives one+# predictable policy for both text and vision calls. Provider retries are disabled+# on every attempt to prevent the two retry layers from multiplying.+_ADAPTER_MAX_ATTEMPTS = 3+_ADAPTER_RETRY_DELAYS_SECONDS = (1.0, 2.0)+_ADAPTER_MAX_RETRY_DELAY_SECONDS = 60.0+_RETRYABLE_HTTP_STATUS_CODES = frozenset({408, 429, 500, 502, 503, 504, 529})+_HTTP_STATUS_PATTERN = re.compile(+ r"\b(?:http(?: status)?|status(?: code)?|error code)\s*[:=-]?\s*(\d{3})\b",+ re.I,+)+class LightRagNotAvailableError(RuntimeError):"""Raised when the optional ``raganything`` dependency is not installed."""@@ -48,6 +65,77 @@ class LightRagNotConfiguredError(RuntimeError):"""Raised when DeepTutor's LLM / embedding config can't back LightRAG."""+def _http_status_code(exc: Exception) -> int | None:+ """Return a structured or safely normalized HTTP status for an LLM error."""+ status_code = getattr(exc, "status_code", None)+ if isinstance(status_code, int) and not isinstance(status_code, bool):+ return status_code++ response = getattr(exc, "response", None)+ response_status = getattr(response, "status_code", None)+ if isinstance(response_status, int) and not isinstance(response_status, bool):+ return response_status++ # The Codex provider currently returns a safe, normalized ``HTTP NNN``+ # message through LLMAPIError instead of preserving the status attribute.+ is_llm_api_error = any(cls.__name__ == "LLMAPIError" for cls in type(exc).__mro__)+ message = getattr(exc, "message", None)+ if is_llm_api_error and isinstance(message, str):+ match = _HTTP_STATUS_PATTERN.search(message)+ if match is not None:+ return int(match.group(1))+ return None+++def _retry_classification(exc: Exception) -> tuple[bool, str]:+ """Classify retryability without inspecting or logging provider payloads."""+ from deeptutor.services.llm.request_compat import is_transient_transport_error++ status_code = _http_status_code(exc)+ if status_code is not None:+ return status_code in _RETRYABLE_HTTP_STATUS_CODES, f"http_{status_code}"+ if is_transient_transport_error(exc):+ return True, "transport"+ return False, "non_retryable"+++def _retry_delay_seconds(exc: Exception, scheduled_delay: float) -> float:+ """Honor a safe Retry-After value without allowing unbounded sleeps."""+ from deeptutor.services.llm.error_mapping import retry_after_seconds++ requested_delay = retry_after_seconds(exc)+ if requested_delay is None:+ return scheduled_delay+ return min(requested_delay, _ADAPTER_MAX_RETRY_DELAY_SECONDS)+++async def _run_adapter_with_retry(+ request: Callable[[], Awaitable[_T]],+ *,+ io_bridge: OwnerLoopBridge | None,+) -> _T:+ """Run one adapter request with bounded, non-multiplying retries."""+ for attempt in range(1, _ADAPTER_MAX_ATTEMPTS + 1):+ try:+ if io_bridge is not None:+ return await io_bridge.run(request)+ return await request()+ except Exception as exc:+ should_retry, status = _retry_classification(exc)+ if not should_retry or attempt == _ADAPTER_MAX_ATTEMPTS:+ raise+ logger.warning(+ "LightRAG adapter retry attempt=%d exception=%s status=%s",+ attempt,+ type(exc).__name__,+ status,+ )+ delay = _retry_delay_seconds(exc, _ADAPTER_RETRY_DELAYS_SECONDS[attempt - 1])+ await asyncio.sleep(delay)++ raise AssertionError("unreachable")++def is_lightrag_available() -> bool:"""True when RAG-Anything (which bundles LightRAG) can be imported.@@ -149,9 +237,11 @@ def build_llm_model_func(*, io_bridge: OwnerLoopBridge | None = None):system_prompt=system_prompt,history_messages=history_messages or [],messages=messages,+ max_retries=0,+ allow_image_fallback=False,)- return await io_bridge.run(request) if io_bridge is not None else await request()+ return await _run_adapter_with_retry(request, io_bridge=io_bridge)return llm_model_func@@ -177,9 +267,11 @@ def build_vision_model_func(*, io_bridge: OwnerLoopBridge | None = None):history_messages=history_messages or [],image_data=image_data,messages=messages,+ max_retries=0,+ allow_image_fallback=False,)- return await io_bridge.run(request) if io_bridge is not None else await request()+ return await _run_adapter_with_retry(request, io_bridge=io_bridge)return vision_model_funcdiff --git a/deeptutor/services/rag/pipelines/lightrag/engine.py b/deeptutor/services/rag/pipelines/lightrag/engine.pyindex f318a557d..7e642c6d6 100644--- a/deeptutor/services/rag/pipelines/lightrag/engine.py+++ b/deeptutor/services/rag/pipelines/lightrag/engine.py@@ -14,6 +14,9 @@ native query modes.from __future__ import annotations+import asyncio+from collections.abc import Awaitable, Callable, Iterable, Mapping+import inspectimport loggingfrom pathlib import Pathfrom typing import Any@@ -120,6 +123,59 @@ async def insert(rag: Any, content_list: list[dict], *, file_name: str, doc_id:)+def _managed_queue_funcs(lightrag: Any) -> Iterable[Callable[..., Any]]:+ """Yield each current LightRAG queue wrapper exactly once."""+ role_funcs = getattr(lightrag, "role_llm_funcs", {})+ candidates: list[object] = []+ if isinstance(role_funcs, Mapping):+ candidates.extend(role_funcs.values())++ embedding = getattr(lightrag, "embedding_func", None)+ candidates.append(getattr(embedding, "func", None))+ candidates.append(getattr(lightrag, "rerank_model_func", None))++ seen: set[int] = set()+ for candidate in candidates:+ if not callable(candidate) or id(candidate) in seen:+ continue+ seen.add(id(candidate))+ yield candidate+++async def _shutdown_queues(lightrag: Any, *, cancel_pending: bool) -> None:+ """Bound cleanup of LightRAG's role, embedding, and rerank queues."""+ shutdowns: list[Awaitable[Any]] = []+ for func in _managed_queue_funcs(lightrag):+ shutdown = getattr(func, "shutdown", None)+ if callable(shutdown):+ result = shutdown(graceful=not cancel_pending, timeout=5.0)+ if inspect.isawaitable(result):+ shutdowns.append(result)+ if not shutdowns:+ return++ results = await asyncio.gather(*shutdowns, return_exceptions=True)+ failures = [result for result in results if isinstance(result, BaseException)]+ if failures:+ raise RuntimeError(+ f"Failed to shut down {len(failures)} LightRAG managed queue(s)"+ ) from failures[0]+++async def finalize(rag: Any, *, cancel_pending: bool) -> None:+ """Stop managed work before finalizing RAG-Anything storage resources."""+ lightrag = getattr(rag, "lightrag", None)+ if lightrag is not None:+ await _shutdown_queues(lightrag, cancel_pending=cancel_pending)++ finalizer = getattr(rag, "finalize_storages", None)+ if not callable(finalizer):+ return+ result = finalizer()+ if inspect.isawaitable(result):+ await result++async def ensure_ready(rag: Any) -> None:"""Ensure RAG-Anything has an initialized LightRAG instance."""if getattr(rag, "lightrag", None) is not None:@@ -156,4 +212,4 @@ async def query(rag: Any, question: str, mode: str | None = None) -> str:return result if isinstance(result, str) else str(result)-__all__ = ["build_rag", "insert", "ensure_ready", "query"]+__all__ = ["build_rag", "ensure_ready", "finalize", "insert", "query"]diff --git a/deeptutor/services/rag/pipelines/lightrag/pipeline.py b/deeptutor/services/rag/pipelines/lightrag/pipeline.pyindex bb028421c..dff0c67d3 100644--- a/deeptutor/services/rag/pipelines/lightrag/pipeline.py+++ b/deeptutor/services/rag/pipelines/lightrag/pipeline.py@@ -143,12 +143,25 @@ class LightRagPipeline:async def job(io_bridge: OwnerLoopBridge) -> int:io_bridge.raise_if_cancelled()rag = engine.build_rag(working_dir, io_bridge=io_bridge)- return await self._ingest(- rag,- file_paths,- io_bridge=io_bridge,- progress_callback=progress_callback,- )+ failed = True+ try:+ result = await self._ingest(+ rag,+ file_paths,+ io_bridge=io_bridge,+ progress_callback=progress_callback,+ )+ failed = False+ return result+ finally:+ try:+ await engine.finalize(rag, cancel_pending=failed)+ except BaseException:+ if not failed:+ raise+ self.logger.exception(+ "LightRAG resource cleanup failed while indexing was aborting"+ )return await run_in_worker_loop(job)diff --git a/deeptutor/services/rag/pipelines/lightrag/worker.py b/deeptutor/services/rag/pipelines/lightrag/worker.pyindex 9b1701cad..2aca5db31 100644--- a/deeptutor/services/rag/pipelines/lightrag/worker.py+++ b/deeptutor/services/rag/pipelines/lightrag/worker.py@@ -15,11 +15,71 @@ from collections.abc import Awaitable, Callableimport concurrent.futuresimport contextvarsimport inspect+import loggingimport threadingfrom typing import Any, TypeVarT = TypeVar("T")+logger = logging.getLogger(__name__)++DEFAULT_WORKER_CANCEL_GRACE_SECONDS = 10.0+++class _WorkerLoopController:+ """Thread-safe cancellation handle for the worker loop's top-level task."""++ def __init__(self) -> None:+ self._lock = threading.Lock()+ self._cancel_requested = threading.Event()+ self._loop: asyncio.AbstractEventLoop | None = None+ self._task: asyncio.Task[Any] | None = None++ def bind_current_task(self) -> None:+ """Bind from inside the worker loop and honor an earlier cancellation."""+ loop = asyncio.get_running_loop()+ task = asyncio.current_task()+ if task is None: # pragma: no cover - asyncio always owns this coroutine+ raise RuntimeError("Worker loop has no current task")+ with self._lock:+ self._loop = loop+ self._task = task+ cancel_requested = self._cancel_requested.is_set()+ if cancel_requested:+ task.cancel()++ def clear(self) -> None:+ """Drop references once the worker job reaches a terminal state."""+ with self._lock:+ self._loop = None+ self._task = None++ def cancel(self) -> None:+ """Cancel the worker's actual top-level task, including before bind."""+ self._cancel_requested.set()+ with self._lock:+ loop = self._loop+ task = self._task+ if loop is None or task is None:+ return+ try:+ loop.call_soon_threadsafe(task.cancel)+ except RuntimeError:+ # The worker completed and closed its loop between the snapshot and+ # the signal. Its executor future will become done independently.+ pass++ def stop_loop(self) -> None:+ """Escalate an async cancellation that exceeded its grace period."""+ with self._lock:+ loop = self._loop+ if loop is None:+ return+ try:+ loop.call_soon_threadsafe(loop.stop)+ except RuntimeError:+ pass+class OwnerLoopBridge:"""Run selected awaitables and callbacks on the service event loop.@@ -91,6 +151,8 @@ class OwnerLoopBridge:async def run_in_worker_loop(job: Callable[[OwnerLoopBridge], Awaitable[T]],+ *,+ cancel_grace_seconds: float = DEFAULT_WORKER_CANCEL_GRACE_SECONDS,) -> T:"""Run one async indexing job on a worker thread's private event loop.@@ -100,13 +162,21 @@ async def run_in_worker_loop("""owner_loop = asyncio.get_running_loop()bridge = OwnerLoopBridge(owner_loop)+ controller = _WorkerLoopController()caller_context = contextvars.copy_context()async def invoke_job() -> T:return await job(bridge)+ async def run_bound_job() -> T:+ controller.bind_current_task()+ try:+ return await invoke_job()+ finally:+ controller.clear()+def run() -> T:- return asyncio.run(invoke_job())+ return asyncio.run(run_bound_job())worker = owner_loop.run_in_executor(None, caller_context.run, run)try:@@ -117,13 +187,36 @@ async def run_in_worker_loop(return await asyncio.shield(worker)except asyncio.CancelledError:bridge.cancel()- while not worker.done():+ controller.cancel()+ grace = max(float(cancel_grace_seconds), 0.0)+ deadline = owner_loop.time() + grace+ while not worker.done() and owner_loop.time() < deadline:try:- await asyncio.shield(worker)+ remaining = max(deadline - owner_loop.time(), 0.0)+ await asyncio.wait({worker}, timeout=remaining)except asyncio.CancelledError:# Repeated cancellation still must not strand the worker on a# request scheduled back to this owner loop.bridge.cancel()+ controller.cancel()+ if not worker.done():+ # Stopping the private loop interrupts async work and makes+ # asyncio.run() cancel its remaining tasks during teardown. It+ # still cannot interrupt arbitrary synchronous Python/native work,+ # so keep waiting rather than returning an orphan that may mutate+ # the KB after the request has reported cancellation.+ logger.error(+ "LightRAG worker did not stop within %.1fs; forcing worker-loop teardown",+ grace,+ )+ controller.stop_loop()+ while not worker.done():+ try:+ await asyncio.wait({worker})+ except asyncio.CancelledError:+ bridge.cancel()+ controller.cancel()+ controller.stop_loop()# Retrieve the terminal exception so the executor Future never emits# an "exception was never retrieved" warning. The caller's# cancellation remains authoritative.@@ -134,4 +227,8 @@ async def run_in_worker_loop(raise-__all__ = ["OwnerLoopBridge", "run_in_worker_loop"]+__all__ = [+ "DEFAULT_WORKER_CANCEL_GRACE_SECONDS",+ "OwnerLoopBridge",+ "run_in_worker_loop",+]diff --git a/tests/services/llm/test_error_mapping.py b/tests/services/llm/test_error_mapping.pyindex 6d4f3c675..80cb2a603 100644--- a/tests/services/llm/test_error_mapping.py+++ b/tests/services/llm/test_error_mapping.py@@ -1,9 +1,12 @@"""Tests for LLM error mapping helpers."""-from deeptutor.services.llm.error_mapping import map_error+from datetime import datetime, timezone++from deeptutor.services.llm.error_mapping import map_error, retry_after_secondsfrom deeptutor.services.llm.exceptions import (LLMAPIError,LLMAuthenticationError,+ LLMProviderTransportError,LLMRateLimitError,ProviderContextWindowError,)@@ -29,6 +32,36 @@ def test_map_error_status_code_rate_limit() -> None:assert isinstance(mapped, LLMRateLimitError)+def test_map_error_preserves_retry_after_header() -> None:+ error = DummyError("rate limited", status_code=429)+ error.response = type(+ "Response",+ (),+ {"headers": {"Retry-After": "12.5"}},+ )()++ mapped = map_error(error, provider="openai")++ assert isinstance(mapped, LLMRateLimitError)+ assert mapped.retry_after == 12.5+++def test_retry_after_seconds_parses_http_date() -> None:+ error = DummyError("temporarily unavailable", status_code=503)+ error.response = type(+ "Response",+ (),+ {"headers": {"Retry-After": "Wed, 21 Oct 2015 07:28:10 GMT"}},+ )()++ delay = retry_after_seconds(+ error,+ now=datetime(2015, 10, 21, 7, 28, tzinfo=timezone.utc),+ )++ assert delay == 10.0++def test_map_error_message_context_window() -> None:"""Context length errors should map to the provider context window error."""mapped = map_error(DummyError("maximum context length exceeded"), provider="openai")@@ -40,3 +73,12 @@ def test_map_error_falls_back_to_api_error() -> None:mapped = map_error(DummyError("boom", status_code=500), provider="openai")assert isinstance(mapped, LLMAPIError)assert mapped.status_code == 500+++def test_map_error_preserves_structured_transport_error() -> None:+ error = LLMProviderTransportError("provider connection failed")++ mapped = map_error(error, provider="openai_codex")++ assert mapped is error+ assert mapped.provider == "openai_codex"diff --git a/tests/services/llm/test_factory_provider_exec.py b/tests/services/llm/test_factory_provider_exec.pyindex f8f66dd7e..7234fccb3 100644--- a/tests/services/llm/test_factory_provider_exec.py+++ b/tests/services/llm/test_factory_provider_exec.py@@ -80,6 +80,21 @@ async def test_complete_merges_config_and_caller_extra_headers(monkeypatch) -> Nassert merged == {"X-Config": "from-config", "X-Caller": "from-caller"}+async def test_complete_honors_explicit_image_fallback_override(monkeypatch) -> None:+ cfg = _make_cfg(model="unknown-model", binding="custom", provider_name="custom")+ provider = _FakeProvider()++ monkeypatch.setattr("deeptutor.services.llm.factory.get_llm_config", lambda: cfg)+ monkeypatch.setattr(+ "deeptutor.services.llm.factory.get_runtime_provider",+ lambda _config: provider,+ )++ assert await complete("hello", allow_image_fallback=False) == "ok"+ assert provider.complete_kwargs["allow_image_fallback"] is False++@pytest.mark.asyncioasync def test_stream_merges_config_and_caller_extra_headers(monkeypatch) -> None:cfg = _make_cfg(extra_headers={"X-Config": "cfg"})diff --git a/tests/services/llm/test_openai_codex_oauth_provider.py b/tests/services/llm/test_openai_codex_oauth_provider.pyindex 60b658e0c..ea8180236 100644--- a/tests/services/llm/test_openai_codex_oauth_provider.py+++ b/tests/services/llm/test_openai_codex_oauth_provider.py@@ -3,10 +3,13 @@ from __future__ import annotationsfrom contextlib import asynccontextmanagerfrom typing import Any, AsyncIterator+import httpcore+import httpximport pytestfrom deeptutor.services.codex_auth.constants import CODEX_RESPONSES_URLfrom deeptutor.services.codex_auth.contracts import CodexAuthError, CodexToken+from deeptutor.services.llm.exceptions import LLMProviderTransportErrorfrom deeptutor.services.llm.provider_core import openai_codex_provider as modulefrom deeptutor.services.llm.provider_core.openai_codex_provider import (CodexHTTPError,@@ -224,6 +227,40 @@ async def test_provider_does_not_expose_network_error_details(assert "token" not in result.content.lower()+ "transport_error",+ [+ httpx.RemoteProtocolError("private proxy host and token"),+ httpcore.RemoteProtocolError("private proxy host and token"),+ ],+)+async def test_transport_failure_raises_sanitized_retryable_error(+ monkeypatch: pytest.MonkeyPatch,+ transport_error: Exception,+) -> None:+ service = FakeCodexService()+ sensitive_message = "private proxy host and token"++ async def transport_failure(+ *_args: Any,+ **_kwargs: Any,+ ) -> tuple[str, list[Any], str]:+ raise transport_error++ monkeypatch.setattr(module, "get_codex_oauth_service", lambda: service)+ monkeypatch.setattr(module, "_request_codex", transport_failure)++ with pytest.raises(LLMProviderTransportError) as exc_info:+ await OpenAICodexProvider().chat(+ [{"role": "user", "content": "hello"}],+ )++ assert str(exc_info.value) == "Codex transport request failed."+ assert sensitive_message not in str(exc_info.value)+ assert exc_info.value.__cause__ is transport_error++def test_provider_source_no_longer_imports_oauth_cli_kit() -> None:source = module.__loader__.get_source(module.__name__) # type: ignore[union-attr]diff --git a/tests/services/rag/test_lightrag_pipeline.py b/tests/services/rag/test_lightrag_pipeline.pyindex 59fdb3cbf..efa05e3d5 100644--- a/tests/services/rag/test_lightrag_pipeline.py+++ b/tests/services/rag/test_lightrag_pipeline.py@@ -13,6 +13,7 @@ import asyncioimport contextvarsimport inspectimport json+import loggingfrom pathlib import Pathimport sysimport threading@@ -21,6 +22,15 @@ import typesimport pytest+from deeptutor.services.llm.exceptions import (+ LLMAPIError,+ LLMAuthenticationError,+ LLMConfigError,+ LLMParseError,+ LLMProviderTransportError,+ LLMRateLimitError,+ LLMTimeoutError,+)from deeptutor.services.rag.factory import (LIGHTRAG_PROVIDER,get_pipeline,@@ -278,6 +288,8 @@ def test_lightrag_llm_adapter_preserves_messages_and_drops_extra_kwargs(assert captured["system_prompt"] == "sys"assert captured["history_messages"] == []assert captured["messages"] == [{"role": "user", "content": "from messages"}]+ assert captured["max_retries"] == 0+ assert captured["allow_image_fallback"] is Falseassert "response_format" not in capturedassert "hashing_kv" not in capturedassert "keyword_extraction" not in captured@@ -312,9 +324,325 @@ def test_lightrag_vision_adapter_preserves_messages(monkeypatch) -> None:assert captured["prompt"] == ""assert captured["image_data"] == "abc123"assert captured["messages"] == [{"role": "user", "content": [{"type": "text", "text": "hi"}]}]+ assert captured["max_retries"] == 0+ assert captured["allow_image_fallback"] is Falseassert bridge.calls == 1+def test_lightrag_llm_adapter_uses_three_total_attempts_and_disables_provider_retry(+ monkeypatch,+) -> None:+ calls: list[dict[str, object]] = []+ sleep_delays: list[float] = []+ failures = [+ LLMAPIError("temporary server error", status_code=503),+ LLMRateLimitError("rate limited"),+ ]++ class _Client:+ def get_model_func(self):+ async def model_func(_prompt, **kwargs):+ calls.append(kwargs)+ if failures:+ raise failures.pop(0)+ return "ok"++ return model_func++ async def fake_sleep(delay: float) -> None:+ sleep_delays.append(delay)++ monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: _Client())+ monkeypatch.setattr(lr_config.asyncio, "sleep", fake_sleep)++ bridge = _RecordingBridge()+ func = lr_config.build_llm_model_func(io_bridge=bridge)++ assert asyncio.run(func("prompt")) == "ok"+ assert len(calls) == 3+ assert [call["max_retries"] for call in calls] == [0, 0, 0]+ assert sleep_delays == [1.0, 2.0]+ assert bridge.calls == 3+++ "error",+ [+ LLMTimeoutError("timeout"),+ LLMProviderTransportError("provider transport failed"),+ TimeoutError("timeout"),+ ConnectionError("connection"),+ LLMRateLimitError("rate limited"),+ LLMAPIError("temporary server error", status_code=500),+ LLMAPIError("temporary overload", status_code=529),+ LLMAPIError("Error calling Codex: Codex returned HTTP 503."),+ LLMAPIError("Error code: 529 - overloaded_error"),+ ],+)+def test_lightrag_adapter_retries_classified_transient_errors(monkeypatch, error) -> None:+ calls = 0++ class _Client:+ def get_model_func(self):+ async def model_func(_prompt, **_kwargs):+ nonlocal calls+ calls += 1+ if calls == 1:+ raise error+ return "ok"++ return model_func++ async def fake_sleep(_delay: float) -> None:+ return None++ monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: _Client())+ monkeypatch.setattr(lr_config.asyncio, "sleep", fake_sleep)++ assert asyncio.run(lr_config.build_llm_model_func()("prompt")) == "ok"+ assert calls == 2+++ "error",+ [+ LLMAuthenticationError("unauthorized"),+ LLMAPIError("forbidden", status_code=403),+ LLMAPIError("not implemented", status_code=501),+ LLMConfigError("bad configuration"),+ LLMParseError("bad response"),+ ValueError("contract mismatch"),+ ],+)+def test_lightrag_adapter_does_not_retry_deterministic_errors(monkeypatch, error) -> None:+ calls = 0++ class _Client:+ def get_model_func(self):+ async def model_func(_prompt, **_kwargs):+ nonlocal calls+ calls += 1+ raise error++ return model_func++ monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: _Client())++ with pytest.raises(type(error)) as captured:+ asyncio.run(lr_config.build_llm_model_func()("prompt"))++ assert captured.value is error+ assert calls == 1+++def test_lightrag_adapter_exhaustion_reraises_original_final_exception(monkeypatch) -> None:+ failures = [+ LLMAPIError("first", status_code=502),+ LLMAPIError("second", status_code=503),+ LLMAPIError("final", status_code=504),+ ]+ final_error = failures[-1]+ calls = 0++ class _Client:+ def get_model_func(self):+ async def model_func(_prompt, **_kwargs):+ nonlocal calls+ calls += 1+ raise failures.pop(0)++ return model_func++ async def fake_sleep(_delay: float) -> None:+ return None++ monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: _Client())+ monkeypatch.setattr(lr_config.asyncio, "sleep", fake_sleep)++ with pytest.raises(LLMAPIError) as captured:+ asyncio.run(lr_config.build_llm_model_func()("prompt"))++ assert captured.value is final_error+ assert calls == 3+++ ("retry_after", "expected_delay"),+ [(7.5, 7.5), (120.0, 60.0), (-1.0, 1.0), ("invalid", 1.0)],+)+def test_lightrag_adapter_honors_bounded_retry_after(+ monkeypatch,+ retry_after,+ expected_delay,+) -> None:+ calls = 0+ sleep_delays: list[float] = []++ class _Client:+ def get_model_func(self):+ async def model_func(_prompt, **_kwargs):+ nonlocal calls+ calls += 1+ if calls == 1:+ raise LLMRateLimitError("rate limited", retry_after=retry_after)+ return "ok"++ return model_func++ async def fake_sleep(delay: float) -> None:+ sleep_delays.append(delay)++ monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: _Client())+ monkeypatch.setattr(lr_config.asyncio, "sleep", fake_sleep)++ assert asyncio.run(lr_config.build_llm_model_func()("prompt")) == "ok"+ assert sleep_delays == [expected_delay]+++def test_lightrag_adapter_honors_retry_after_response_header(monkeypatch) -> None:+ calls = 0+ sleep_delays: list[float] = []++ class RetryableResponseError(Exception):+ status_code = 503+ response = types.SimpleNamespace(headers={"Retry-After": "4"})++ class _Client:+ def get_model_func(self):+ async def model_func(_prompt, **_kwargs):+ nonlocal calls+ calls += 1+ if calls == 1:+ raise RetryableResponseError("temporary")+ return "ok"++ return model_func++ async def fake_sleep(delay: float) -> None:+ sleep_delays.append(delay)++ monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: _Client())+ monkeypatch.setattr(lr_config.asyncio, "sleep", fake_sleep)++ assert asyncio.run(lr_config.build_llm_model_func()("prompt")) == "ok"+ assert sleep_delays == [4.0]+++def test_lightrag_adapter_preserves_cancellation_without_retry(monkeypatch) -> None:+ calls = 0++ class _Client:+ def get_model_func(self):+ async def model_func(_prompt, **_kwargs):+ nonlocal calls+ calls += 1+ raise asyncio.CancelledError++ return model_func++ monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: _Client())++ with pytest.raises(asyncio.CancelledError):+ asyncio.run(lr_config.build_llm_model_func()("prompt"))++ assert calls == 1+++async def test_lightrag_vision_adapter_disables_provider_image_fallback(+ monkeypatch,+) -> None:+ from deeptutor.services.llm.client import LLMClient+ from deeptutor.services.llm.config import LLMConfig+ from deeptutor.services.llm.multimodal import has_image_parts+ from deeptutor.services.llm.provider_core.base import LLMProvider, LLMResponse++ class ScriptedProvider(LLMProvider):+ def __init__(self) -> None:+ super().__init__()+ self.calls_had_image: list[bool] = []++ async def chat(self, messages, **kwargs):+ del kwargs+ self.calls_had_image.append(has_image_parts(messages))+ if len(self.calls_had_image) == 1:+ return LLMResponse(+ content="this model does not support images",+ finish_reason="error",+ )+ return LLMResponse(content="text fallback should not run")++ def get_default_model(self) -> str:+ return "unknown-model"++ config = LLMConfig(+ model="unknown-model",+ api_key="test-key",+ base_url="https://api.example.com/v1",+ binding="custom",+ provider_name="custom",+ )+ client = LLMClient(config)+ provider = ScriptedProvider()++ monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: client)+ monkeypatch.setattr("deeptutor.services.llm.factory.get_llm_config", lambda: config)+ monkeypatch.setattr(+ "deeptutor.services.llm.factory.get_runtime_provider",+ lambda _config: provider,+ )++ func = lr_config.build_vision_model_func()+ with pytest.raises(LLMAPIError, match="does not support images"):+ await func("prompt", image_data="QUJD")++ assert provider.calls_had_image == [True]+++def test_lightrag_vision_adapter_preserves_payload_and_redacts_retry_log(+ monkeypatch,+ caplog,+) -> None:+ sensitive_message = "prompt-secret base64-secret token-secret account-secret"+ image_payload = "base64-secret-image-payload"+ image_calls: list[object] = []+ retry_settings: list[object] = []+ calls = 0++ class _Client:+ def get_vision_model_func(self):+ async def model_func(_prompt, **kwargs):+ nonlocal calls+ calls += 1+ image_calls.append(kwargs["image_data"])+ retry_settings.append(kwargs["max_retries"])+ if calls == 1:+ raise ConnectionError(sensitive_message)+ return "ok"++ return model_func++ async def fake_sleep(_delay: float) -> None:+ return None++ monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: _Client())+ monkeypatch.setattr(lr_config.asyncio, "sleep", fake_sleep)+ caplog.set_level(logging.WARNING, logger=lr_config.__name__)++ func = lr_config.build_vision_model_func()+ assert asyncio.run(func("prompt-secret", image_data=image_payload)) == "ok"++ assert calls == 2+ assert all(payload is image_payload for payload in image_calls)+ assert retry_settings == [0, 0]+ assert sensitive_message not in caplog.text+ assert "prompt-secret" not in caplog.text+ assert image_payload not in caplog.text+ assert (+ "LightRAG adapter retry attempt=1 exception=ConnectionError status=transport" in caplog.text+ )++def test_build_rag_skips_raganything_parser_install_check(monkeypatch) -> None:"""Regression for issue #594.@@ -631,6 +959,112 @@ def test_indexing_cancellation_waits_for_worker_loop_to_close() -> None:assert owner_callback_called is False+def test_indexing_cancellation_cancels_worker_main_task() -> None:+ started = threading.Event()+ stopped = threading.Event()+ worker_loop: asyncio.AbstractEventLoop | None = None++ async def scenario() -> None:+ async def job(_io_bridge) -> None:+ nonlocal worker_loop+ worker_loop = asyncio.get_running_loop()+ started.set()+ try:+ await asyncio.Event().wait()+ finally:+ stopped.set()++ task = asyncio.create_task(run_in_worker_loop(job))+ while not started.is_set():+ await asyncio.sleep(0)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(task, timeout=0.5)++ asyncio.run(scenario())++ assert stopped.is_set()+ assert worker_loop is not None+ assert worker_loop.is_closed()+++def test_indexing_cancellation_escalates_when_worker_suppresses_first_cancel() -> None:+ started = threading.Event()+ first_cancel = threading.Event()+ stopped = threading.Event()+ worker_loop: asyncio.AbstractEventLoop | None = None++ async def scenario() -> None:+ async def job(_io_bridge) -> None:+ nonlocal worker_loop+ worker_loop = asyncio.get_running_loop()+ started.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ first_cancel.set()+ await asyncio.Event().wait()+ finally:+ stopped.set()++ task = asyncio.create_task(run_in_worker_loop(job, cancel_grace_seconds=0.01))+ while not started.is_set():+ await asyncio.sleep(0)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(task, timeout=0.5)++ asyncio.run(scenario())++ assert first_cancel.is_set()+ assert stopped.is_set()+ assert worker_loop is not None+ assert worker_loop.is_closed()+++def test_indexing_failure_forces_queue_shutdown_and_finalizes_storage(+ tmp_path,+ monkeypatch,+) -> None:+ calls: list[tuple[object, ...]] = []++ class _QueueFunc:+ async def __call__(self, *_args, **_kwargs) -> None:+ return None++ async def shutdown(self, *, graceful: bool, timeout: float) -> None:+ calls.append(("shutdown", graceful, timeout))++ queue_func = _QueueFunc()++ class _FailingRag:+ def __init__(self, working_dir) -> None:+ self.working_dir = Path(working_dir)+ self.lightrag = types.SimpleNamespace(+ role_llm_funcs={"extract": queue_func},+ embedding_func=types.SimpleNamespace(func=queue_func),+ rerank_model_func=None,+ )++ async def insert_content_list(self, **_kwargs) -> None:+ raise RuntimeError("entity extraction failed")++ async def finalize_storages(self) -> None:+ calls.append(("finalize",))++ monkeypatch.setattr(engine, "build_rag", lambda wd, **_: _FailingRag(wd))+ _stub_parse(monkeypatch, blocks=[{"type": "text", "text": "x", "page_idx": 0}])+ _force_available(monkeypatch, True)+ document = tmp_path / "bad.pdf"+ document.write_bytes(b"%PDF")++ pipe = LightRagPipeline(kb_base_dir=str(tmp_path))+ with pytest.raises(RuntimeError, match="entity extraction failed"):+ asyncio.run(pipe.initialize("kb", [str(document)]))++ assert calls == [("shutdown", False, 5.0), ("finalize",)]++def test_initialize_requires_lightrag(tmp_path, monkeypatch) -> None:_force_available(monkeypatch, False)pipe = LightRagPipeline(kb_base_dir=str(tmp_path))