perf(python): deduplicate sync query preparation (#5130)

## Summary

Sync query execution rebuilt schema-derived state several times inside
one call: for vector-column inference, blob projection validation,
row-id preparation, async handoff, and result finalization. A plain
point lookup paid five schema reads and five background-loop submissions
per `to_arrow()`.

This change prepares the schema and projected blob sources once per
execution and reuses them through scan setup, result finalization, and
the async handoff. Sync-prepared queries tell the async layer that blob
row ids are already resolved; nothing is cached between executions, so a
reused builder still observes schema changes. Plain scans and explicit
vector columns no longer read the schema just to infer a vector column,
and the dead vector conversion in `LanceVectorQueryBuilder.to_batches()`
is removed.

Non-lazy vector `to_arrow()` stays on its lazy materialization path, so
reranking and snapshot merging run once before the aggregate blob
conversion. Async behavior, namespace routing, fragments, timeouts, and
public APIs are unchanged. A direct synchronous Rust terminal remains
follow-up work.

## Benchmark

Workload: 200,000 rows, 64 dimensions, BTREE on `id`, IVF_PQ on
`vector`; 50 warmups + 500 calls per run; p50 of three runs. Baseline
and candidate Python packages ran against the same `release-no-lto`
extension built at `a2176f9b`; only package source differed. Local NVMe,
single host.

| Workload | Loop/schema per call before -> after | p50 before -> after
|
|---|---|---|
| plain point lookup `to_arrow()` | 5 / 5 -> 2 / 1 | 6.06 / 6.08 / 5.67
ms -> 3.26 / 3.26 / 3.33 ms |
| indexed vector `to_arrow()` | 5 / 5 -> 3 / 2 | 8.82 / 8.21 / 8.35 ms
-> 6.40 / 6.55 / 6.60 ms |
| plain point lookup `to_batches().read_all()` | 6 / 4 -> 4 / 1 | 6.88 /
7.25 / 6.94 ms -> 4.37 / 4.80 / 3.76 ms |

`release-no-lto` is a local comparison build, not a release-profile
number. The branch includes a merge of current main (`a2176f9b`, #5129);
the affected blob, reranker, FTS, query, and namespace checks were rerun
against the merged tree.

Refs OSS-2867 (non-closing).
This commit is contained in:
Xuanwo
2026-11-21 00:49:47 +08:00
committed by GitHub
parent a2176f9bcd
commit 03fc5404ae
6 changed files with 343 additions and 70 deletions
+71
View File
@@ -2399,6 +2399,77 @@ class _KeepAllScoresReranker(Reranker):
return combined.append_column("_relevance_score", scores)
class _RecordingVectorReranker(Reranker):
def __init__(self):
super().__init__(return_score="all")
self.calls = []
def rerank_hybrid(self, query, vector_results, fts_results):
raise AssertionError("vector queries must not call rerank_hybrid")
def rerank_vector(self, query, vector_results):
self.calls.append((query, vector_results))
return vector_results.append_column(
"_relevance_score",
pa.array([1.0] * len(vector_results), type=pa.float32()),
)
@pytest.mark.parametrize("blob_mode", ["descriptions", "bytes"])
def test_vector_to_arrow_reranks_before_blob_conversion(blob_mode, monkeypatch):
db = lancedb.connect("memory:///")
schema = pa.schema(
[
pa.field("id", pa.int64()),
pa.field("vector", pa.list_(pa.float32(), list_size=2)),
lancedb.blob("image"),
]
)
table = db.create_table(f"vector_rerank_{blob_mode}", schema=schema)
rows = 1100
table.add(
[
{
"id": row_id,
"vector": [1.0, float(row_id % 2)],
"image": f"image-{row_id}".encode(),
}
for row_id in range(rows)
]
)
fetched = []
fetch_blobs = table.fetch_blobs
def fetch(column, row_ids):
fetched.append((column, len(row_ids)))
return fetch_blobs(column, row_ids)
monkeypatch.setattr(table, "fetch_blobs", fetch)
reranker = _RecordingVectorReranker()
hits = (
table.search([1.0, 0.0])
.limit(rows)
.select(["id", "image"])
.rerank(reranker, "hello")
.to_arrow(blob_mode=blob_mode)
)
assert len(reranker.calls) == 1
query, source = reranker.calls[0]
assert query == "hello"
# The reranker sees descriptors, not already-converted payload bytes.
assert not pa.types.is_large_binary(source.schema.field("image").type)
assert "_relevance_score" in hits.column_names
assert len(hits) == rows
if blob_mode == "bytes":
# The whole lazy result is materialized before one aggregate conversion.
assert fetched == [("image", rows)]
assert pa.types.is_large_binary(hits.schema.field("image").type)
else:
assert fetched == []
assert not pa.types.is_large_binary(hits.schema.field("image").type)
def test_bytes_mode_rejects_legacy_blob_after_reranker_drops_metadata(tmp_path):
db = lancedb.connect(tmp_path)
table = db.create_table(
+64 -10
View File
@@ -1739,17 +1739,16 @@ def test_query_builder_with_different_vector_column():
ds = mock.Mock()
table.to_lance.return_value = ds
builder.to_arrow()
table._execute_arrow.assert_called_once_with(
Query(
vector=query,
filter="b < 10",
limit=2,
distance_type="cosine",
columns=["b"],
vector_column="foo_vector",
),
timeout=None,
expected = Query(
vector=query,
filter="b < 10",
limit=2,
distance_type="cosine",
columns=["b"],
vector_column="foo_vector",
)
expected._blob_row_id_prepared = True
table._execute_arrow.assert_called_once_with(expected, timeout=None)
def cosine_distance(vec1, vec2):
@@ -2657,6 +2656,61 @@ def test_query_schema(tmp_path):
)
def test_sync_query_prepares_schema_once_per_execution(tmp_path, monkeypatch):
db = lancedb.connect(tmp_path)
table = db.create_table(
"test",
pa.table(
{
"id": [1, 2, 3],
"vector": pa.array(
[[1, 2], [3, 4], [5, 6]],
pa.list_(pa.float32(), list_size=2),
),
}
),
)
calls = 0
original = AsyncTable.schema
async def counted(self):
nonlocal calls
calls += 1
return await original(self)
monkeypatch.setattr(AsyncTable, "schema", counted)
table.search().where("id = 1").select(["id"]).to_arrow()
assert calls <= 1
calls = 0
table.search([1, 2], vector_column_name="vector").limit(1).to_arrow()
assert calls <= 1
calls = 0
table.search([1, 2]).limit(1).to_arrow()
# At most one lookup infers the vector column, one prepares execution.
assert calls <= 2
calls = 0
table.search().where("id = 1").select(["id"]).to_batches().read_all()
assert calls <= 1
builder = table.search().where("id = 1")
before = builder.to_arrow()
assert "extra" not in before.column_names
assert "image" not in before.column_names
table.add_columns(pa.schema([pa.field("extra", pa.int64()), lancedb.blob("image")]))
calls = 0
after = builder.to_arrow()
assert calls <= 1
assert after["extra"].to_pylist() == [None]
assert "_lance_row_id" in str(after.schema)
assert "_rowid" not in after.column_names
@pytest.mark.asyncio
async def test_query_schema_async(tmp_path):
db = await lancedb.connect_async(tmp_path)
+1 -1
View File
@@ -120,7 +120,7 @@ def test_wal_hybrid_fuses_on_the_key_and_drops_it_again():
with_row_ids=True,
)
results = builder._finish_hybrid_results(
combined, blob_mode="lazy", blob_sources={}
combined, blob_mode="lazy", blob_sources={}, schema=None
)
assert "_rowid" not in results.column_names, "the surrogate is internal"