fix(python)!: fetch minimum rank-fusion window per side in hybrid search (#4772)

BREAKING CHANGE: Executing or analyzing an async Python hybrid query
with `limit(0)` now raises `ValueError` before either search runs. In
0.41.0, `offset(2).limit(0).to_arrow()` returned a typed empty table
after retrieval and reranking. Skip query execution and `analyze_plan()`
when the requested page size is zero.

Refs #4758

## Problem
Each side of a hybrid query fetched only `limit + offset` rows before
rank fusion, so asking for fewer results could return a different top
result instead of just a shorter list.

Repro (lancedb 0.41.0, 300 rows, RRF reranker):
- `limit=1` -> top id 294
- `limit=10` -> top id 269

## Fix
With the default RRF reranker, both hybrid paths
(`LanceHybridQueryBuilder._create_query_builders` and
`AsyncHybridQuery._create_child_queries`) now fetch `max(limit + offset,
DEFAULT_HYBRID_RANK_WINDOW)` rows per side, with
`DEFAULT_HYBRID_RANK_WINDOW = 50`. The requested limit/offset window is
still sliced out of the fused results as before. This implements option
1 from the issue: a fixed minimum window, no new API surface.

Custom and model rerankers keep the caller's `limit + offset` budget per
side, since every candidate is sent to them (for example
`OpenaiReranker` puts all merged texts in one prompt). Callers who want
a wider window for those rerankers can raise `limit()`. An explicit
`limit(0)` never gets the floor. In the async builder it raises
`ValueError` before schema discovery or either sub-query runs, with or
without an offset, so neither Embedded nor Enterprise retrieves or
scores anything. On main, async `limit(0)` was rejected by the native
`k` check only without an offset; `offset(2).limit(0)` fetched and
reranked two rows per side and returned nothing. The sync builder still
treats `limit(0)` as the default of 10, as before.

Trade-off: default RRF queries with small limits now fetch up to 50 rows
per side, and their result orderings can change, which is the bug being
fixed.

## Tests
- `test_hybrid_query_top_result_stable_across_limits` and its async
mirror (issue repro): fail on base, pass with the fix
- `test_hybrid_query_custom_reranker_keeps_candidate_budget` and its
async mirror: a recording reranker receives 1 vector and 1 FTS candidate
for `limit(1)` and 5 of each for `offset(2).limit(3)`
- `test_async_hybrid_query_default_rrf_candidate_window`: default RRF
receives 50 of each for `limit(1)`
- `test_async_hybrid_query_empty_page_does_not_fetch_candidates` (offset
0 and 2): `limit(0)` raises, and neither sub-query nor the reranker runs
- `test_remote_db.py::test_async_hybrid_zero_limit_sends_no_query`
(offset 0 and 2): `limit(0)` raises and no `/query/` request is sent;
fails on 281fdc7, passes on this head
- `test_remote_db.py::test_query_sync_hybrid` now expects `k=50` for the
default RRF request with `limit(42)`
- `test_hybrid_query.py`: 30 passed, 1 failed. The failure is
pre-existing and unrelated
(`test_hybrid_query_with_stale_fixed_size_binary_prefilter` needs the
`lance` package)
- `test_wal_hybrid.py`: 15 passed
- `ruff check` and `ruff format --check` clean on the touched files

Local runs used the lancedb 0.41.0 wheel with this PR's `query.py` diff
applied, since main needs a newer native extension than the published
wheel. `test_query_sync_hybrid` and the new remote zero-limit test were
run from an extracted copy because `test_remote_db.py` imports
`lancedb.graph`, which 0.41.0 does not have.

---------

Signed-off-by: shadowmodder <sudhirvissa@gmail.com>
Signed-off-by: Sudhir Vissa <sudhirvissa@gmail.com>
This commit is contained in:
Sudhir Vissa
2026-11-30 20:42:12 +08:00
committed by GitHub
parent 83af5dec3e
commit 97c88659f4
4 changed files with 570 additions and 22 deletions
+74 -7
View File
@@ -184,6 +184,29 @@ _SYNC_VECTOR_QUERY_TYPES = (list, tuple, np.ndarray, pa.Array, pa.ChunkedArray)
# mirrors the default the Rust query builder applies to its sub-queries.
DEFAULT_HYBRID_LIMIT = 10
# Minimum number of rows each side of a hybrid query fetches before rank
# fusion. Fusion needs a candidate window larger than the page it returns:
# with only `limit + offset` rows per side, asking for fewer results can
# return a different top result instead of just a shorter list (#4758).
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):
@@ -4012,9 +4035,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.
# 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 = limit + (self._offset or 0)
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.
@@ -5820,7 +5849,30 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
return self
def _reject_explicit_zero_limit(self) -> None:
"""Reject an explicit zero limit before any work runs for this query.
`_run_hybrid` checks the limit that `_create_child_queries`
derives, but Blob schema discovery and plan analysis do not go
through it, so they call this first instead. The effective limit
can sit on either sub-query (see `_create_child_queries`), so look
at both.
"""
fts_req = self._inner.to_fts_query().to_query_request()
vec_req = self._inner.to_vector_query().to_query_request()
limit = fts_req.limit if fts_req.limit is not None else vec_req.limit
if limit is None:
limit = DEFAULT_HYBRID_LIMIT
if limit == 0:
raise ValueError(
"k must be positive: a hybrid query needs limit(1) or more"
)
async def _blob_output_schema(self) -> pa.Schema:
# Schema discovery calls output_schema() on the vector leg, which
# on a remote table sends the query itself, so an explicit zero
# limit has to be rejected before it runs.
self._reject_explicit_zero_limit()
vector_query = AsyncVectorQuery(self._inner.to_vector_query(), self._table)
return await vector_query.output_schema()
@@ -5878,9 +5930,13 @@ 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.
fts_query.limit(limit + offset)
vec_query.limit(limit + offset)
# 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)
vec_query.offset(0)
@@ -5922,6 +5978,14 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
blob_sources: Optional[dict[str, str]] = None,
) -> AsyncRecordBatchReader:
fts_query, vec_query, limit, offset = await self._create_child_queries()
if limit == 0:
# An empty page needs no candidates. Reject it before anything
# runs, whatever the offset: building an empty result would need
# the output schema, and on a remote table output_schema() itself
# sends the vector and full-text queries.
raise ValueError(
"k must be positive: a hybrid query needs limit(1) or more"
)
req = fts_query._inner.to_query_request()
blob_auto_row_id = bool(blob_sources)
@@ -5995,14 +6059,14 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
RRFReranker(K=60)
ProjectionExec: expr=[vector@0 as vector, text@3 as text, _distance@2 as _distance, _rowid@1 as _rowid]
LanceRead: uri=..., projection=[text], source=stream(_rowid)
GlobalLimitExec: skip=0, fetch=10
GlobalLimitExec: skip=0, fetch=50
FilterExec: _distance@2 IS NOT NULL
SortExec: TopK(fetch=1), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false]
KNNVectorDistance: metric=l2
LanceRead: uri=..., projection=[vector], num_fragments=..., ...
ProjectionExec: expr=[vector@2 as vector, text@3 as text, _score@1 as _score, _rowid@0 as _rowid]
LanceRead: uri=..., projection=[vector, text], source=stream(_rowid)
GlobalLimitExec: skip=0, fetch=10
GlobalLimitExec: skip=0, fetch=50
MatchQuery: column=text, query=[hello]
Parameters
@@ -6044,6 +6108,9 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
-------
plan : str
"""
# Plan analysis executes both legs, so an explicit zero limit has
# to be rejected before either of them runs.
self._reject_explicit_zero_limit()
fts_query, vec_query, _, _ = await self._create_child_queries()
results = ["Vector Search Query:"]
+402 -13
View File
@@ -1,12 +1,15 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import random
from unittest import mock
import lancedb
from lancedb.query import LanceHybridQueryBuilder
from lancedb.query import AsyncFTSQuery, AsyncVectorQuery, LanceHybridQueryBuilder
from lancedb.rerankers.base import Reranker
from lancedb.rerankers.rrf import RRFReranker
import numpy as np
import pyarrow as pa
import pyarrow.compute as pc
import pytest
@@ -58,8 +61,10 @@ async def test_async_hybrid_query(table: AsyncTable):
table.query().nearest_to([0.0, 0.4]).nearest_to_text("dog").limit(2).to_arrow()
)
assert len(result) == 2
# ensure we get results that would match well for text and vector
assert result["text"].to_pylist() == ["a", "dog"]
# ensure we get results that would match well for text and vector.
# 'dog' matches both the text query and the vector query, so rank fusion
# over the full candidate window (#4758) puts it first.
assert result["text"].to_pylist() == ["dog", "a"]
# ensure there is no rowid by default
assert "_rowid" not in result
@@ -76,9 +81,11 @@ async def test_async_hybrid_query_with_row_ids(table: AsyncTable):
.to_arrow()
)
assert len(result) == 2
# ensure we get results that would match well for text and vector
assert result["text"].to_pylist() == ["a", "dog"]
assert result["_rowid"].to_pylist() == [0, 3]
# ensure we get results that would match well for text and vector.
# 'dog' matches both the text query and the vector query, so rank fusion
# over the full candidate window (#4758) puts it first.
assert result["text"].to_pylist() == ["dog", "a"]
assert result["_rowid"].to_pylist() == [3, 0]
def test_hybrid_rerank_return_score_all_omits_unrequested_rowid(sync_table: Table):
@@ -343,10 +350,11 @@ async def test_async_hybrid_query_fts_first_default_limit(table: AsyncTable):
@pytest.mark.asyncio
async def test_async_hybrid_query_explain_plan_matches_execution(table: AsyncTable):
# Paging rewrites the sub-queries: each one fetches limit + offset rows with
# no offset of its own, and the window is sliced out after fusion. The plans
# have to be built from those rewritten sub-queries, otherwise explain_plan
# and analyze_plan describe a query that is never run.
# Paging rewrites the sub-queries: each one fetches enough rows to cover
# limit + offset, and never fewer than the rank-fusion window (#4758),
# with no offset of its own, and the window is sliced out after fusion.
# The plans have to be built from those rewritten sub-queries, otherwise
# explain_plan and analyze_plan describe a query that is never run.
query = (
table.query().nearest_to([0.0, 0.4]).nearest_to_text("dog").offset(2).limit(2)
)
@@ -356,12 +364,12 @@ async def test_async_hybrid_query_explain_plan_matches_execution(table: AsyncTab
assert [
line.strip() for line in plan.splitlines() if "GlobalLimitExec" in line
] == [
"GlobalLimitExec: skip=0, fetch=4",
"GlobalLimitExec: skip=0, fetch=4",
"GlobalLimitExec: skip=0, fetch=50",
"GlobalLimitExec: skip=0, fetch=50",
]
analyzed = await query.analyze_plan()
assert analyzed.count("skip=0, fetch=4") == 2
assert analyzed.count("skip=0, fetch=50") == 2
assert "skip=2" not in analyzed
@@ -390,6 +398,81 @@ def test_hybrid_query_offset(sync_table: Table):
assert offset_result["_rowid"].to_pylist() == full["_rowid"].to_pylist()[2:]
def test_hybrid_query_top_result_stable_across_limits(tmpdir_factory):
# Regression test for #4758: the top result of a hybrid search must not
# depend on `limit`. Each side used to fetch only `limit + offset` rows
# before fusion, so asking for fewer results could return a different
# first result instead of just a shorter list.
rng = np.random.default_rng(0)
random.seed(0)
words = "alpha beta gamma delta epsilon zeta eta theta iota kappa".split()
rows = [
{
"id": i,
"text": " ".join(random.choice(words) for _ in range(12)),
"vector": rng.random(16).astype("float32"),
}
for i in range(300)
]
tmp_path = str(tmpdir_factory.mktemp("data"))
table = lancedb.connect(tmp_path).create_table("t", data=rows)
table.create_fts_index("text", with_position=False)
query_vec = rng.random(16).astype("float32")
def top_id(limit):
result = (
table.search(query_type="hybrid")
.vector(query_vec)
.text("alpha beta gamma")
.limit(limit)
.to_list()
)
assert len(result) == limit
return result[0]["id"]
assert top_id(1) == top_id(3) == top_id(10)
@pytest.mark.asyncio
async def test_async_hybrid_query_top_result_stable_across_limits(tmpdir_factory):
# Async mirror of test_hybrid_query_top_result_stable_across_limits:
# regression test for #4758. The top result of a hybrid search must not
# depend on `limit`. The async path previously had no behavioral
# assertion for this — only the explain-plan fetch=50 check — so a
# regression on this side would have slipped through.
rng = np.random.default_rng(0)
random.seed(0)
words = "alpha beta gamma delta epsilon zeta eta theta iota kappa".split()
rows = [
{
"id": i,
"text": " ".join(random.choice(words) for _ in range(12)),
"vector": rng.random(16).astype("float32"),
}
for i in range(300)
]
tmp_path = str(tmpdir_factory.mktemp("data"))
db = await lancedb.connect_async(tmp_path)
table = await db.create_table("t", data=rows)
await table.create_index("text", config=FTS(with_position=False))
query_vec = rng.random(16).astype("float32")
async def top_id(limit):
result = await (
table.query()
.nearest_to(query_vec)
.nearest_to_text("alpha beta gamma")
.limit(limit)
.to_list()
)
assert len(result) == limit
return result[0]["id"]
assert await top_id(1) == await top_id(3) == await top_id(10)
@pytest.mark.parametrize(
"query_vector",
[
@@ -731,3 +814,309 @@ 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)]
def _counting_child_queries():
# Count executions of the two hybrid sub-queries: a limit(0) page must
# run neither retrieval, so both counters have to stay at zero.
executions = []
original_fts = AsyncFTSQuery.to_arrow
original_vec = AsyncVectorQuery.to_arrow
async def counting_fts(self, *args, **kwargs):
executions.append("fts")
return await original_fts(self, *args, **kwargs)
async def counting_vec(self, *args, **kwargs):
executions.append("vec")
return await original_vec(self, *args, **kwargs)
patchers = (
mock.patch.object(AsyncFTSQuery, "to_arrow", counting_fts),
mock.patch.object(AsyncVectorQuery, "to_arrow", counting_vec),
)
return executions, patchers
@pytest.mark.asyncio
@pytest.mark.parametrize("offset", [0, 2])
async def test_async_hybrid_query_empty_page_does_not_fetch_candidates(
tmpdir_factory, offset
):
# An empty page must not get the #4758 candidate floor, and must not
# fetch or score anything at all: limit(0) is rejected before either
# sub-query runs, whatever the offset. With offset(2) the sub-queries
# would otherwise carry k=2 and fetch two rows per side for 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()
executions, patchers = _counting_child_queries()
query = (
table.query()
.nearest_to([0.5, 0.5])
.nearest_to_text("match")
.rerank(reranker)
.offset(offset)
.limit(0)
)
with patchers[0], patchers[1]:
with pytest.raises(ValueError, match="k must be positive"):
await query.to_arrow()
assert reranker.calls == []
assert executions == []
def _counting_leg_plans():
# Count plan executions of the two hybrid legs: analyze_plan runs both
# legs, so a limit(0) page must leave both counters at zero.
executions = []
original_fts = AsyncFTSQuery.analyze_plan
original_vec = AsyncVectorQuery.analyze_plan
async def counting_fts(self, *args, **kwargs):
executions.append("fts")
return await original_fts(self, *args, **kwargs)
async def counting_vec(self, *args, **kwargs):
executions.append("vec")
return await original_vec(self, *args, **kwargs)
patchers = (
mock.patch.object(AsyncFTSQuery, "analyze_plan", counting_fts),
mock.patch.object(AsyncVectorQuery, "analyze_plan", counting_vec),
)
return executions, patchers
@pytest.mark.asyncio
@pytest.mark.parametrize("offset", [0, 2])
async def test_async_hybrid_query_empty_page_analyze_plan_does_not_execute(
tmpdir_factory, offset
):
# analyze_plan does not go through _run_hybrid: it executes both legs
# itself, so it has to reject an explicit zero limit before either leg
# runs, whatever the offset.
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))
executions, patchers = _counting_leg_plans()
query = (
table.query()
.nearest_to([0.5, 0.5])
.nearest_to_text("match")
.offset(offset)
.limit(0)
)
with patchers[0], patchers[1]:
with pytest.raises(ValueError, match="k must be positive"):
await query.analyze_plan()
assert executions == []
def _candidate_rows_with_blob():
# _candidate_rows plus a blob v2 column, built from the storage struct
# the way test_blob.py builds blob arrays.
rows = _candidate_rows()
field = lancedb.blob("payload")
storage_type = field.type.storage_type
storage = pa.StructArray.from_arrays(
[
pa.array(
[b"blob-%d" % i for i in range(rows.num_rows)],
type=pa.large_binary(),
),
pa.array([None] * rows.num_rows, type=pa.string()),
pa.array([None] * rows.num_rows, type=pa.uint64()),
pa.array([None] * rows.num_rows, type=pa.uint64()),
],
fields=list(storage_type),
)
payload = pa.ExtensionArray.from_storage(field.type, storage)
return rows.append_column(field, payload)
def _counting_vector_output_schema():
# Count Blob schema discovery calls: _blob_output_schema asks the
# vector leg for its output schema, which on a remote table sends the
# query itself, so a limit(0) page must leave this counter at zero.
calls = []
original = AsyncVectorQuery.output_schema
async def counting(self, *args, **kwargs):
calls.append(1)
return await original(self, *args, **kwargs)
patcher = mock.patch.object(AsyncVectorQuery, "output_schema", counting)
return calls, patcher
@pytest.mark.asyncio
async def test_async_hybrid_query_empty_page_blob_bytes_skips_discovery(
tmpdir_factory,
):
# to_arrow(blob_mode="bytes") discovers the Blob output schema before
# the query runs, and on a remote table that discovery sends the
# vector query itself. An explicit zero limit has to be rejected
# before discovery runs, not by it.
db = await lancedb.connect_async(str(tmpdir_factory.mktemp("data")))
table = await db.create_table("t", _candidate_rows_with_blob())
await table.create_index("text", config=FTS(with_position=False))
reranker = _RecordingReranker()
executions, exec_patchers = _counting_child_queries()
schema_calls, schema_patcher = _counting_vector_output_schema()
query = (
table.query()
.nearest_to([0.5, 0.5])
.nearest_to_text("match")
.rerank(reranker)
.limit(0)
)
with exec_patchers[0], exec_patchers[1], schema_patcher:
with pytest.raises(ValueError, match="k must be positive") as excinfo:
await query.to_arrow(blob_mode="bytes")
# The rejection is the query builder's, not the native "Invalid input"
# error the undiscovered schema call would have raised instead.
assert str(excinfo.value) == (
"k must be positive: a hybrid query needs limit(1) or more"
)
assert schema_calls == []
assert executions == []
assert reranker.calls == []
# A positive limit still discovers the schema and returns the rows.
result = await (
table.query()
.nearest_to([0.5, 0.5])
.nearest_to_text("match")
.limit(2)
.to_arrow(blob_mode="bytes")
)
assert len(result) == 2
@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)]
+83 -2
View File
@@ -5221,6 +5221,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
@@ -5229,7 +5232,7 @@ def test_query_sync_hybrid():
"query": "puppy",
"columns": [],
},
"k": 42,
"k": 50,
"vector": [],
"prefilter": True,
"with_row_id": True,
@@ -5239,7 +5242,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],
@@ -5263,6 +5266,84 @@ def test_query_sync_hybrid():
(table.search("puppy", query_type="hybrid").limit(42).to_list())
@pytest.mark.asyncio
@pytest.mark.parametrize("offset", [0, 2])
async def test_async_hybrid_zero_limit_sends_no_query(offset):
# An explicit limit(0) is rejected before schema discovery or retrieval,
# so the remote client never sends a /query/ request for an empty page.
query_ks = []
def handler(request):
if request.path.endswith("/describe/"):
data = json.dumps(
{
"version": 1,
"schema": {
"fields": [
{
"name": "text",
"type": {"type": "string"},
"nullable": True,
},
{
"name": "vector",
"type": {
"type": "fixed_size_list",
"length": 2,
"fields": [
{
"name": "item",
"type": {"type": "float"},
"nullable": True,
}
],
},
"nullable": True,
},
]
},
}
).encode()
content_type = "application/json"
elif request.path.endswith("/query/"):
length = int(request.headers["Content-Length"])
body = json.loads(request.rfile.read(length))
query_ks.append(body["k"])
score = "_score" if "full_text_query" in body else "_distance"
table = pa.table(
{
"_rowid": pa.array([1], type=pa.uint64()),
score: pa.array([1.0], type=pa.float32()),
}
)
sink = pa.BufferOutputStream()
with pa.ipc.new_file(sink, table.schema) as writer:
writer.write_table(table)
data = sink.getvalue().to_pybytes()
content_type = "application/vnd.apache.arrow.file"
else:
request.send_response(404)
request.end_headers()
return
request.send_response(200)
request.send_header("Content-Type", content_type)
request.end_headers()
request.wfile.write(data)
async with mock_lancedb_connection_async(handler) as db:
table = await db.open_table("test")
query = (
table.query()
.nearest_to([0.5, 0.5])
.nearest_to_text("match")
.offset(offset)
.limit(0)
)
with pytest.raises(ValueError, match="k must be positive"):
await query.to_arrow()
assert query_ks == []
def test_create_client():
mandatory_args = {
"uri": "db://dev",