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(search): rank same-named symbols by one shared key (#2701)

Swati Ahuja5a21f11c6aec
diff --git a/packages/server/src/repowise/server/mcp_server/_symbol_lookup.py b/packages/server/src/repowise/server/mcp_server/_symbol_lookup.py
index 12a875931..0298e9a80 100644
--- a/packages/server/src/repowise/server/mcp_server/_symbol_lookup.py
+++ b/packages/server/src/repowise/server/mcp_server/_symbol_lookup.py
@@ -21,6 +21,8 @@ from sqlalchemy import or_, select
from repowise.core.persistence.models import WikiSymbol
from repowise.core.persistence.sql import LIKE_ESCAPE, escape_like
+from repowise.core.support_paths import is_support_path
+from repowise.core.test_paths import is_test_path
# Separators used between name segments AFTER the file path.
NAME_SEPARATORS = (".", "::", "/")
@@ -99,6 +101,58 @@ def bare_name(name: str) -> str:
return tail
+# Kinds a bare name most likely means, best first; everything else (variables,
+# constants, fields) ranks after methods.
+_KIND_RANK = {
+ "class": 0,
+ "struct": 0,
+ "enum": 0,
+ "interface": 1,
+ "trait": 1,
+ "type_alias": 1,
+ "function": 2,
+ "method": 3,
+}
+_OTHER_KIND_RANK = 4
+
+
+def _dotted(name: str) -> str:
+ for sep in NAME_SEPARATORS[1:]:
+ name = name.replace(sep, ".")
+ return name
+
+
+def symbol_rank_key(
+ query: str,
+ *,
+ name: str | None,
+ qualified_name: str | None,
+ kind: str | None,
+ path: str | None,
+ language: str | None = None,
+ centrality: float = 0.0,
+) -> tuple:
+ """Sort key (ascending) for symbols competing for one name, best first.
+
+ Exact case, then exact name, then kind (class > interface > function >
+ method > variable), then code over test/docs/examples paths, then file
+ centrality, then the shorter path. Shared by every surface that picks
+ among same-named symbols, so they agree on which one a name means.
+ """
+ q = _dotted(query.strip())
+ names = (name or "", _dotted(qualified_name or ""))
+ path = path or ""
+ return (
+ q not in names,
+ q.lower() not in {n.lower() for n in names},
+ _KIND_RANK.get(kind or "", _OTHER_KIND_RANK),
+ is_test_path(path, language) or is_support_path(path),
+ -(centrality or 0.0),
+ len(path),
+ path,
+ )
+
+
def order_candidates(rows: list[WikiSymbol], queried_file_path: str | None) -> list[WikiSymbol]:
"""Deterministically order a candidate list, best match first.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py b/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py
index 5b24478c6..e693c2af6 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_search_symbols.py
@@ -34,6 +34,7 @@ from repowise.server.mcp_server._helpers import (
is_excluded,
)
from repowise.server.mcp_server._query_shape import _qual_norm
+from repowise.server.mcp_server._symbol_lookup import symbol_rank_key
# Candidate ceiling: scoring/sorting happens in Python, so the SQL pre-filter
# caps how many rows we pull. Generous enough that the true top-`limit` is
@@ -68,8 +69,8 @@ def _score_symbol(row: WikiSymbol, gnode: GraphNode | None, qtokens: set[str], q
Tiers, in priority order: exact name / qualified-name match, the query's
leaf token naming the symbol, query-token coverage, substring fallback,
- then graph-centrality and entry-point boosts. Tests are penalised so a
- non-test definition ranks above its test unless the caller asked for tests.
+ then graph-centrality and entry-point boosts. Non-exact tests are penalised
+ so a non-test definition ranks above its test unless the caller asked for tests.
"""
name = (row.name or "").lower()
qn = _qual_norm(row.qualified_name)
@@ -77,7 +78,8 @@ def _score_symbol(row: WikiSymbol, gnode: GraphNode | None, qtokens: set[str], q
score = 0.0
# Exact match on the bare name or the (separator-normalised) qualified name.
- if qnorm and qnorm in (name, qn):
+ exact = bool(qnorm) and qnorm in (name, qn)
+ if exact:
score += 100.0
# The query explicitly names the leaf identifier (e.g. "...index_repo").
if name and name in qtokens:
@@ -94,7 +96,8 @@ def _score_symbol(row: WikiSymbol, gnode: GraphNode | None, qtokens: set[str], q
# Graph signals — bounded so a high-pagerank file can't outrank a real
# name match. pagerank/betweenness are small floats; cap their reach.
- if gnode is not None:
+ # Exact matches tie here and `symbol_rank_key` orders them instead.
+ if gnode is not None and not exact:
score += min(gnode.pagerank or 0.0, 0.1) * 50.0
score += min(gnode.betweenness or 0.0, 0.1) * 20.0
if gnode.is_entry_point:
@@ -104,8 +107,11 @@ def _score_symbol(row: WikiSymbol, gnode: GraphNode | None, qtokens: set[str], q
# the query was after, so it keeps its score. The flag is read first for the
# same reason everywhere else does, but note it decides nothing here today —
# it is stamped on file nodes and these are symbol nodes, so the path rules
- # are what answer in practice.
- if (gnode is not None and gnode.is_test) or is_test_path(row.file_path or "", row.language):
+ # are what answer in practice. Exact matches skip it: the shared key ranks
+ # kind before test path for them.
+ if not exact and (
+ (gnode is not None and gnode.is_test) or is_test_path(row.file_path or "", row.language)
+ ):
score -= 5.0
return score
@@ -214,12 +220,12 @@ async def search_symbols_single(
if not rows:
return []
- # One batched fetch of graph nodes for the candidate symbol_ids.
- sym_ids = [r.symbol_id for r in rows]
+ # One batched fetch of graph nodes: the symbols and their files.
+ node_ids = {r.symbol_id for r in rows} | {r.file_path for r in rows}
gres = await session.execute(
select(GraphNode).where(
GraphNode.repository_id == repository.id,
- GraphNode.node_id.in_(sym_ids),
+ GraphNode.node_id.in_(node_ids),
)
)
gmap = {g.node_id: g for g in gres.scalars().all()}
@@ -241,8 +247,25 @@ async def search_symbols_single(
continue
scored.append((_score_symbol(row, g, qtokens, qnorm), row))
- # Highest score first; deterministic tiebreak on symbol_id.
- scored.sort(key=lambda pair: (-pair[0], pair[1].symbol_id or ""))
+ def _rank(pair: tuple[float, WikiSymbol]) -> tuple:
+ score, row = pair
+ file_node = gmap.get(row.file_path)
+ return (
+ -score,
+ symbol_rank_key(
+ query,
+ name=row.name,
+ qualified_name=row.qualified_name,
+ kind=row.kind,
+ path=row.file_path,
+ language=row.language,
+ centrality=(file_node.pagerank or 0.0) if file_node is not None else 0.0,
+ ),
+ row.symbol_id or "",
+ )
+
+ # Highest score first; equal scores (every exact match) by the shared key.
+ scored.sort(key=_rank)
return [_symbol_result(row, score) for score, row in scored[:limit]]
diff --git a/tests/unit/server/mcp/test_search.py b/tests/unit/server/mcp/test_search.py
index 2162f3811..d1c345d53 100644
--- a/tests/unit/server/mcp/test_search.py
+++ b/tests/unit/server/mcp/test_search.py
@@ -569,7 +569,7 @@ class TestSymbolTestPenalty:
"""The -5 a symbol takes for living in a test file (#1103)."""
@staticmethod
- def _score(path: str, language: str = "python") -> float:
+ def _score(path: str, language: str = "python", query: str = "build index") -> float:
from repowise.core.persistence.models import WikiSymbol
from repowise.server.mcp_server.tool_search_symbols import _score_symbol
@@ -581,11 +581,14 @@ class TestSymbolTestPenalty:
)
# No graph node: symbol nodes never carry `is_test`, so the path rules
# are what decide here in practice.
- return _score_symbol(row, None, {"build", "index"}, "build_index")
+ return _score_symbol(row, None, {"build", "index"}, query)
def test_tests_are_penalised_and_support_is_not(self):
base = self._score("src/indexing/build.py")
assert self._score("packages/core/tests/test_build.py") == base - 5.0
+ # An exact match is left to the shared rank key, which puts kind first.
+ exact = self._score("src/indexing/build.py", query="build_index")
+ assert self._score("packages/core/tests/test_build.py", query="build_index") == exact
assert self._score("myapp/tests.py") == base - 5.0
# A fixture factory is often what the query was after.
assert self._score("packages/core/tests/conftest.py") == base
@@ -1327,3 +1330,102 @@ async def test_an_exact_name_outranks_a_crowd_of_substring_neighbours(
assert res["mode"] == "symbol"
assert res["exact_match"] is True
assert res["results"][0]["symbol_id"] == "src/zzz_last.py::load"
+
+
+def test_rank_key_orders_same_named_symbols():
+ from repowise.server.mcp_server._symbol_lookup import symbol_rank_key
+
+ def key(name, kind, path, centrality=0.0):
+ return symbol_rank_key(
+ "Gadgets", name=name, qualified_name=name, kind=kind, path=path,
+ centrality=centrality,
+ )
+
+ ranked = sorted(
+ [
+ ("GADGETS", "constant", "src/lib/gadgets.py"),
+ ("gadgets", "function", "src/lib/gadgets.py"),
+ ("Gadgets", "class", "docs/snippets/gadgets.py"),
+ ("Gadgets", "method", "src/lib/core.py"),
+ ("Gadgets", "class", "tests/test_gadgets.py"),
+ ("Gadgets", "class", "src/lib/core.py"),
+ ],
+ key=lambda row: key(*row),
+ )
+ assert ranked == [
+ ("Gadgets", "class", "src/lib/core.py"),
+ ("Gadgets", "class", "tests/test_gadgets.py"),
+ ("Gadgets", "class", "docs/snippets/gadgets.py"),
+ ("Gadgets", "method", "src/lib/core.py"),
+ ("gadgets", "function", "src/lib/gadgets.py"),
+ ("GADGETS", "constant", "src/lib/gadgets.py"),
+ ]
+ # Centrality, then the shorter path, decide between otherwise equal hits.
+ assert key("Gadgets", "class", "a/b/c/x.py", 0.5) < key("Gadgets", "class", "x.py")
+ assert key("Gadgets", "class", "x.py") < key("Gadgets", "class", "a/x.py")
+
+
+async def test_a_bare_name_search_leads_with_the_class_over_a_docs_constant(
+ session, populated_db, setup_mcp
+) -> None:
+ """Case-folded, a docs constant and the core class share a name and score;
+ the central docs file used to win the tie."""
+ from repowise.core.persistence.models import GraphNode, WikiSymbol
+ from repowise.server.mcp_server.tool_search import search_codebase
+
+ rid = populated_db
+ rows = [
+ ("docs/snippets/listing.py", "GIZMOS", "constant", 0.9),
+ ("src/gizmo/core.py", "Gizmos", "class", 0.01),
+ ]
+ for path, name, kind, pagerank in rows:
+ session.add(
+ WikiSymbol(
+ id=f"gz-{name}", repository_id=rid, file_path=path,
+ symbol_id=f"{path}::{name}", name=name, qualified_name=name,
+ kind=kind, signature=name, start_line=1, end_line=5, language="python",
+ )
+ )
+ for node_id in (path, f"{path}::{name}"):
+ session.add(
+ GraphNode(
+ id=f"gzn-{node_id}", repository_id=rid, node_id=node_id,
+ node_type="file" if node_id == path else "symbol", name=name,
+ file_path=path, language="python", pagerank=pagerank,
+ betweenness=pagerank,
+ )
+ )
+ await session.commit()
+
+ res = await search_codebase(query="Gizmos", limit=5)
+ assert [r["symbol_id"] for r in res["results"][:2]] == [
+ "src/gizmo/core.py::Gizmos",
+ "docs/snippets/listing.py::GIZMOS",
+ ]
+ res = await search_codebase(query="gizmos", limit=5)
+ assert res["results"][0]["symbol_id"] == "src/gizmo/core.py::Gizmos"
+
+
+async def test_an_exact_test_class_outranks_an_exact_code_function(
+ session, populated_db, setup_mcp
+) -> None:
+ """For exact matches the shared key decides, and it ranks kind before test path."""
+ from repowise.core.persistence.models import WikiSymbol
+ from repowise.server.mcp_server.tool_search import search_codebase
+
+ rid = populated_db
+ for path, kind in (("src/widget/core.py", "function"), ("tests/test_widget.py", "class")):
+ session.add(
+ WikiSymbol(
+ id=f"wd-{path}", repository_id=rid, file_path=path,
+ symbol_id=f"{path}::Widgets", name="Widgets", qualified_name="Widgets",
+ kind=kind, signature="Widgets", start_line=1, end_line=5, language="python",
+ )
+ )
+ await session.commit()
+
+ res = await search_codebase(query="Widgets", limit=5)
+ assert [r["symbol_id"] for r in res["results"][:2]] == [
+ "tests/test_widget.py::Widgets",
+ "src/widget/core.py::Widgets",
+ ]