diff --git a/docs/web/search/hybrid-search.mdx b/docs/web/search/hybrid-search.mdx index 29d79c9a0..ae2d79e97 100644 --- a/docs/web/search/hybrid-search.mdx +++ b/docs/web/search/hybrid-search.mdx @@ -283,12 +283,15 @@ Set `limit()` to the number of results your application needs. The default is 10 A larger candidate set can help a reranker find relevant records, but adds work. -In the Python API, each side of a hybrid query (vector and full-text) fetches -at least 50 candidates before rank fusion — `max(limit + offset, 50)` — so for -windows where `limit + offset <= 50`, asking for fewer results returns a -shorter list, not a different ranking. This candidate floor is separate from -`limit()`, which only controls how many fused results are returned (default -10). The Rust and TypeScript APIs retain their existing candidate limits. +In the Python API, with the default RRF reranker, each side of a hybrid query +(vector and full-text) fetches at least 50 candidates before rank fusion — +`max(limit + offset, 50)` — so for windows where `limit + offset <= 50`, asking +for fewer results returns a shorter list, not a different ranking. This +candidate floor is separate from `limit()`, which only controls how many fused +results are returned (default 10). Custom and model rerankers keep receiving +`limit + offset` candidates per side, so raise `limit()` if you want them to +score a wider window. The Rust and TypeScript APIs retain their existing +candidate limits. ### Returning row IDs {#returning-row-ids} diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index c9fe2a22e..38bbf2c2f 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -95,6 +95,23 @@ DEFAULT_HYBRID_LIMIT = 10 DEFAULT_HYBRID_RANK_WINDOW = 50 +def _hybrid_sub_query_limit( + limit: int, offset: int, reranker: Optional[Reranker] +) -> int: + """Number of rows each side of a hybrid query fetches before reranking. + + Each side always fetches the skipped prefix plus the page itself. For the + default RRF reranker the window is raised to DEFAULT_HYBRID_RANK_WINDOW so + that a smaller page does not change the fused ranking (#4758). Custom and + model rerankers keep the caller's `limit + offset` budget, since every + candidate is sent to them, and an empty page never gets the floor. + """ + window = limit + offset + if limit > 0 and (reranker is None or type(reranker) is RRFReranker): + return max(window, DEFAULT_HYBRID_RANK_WINDOW) + return window + + @runtime_checkable class _LanceScanner(Protocol): projected_schema: pa.Schema | None @@ -3181,12 +3198,15 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): # Apply common configurations # The final offset/limit window is sliced out of the combined, # reranked results, so each sub-query must fetch enough rows to - # cover the skipped prefix as well as the window itself. Rank fusion - # additionally needs a candidate window larger than the returned page - # (#4758): with only `limit + offset` rows per side, a smaller limit - # can return a different top result instead of just a shorter list. + # cover the skipped prefix as well as the window itself. Default RRF + # fusion additionally needs a candidate window larger than the + # returned page (#4758): with only `limit + offset` rows per side, a + # smaller limit can return a different top result instead of just a + # shorter list. limit = self._limit or DEFAULT_HYBRID_LIMIT - sub_query_limit = max(limit + (self._offset or 0), DEFAULT_HYBRID_RANK_WINDOW) + sub_query_limit = _hybrid_sub_query_limit( + limit, self._offset or 0, self._reranker + ) self._vector_query.limit(sub_query_limit) self._fts_query.limit(sub_query_limit) # WAL-PK-FUSION: without the fallback, select `self._columns` as is. @@ -4619,11 +4639,11 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): # offset() pushes the offset down into both sub-queries, which would make # each of them skip its own first `offset` rows. The window has to be # taken out of the combined, reranked results instead, so fetch the - # skipped prefix here too and slice it off afterwards. Rank fusion - # additionally needs a candidate window larger than the returned page - # (#4758), so never fetch fewer than DEFAULT_HYBRID_RANK_WINDOW rows - # per side. - sub_query_limit = max(limit + offset, DEFAULT_HYBRID_RANK_WINDOW) + # skipped prefix here too and slice it off afterwards. Default RRF + # fusion additionally needs a candidate window larger than the + # returned page (#4758), so with that reranker never fetch fewer than + # DEFAULT_HYBRID_RANK_WINDOW rows per side. + sub_query_limit = _hybrid_sub_query_limit(limit, offset, self._reranker) fts_query.limit(sub_query_limit) vec_query.limit(sub_query_limit) fts_query.offset(0) diff --git a/python/python/tests/test_hybrid_query.py b/python/python/tests/test_hybrid_query.py index 50e03d812..7d2e8a8e5 100644 --- a/python/python/tests/test_hybrid_query.py +++ b/python/python/tests/test_hybrid_query.py @@ -7,6 +7,7 @@ from unittest import mock import lancedb from lancedb.query import LanceHybridQueryBuilder +from lancedb.rerankers.base import Reranker from lancedb.rerankers.rrf import RRFReranker import numpy as np import pyarrow as pa @@ -670,3 +671,151 @@ def test_hybrid_query_rejects_query_with_vector(sync_table: Table): "or set `vector()` and `text()` explicitly for hybrid search. " "But not both." ) + + +class _RecordingReranker(Reranker): + """Records how many candidates each side of a hybrid query hands over.""" + + def __init__(self): + super().__init__() + self.calls = [] + + def rerank_hybrid(self, query, vector_results, fts_results): + self.calls.append((len(vector_results), len(fts_results))) + combined = self.merge_results(vector_results, fts_results) + scores = pa.array([1.0] * len(combined), type=pa.float32()) + return combined.append_column("_relevance_score", scores) + + +def _candidate_rows(): + rng = np.random.default_rng(0) + return pa.table( + { + "id": pa.array(range(100), type=pa.int64()), + "text": pa.array(["match"] * 100), + "vector": pa.array( + rng.random((100, 2)).astype("float32").tolist(), + type=pa.list_(pa.float32(), list_size=2), + ), + } + ) + + +def test_hybrid_query_custom_reranker_keeps_candidate_budget(tmpdir_factory): + # The #4758 candidate floor only applies to the default RRF reranker. + # Custom and model rerankers get every candidate, so they must keep + # receiving `limit + offset` rows per side. + db = lancedb.connect(str(tmpdir_factory.mktemp("data"))) + table = db.create_table("t", _candidate_rows()) + table.create_fts_index("text", with_position=False) + + reranker = _RecordingReranker() + result = ( + table.search(query_type="hybrid") + .vector([0.5, 0.5]) + .text("match") + .rerank(reranker) + .limit(1) + .to_list() + ) + assert len(result) == 1 + assert reranker.calls == [(1, 1)] + + reranker = _RecordingReranker() + result = ( + table.search(query_type="hybrid") + .vector([0.5, 0.5]) + .text("match") + .rerank(reranker) + .offset(2) + .limit(3) + .to_list() + ) + assert len(result) == 3 + assert reranker.calls == [(5, 5)] + + +@pytest.mark.asyncio +async def test_async_hybrid_query_custom_reranker_keeps_candidate_budget( + tmpdir_factory, +): + # Async mirror of test_hybrid_query_custom_reranker_keeps_candidate_budget. + db = await lancedb.connect_async(str(tmpdir_factory.mktemp("data"))) + table = await db.create_table("t", _candidate_rows()) + await table.create_index("text", config=FTS(with_position=False)) + + reranker = _RecordingReranker() + result = await ( + table.query() + .nearest_to([0.5, 0.5]) + .nearest_to_text("match") + .rerank(reranker) + .limit(1) + .to_arrow() + ) + assert len(result) == 1 + assert reranker.calls == [(1, 1)] + + reranker = _RecordingReranker() + result = await ( + table.query() + .nearest_to([0.5, 0.5]) + .nearest_to_text("match") + .rerank(reranker) + .offset(2) + .limit(3) + .to_arrow() + ) + assert len(result) == 3 + assert reranker.calls == [(5, 5)] + + +@pytest.mark.asyncio +async def test_async_hybrid_query_empty_page_does_not_fetch_candidates( + tmpdir_factory, +): + # An empty page must not get the #4758 candidate floor: limit(0) should + # not retrieve and score 50 rows per side just to return nothing. + db = await lancedb.connect_async(str(tmpdir_factory.mktemp("data"))) + table = await db.create_table("t", _candidate_rows()) + await table.create_index("text", config=FTS(with_position=False)) + + reranker = _RecordingReranker() + query = ( + table.query() + .nearest_to([0.5, 0.5]) + .nearest_to_text("match") + .rerank(reranker) + .limit(0) + ) + # Same as before the floor: the empty window is rejected up front. + with pytest.raises(ValueError, match="k must be positive"): + await query.to_arrow() + assert reranker.calls == [] + + +@pytest.mark.asyncio +async def test_async_hybrid_query_default_rrf_candidate_window(tmpdir_factory): + # The default RRF reranker gets the #4758 floor: 50 candidates per side + # even when a single row is requested. + db = await lancedb.connect_async(str(tmpdir_factory.mktemp("data"))) + table = await db.create_table("t", _candidate_rows()) + await table.create_index("text", config=FTS(with_position=False)) + + seen = [] + original = RRFReranker.rerank_hybrid + + def recording_rerank_hybrid(self, query, vector_results, fts_results, *a, **kw): + seen.append((len(vector_results), len(fts_results))) + return original(self, query, vector_results, fts_results, *a, **kw) + + with mock.patch.object(RRFReranker, "rerank_hybrid", recording_rerank_hybrid): + result = await ( + table.query() + .nearest_to([0.5, 0.5]) + .nearest_to_text("match") + .limit(1) + .to_arrow() + ) + assert len(result) == 1 + assert seen == [(50, 50)] diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index acbe7542c..825326457 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -3030,6 +3030,9 @@ def test_query_sync_fts_document_granularity(): def test_query_sync_hybrid(): + # With the default RRF reranker each side fetches at least + # DEFAULT_HYBRID_RANK_WINDOW (50) rows before fusion (#4758), so a + # limit of 42 sends k=50 on both requests. def handler(body): if "full_text_query" in body: # FTS query @@ -3038,7 +3041,7 @@ def test_query_sync_hybrid(): "query": "puppy", "columns": [], }, - "k": 42, + "k": 50, "vector": [], "prefilter": True, "with_row_id": True, @@ -3048,7 +3051,7 @@ def test_query_sync_hybrid(): else: # Vector query assert body == { - "k": 42, + "k": 50, "prefilter": True, "refine_factor": None, "vector": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],