Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(mcp): stop the first tool call racing the lancedb import (#1231)

Raghav Chamadiya3b7e1ef79f0b
diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.py
index 0ea472292..34b73a8f1 100644
--- a/packages/server/src/repowise/server/mcp_server/__init__.py
+++ b/packages/server/src/repowise/server/mcp_server/__init__.py
@@ -100,6 +100,7 @@ _STATE_NAMES = frozenset(
"_fts",
"_repo_path",
"_vector_store_ready",
+ "_lancedb_ready",
"_registry",
"_workspace_root",
"_cross_repo_enricher",
diff --git a/packages/server/src/repowise/server/mcp_server/_failure_shield.py b/packages/server/src/repowise/server/mcp_server/_failure_shield.py
index 63b243ece..72c3dbdde 100644
--- a/packages/server/src/repowise/server/mcp_server/_failure_shield.py
+++ b/packages/server/src/repowise/server/mcp_server/_failure_shield.py
@@ -15,6 +15,7 @@ still sees (and dead-end-debits) the shaped error response.
from __future__ import annotations
+import asyncio
import contextlib
import functools
import inspect
@@ -22,8 +23,15 @@ import logging
from collections.abc import Callable
from typing import Any
+from repowise.server.mcp_server import _state
+
logger = logging.getLogger(__name__)
+# Ceiling on how long a tool call waits for the deferred `import lancedb` to
+# finish. The import is seconds, not minutes; the bound exists only so a
+# pathological environment degrades to a slow answer rather than a stuck one.
+_WARMUP_TIMEOUT_S = 60.0
+
# _get_repo raises LookupError with these two message shapes; matching on the
# message keeps _helpers.py free of any import back-reference to this module.
_NOT_INDEXED_MARKER = "No repositories found"
@@ -84,6 +92,34 @@ def _shape_exception(tool: str, exc: Exception) -> dict[str, Any]:
return _shape_internal_error(tool, exc)
+async def _await_import_warmup(tool: str) -> None:
+ """Hold a tool call until the deferred ``import lancedb`` has finished.
+
+ That import runs on a worker thread so the loop keeps answering while it
+ proceeds. But an import on a worker thread holds Python's import locks, and
+ every tool body lazily imports something: when the two overlap they block
+ each other and the *event loop itself* stops making progress. Nothing
+ recovers from that state, because the pending ``asyncio.wait_for`` bounds
+ that would otherwise cap the call need the loop in order to fire. The
+ observed symptom is the first tool call of a session never returning.
+
+ Waiting here, before any handler body runs, keeps the main thread out of
+ the import machinery for the duration, which is what breaks the cycle.
+ """
+ ready = _state._lancedb_ready
+ if ready is None or ready.is_set():
+ return
+ try:
+ await asyncio.wait_for(ready.wait(), timeout=_WARMUP_TIMEOUT_S)
+ except TimeoutError:
+ logger.warning(
+ "mcp tool %s proceeding after waiting %.0fs for the lancedb import; "
+ "vector search may be unavailable for this call",
+ tool,
+ _WARMUP_TIMEOUT_S,
+ )
+
+
def shield(fn: Callable[..., Any]) -> Callable[..., Any]:
"""Wrap an async MCP tool so no exception escapes to FastMCP.
@@ -98,6 +134,7 @@ def shield(fn: Callable[..., Any]) -> Callable[..., Any]:
@functools.wraps(fn)
async def _wrapped(*args: Any, **kwargs: Any) -> Any:
try:
+ await _await_import_warmup(tool)
return await fn(*args, **kwargs)
except Exception as exc:
logger.warning("mcp tool %s shielded exception: %s", tool, exc, exc_info=True)
diff --git a/packages/server/src/repowise/server/mcp_server/_server.py b/packages/server/src/repowise/server/mcp_server/_server.py
index 252bd4801..102a8a4c4 100644
--- a/packages/server/src/repowise/server/mcp_server/_server.py
+++ b/packages/server/src/repowise/server/mcp_server/_server.py
@@ -220,6 +220,38 @@ def _resolve_embedder():
return MockEmbedder()
+async def _cancel_task(task: asyncio.Task) -> None:
+ """Cancel a lifespan background task and swallow its unwind."""
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError, Exception):
+ await task
+
+
+async def _warm_lancedb() -> None:
+ """Import lancedb once, off the event loop, and signal when it is done.
+
+ The import pulls in numpy/pyarrow and their native extensions, which costs
+ seconds on a cold filesystem. Running it on a worker thread keeps the loop
+ answering, but a worker-thread import holds Python's import locks, and tool
+ bodies lazily import as they run. When the two overlap they block each
+ other and the event loop stops making progress entirely — at which point
+ the timeouts that would cap the call cannot fire either, because firing
+ them needs the loop.
+
+ Tool dispatch waits on this event before running any handler body (see
+ ``_failure_shield``), so the two never overlap.
+ """
+ try:
+ await asyncio.to_thread(__import__, "lancedb")
+ except ImportError:
+ pass # optional dependency — the InMemory fallback covers it
+ except Exception:
+ _log.warning("lancedb import failed — vector search falls back to InMemory")
+ finally:
+ if _state._lancedb_ready is not None:
+ _state._lancedb_ready.set()
+
+
async def _load_vector_stores(repo_path: str | None) -> None:
"""Load embedder + vector stores in the background.
@@ -330,6 +362,12 @@ async def _lifespan(server: FastMCP):
_state._vector_store_ready before querying the vector store.
"""
+ # Start the lancedb import immediately and gate tool dispatch on it. Both
+ # modes load vector stores in the background, and in both the first tool
+ # call can otherwise land mid-import and wedge the loop.
+ _state._lancedb_ready = asyncio.Event()
+ _warm_task = asyncio.create_task(_warm_lancedb(), name="lancedb-warmup")
+
# --- Workspace detection ------------------------------------------------
ws_root, ws_config, ws_repo_alias = _detect_workspace(_state._repo_path)
@@ -401,6 +439,8 @@ async def _lifespan(server: FastMCP):
yield
+ await _cancel_task(_warm_task)
+ _state._lancedb_ready = None
_state._cross_repo_enricher = None
await registry.close()
_state._registry = None
@@ -454,9 +494,9 @@ async def _lifespan(server: FastMCP):
yield
- _bg_task.cancel()
- with contextlib.suppress(asyncio.CancelledError, Exception):
- await _bg_task
+ await _cancel_task(_bg_task)
+ await _cancel_task(_warm_task)
+ _state._lancedb_ready = None
await engine.dispose()
# _decision_store is an alias for _vector_store — close only once.
diff --git a/packages/server/src/repowise/server/mcp_server/_state.py b/packages/server/src/repowise/server/mcp_server/_state.py
index bf42a8f94..e89795974 100644
--- a/packages/server/src/repowise/server/mcp_server/_state.py
+++ b/packages/server/src/repowise/server/mcp_server/_state.py
@@ -16,6 +16,14 @@ _repo_path: str | None = None
# tool_search awaits this before searching to avoid racing a background load.
_vector_store_ready: asyncio.Event | None = None
+# Set to an asyncio.Event by _lifespan; signals that the deferred `import
+# lancedb` has finished (successfully or not). Tool dispatch waits on this
+# before running any handler body, because that import runs on a worker thread
+# and holds import locks: a handler that lazily imports while it is in flight
+# deadlocks the event loop, and no asyncio timeout can recover a loop that is
+# itself blocked. ``None`` when no background import was started.
+_lancedb_ready: asyncio.Event | None = None
+
# Workspace mode — set by _lifespan when a workspace is detected.
_registry: Any = None # RepoRegistry | None
_workspace_root: str | None = None
diff --git a/tests/unit/server/mcp/test_failure_shield.py b/tests/unit/server/mcp/test_failure_shield.py
index 533ed1c7c..5aeab214e 100644
--- a/tests/unit/server/mcp/test_failure_shield.py
+++ b/tests/unit/server/mcp/test_failure_shield.py
@@ -119,3 +119,93 @@ def test_server_composes_shield_into_middleware():
source = _inspect.getsource(mcp_mod)
assert "_failure_shield" in source
assert "_savings_instrument(_failure_shield(fn))" in source
+
+
+# ---------------------------------------------------------------------------
+# Import warm-up gate
+#
+# The deferred `import lancedb` runs on a worker thread and holds Python's
+# import locks. A tool body that lazily imports while it is in flight blocks
+# against it, and the event loop stops making progress — which also stops the
+# asyncio timeouts that would otherwise cap the call from ever firing. The
+# observed symptom was the first tool call of a session never returning. The
+# shield holds calls until the import is done so the two never overlap.
+# ---------------------------------------------------------------------------
+
+
+async def test_tool_waits_for_the_lancedb_import(monkeypatch):
+ """A call that arrives mid-import runs only after the import signals done."""
+ import asyncio
+
+ from repowise.server.mcp_server import _state
+
+ ready = asyncio.Event()
+ monkeypatch.setattr(_state, "_lancedb_ready", ready, raising=False)
+
+ started = asyncio.Event()
+
+ async def tool() -> dict:
+ started.set()
+ return {"ok": True}
+
+ task = asyncio.create_task(shield(tool)())
+ await asyncio.sleep(0.05)
+ assert not started.is_set(), "handler body ran while the import was in flight"
+
+ ready.set()
+ assert await task == {"ok": True}
+ assert started.is_set()
+
+
+async def test_no_wait_once_the_import_is_done(monkeypatch):
+ """A warmed server pays nothing: the gate is a set-Event check."""
+ import asyncio
+
+ from repowise.server.mcp_server import _state
+
+ ready = asyncio.Event()
+ ready.set()
+ monkeypatch.setattr(_state, "_lancedb_ready", ready, raising=False)
+
+ async def tool() -> dict:
+ return {"ok": True}
+
+ assert await shield(tool)() == {"ok": True}
+
+
+async def test_no_gate_when_no_import_was_started(monkeypatch):
+ """No background import (no event) means no wait at all."""
+ from repowise.server.mcp_server import _state
+
+ monkeypatch.setattr(_state, "_lancedb_ready", None, raising=False)
+
+ async def tool() -> dict:
+ return {"ok": True}
+
+ assert await shield(tool)() == {"ok": True}
+
+
+async def test_gate_is_bounded(monkeypatch):
+ """A pathological import degrades to a slow answer, never a stuck client."""
+ import asyncio
+
+ # Reach the module through importlib: the package re-exports `shield`
+ # under the name `_failure_shield`, so attribute access finds the function
+ # rather than the submodule.
+ import importlib
+
+ from repowise.server.mcp_server import _state
+
+ shield_mod = importlib.import_module("repowise.server.mcp_server._failure_shield")
+
+ monkeypatch.setattr(_state, "_lancedb_ready", asyncio.Event(), raising=False)
+ monkeypatch.setattr(shield_mod, "_WARMUP_TIMEOUT_S", 0.05)
+
+ async def tool() -> dict:
+ return {"ok": True}
+
+ assert await shield(tool)() == {"ok": True}