Skip to content

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

Repair stale Pandas Arrow registrations before GraphRAG workers start (#1414)

georgelichen8aac8b4061bb
diff --git a/deeptutor/services/rag/pipelines/graphrag/engine.py b/deeptutor/services/rag/pipelines/graphrag/engine.py
index fe254f4a1..2450c9eb4 100644
--- a/deeptutor/services/rag/pipelines/graphrag/engine.py
+++ b/deeptutor/services/rag/pipelines/graphrag/engine.py
@@ -34,6 +34,7 @@ from .errors import (
classify_embedding_error,
classify_model_error,
)
+from .pandas_compat import prepare_pandas_arrow_extensions
from .provider import (
COMPLETION_TYPE,
resolve_completion_call_args,
@@ -106,6 +107,7 @@ async def _run_isolated(work: Callable[[], Awaitable[_T]]) -> _T:
"""
def _runner() -> _T:
+ prepare_pandas_arrow_extensions()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
diff --git a/deeptutor/services/rag/pipelines/graphrag/pandas_compat.py b/deeptutor/services/rag/pipelines/graphrag/pandas_compat.py
new file mode 100644
index 000000000..7759a6209
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/graphrag/pandas_compat.py
@@ -0,0 +1,68 @@
+"""Scoped compatibility for stale Pandas/Arrow extension registrations."""
+
+from __future__ import annotations
+
+import importlib
+import threading
+from typing import Any
+
+_PANDAS_ARROW_EXTENSION_MODULE = "pandas.core.arrays.arrow.extension_types"
+_PANDAS_ARROW_EXTENSION_NAMES = ("pandas.period", "pandas.interval")
+_extension_registration_lock = threading.Lock()
+
+
+def _is_duplicate_registration_error(error: BaseException) -> bool:
+ message = str(error)
+ return (
+ "A type extension with name" in message
+ and "already defined" in message
+ and any(name in message for name in _PANDAS_ARROW_EXTENSION_NAMES)
+ )
+
+
+def _unregister_stale_extension_types(
+ pyarrow: Any,
+ arrow_key_error: type[BaseException],
+) -> None:
+ for name in _PANDAS_ARROW_EXTENSION_NAMES:
+ try:
+ pyarrow.unregister_extension_type(name)
+ except arrow_key_error:
+ # The extension may not have been registered yet.
+ continue
+
+
+def prepare_pandas_arrow_extensions() -> None:
+ """Import Pandas Arrow extensions, repairing stale registry entries.
+
+ Pandas registers ``pandas.period`` and ``pandas.interval`` as a module import
+ side effect. If a test runner, plugin, or reload hook removes that module from
+ ``sys.modules`` without unregistering the pyarrow types, importing it again
+ raises ``pyarrow.lib.ArrowKeyError``. GraphRAG runs in isolated worker threads,
+ so this repair is performed immediately inside each worker before GraphRAG
+ imports its pandas users.
+
+ The helper is a no-op when pyarrow is not installed. Other import or registry
+ errors are allowed to propagate so a real dependency failure is not hidden.
+ """
+ try:
+ import pyarrow
+ from pyarrow.lib import ArrowKeyError
+ except ImportError:
+ return
+
+ with _extension_registration_lock:
+ try:
+ importlib.import_module(_PANDAS_ARROW_EXTENSION_MODULE)
+ except ModuleNotFoundError as error:
+ if error.name == "pandas":
+ return
+ raise
+ except ArrowKeyError as error:
+ if not _is_duplicate_registration_error(error):
+ raise
+ _unregister_stale_extension_types(pyarrow, ArrowKeyError)
+ importlib.import_module(_PANDAS_ARROW_EXTENSION_MODULE)
+
+
+__all__ = ["prepare_pandas_arrow_extensions"]
diff --git a/tests/services/rag/test_graphrag_pandas_compat.py b/tests/services/rag/test_graphrag_pandas_compat.py
new file mode 100644
index 000000000..50029247d
--- /dev/null
+++ b/tests/services/rag/test_graphrag_pandas_compat.py
@@ -0,0 +1,69 @@
+"""Regression tests for Pandas/Arrow extension registration in GraphRAG."""
+
+from __future__ import annotations
+
+import importlib
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+import pytest
+
+
+def test_prepare_pandas_arrow_extensions_repairs_stale_registration() -> None:
+ """A re-import after module removal must not hit ArrowKeyError."""
+ pytest.importorskip("pandas", reason="pandas is required for this regression test")
+ pytest.importorskip("pyarrow", reason="pyarrow is required for this regression test")
+ root = Path(__file__).parents[3]
+ script = """
+import importlib
+import sys
+
+import pandas.core.arrays.arrow.extension_types
+
+module_name = "pandas.core.arrays.arrow.extension_types"
+del sys.modules[module_name]
+
+from deeptutor.services.rag.pipelines.graphrag.pandas_compat import (
+ prepare_pandas_arrow_extensions,
+)
+
+prepare_pandas_arrow_extensions()
+importlib.import_module(module_name)
+print("ok")
+"""
+ env = os.environ.copy()
+ env["PYTHONPATH"] = os.pathsep.join(
+ part for part in (str(root), env.get("PYTHONPATH", "")) if part
+ )
+ result = subprocess.run(
+ [sys.executable, "-c", script],
+ cwd=root,
+ env=env,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+
+ assert result.returncode == 0, result.stderr
+ assert result.stdout.strip().endswith("ok")
+
+
+def test_prepare_pandas_arrow_extensions_does_not_hide_unrelated_arrow_errors(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Only the known duplicate-registration error is recovered."""
+ pytest.importorskip("pyarrow", reason="pyarrow is required for this regression test")
+
+ from pyarrow.lib import ArrowKeyError
+
+ from deeptutor.services.rag.pipelines.graphrag import pandas_compat
+
+ def raise_unrelated_error(_name: str) -> None:
+ raise ArrowKeyError("unrelated Arrow registry failure")
+
+ monkeypatch.setattr(importlib, "import_module", raise_unrelated_error)
+
+ with pytest.raises(ArrowKeyError, match="unrelated Arrow registry failure"):
+ pandas_compat.prepare_pandas_arrow_extensions()
diff --git a/tests/services/rag/test_graphrag_pipeline.py b/tests/services/rag/test_graphrag_pipeline.py
index bffc89415..9b0eab9e6 100644
--- a/tests/services/rag/test_graphrag_pipeline.py
+++ b/tests/services/rag/test_graphrag_pipeline.py
@@ -382,6 +382,23 @@ def test_engine_entry_points_run_on_a_private_loop() -> None:
assert seen["current"] is seen["running"]
+def test_engine_isolated_runtime_prepares_pandas_arrow_extensions(monkeypatch) -> None:
+ calls: list[str] = []
+
+ monkeypatch.setattr(
+ engine,
+ "prepare_pandas_arrow_extensions",
+ lambda: calls.append("prepared"),
+ )
+
+ async def work() -> str:
+ calls.append("work")
+ return "done"
+
+ assert asyncio.run(engine._run_isolated(work)) == "done"
+ assert calls == ["prepared", "work"]
+
+
def test_compatibility_probe_resolves_candidate_without_mutating_active_model(
monkeypatch, tmp_path: Path
) -> None: