fix(python): preserve Arrow payloads in linear reranking (#5368)

## Summary

Keep payload columns in Arrow during
`LinearCombinationReranker.merge_results()`
(`python/python/lancedb/rerankers/linear_combination.py`) instead of
round-tripping entire rows through `.to_pylist()` and
`pa.Table.from_pylist()`.

### Root Cause
- `LinearCombinationReranker.merge_results()` converted all columns of
`vector_results` and `fts_results` to Python dictionaries via
`.to_pylist()` and reconstructed the output table with
`pa.Table.from_pylist()`.
- Round-tripping through Python objects silently truncates
sub-microsecond precision on Arrow `time64[ns]` columns (e.g. `[1001,
2002, 3003]` becomes `[2000, 1000, 3000]`) and raises
`NotImplementedError` on `FixedShapeTensorArray` columns (the same Arrow
types already tested for `RRFReranker` in `test_rerankers.py`).

### Changes
- Project only `_rowid`, `_distance`, and `_score` to Python for the
relevance score computation, then select the deduplicated payload rows
directly in Arrow via `pa.concat_tables(...).take(...)` and
attach/update `_score` (when `return_score="all"`) and
`_relevance_score` before sorting.
- Preserve existing duplicate-row precedence, missing-score penalties,
tie ordering, and both `return_score="relevance"` and
`return_score="all"` modes.
- Add unit tests in
`python/python/tests/test_linear_combination_payload.py` covering
`pa.time64("ns")` and `pa.FixedShapeTensorArray` in both `return_score`
modes.

### Verification
- **Baseline RED (`787ad381`)**: All 4 parametrized cases in
`test_linear_combination_payload.py` fail (nanosecond precision loss for
`time64("ns")` and `NotImplementedError` for `FixedShapeTensorArray`).
- **With fix GREEN**: `test_linear_combination_payload.py` -> `4
passed`.
- `ruff check`, `ruff format --check`, and `git diff --check` pass
cleanly on both modified files.

Signed-off-by: bc15575202581 <bc15575202581@gmail.com>
This commit is contained in:
AWA
2026-12-02 20:05:31 +00:00
committed by GitHub
parent 3857320202
commit 2a88c3ad35
2 changed files with 83 additions and 22 deletions
@@ -2,7 +2,6 @@
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
from collections import defaultdict
import pyarrow as pa
from .base import Reranker
@@ -102,18 +101,27 @@ class LinearCombinationReranker(Reranker):
pa.nulls(len(vector_results), type=pa.float32()),
)
return results
results = defaultdict()
for vector_result in vector_results.to_pylist():
results[vector_result["_rowid"]] = vector_result
for fts_result in fts_results.to_pylist():
# Convert only the values used for scoring to Python. The payload stays
# in Arrow so types such as time64[ns] keep their full precision.
score_columns = ("_rowid", "_distance", "_score")
vector_scores = vector_results.select(
[name for name in score_columns if name in vector_results.column_names]
)
fts_scores = fts_results.select(
[name for name in score_columns if name in fts_results.column_names]
)
results = {}
for index, vector_result in enumerate(vector_scores.to_pylist()):
results[vector_result["_rowid"]] = (index, vector_result)
for index, fts_result in enumerate(fts_scores.to_pylist(), len(vector_results)):
row_id = fts_result["_rowid"]
if row_id in results:
results[row_id]["_score"] = fts_result["_score"]
results[row_id][1]["_score"] = fts_result["_score"]
else:
results[row_id] = fts_result
results[row_id] = (index, fts_result)
combined_list = []
for row_id, result in results.items():
relevance_scores = []
for _, result in results.values():
# Convert vector distance to a relevance score in [0, 1] where
# higher is better. Missing vector entries are penalised with
# `_invert_score(fill)` = 1 - fill (= 0.0 for the default fill=1).
@@ -123,20 +131,33 @@ class LinearCombinationReranker(Reranker):
# `1 - fill` so that the same `fill` value drives both missing-vector
# and missing-FTS penalties in the same direction.
fts_score = result.get("_score", missing_fts_score)
result["_relevance_score"] = self._combine_score(vector_score, fts_score)
combined_list.append(result)
relevance_scores.append(self._combine_score(vector_score, fts_score))
relevance_score_schema = pa.schema(
[
pa.field("_relevance_score", pa.float32()),
]
)
combined_schema = pa.unify_schemas(
[vector_results.schema, fts_results.schema, relevance_score_schema]
)
tbl = pa.Table.from_pylist(combined_list, schema=combined_schema).sort_by(
[("_relevance_score", "descending")]
)
tbl = pa.concat_tables(
[vector_results, fts_results], **self._concat_tables_args
).take([index for index, _ in results.values()])
if self.score == "all" and "_score" in tbl.column_names:
score_index = tbl.schema.get_field_index("_score")
score_field = tbl.schema.field(score_index)
tbl = tbl.set_column(
score_index,
score_field,
pa.array(
[result.get("_score") for _, result in results.values()],
type=score_field.type,
),
)
relevance = pa.array(relevance_scores, type=pa.float32())
relevance_index = tbl.schema.get_field_index("_relevance_score")
if relevance_index >= 0:
tbl = tbl.set_column(
relevance_index,
tbl.schema.field(relevance_index).with_type(relevance.type),
relevance,
)
else:
tbl = tbl.append_column("_relevance_score", relevance)
tbl = tbl.sort_by([("_relevance_score", "descending")])
if self.score == "relevance":
tbl = self._keep_relevance_score(tbl)
return tbl
@@ -0,0 +1,40 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import numpy as np
import pyarrow as pa
import pytest
from lancedb.rerankers import LinearCombinationReranker
@pytest.mark.parametrize("return_score", ["relevance", "all"])
@pytest.mark.parametrize(
"payload",
[
pa.array([1001, 2002, 3003], type=pa.time64("ns")),
pa.FixedShapeTensorArray.from_numpy_ndarray(
np.arange(6, dtype=np.float32).reshape(3, 2)
),
],
ids=["nanosecond-time", "fixed-shape-tensor"],
)
def test_linear_combination_preserves_arrow_payload(return_score, payload):
vector_results = pa.table(
{"_rowid": [0, 1], "_distance": [0.0, 0.25], "payload": payload.slice(0, 2)}
)
fts_results = pa.table(
{"_rowid": [1, 2], "_score": [1.0, 0.25], "payload": payload.slice(1, 2)}
)
reranker = LinearCombinationReranker(weight=0.5, return_score=return_score)
result = reranker.rerank_hybrid("query", vector_results, fts_results)
assert result["_rowid"].to_pylist() == [1, 0, 2]
assert result["_relevance_score"].to_pylist() == [0.875, 0.5, 0.125]
if return_score == "all":
assert result["_distance"].to_pylist() == [0.25, 0.0, None]
assert result["_score"].to_pylist() == [1.0, None, 0.25]
else:
assert result.column_names == ["_rowid", "payload", "_relevance_score"]
assert result["payload"].combine_chunks().equals(payload.take([1, 0, 2]))