From 8c101f49b908773dc02f87b5f1b5966fb5c94225 Mon Sep 17 00:00:00 2001 From: Christopher Krah Date: Mon, 30 Nov 2026 13:11:51 +0100 Subject: [PATCH] fix(python): give tied scores the same rank in hybrid rank normalization (#5253) Refs #4857, which expected tied FTS matches to count as the best FTS result in both normalize modes. #4858 fixed the zero-range case and left the tie-breaking in `_rank` open. With `normalize="rank"`, `_rank` numbers equal scores in argsort order. Of two matches with the same BM25 score, argsort order alone picks the one that gets the lowest rank and normalizes to 0, the value `LinearCombinationReranker` gives a document without the keyword: ```python rows = [{"text": "zebra apple", "vector": [5.0, 5.0]}, {"text": "zebra grape", "vector": [5.0, 5.1]}, {"text": "cherry plum", "vector": [0.0, 0.0]}] # both zebra rows: _score 0.4700036 (tbl.search(query_type="hybrid").vector([0.0, 0.0]).text("zebra") .rerank(LinearCombinationReranker(weight=0.3), normalize="rank")) # fdc8041, 0.42.0b38: zebra grape 0.70, cherry plum 0.30, zebra apple 0.15 # this change: zebra apple 0.85, zebra grape 0.70, cherry plum 0.30 # normalize="score" already gives the second order ``` Equal scores now share the average of their ranks, as `scipy.stats.rankdata` does by default. Without ties the ranks are unchanged, and RRF and MRR do not read them. This also covers equal vector distances. An untied lowest FTS hit still normalizes to the fill value, and this PR leaves that as it is. ``` $ cd python && pytest python/tests/test_hybrid_query.py -q # fdc8041 + 0.42.0b38 native module 30 passed, 1 skipped in 1.48s # query.py reverted, tests kept: 2 failed (test_hybrid_tied_fts_matches_share_fts_weight[rank], test_rank_gives_tied_scores_the_same_rank) $ ruff format --check . && ruff check . # ruff 0.9.9, as CI pins 198 files already formatted All checks passed! $ pytest python/tests -m "not slow and not s3_test" -q -n 4 # fresh data/ dir each side # fdc8041: 11 failed, 4474 passed, 375 skipped, 3 errors # this change: 12 failed, 4476 passed, 375 skipped, 3 errors # same 11 on both sides (namespace and stable-row-id tests, missing extras); the 12th, test_table.py::test_merge_insert, passed alone 3 times and in test_table.py -n 4 $ pytest --doctest-modules python/lancedb/query.py -q 23 passed $ pyright # 1.1.395: 5 errors in __init__.py and schema.py, the same at fdc8041; query.py is outside the include list ``` @Xuanwo, I picked the average over the best rank of the group, because the average treats both directions the same. If you want tied FTS matches to all get the top rank, I will change one line. Signed-off-by: Christopher Krah <48338417+chrikrah@users.noreply.github.com> --- python/python/lancedb/query.py | 6 +++- python/python/tests/test_hybrid_query.py | 37 ++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index ad456f635..3a66c2ed7 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -3545,8 +3545,12 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): sort_indices = np.argsort(scores) if not ascending: sort_indices = sort_indices[::-1] - ranks = np.empty_like(sort_indices) + ranks = np.empty(len(scores)) ranks[sort_indices] = np.arange(len(scores)) + 1 + # Equal scores share the average of their ranks, so the order argsort + # happens to put them in does not decide which one counts as better. + _, groups, counts = np.unique(scores, return_inverse=True, return_counts=True) + ranks = (np.bincount(groups, weights=ranks) / counts)[groups] # replace the _score column with the ranks _score_idx = results.column_names.index(column) results = results.set_column( diff --git a/python/python/tests/test_hybrid_query.py b/python/python/tests/test_hybrid_query.py index 7ed2e3292..d173b2e1e 100644 --- a/python/python/tests/test_hybrid_query.py +++ b/python/python/tests/test_hybrid_query.py @@ -684,6 +684,43 @@ def test_hybrid_single_fts_match_keeps_fts_weight(tmp_path, normalize): ] +@pytest.mark.parametrize("normalize", ["score", "rank"]) +def test_hybrid_tied_fts_matches_share_fts_weight(tmp_path, normalize): + from lancedb.rerankers import LinearCombinationReranker + + db = lancedb.connect(tmp_path) + table = db.create_table( + "test", + [ + {"text": "zebra apple", "vector": [5.0, 5.0]}, + {"text": "zebra grape", "vector": [5.0, 5.1]}, + {"text": "cherry plum", "vector": [0.0, 0.0]}, + ], + ) + table.create_fts_index("text") + + results = ( + table.search(query_type="hybrid") + .vector([0.0, 0.0]) + .text("zebra") + .rerank(LinearCombinationReranker(weight=0.3), normalize=normalize) + .limit(3) + .to_arrow() + ) + + # Both FTS matches have the same BM25 score, so both rank above the + # document without the keyword. + assert results["text"].to_pylist()[-1] == "cherry plum" + + +def test_rank_gives_tied_scores_the_same_rank(): + table = pa.table({"_score": pa.array([0.5, 0.9, 0.5, 0.1], pa.float32())}) + ranked = LanceHybridQueryBuilder._rank(table, "_score") + assert ranked["_score"].to_pylist() == [2.5, 4.0, 2.5, 1.0] + ranked = LanceHybridQueryBuilder._rank(table, "_score", ascending=False) + assert ranked["_score"].to_pylist() == [2.5, 1.0, 2.5, 4.0] + + def test_hybrid_query_rejects_query_with_vector(sync_table: Table): # Pins the full message: the space between "hybrid search." and "But" is # load-bearing (see the _validate_query literal concatenation).