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
perf(answer): embed the question once per call, not once per stage (#1182)
Swati Ahuja18448e1c1ac4
diff --git a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.pyindex 57b7d570b..5e464ab4a 100644--- a/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py+++ b/packages/server/src/repowise/server/mcp_server/_answer_pipeline.py@@ -37,7 +37,9 @@ from __future__ import annotationsimport asyncioimport contextlib+import loggingimport re+from collections import OrderedDictfrom typing import Anyfrom sqlalchemy import select@@ -46,6 +48,8 @@ from repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import GraphEdge, GraphNode, Pagefrom repowise.core.test_paths import is_test_path+_log = logging.getLogger("repowise.mcp.answer")+# How many candidates each retriever fetches before merging. Both modes# tend to put the right answer in their top ~10, so 15 gives RRF room to# resolve ties without dragging weak tail hits into the merge.@@ -85,6 +89,87 @@ _PAGERANK_BIAS_MAX = 0.3# rank-3/4 hit (~3.0-3.5)._GRAPH_EXPAND_DAMPING = 0.7+# Budget for embedding the question. The searches that used to embed inline were+# bounded at 8s including the embed, so the round-trip keeps that ceiling now+# that it happens on its own.+_EMBED_TIMEOUT_S = 8.0+++# ---------------------------------------------------------------------------+# The question's embedding, computed once per call+# ---------------------------------------------------------------------------++# Answering one question used to embed its text up to three times: once for the+# main fetch, once for the concept lookup on a subsystem-shaped question, once+# for the neighbourhood re-rank on a flow-shaped one. Each is a network+# round-trip to the embedding provider, billed, for a vector that cannot differ+# between them.+#+# Keyed by ``(id(store), question)`` and holding the store in the value, so an+# id can never be recycled onto a different store while its entries are live.+# Capacity is a handful of entries rather than one: concurrent calls with+# different questions would otherwise evict each other and re-embed. An entry is+# a pure function of (embedder, text), so a hit across calls is as correct as a+# hit within one.+_QUESTION_VECTOR_CACHE_MAX = 4+_QUESTION_VECTORS: OrderedDict[tuple[int, str], tuple[Any, list[float]]] = OrderedDict()+++async def question_vector(ctx: Any, question: str) -> list[float] | None:+ """The question's embedding, computed at most once per store and question.++ Returns None when there is no store, the backend holds no embedder of its+ own, or the embed failed — callers then fall back to the store's own+ ``search(text)``, which embeds inline. That fallback is a cost regression,+ never a correctness one, so it warns rather than raising.+ """+ store = getattr(ctx, "vector_store", None)+ if store is None or not question:+ return None++ key = (id(store), question)+ cached = _QUESTION_VECTORS.get(key)+ if cached is not None:+ _QUESTION_VECTORS.move_to_end(key)+ return cached[1]++ try:+ vectors = await asyncio.wait_for(store.embed_texts([question]), timeout=_EMBED_TIMEOUT_S)+ except Exception:+ _log.warning(+ "get_answer could not embed the question up front; each retrieval "+ "stage will embed it again",+ exc_info=True,+ )+ return None+ if not vectors:+ # Backend without an embedder of its own. Not an error — but it means+ # every stage pays for its own round-trip, so it is worth seeing.+ _log.debug("Vector store cannot embed directly; per-stage embedding stands")+ return None++ vector = [float(v) for v in vectors[0]]+ _QUESTION_VECTORS[key] = (store, vector)+ while len(_QUESTION_VECTORS) > _QUESTION_VECTOR_CACHE_MAX:+ _QUESTION_VECTORS.popitem(last=False)+ return vector+++async def vector_search(+ store: Any, question: str, limit: int, *, vector: list[float] | None+) -> list[Any]:+ """Nearest pages to *question*, reusing *vector* when the backend allows it.++ Every backend that can search by raw vector is spared a second embedding of+ text it has already embedded; one that cannot returns None from+ ``search_by_vector`` and is asked to search the text as before.+ """+ if vector is not None:+ by_vector = await store.search_by_vector(vector, limit=limit)+ if by_vector is not None:+ return by_vector+ return await store.search(question, limit=limit)+# ---------------------------------------------------------------------------# Stage 1: Hybrid retrieval (FTS + vector → RRF merge)@@ -163,9 +248,12 @@ async def _safe_vector_search(ctx: Any, question: str) -> list[Any]:if ready is not None:with contextlib.suppress(TimeoutError):await asyncio.wait_for(ready.wait(), timeout=30.0)+ # Embedded here, before the store is asked anything: this is the first stage+ # to need the vector, and every later stage reads the same one back.+ vector = await question_vector(ctx, question)try:return await asyncio.wait_for(- ctx.vector_store.search(question, limit=_RETRIEVAL_FETCH_LIMIT),+ vector_search(ctx.vector_store, question, _RETRIEVAL_FETCH_LIMIT, vector=vector),timeout=8.0,)except Exception:@@ -519,7 +607,10 @@ async def _semantic_concept_paths(question: str, ctx: Any) -> list[str]:return []try:results = await asyncio.wait_for(- vs.search(question, limit=_CONCEPT_FETCH_LIMIT), timeout=8.0+ vector_search(+ vs, question, _CONCEPT_FETCH_LIMIT, vector=await question_vector(ctx, question)+ ),+ timeout=8.0,)except Exception:return []@@ -561,11 +652,9 @@ async def expand_via_parent_page(hits: list[dict], question: str, ctx: Any) -> l# Cluster on the strongest real hits: skip decision records and any hit# without a path so decision noise crowding the top slots can't starve the# clustering of the member files that reveal the subsystem.- top = [- h- for h in hits- if h.get("target_path") and h.get("page_type") != "decision_record"- ][:_PARENT_EXPAND_TOP_N]+ top = [h for h in hits if h.get("target_path") and h.get("page_type") != "decision_record"][+ :_PARENT_EXPAND_TOP_N+ ]if not top:return hitsdiff --git a/packages/server/src/repowise/server/mcp_server/_neighbor_rerank.py b/packages/server/src/repowise/server/mcp_server/_neighbor_rerank.pyindex e814127af..d95f06aed 100644--- a/packages/server/src/repowise/server/mcp_server/_neighbor_rerank.py+++ b/packages/server/src/repowise/server/mcp_server/_neighbor_rerank.py@@ -23,6 +23,7 @@ from typing import Anyfrom sqlalchemy import selectfrom repowise.core.persistence.models import Page+from repowise.server.mcp_server._answer_pipeline import question_vector, vector_searchfrom repowise.server.mcp_server._flow_path import _is_plumbing, _load_file_adjacency# Motion cues that mark a data-flow question. Loose on purpose: the walk (reaches@@ -136,17 +137,26 @@ def _walk_neighborhood(adj: dict[str, set[str]], seeds: list[str]) -> set[str]:return {n for n in reached if n not in seed_set and not _is_plumbing(n)}-async def _relevance_order(searcher: Any, question: str, pool: set[str]) -> list[str]:+async def _relevance_order(+ searcher: Any, question: str, pool: set[str], *, vector: list[float] | None = None+) -> list[str]:"""Rank ``pool`` members by a store's relevance to ``question``.One corpus-wide search, kept in the store's returned order — order is all RRFconsumes, so the two stores' score scales never need reconciling. Returns []on any store failure; the other arm then drives the fusion alone.++ ``vector`` is the question's already-computed embedding. Passing it spares+ the embedding arm a second round-trip for text the main fetch already+ embedded; the lexical arm has no use for it and ignores it."""if searcher is None or not pool:return []try:- results = await searcher.search(question, limit=_RANK_SCAN)+ if vector is not None:+ results = await vector_search(searcher, question, _RANK_SCAN, vector=vector)+ else:+ results = await searcher.search(question, limit=_RANK_SCAN)except Exception:return []order, seen = [], set()@@ -197,7 +207,12 @@ async def expand_via_neighbor_rerank(# Fuse embedding + lexical relevance over the pool AND the seeds (so buried# originals contest on the same signal), reusing the pipeline's two stores.scored = pool | set(seed_paths)- vec_order = await _relevance_order(getattr(ctx, "vector_store", None), question, scored)+ vec_order = await _relevance_order(+ getattr(ctx, "vector_store", None),+ question,+ scored,+ vector=await question_vector(ctx, question),+ )fts_order = await _relevance_order(getattr(ctx, "fts", None), question, scored)fused = _rrf_fuse(vec_order, fts_order)if not fused:diff --git a/tests/unit/server/mcp/test_answer_question_embedding.py b/tests/unit/server/mcp/test_answer_question_embedding.pynew file mode 100644index 000000000..2057cfa0d--- /dev/null+++ b/tests/unit/server/mcp/test_answer_question_embedding.py@@ -0,0 +1,183 @@+"""One question, one embedding round-trip.++Answering a question embedded its text up to three times: the main hybrid+fetch, the concept lookup a subsystem-shaped question triggers, and the+neighbourhood re-rank a flow-shaped question triggers. Each one is a billed+network call to the embedding provider for a vector that cannot differ between+them — the store already exposes ``embed_texts`` / ``search_by_vector`` for+exactly this, and the answer path was the one caller not using them.++The spy here counts calls into the embedder, which is the only place the waste+was visible: every stage returned correct results while paying three times.+"""++from __future__ import annotations++import logging+from types import SimpleNamespace++import pytest++from repowise.core.persistence.vector_store import InMemoryVectorStore+from repowise.core.providers.embedding.base import MockEmbedder+from repowise.server.mcp_server import _answer_pipeline as pipeline+from repowise.server.mcp_server import _neighbor_rerank as rerank++_QUESTION = "walk me through how a changed file travels into the persist path"+++class _SpyEmbedder:+ """MockEmbedder that records every batch of texts it is asked to embed."""++ def __init__(self) -> None:+ self._inner = MockEmbedder()+ self.batches: list[list[str]] = []++ @property+ def dimensions(self) -> int:+ return self._inner.dimensions++ async def embed(self, texts: list[str]) -> list[list[float]]:+ self.batches.append(list(texts))+ return await self._inner.embed(texts)+++async def spy_store():+ embedder = _SpyEmbedder()+ store = InMemoryVectorStore(embedder=embedder)+ await store.embed_batch(+ [+ (+ f"file_page:pkg/alpha/{name}.py",+ f"The {name} module hands changed files to the persist path.",+ {+ "title": name,+ "page_type": "file_page",+ "target_path": f"pkg/alpha/{name}.py",+ },+ )+ for name in ("one", "two", "three")+ ]+ )+ embedder.batches.clear() # indexing is not what is under test+ yield store, embedder+ await store.close()++[email protected](autouse=True)+def _clear_vector_cache():+ """Cross-test isolation: the cache is module-level, as the store it keys on+ is process-lived."""+ cache = getattr(pipeline, "_QUESTION_VECTORS", None)+ if cache is not None:+ cache.clear()+ yield+ if cache is not None:+ cache.clear()+++def _questions_embedded(embedder: _SpyEmbedder) -> list[str]:+ return [t for batch in embedder.batches for t in batch]+++async def test_the_main_fetch_embeds_the_question_once(spy_store):+ store, embedder = spy_store+ ctx = SimpleNamespace(fts=None, vector_store=store)++ hits = await pipeline.hybrid_retrieve(_QUESTION, ctx)++ assert hits, "the fetch must still return hits"+ assert _questions_embedded(embedder) == [_QUESTION]+++async def test_the_concept_lookup_does_not_re_embed_after_the_main_fetch(spy_store):+ """A subsystem-shaped question runs both stages; both need the same vector."""+ store, embedder = spy_store+ ctx = SimpleNamespace(fts=None, vector_store=store)++ await pipeline.hybrid_retrieve(_QUESTION, ctx)+ await pipeline._semantic_concept_paths(_QUESTION, ctx)++ assert _questions_embedded(embedder) == [_QUESTION]+++async def test_three_stages_share_one_embedding(spy_store):+ """The gate: the main fetch, the concept lookup and the neighbourhood+ re-rank each need the question's vector and between them pay once."""+ store, embedder = spy_store+ ctx = SimpleNamespace(fts=None, vector_store=store)+ pool = {"pkg/alpha/two.py", "pkg/alpha/three.py"}++ await pipeline.hybrid_retrieve(_QUESTION, ctx)+ await pipeline._semantic_concept_paths(_QUESTION, ctx)+ await rerank._relevance_order(+ store, _QUESTION, pool, vector=await pipeline.question_vector(ctx, _QUESTION)+ )++ assert _questions_embedded(embedder) == [_QUESTION]+++async def test_the_relevance_scan_still_ranks_the_pool_from_the_shared_vector(spy_store):+ """Reusing the vector must return the same pool members as searching the+ text — a cheaper call that ranked nothing would be a silent regression."""+ store, embedder = spy_store+ ctx = SimpleNamespace(fts=None, vector_store=store)+ pool = {"pkg/alpha/two.py", "pkg/alpha/three.py"}++ from_text = await rerank._relevance_order(store, _QUESTION, pool)+ embedder.batches.clear()+ from_vector = await rerank._relevance_order(+ store, _QUESTION, pool, vector=await pipeline.question_vector(ctx, _QUESTION)+ )++ assert from_vector == from_text+ assert sorted(from_vector) == sorted(pool)+++async def test_a_backend_that_cannot_embed_directly_still_retrieves(spy_store, caplog):+ """``embed_texts`` returns None for a store holding no embedder of its own.+ The stages then embed per-search as before, which costs money but must not+ cost results."""+ store, embedder = spy_store+ ctx = SimpleNamespace(fts=None, vector_store=store)++ async def _no_embedder(_texts):+ return None++ store.embed_texts = _no_embedder # type: ignore[method-assign]++ assert await pipeline.question_vector(ctx, _QUESTION) is None+ hits = await pipeline.hybrid_retrieve(_QUESTION, ctx)++ assert hits+ assert _questions_embedded(embedder) == [_QUESTION]+++async def test_a_failing_embed_warns_and_leaves_retrieval_working(spy_store, caplog):+ """The up-front embed is an optimisation. Losing it silently would hide a+ broken embedder behind three per-stage calls that also fail."""+ store, _embedder = spy_store+ ctx = SimpleNamespace(fts=None, vector_store=store)++ async def _boom(_texts):+ raise RuntimeError("embedding provider down")++ store.embed_texts = _boom # type: ignore[method-assign]++ with caplog.at_level(logging.WARNING, logger="repowise.mcp.answer"):+ assert await pipeline.question_vector(ctx, _QUESTION) is None++ assert any("embed the question" in r.getMessage() for r in caplog.records), caplog.text+++async def test_the_cache_is_bounded(spy_store):+ """A per-question entry that is never evicted is a leak in a long-lived+ server."""+ store, _embedder = spy_store+ ctx = SimpleNamespace(fts=None, vector_store=store)++ for i in range(pipeline._QUESTION_VECTOR_CACHE_MAX + 3):+ await pipeline.question_vector(ctx, f"question number {i}")++ assert len(pipeline._QUESTION_VECTORS) == pipeline._QUESTION_VECTOR_CACHE_MAX