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): weight the path and title columns in the full-text rank (#2191)

Raghav Chamadiya1599224a3e45
diff --git a/packages/core/src/repowise/core/persistence/search.py b/packages/core/src/repowise/core/persistence/search.py
index 2ede5bdf7..1afce0a84 100644
--- a/packages/core/src/repowise/core/persistence/search.py
+++ b/packages/core/src/repowise/core/persistence/search.py
@@ -123,6 +123,15 @@ _DF_CACHE_MAX = 2048
# concatenated. Small enough not to disturb any threshold downstream.
_SCORE_EPSILON = 1e-6
+# Per-column bm25 weights, in ``PAGE_FTS_COLUMNS`` order: title and
+# target_path name the file a page is about, content and summary only mention
+# it. ``page_id`` is UNINDEXED and contributes nothing, but bm25() takes one
+# weight per column, so it still needs one. bm25() ignores a weight past the
+# last column and defaults a missing one to 1.0, so the arity is checked by
+# test_search_fts_columns rather than by anything raising here.
+_BM25_COLUMN_WEIGHTS = (0.0, 4.0, 1.0, 1.0, 3.0)
+_BM25_SCORE = "bm25(page_fts, " + ", ".join(str(w) for w in _BM25_COLUMN_WEIGHTS) + ")"
+
_log = logging.getLogger(__name__)
@@ -610,10 +619,10 @@ class FullTextSearch:
async def _matching_rows(self, conn, fts_query: str, limit: int) -> list:
rows = await conn.execute(
text(
- "SELECT f.page_id, f.title, f.content, f.rank "
+ f"SELECT f.page_id, f.title, f.content, {_BM25_SCORE} "
"FROM page_fts f "
"WHERE page_fts MATCH :q "
- "ORDER BY rank "
+ f"ORDER BY {_BM25_SCORE} "
"LIMIT :lim"
),
{"q": fts_query, "lim": limit},
@@ -621,7 +630,7 @@ class FullTextSearch:
return list(rows.fetchall())
async def _search_sqlite(self, query: str, limit: int) -> list[SearchResult]:
- """FTS5 search. ``rank`` is negative; we negate it to get a positive score."""
+ """FTS5 search. bm25 is negative; we negate it to get a positive score."""
async with self._engine.connect() as conn:
async def df(term: str) -> int:
diff --git a/tests/unit/persistence/test_search.py b/tests/unit/persistence/test_search.py
index 9eb32be5d..e28391258 100644
--- a/tests/unit/persistence/test_search.py
+++ b/tests/unit/persistence/test_search.py
@@ -210,3 +210,47 @@ async def test_a_page_id_repeated_in_one_batch_keeps_its_last_entry(fts):
async def test_index_many_of_nothing_is_a_no_op(fts):
await fts.index_many([])
assert await _indexed_ids(fts) == set()
+
+
+async def test_path_only_match_outranks_content_only_match(fts):
+ """A page the query names by path beats one that only mentions the word.
+
+ Both pages carry the term once, and the path-matching one has the longer
+ body, so bm25's length normalisation ranks it second under uniform column
+ weights. Only weighting target_path above content flips it.
+
+ The fillers keep the corpus off the degenerate case where every page
+ matches and bm25 clamps a non-positive idf to a floor, leaving every score
+ at ~1e-6.
+ """
+ sentence = "This module handles records for the wider system and explains its use. "
+ await fts.index(
+ "path-match",
+ "Collector",
+ sentence * 6,
+ summary="A collector module.",
+ target_path="packages/core/telemetry/collector.py",
+ )
+ await fts.index(
+ "content-match",
+ "Emitter",
+ sentence * 2 + " It forwards each record to telemetry.",
+ summary="An emitter module.",
+ target_path="packages/core/reporting/emitter.py",
+ )
+ await fts.index_many(
+ [
+ (
+ f"filler{i}",
+ f"Filler {i}",
+ "An unrelated module about parsing and graphs. " * 3,
+ "Filler.",
+ f"packages/core/other/mod{i}.py",
+ )
+ for i in range(10)
+ ]
+ )
+
+ results = await fts.search("telemetry")
+
+ assert [r.page_id for r in results] == ["path-match", "content-match"]
diff --git a/tests/unit/persistence/test_search_fts_columns.py b/tests/unit/persistence/test_search_fts_columns.py
index ebb949e02..02791e1d0 100644
--- a/tests/unit/persistence/test_search_fts_columns.py
+++ b/tests/unit/persistence/test_search_fts_columns.py
@@ -18,7 +18,11 @@ import pytest
from sqlalchemy.sql import text
from repowise.core.persistence.crud import upsert_page
-from repowise.core.persistence.search import PAGE_FTS_COLUMNS, FullTextSearch
+from repowise.core.persistence.search import (
+ _BM25_COLUMN_WEIGHTS,
+ PAGE_FTS_COLUMNS,
+ FullTextSearch,
+)
from tests.unit.persistence.helpers import insert_repo
_OLD_SCHEMA_DDL = "CREATE VIRTUAL TABLE page_fts USING fts5(page_id UNINDEXED, title, content)"
@@ -312,3 +316,13 @@ async def test_ensure_index_prunes_orphans_on_a_current_schema(
await FullTextSearch(async_engine).ensure_index()
assert await _indexed_ids(async_engine) == set()
+
+
+def test_one_bm25_weight_per_indexed_column():
+ """A column added without a weight would be ranked, silently, at 1.0.
+
+ bm25() takes its weights positionally and validates nothing: a sixth
+ column defaults to 1.0 and a surplus weight is dropped, so drift here
+ changes ranking without raising anywhere.
+ """
+ assert len(_BM25_COLUMN_WEIGHTS) == len(PAGE_FTS_COLUMNS)