fix(python): skip null texts when reranking with a cross encoder (#5365)

## Summary

A vector, full-text or hybrid search can return a row whose reranking
text is null. `CrossEncoderReranker` built a `[query, None]` pair for
that row and passed it to `CrossEncoder.predict`. The Hugging Face
tokenizer only accepts strings (a `[query, None]` pair raises
`TypeError: TextInputSequence must be str`), so one row with missing
text made the whole rerank call fail.

Filter rows with null text out of the Arrow table before building the
pairs, so each score lines up with the right row. When every candidate
has null text, return an empty scored table without calling the model.
The class docstring now says that rows with a null `column` value are
left out of the reranked results.

This is the same behaviour as #5283 (Cohere) and #5296 (Jina), applied
to the cross-encoder reranker. #5336 and #5337 do the same for VoyageAI
and watsonx.ai.

## Verification

- Added `test_cross_encoder_reranker_nullable_documents`, run through a
real local table and `table.search(...).rerank(...)` with a mocked
model, with two cases:
- a null between two valid documents: only the two valid pairs reach
`predict`, and the result keeps the correct row IDs in score order, the
`_distance` column and a `float32` `_relevance_score`;
- all-null input, where `predict` is never called and an empty typed
result comes back.
- Both cases fail on `main` (the model receives `['Which document is
last?', None]`) and pass with this change.
- Checked the tokenizer behaviour directly with the `tokenizers`
library: encoding a `(query, None)` pair raises the `TypeError` above.
- Ran against LanceDB 0.42.1 and CPU PyTorch 2.15, with the changed
reranker module copied over the installed one. The installed
`cross_encoder.py` is identical to `main`. I did not download a real
cross-encoder model.
- Repository Ruff lint and format checks pass.

Co-authored-by: Xuanwo <github@xuanwo.io>
This commit is contained in:
Vibhanshu Singh
2026-12-02 21:35:57 +00:00
committed by GitHub
co-authored by Xuanwo
parent 50de29bdd5
commit 74503e13f6
2 changed files with 57 additions and 0 deletions
@@ -16,6 +16,8 @@ class CrossEncoderReranker(Reranker):
Reranks the results using a cross encoder model. The cross encoder model is
used to score the query and each result. The results are then sorted by the score.
Rows with null values in ``column`` are omitted from the reranked results.
Parameters
----------
model_name : str, default "cross-encoder/ms-marco-TinyBERT-L-6"
@@ -77,6 +79,9 @@ class CrossEncoderReranker(Reranker):
return cross_encoder
def _rerank(self, result_set: pa.Table, query: str):
if len(result_set) > 0 and result_set[self.column].null_count:
# The model can only score text, so rows without it are left out.
result_set = result_set.filter(result_set[self.column].is_valid())
result_set = self._handle_empty_results(result_set)
if len(result_set) == 0:
return result_set
+52
View File
@@ -1684,3 +1684,55 @@ def test_watsonx_reranker_nullable_documents(tmp_path, mocker, texts, expected_i
)
else:
reranker._client.generate.assert_not_called()
@pytest.mark.parametrize(
("texts", "expected_ids"),
[
(["first document", None, "last document"], [2, 0]),
([None, None, None], []),
],
)
def test_cross_encoder_reranker_nullable_documents(
tmp_path, mocker, texts, expected_ids
):
pytest.importorskip("torch")
table = lancedb.connect(tmp_path).create_table(
"documents",
pa.table(
{
"id": [0, 1, 2],
"text": pa.array(texts, type=pa.string()),
"vector": pa.array(
[[0.0, 0.0], [0.5, 0.0], [1.0, 0.0]],
type=pa.list_(pa.float32(), 2),
),
}
),
)
reranker = CrossEncoderReranker(device="cpu", return_score="all")
reranker.model = mocker.Mock()
def predict(pairs, **kwargs):
assert pairs == [
["Which document is last?", "first document"],
["Which document is last?", "last document"],
]
return [0.7, 0.9]
reranker.model.predict.side_effect = predict
result = (
table.search([0.0, 0.0])
.limit(3)
.rerank(reranker, query_string="Which document is last?")
.to_arrow()
)
assert result["id"].to_pylist() == expected_ids
assert result.schema.field("_relevance_score").type == pa.float32()
assert "_distance" in result.column_names
if expected_ids:
assert result["_relevance_score"].to_pylist() == pytest.approx([0.9, 0.7])
reranker.model.predict.assert_called_once()
else:
reranker.model.predict.assert_not_called()