mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-04 14:39:34 +08:00
fix(rag): run GraphRAG off the server's uvloop loop (#695)
`graphrag_llm` calls `nest_asyncio2.apply()` at import time, and that patch refuses uvloop — the loop `uvicorn[standard]` gives the backend on macOS/Linux. So the first GraphRAG import raised "Can't patch loop of type <class 'uvloop.Loop'>" and indexing died before it started; the reporter's workaround was to force UVICORN_LOOP=asyncio for the whole app. Drive every GraphRAG entry point from a worker thread that owns a stock asyncio loop: the import-time patch and GraphRAG's own nested `run_until_complete` calls get the reentrant loop they expect, and the server's loop is left alone. The adapter stays the only graphrag-aware module, so its function-local imports now also decide where that patch lands. Completes #695 — the settings.yaml `$` escape and the `cache.type` fix landed in #699.
This commit is contained in:
@@ -11,9 +11,11 @@ used — DeepTutor runs fine without the optional dependency installed.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Awaitable, Callable
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from typing import Any, TypeVar
|
||||
|
||||
from .config import DEFAULT_MODE, normalize_mode, query_config_from_settings
|
||||
|
||||
@@ -40,18 +42,55 @@ _OUTPUTS_BY_MODE: dict[str, tuple[list[str], list[str]]] = {
|
||||
}
|
||||
|
||||
|
||||
_T = TypeVar("_T")
|
||||
|
||||
|
||||
def _load_config(root_dir: Path):
|
||||
from graphrag.config.load_config import load_config
|
||||
|
||||
return load_config(root_dir=Path(root_dir))
|
||||
|
||||
|
||||
async def _run_isolated(work: Callable[[], Awaitable[_T]]) -> _T:
|
||||
"""Run one GraphRAG entry point on a private, plain-asyncio event loop.
|
||||
|
||||
``graphrag_llm`` calls ``nest_asyncio2.apply()`` at import time, and that
|
||||
patch refuses uvloop ("Can't patch loop of type <class 'uvloop.Loop'>") —
|
||||
which is precisely the loop ``uvicorn[standard]`` gives the backend, so on
|
||||
macOS/Linux the first GraphRAG import aborted indexing before it started
|
||||
(issue #695). Importing and driving GraphRAG from a worker thread that owns
|
||||
a stock asyncio loop hands that patch — and GraphRAG's own nested
|
||||
``run_until_complete`` calls — the reentrant loop they expect, and leaves
|
||||
the server's uvloop loop untouched.
|
||||
|
||||
Every ``graphrag`` import therefore has to happen inside ``work``, which is
|
||||
why the entry points below keep their imports function-local.
|
||||
"""
|
||||
|
||||
def _runner() -> _T:
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
try:
|
||||
return loop.run_until_complete(work())
|
||||
finally:
|
||||
try:
|
||||
loop.close()
|
||||
finally:
|
||||
asyncio.set_event_loop(None)
|
||||
|
||||
return await asyncio.to_thread(_runner)
|
||||
|
||||
|
||||
async def build(root_dir: Path, *, is_update: bool = False) -> None:
|
||||
"""Run the GraphRAG indexing pipeline rooted at ``root_dir``.
|
||||
|
||||
Raises on any failed workflow so the caller can surface an error and clean
|
||||
up the (incomplete) version directory.
|
||||
"""
|
||||
await _run_isolated(lambda: _build_impl(root_dir, is_update=is_update))
|
||||
|
||||
|
||||
async def _build_impl(root_dir: Path, *, is_update: bool) -> None:
|
||||
from graphrag.api import build_index
|
||||
from graphrag.config.enums import IndexingMethod
|
||||
|
||||
@@ -92,6 +131,10 @@ async def search(root_dir: Path, query: str, mode: str | None = None) -> tuple[s
|
||||
``context_data`` is normalised to a dict of record lists
|
||||
(reports/entities/relationships/claims/sources) via GraphRAG's own helper.
|
||||
"""
|
||||
return await _run_isolated(lambda: _search_impl(root_dir, query, mode))
|
||||
|
||||
|
||||
async def _search_impl(root_dir: Path, query: str, mode: str | None) -> tuple[str, dict]:
|
||||
import graphrag.api as api
|
||||
from graphrag.utils.api import reformat_context_data
|
||||
|
||||
|
||||
@@ -126,6 +126,29 @@ def test_local_api_key_placeholder_when_missing() -> None:
|
||||
)
|
||||
|
||||
|
||||
def test_engine_entry_points_run_on_a_private_loop() -> None:
|
||||
"""GraphRAG's LLM layer patches the *current* loop at import time and
|
||||
refuses uvloop — the loop uvicorn[standard] runs the backend on. Every
|
||||
entry point must therefore execute on its own plain-asyncio loop, off the
|
||||
caller's (issue #695)."""
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
async def work() -> str:
|
||||
seen["running"] = asyncio.get_running_loop()
|
||||
seen["current"] = asyncio.get_event_loop()
|
||||
return "done"
|
||||
|
||||
async def caller() -> str:
|
||||
seen["outer"] = asyncio.get_running_loop()
|
||||
return await engine._run_isolated(work)
|
||||
|
||||
assert asyncio.run(caller()) == "done"
|
||||
assert seen["running"] is not seen["outer"]
|
||||
# ``nest_asyncio2.apply()`` patches whatever ``get_event_loop()`` returns,
|
||||
# so the private loop has to be the thread's current one, not just running.
|
||||
assert seen["current"] is seen["running"]
|
||||
|
||||
|
||||
def test_write_settings_roundtrips(tmp_path) -> None:
|
||||
import yaml
|
||||
|
||||
|
||||
Reference in New Issue
Block a user