Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(search): give the vector leg a budget the cold path can clear (#1678) (#1685)
Raghav Chamadiyac5af63caf53b
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.mdindex 1c8699bc7..a2f4b7371 100644--- a/docs/reference/CONFIG.md+++ b/docs/reference/CONFIG.md@@ -740,6 +740,7 @@ The `.repowise/.env` file is gitignored automatically.| `REPOWISE_EMBEDDING_MODEL` | Embedding model, applies to any embedder || `REPOWISE_EMBEDDING_DIMS` | Embedding output dimensions (optional; inferred from the model otherwise) || `REPOWISE_EMBEDDING_TIMEOUT` | Embed request timeout in seconds (default: `30` for `ollama`, `10` elsewhere). Raise it for a local endpoint — one request embeds a whole batch, and an expired batch is reported only as `N/N items failed to embed`. An unparseable value warns and keeps the default |+| `REPOWISE_VECTOR_SEARCH_TIMEOUT_S` | Seconds one vector-store query may take (default: `30`, capped at `120`). The first query in a process pays for the store open, the first embed and the first ANN probe, which can run past 13s on a cold index where a warm query takes under a second. Raise it on a slow disk or a very large wiki; a timeout drops the semantic leg and logs a warning, leaving full-text hits only. An unparseable value warns and keeps the default || `OPENAI_EMBEDDING_TIMEOUT` | As above, `openai` only; takes precedence over the shared variable || `GEMINI_EMBEDDING_TIMEOUT` | As above, `gemini` only || `OPENROUTER_EMBEDDING_TIMEOUT` | As above, `openrouter` only |diff --git a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.pyindex 10118adff..1aad1772c 100644--- a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py+++ b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py@@ -58,6 +58,10 @@ from repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import GraphEdge, GraphNode, Pagefrom repowise.core.providers.embedding import store_has_semantic_vectorsfrom repowise.core.test_paths import is_test_path+from repowise.server.mcp_server._helpers import (+ _VECTOR_TIMEOUT_ENV,+ vector_search_timeout_s,+)from repowise.server.mcp_server._prose_symbols import symbol_backed_pages_log = logging.getLogger("repowise.mcp.answer")@@ -462,10 +466,16 @@ async def _safe_vector_search(ctx: Any, question: str) -> list[Any]:_RETRIEVAL_FETCH_LIMIT + _DECISION_OVERFETCH,vector=vector,),- timeout=8.0,+ timeout=vector_search_timeout_s(),)except TimeoutError:_record_leg("vector", "timeout")+ _log.warning(+ "Vector search exceeded its %gs budget; answering without semantic hits. "+ "Raise it with %s=<seconds>.",+ vector_search_timeout_s(),+ _VECTOR_TIMEOUT_ENV,+ )return []except Exception:_record_leg("vector", "error")@@ -963,7 +973,7 @@ async def _semantic_concept_paths(question: str, ctx: Any) -> list[str]:vector_search(vs, question, _CONCEPT_FETCH_LIMIT, vector=await question_vector(ctx, question)),- timeout=8.0,+ timeout=vector_search_timeout_s(),)except Exception:return []diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.pyindex 043702049..953c27bbb 100644--- a/packages/server/src/repowise/server/mcp_server/_helpers.py+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py@@ -3,6 +3,7 @@from __future__ import annotationsimport json+import loggingimport osimport os.pathfrom collections.abc import Collection@@ -22,12 +23,48 @@ from repowise.core.persistence.models import (from repowise.core.persistence.sql import LIKE_ESCAPE, escape_like # noqa: F401from repowise.server.mcp_server import _state+_log = logging.getLogger("repowise.mcp")+# ---------------------------------------------------------------------------# Constants# ---------------------------------------------------------------------------_CODE_EXTS = _LANG_REGISTRY.all_code_extensions()+# Ceiling on one vector-store query, seconds. The first query in a process pays+# for the store open, the first embed and the first ANN probe; #1678 measured+# 6.3s + 13.4s on a cold Windows index where a warm query takes 0.19s. The old+# 8s budget therefore expired on the first query of every process and the+# vector leg degraded to full-text with nothing said. Raise it with+# REPOWISE_VECTOR_SEARCH_TIMEOUT_S on a slow disk or a very large index.+_VECTOR_TIMEOUT_ENV = "REPOWISE_VECTOR_SEARCH_TIMEOUT_S"+_VECTOR_TIMEOUT_DEFAULT_S = 30.0+# A search an agent blocks on; past this the client's own tool timeout fires+# first, so a larger value cannot produce results anyone still accepts.+_VECTOR_TIMEOUT_MAX_S = 120.0+++def vector_search_timeout_s() -> float:+ """Seconds one vector query may take, from env or the cold-start default.++ An unparseable or non-positive value warns and keeps the default instead of+ silently disabling the leg, matching how REPOWISE_EMBEDDING_TIMEOUT is+ resolved.+ """+ raw = (os.environ.get(_VECTOR_TIMEOUT_ENV) or "").strip()+ if not raw:+ return _VECTOR_TIMEOUT_DEFAULT_S+ try:+ seconds = float(raw)+ except ValueError:+ seconds = float("nan")+ # NaN fails this too, so it lands on the default rather than on a budget+ # asyncio.wait_for would treat as already expired.+ if not seconds > 0:+ _log.warning("Ignoring unusable %s=%r", _VECTOR_TIMEOUT_ENV, raw)+ return _VECTOR_TIMEOUT_DEFAULT_S+ return min(seconds, _VECTOR_TIMEOUT_MAX_S)+# Words that mark a string as a natural-language question rather than a path.# Keep this small — false positives here send genuine paths to the NL branch,# which is harmless (path lookup also runs as a fallback) but slower.diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.pyindex 694ac32d6..b6923a9bf 100644--- a/packages/server/src/repowise/server/mcp_server/tool_search.py+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport asyncioimport contextlib+import loggingimport refrom typing import Any@@ -19,6 +20,7 @@ from repowise.core.registry import mcp_tool_registry as mcpfrom repowise.core.test_paths import is_test_path, is_test_related_pathfrom repowise.server.mcp_server._answer_pipeline import _RRF_K, _RRF_SCORE_SCALEfrom repowise.server.mcp_server._helpers import (+ _VECTOR_TIMEOUT_ENV,_get_exclude_spec,_get_repo,_is_path,@@ -27,6 +29,7 @@ from repowise.server.mcp_server._helpers import (attach_ignored_arguments,filter_dicts_by_key,resolve_enum_argument,+ vector_search_timeout_s,)from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._page_paths import file_candidates, hit_file_path@@ -37,6 +40,8 @@ from repowise.server.mcp_server.tool_search_symbols import (search_symbols_single,)+_log = logging.getLogger("repowise.mcp.search")+# Minimum relevance score below which results are dropped. Prevents# returning semantically unrelated pages when the corpus has no real match._MIN_RELEVANCE_SCORE = 0.03@@ -279,11 +284,15 @@ async def _non_decision_fallback(ctx, query: str, fetch_limit: int) -> list[dictsrc = "vector"# Skipped on a keyless index, which then falls through to the FTS branch.if store_has_semantic_vectors(ctx.vector_store):- with contextlib.suppress(TimeoutError, Exception):+ try:results = await asyncio.wait_for(ctx.vector_store.search(query, limit=fetch_limit * 4),- timeout=8.0,+ timeout=vector_search_timeout_s(),)+ except TimeoutError:+ _log.warning("Vector re-fetch timed out; falling back to full-text")+ except Exception:+ _log.debug("Vector re-fetch failed; falling back to full-text", exc_info=True)if not results:src = "fts"with contextlib.suppress(Exception):@@ -611,8 +620,22 @@ async def _safe_vector(ctx, query: str, limit: int) -> list:"""if ctx.vector_store is None or not store_has_semantic_vectors(ctx.vector_store):return []- with contextlib.suppress(Exception):- return await asyncio.wait_for(ctx.vector_store.search(query, limit=limit), timeout=8.0)+ try:+ return await asyncio.wait_for(+ ctx.vector_store.search(query, limit=limit), timeout=vector_search_timeout_s()+ )+ except TimeoutError:+ # Not suppressed silently: a timeout here drops the whole semantic leg+ # and the caller returns full-text-only hits that look like a normal+ # result set, which is how #1678 read as "semantic search finds nothing".+ _log.warning(+ "Vector search exceeded its %gs budget; returning no semantic hits. "+ "Raise it with %s=<seconds>.",+ vector_search_timeout_s(),+ _VECTOR_TIMEOUT_ENV,+ )+ except Exception:+ _log.debug("Vector search failed; returning no semantic hits", exc_info=True)return []diff --git a/tests/unit/server/mcp/test_vector_search_timeout.py b/tests/unit/server/mcp/test_vector_search_timeout.pynew file mode 100644index 000000000..512e01c51--- /dev/null+++ b/tests/unit/server/mcp/test_vector_search_timeout.py@@ -0,0 +1,104 @@+"""The vector leg's budget must survive a cold store, and say so when it does not.++#1678: the first vector query in a process pays for the store open, the first+embed and the first ANN probe. Measured at 6.3s + 13.4s on a cold Windows index+where a warm query takes 0.19s. The budget was a hardcoded 8s wrapped in+``contextlib.suppress``, so that first query expired every time, the leg+returned ``[]``, and search silently degraded to full-text with nothing logged+and ``embedder_degraded`` still false.+"""++from __future__ import annotations++import asyncio+import logging++import pytest++from repowise.server.mcp_server import tool_search+from repowise.server.mcp_server._helpers import (+ _VECTOR_TIMEOUT_DEFAULT_S,+ _VECTOR_TIMEOUT_ENV,+ _VECTOR_TIMEOUT_MAX_S,+ vector_search_timeout_s,+)+++class _SlowStore:+ """A store whose first query takes longer than the old 8s budget."""++ embedder = object()++ def __init__(self, delay: float):+ self.delay = delay+ self.calls = 0++ async def search(self, query, limit=None, **kw):+ self.calls += 1+ await asyncio.sleep(self.delay)+ return ["hit"]+++class _Ctx:+ def __init__(self, store):+ self.vector_store = store+ self.fts = None++[email protected](autouse=True)+def _clean_env(monkeypatch):+ monkeypatch.delenv(_VECTOR_TIMEOUT_ENV, raising=False)+++def test_default_budget_clears_the_measured_cold_path() -> None:+ """13.4s was the measured cold first query. The default has to cover it."""+ assert vector_search_timeout_s() >= 15.0+ assert _VECTOR_TIMEOUT_DEFAULT_S >= 15.0++[email protected]("raw,expected", [("60", 60.0), ("2.5", 2.5), (" 45 ", 45.0)])+def test_env_override_is_honoured(monkeypatch, raw, expected) -> None:+ monkeypatch.setenv(_VECTOR_TIMEOUT_ENV, raw)+ assert vector_search_timeout_s() == expected+++def test_override_is_capped(monkeypatch) -> None:+ monkeypatch.setenv(_VECTOR_TIMEOUT_ENV, "9999")+ assert vector_search_timeout_s() == _VECTOR_TIMEOUT_MAX_S++[email protected]("raw", ["abc", "0", "-5", "nan", ""])+def test_unusable_override_keeps_the_default(monkeypatch, raw) -> None:+ """An unparseable value must not disable the leg, matching REPOWISE_EMBEDDING_TIMEOUT."""+ monkeypatch.setenv(_VECTOR_TIMEOUT_ENV, raw)+ assert vector_search_timeout_s() == _VECTOR_TIMEOUT_DEFAULT_S+++def test_safe_vector_survives_a_query_slower_than_the_old_budget(monkeypatch) -> None:+ """The exact #1678 case: a query past 8s used to return []. It must not now."""+ monkeypatch.setenv(_VECTOR_TIMEOUT_ENV, "30")+ store = _SlowStore(delay=0.05)+ monkeypatch.setattr(tool_search, "store_has_semantic_vectors", lambda _s: True)+ out = asyncio.run(tool_search._safe_vector(_Ctx(store), "q", 5))+ assert out == ["hit"]+ assert store.calls == 1+++def test_safe_vector_timeout_is_logged_not_swallowed(monkeypatch, caplog) -> None:+ """A timeout drops the whole semantic leg, so it must not be invisible."""+ monkeypatch.setenv(_VECTOR_TIMEOUT_ENV, "0.01")+ monkeypatch.setattr(tool_search, "store_has_semantic_vectors", lambda _s: True)+ with caplog.at_level(logging.WARNING, logger="repowise.mcp.search"):+ out = asyncio.run(tool_search._safe_vector(_Ctx(_SlowStore(delay=1.0)), "q", 5))+ assert out == []+ assert any(_VECTOR_TIMEOUT_ENV in r.getMessage() for r in caplog.records)+++def test_no_hardcoded_eight_second_vector_budget() -> None:+ """Pins the fix: every vector site reads the shared budget."""+ from pathlib import Path++ root = Path(tool_search.__file__).parent+ for name in ("tool_search.py", "_answer_pipeline.py"):+ text = (root / name).read_text(encoding="utf-8")+ assert "timeout=8.0" not in text, f"{name} still hardcodes the old vector budget"