mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
### Summary & Reasoning Embedded Python `to_pandas()` previously incurred three avoidable bottlenecks on tables without blob columns: 1. **Unconditional `output_schema()` re-planning**: Both sync and async `to_pandas()` invoked `output_schema()` before execution, running the full Rust/DataFusion physical query planner (`create_plan()` — dataset lookup, row count, SQL/subquery prep, index loading, plan construction) only to discard the plan and build it a second time. For sync queries, `_output_schema()` also hopped across `LOOP.run(...)`, bypassing the direct `execute_to_reader_sync` fast path. 2. **Async eager-collector bypass**: `AsyncQueryBase.to_pandas()` rewrote the default `blob_mode="lazy"` to `"descriptions"`, causing `to_arrow()` to skip `#5127`'s native eager collector (`execute_to_reader`) and fall back to per-batch `to_batches()` streaming (1,024-row slicing and one Python future per batch). Sync `LanceTakeQueryBuilder.to_pandas()` hit the same path via `BaseQueryBuilder`. 3. **Redundant `table.schema` fetches and `to_query_request()` vector FFI clones**: Blob row-id and source checks cloned query requests across FFI and fetched `table.schema` multiple times per execution (2x on non-hybrid, 4x-5x on hybrid / WAL-PK tables) even when the table schema contained no blob columns or `with_row_id()` was already set. ### Chosen Direction & Trade-Offs - **Schema-gated fast path**: `schema_has_blob_field(table_schema)` matches strictly schema-declared blob columns (including nested structs and lists), so a query over a non-blob table cannot produce blob output fields. Fetching `table_schema` once and gating `output_schema()` and `blob_mode` rewrites on it avoids double planning, keeps non-blob `to_pandas()` and `to_arrow(blob_mode="descriptions"|"bytes")` on the eager collector, and brings execution down to a single schema fetch (including across hybrid child legs and WAL-PK retries). - **Conservative on blob tables & unbound queries**: Tables containing blob columns still run `output_schema()` so projected/quoted/nested blob edge cases keep identical behavior (while reusing the pre-fetched schema to avoid extra schema fetches). Unbound `AsyncQueryBase` (`table=None`) keeps the conservative fallback. - **Preserving overrides & monkeypatches**: Internal schema-threaded helpers are only entered when built-in `to_arrow`/`to_batches` methods have not been overridden or monkeypatched (including hybrid child legs), so custom subclasses without `blob_mode` and test spies behave identically. - **Enterprise tables**: Early Enterprise execution paths are unchanged (preserving zero extra schema requests in `"lazy"` mode and existing `_blob_paths` / snapshot behavior). - **Out of scope**: Skipping `output_schema()` when a query on a blob table projects only non-blob columns, and Rust-side `create_plan()` optimizations. ### Benchmarks Measured on **AMD Ryzen 9 7950X3D**, runner and child processes pinned to **CCD0 (`ProcessorAffinity = 0xFFFF`, logical CPUs 0-15, verified via `GetProcessAffinityMask`)**, interleaved **`A -> B -> B -> A`** cells on shared datasets and the exact same compiled `_lancedb.pyd` extension (`A` = `c3f005f7`, `B` = patched): | Workload | Baseline `A` (med / p95) | Candidate `B` (med / p95) | Speedup | Per-cell medians (`A1, B1, B2, A2`) | | :--- | ---: | ---: | ---: | :--- | | Sync indexed vector `10k x 128d` `limit(10)` (`n=100`/cell) | `6.541 ms` / `6.834 ms` | `5.196 ms` / `5.439 ms` | **1.26x (-20.6%)** | `6.627, 5.148, 5.249, 6.464 ms` | | Async indexed vector `10k x 128d` `limit(10)` (`n=100`/cell) | `6.835 ms` / `8.063 ms` | `5.358 ms` / `5.632 ms` | **1.28x (-21.6%)** | `6.924, 5.323, 5.410, 6.790 ms` | | Sync scan `500k x 3` (`n=10`/cell) | `11.027 ms` / `11.901 ms` | `9.543 ms` / `10.253 ms` | **1.16x (-13.5%)** | `10.769, 9.452, 9.591, 11.134 ms` | | Async scan `500k x 3` (`n=10`/cell) | `152.783 ms` / `154.980 ms` | `9.447 ms` / `9.817 ms` | **16.17x (-93.8%)** | `151.034, 9.602, 9.431, 154.107 ms` | ### Verification - **Executed on Windows host**: - Targeted pytest suite (11 files covering sync direct, eager collector, query, blob, blob-without-pylance, hybrid, WAL hybrid, FTS wand factor, Enterprise `test_remote_db.py`, namespace, and table tests): **2,150 passed, 0 failed, 21 skipped** (0 missing-`pandas`/`pylance` skips; skips limited to Linux `sched_setaffinity`/`fork`, optional `av`/`torch`, and `experimental_functions`). - No-`pandas` / no-`pylance` parity check (blocking `pandas` and `lance` imports on `test_sync_query_direct.py`, `test_eager_collector.py`, `test_wal_hybrid.py`): **21 passed, 0 failed, 6 skipped**. - Doctests on `python/lancedb/query.py`: **23 passed, 0 failed**. - `ruff==0.9.9 format --check .` and `ruff==0.9.9 check .`: passed. - `pyright --pythonplatform Linux`: 0 errors; diff-scoped `pyright` on `python/lancedb/query.py`: 0 errors across all changed lines. - `typos` on all modified files: passed. - **Pending CI**: Full cross-platform Python matrix (Linux/macOS/Windows), Linux-only `sched_setaffinity`/`fork` tests, and CI commitlint/license-header workflows. --------- Co-authored-by: Xuanwo <github@xuanwo.io>
422 lines
13 KiB
Python
422 lines
13 KiB
Python
# SPDX-License-Identifier: Apache-2.0
|
|
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
|
|
|
"""WAL-PK-FUSION: delete this file with `lancedb/_wal_hybrid.py`."""
|
|
|
|
from unittest import mock
|
|
|
|
import lancedb
|
|
import pyarrow as pa
|
|
import pytest
|
|
from lancedb._wal_hybrid import WAL_ROW_ID_UNSUPPORTED, with_pk_fallback
|
|
from lancedb.index import FTS
|
|
from lancedb.query import AsyncQueryBase, LanceHybridQueryBuilder, LanceQueryBuilder
|
|
from lancedb.rerankers import RRFReranker
|
|
from lancedb.table import AsyncTable
|
|
|
|
|
|
def _wal_table(schema: pa.Schema) -> mock.Mock:
|
|
"""An RTE-backed table a previous query has already been refused
|
|
`_rowid` on, so the fusion goes straight to the primary key."""
|
|
table = mock.Mock()
|
|
table._hybrid_pk_fusion_learned.return_value = True
|
|
table.schema = schema
|
|
return table
|
|
|
|
|
|
_PK_SCHEMA = pa.schema(
|
|
[
|
|
pa.field(
|
|
"id",
|
|
pa.string(),
|
|
metadata={b"lance-schema:unenforced-primary-key:position": b"1"},
|
|
),
|
|
pa.field("text", pa.string()),
|
|
]
|
|
)
|
|
|
|
|
|
def _wal_hybrid(**select):
|
|
builder = (
|
|
LanceHybridQueryBuilder(_wal_table(_PK_SCHEMA)).vector([0.1, 0.2]).text("puppy")
|
|
)
|
|
if "columns" in select:
|
|
builder = builder.select(select["columns"])
|
|
return builder
|
|
|
|
|
|
def test_wal_hybrid_projects_the_key_instead_of_asking_for_row_ids():
|
|
builder = _wal_hybrid(columns=["text"])
|
|
builder._create_query_builders()
|
|
|
|
assert builder._pk_fusion.pk_columns == ["id"]
|
|
assert builder._pk_fusion.injected == ["id"]
|
|
for leg in (builder._vector_query, builder._fts_query):
|
|
assert leg._columns == ["text", "id"]
|
|
# An RTE table rejects with_row_id before it plans.
|
|
assert leg._with_row_id is not True
|
|
|
|
|
|
def test_wal_hybrid_selecting_the_key_injects_nothing():
|
|
builder = _wal_hybrid(columns=["text", "id"])
|
|
builder._create_query_builders()
|
|
assert builder._pk_fusion.injected == []
|
|
|
|
|
|
def test_wal_hybrid_without_a_projection_leaves_it_alone():
|
|
builder = _wal_hybrid()
|
|
builder._create_query_builders()
|
|
# Select-all already returns the key.
|
|
assert builder._pk_fusion.injected == []
|
|
assert builder._vector_query._columns is None
|
|
|
|
|
|
def test_base_table_hybrid_still_joins_on_row_ids():
|
|
table = mock.Mock()
|
|
table._hybrid_pk_fusion_learned.return_value = False
|
|
builder = LanceHybridQueryBuilder(table).vector([0.1, 0.2]).text("puppy")
|
|
builder._create_query_builders()
|
|
|
|
# `to_arrow` is what turns row ids on for this path; all that matters here
|
|
# is that no key was resolved and no projection was touched.
|
|
assert builder._pk_fusion is None
|
|
assert builder._vector_query._columns is None
|
|
|
|
|
|
def test_wal_hybrid_with_use_rte_false_joins_on_row_ids():
|
|
builder = _wal_hybrid().use_rte(False)
|
|
builder._create_query_builders()
|
|
assert builder._pk_fusion is None
|
|
|
|
|
|
def test_wal_hybrid_refuses_an_explicit_with_row_id():
|
|
builder = _wal_hybrid().with_row_id(True)
|
|
with pytest.raises(NotImplementedError, match="use_rte"):
|
|
builder._create_query_builders()
|
|
|
|
|
|
def test_wal_hybrid_return_score_all_is_not_refused():
|
|
"""`return_score="all"` turns row ids on for the reranker, not the caller."""
|
|
builder = _wal_hybrid().rerank(RRFReranker(return_score="all"))
|
|
builder._create_query_builders()
|
|
assert builder._pk_fusion.pk_columns == ["id"]
|
|
|
|
|
|
def test_wal_hybrid_fuses_on_the_key_and_drops_it_again():
|
|
builder = _wal_hybrid(columns=["text"])
|
|
builder._create_query_builders()
|
|
|
|
vector_results = pa.table(
|
|
{"text": ["a", "b"], "id": ["a", "b"], "_distance": [0.1, 0.2]}
|
|
)
|
|
fts_results = pa.table({"text": ["b", "c"], "id": ["b", "c"], "_score": [1.0, 2.0]})
|
|
vector_results, fts_results = builder._pk_fusion.stamp(vector_results, fts_results)
|
|
|
|
combined = LanceHybridQueryBuilder._combine_hybrid_results(
|
|
fts_results=fts_results,
|
|
vector_results=vector_results,
|
|
norm="score",
|
|
fts_query="puppy",
|
|
reranker=RRFReranker(),
|
|
limit=10,
|
|
with_row_ids=True,
|
|
)
|
|
results = builder._finish_hybrid_results(
|
|
combined, blob_mode="lazy", blob_sources={}, schema=None
|
|
)
|
|
|
|
assert "_rowid" not in results.column_names, "the surrogate is internal"
|
|
assert "id" not in results.column_names, "the caller selected only `text`"
|
|
assert sorted(results.column("text").to_pylist()) == ["a", "b", "c"]
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"row_id_first", [True, False], ids=["row_id_first", "rerank_first"]
|
|
)
|
|
def test_wal_hybrid_refuses_row_id_even_with_return_score_all(row_id_first: bool):
|
|
"""`return_score="all"` sets the same flag the caller's request does, so
|
|
asking for both must still be refused — in either call order."""
|
|
builder = _wal_hybrid()
|
|
reranker = RRFReranker(return_score="all")
|
|
if row_id_first:
|
|
builder = builder.with_row_id(True).rerank(reranker)
|
|
else:
|
|
builder = builder.rerank(reranker).with_row_id(True)
|
|
|
|
with pytest.raises(NotImplementedError, match="use_rte"):
|
|
builder._create_query_builders()
|
|
|
|
|
|
def test_wal_hybrid_refuses_a_blob_projection_with_return_score_all():
|
|
"""A projected blob needs a real row id to fetch through, which the
|
|
reranker turning `_with_row_id` on does not provide."""
|
|
schema = pa.schema(
|
|
[
|
|
pa.field(
|
|
"id",
|
|
pa.string(),
|
|
metadata={b"lance-schema:unenforced-primary-key:position": b"1"},
|
|
),
|
|
pa.field("text", pa.string()),
|
|
lancedb.blob("blob"),
|
|
]
|
|
)
|
|
builder = (
|
|
LanceHybridQueryBuilder(_wal_table(schema))
|
|
.vector([0.1, 0.2])
|
|
.text("puppy")
|
|
.select(["blob"])
|
|
.rerank(RRFReranker(return_score="all"))
|
|
)
|
|
|
|
with pytest.raises(NotImplementedError, match="blob"):
|
|
builder._create_query_builders()
|
|
|
|
|
|
_REFUSAL = RuntimeError(
|
|
"Bad request: the MemWAL LSM scanner does not support with_row_id"
|
|
)
|
|
|
|
|
|
def test_fallback_retries_on_the_key_and_remembers_it():
|
|
table = mock.Mock()
|
|
attempts = []
|
|
|
|
def run():
|
|
attempts.append(len(attempts))
|
|
if len(attempts) == 1:
|
|
raise _REFUSAL
|
|
return "fused"
|
|
|
|
result = with_pk_fallback(
|
|
run, table, fused=lambda: False, caller_requested_row_id=False
|
|
)
|
|
|
|
assert result == "fused"
|
|
assert len(attempts) == 2
|
|
table._note_hybrid_pk_fusion.assert_called_once()
|
|
|
|
|
|
def test_fallback_explains_the_refusal_to_a_caller_who_asked_for_row_ids():
|
|
def run():
|
|
raise _REFUSAL
|
|
|
|
with pytest.raises(NotImplementedError, match="use_rte") as info:
|
|
with_pk_fallback(
|
|
run, mock.Mock(), fused=lambda: False, caller_requested_row_id=True
|
|
)
|
|
assert str(info.value) == WAL_ROW_ID_UNSUPPORTED
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"error, fused",
|
|
[(ValueError("unrelated"), False), (_REFUSAL, True)],
|
|
ids=["other_error", "already_fused"],
|
|
)
|
|
def test_fallback_reraises_what_it_cannot_retry(error, fused):
|
|
def run():
|
|
raise error
|
|
|
|
table = mock.Mock()
|
|
with pytest.raises(type(error)):
|
|
with_pk_fallback(run, table, fused=lambda: fused, caller_requested_row_id=False)
|
|
table._note_hybrid_pk_fusion.assert_not_called()
|
|
|
|
|
|
def _pk_hybrid_data() -> pa.Table:
|
|
return pa.table(
|
|
{
|
|
"id": pa.array(["a", "b", "c"], type=pa.string()),
|
|
"text": pa.array(["alpha beta", "alpha gamma", "delta epsilon"]),
|
|
"vector": pa.array(
|
|
[[1.0, 0.0], [0.5, 0.5], [0.0, 1.0]],
|
|
type=pa.list_(pa.float32(), 2),
|
|
),
|
|
},
|
|
schema=pa.schema(
|
|
[
|
|
pa.field(
|
|
"id",
|
|
pa.string(),
|
|
nullable=False,
|
|
metadata={b"lance-schema:unenforced-primary-key:position": b"1"},
|
|
),
|
|
pa.field("text", pa.string()),
|
|
pa.field("vector", pa.list_(pa.float32(), 2)),
|
|
]
|
|
),
|
|
)
|
|
|
|
|
|
def _install_learned_hooks(monkeypatch, table):
|
|
learned = [False]
|
|
monkeypatch.setattr(table, "_hybrid_pk_fusion_learned", lambda: learned[0])
|
|
monkeypatch.setattr(
|
|
table, "_note_hybrid_pk_fusion", lambda: learned.__setitem__(0, True)
|
|
)
|
|
return learned
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_async_wal_hybrid_to_arrow_schema_count_learned_and_retry(
|
|
tmp_path, monkeypatch
|
|
):
|
|
db = await lancedb.connect_async(tmp_path)
|
|
table = await db.create_table("wal_async_arrow", _pk_hybrid_data())
|
|
await table.create_index("text", config=FTS(with_position=True))
|
|
_install_learned_hooks(monkeypatch, table)
|
|
|
|
orig_execute_eager = AsyncQueryBase._execute_eager
|
|
|
|
async def refusing_execute_eager(self, *args, **kwargs):
|
|
if self._with_row_id is True:
|
|
raise _REFUSAL
|
|
return await orig_execute_eager(self, *args, **kwargs)
|
|
|
|
monkeypatch.setattr(AsyncQueryBase, "_execute_eager", refusing_execute_eager)
|
|
|
|
schema_calls = 0
|
|
orig_schema = AsyncTable.schema
|
|
|
|
async def counted_schema(self):
|
|
nonlocal schema_calls
|
|
schema_calls += 1
|
|
return await orig_schema(self)
|
|
|
|
monkeypatch.setattr(AsyncTable, "schema", counted_schema)
|
|
|
|
first = (
|
|
await table.vector_search([1.0, 0.0])
|
|
.nearest_to_text("alpha")
|
|
.select(["text"])
|
|
.limit(2)
|
|
.to_arrow()
|
|
)
|
|
assert first.num_rows == 2
|
|
assert "id" not in first.column_names
|
|
assert "_rowid" not in first.column_names
|
|
assert table._hybrid_pk_fusion_learned() is True
|
|
assert schema_calls == 2
|
|
|
|
schema_calls = 0
|
|
second = (
|
|
await table.vector_search([1.0, 0.0])
|
|
.nearest_to_text("alpha")
|
|
.select(["text"])
|
|
.limit(2)
|
|
.to_arrow()
|
|
)
|
|
assert second.num_rows == 2
|
|
assert "id" not in second.column_names
|
|
assert "_rowid" not in second.column_names
|
|
assert schema_calls == 1
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_wal_hybrid_to_pandas_schema_count_learned_and_retry(
|
|
tmp_path, monkeypatch
|
|
):
|
|
pytest.importorskip("pandas")
|
|
|
|
# Sync LanceTable path
|
|
sync_db = lancedb.connect(tmp_path / "sync_wal")
|
|
sync_table = sync_db.create_table("wal_sync_pandas", _pk_hybrid_data())
|
|
sync_table.create_index("text", config=FTS(with_position=True))
|
|
_install_learned_hooks(monkeypatch, sync_table)
|
|
|
|
orig_exec_arrow = LanceQueryBuilder._execute_arrow_prepared
|
|
|
|
def refusing_exec_arrow(self, query, *args, **kwargs):
|
|
if query.with_row_id is True:
|
|
raise _REFUSAL
|
|
return orig_exec_arrow(self, query, *args, **kwargs)
|
|
|
|
monkeypatch.setattr(
|
|
LanceQueryBuilder, "_execute_arrow_prepared", refusing_exec_arrow
|
|
)
|
|
|
|
sync_schema_calls = 0
|
|
orig_schema_sync = AsyncTable._schema_sync
|
|
|
|
def counted_schema_sync(self):
|
|
nonlocal sync_schema_calls
|
|
sync_schema_calls += 1
|
|
return orig_schema_sync(self)
|
|
|
|
monkeypatch.setattr(AsyncTable, "_schema_sync", counted_schema_sync)
|
|
|
|
sync_first = (
|
|
sync_table.search(query_type="hybrid", vector_column_name="vector")
|
|
.vector([1.0, 0.0])
|
|
.text("alpha")
|
|
.select(["text"])
|
|
.limit(2)
|
|
.to_pandas()
|
|
)
|
|
assert len(sync_first) == 2
|
|
assert "id" not in sync_first.columns
|
|
assert "_rowid" not in sync_first.columns
|
|
assert sync_table._hybrid_pk_fusion_learned() is True
|
|
assert sync_schema_calls == 1
|
|
|
|
sync_schema_calls = 0
|
|
sync_second = (
|
|
sync_table.search(query_type="hybrid", vector_column_name="vector")
|
|
.vector([1.0, 0.0])
|
|
.text("alpha")
|
|
.select(["text"])
|
|
.limit(2)
|
|
.to_pandas()
|
|
)
|
|
assert len(sync_second) == 2
|
|
assert sync_schema_calls == 1
|
|
|
|
# Async AsyncTable path
|
|
async_db = await lancedb.connect_async(tmp_path / "async_wal")
|
|
async_table = await async_db.create_table("wal_async_pandas", _pk_hybrid_data())
|
|
await async_table.create_index("text", config=FTS(with_position=True))
|
|
_install_learned_hooks(monkeypatch, async_table)
|
|
|
|
orig_execute_eager = AsyncQueryBase._execute_eager
|
|
|
|
async def refusing_execute_eager(self, *args, **kwargs):
|
|
if self._with_row_id is True:
|
|
raise _REFUSAL
|
|
return await orig_execute_eager(self, *args, **kwargs)
|
|
|
|
monkeypatch.setattr(AsyncQueryBase, "_execute_eager", refusing_execute_eager)
|
|
|
|
async_schema_calls = 0
|
|
orig_schema = AsyncTable.schema
|
|
|
|
async def counted_schema(self):
|
|
nonlocal async_schema_calls
|
|
async_schema_calls += 1
|
|
return await orig_schema(self)
|
|
|
|
monkeypatch.setattr(AsyncTable, "schema", counted_schema)
|
|
|
|
async_first = (
|
|
await async_table.vector_search([1.0, 0.0])
|
|
.nearest_to_text("alpha")
|
|
.select(["text"])
|
|
.limit(2)
|
|
.to_pandas()
|
|
)
|
|
assert len(async_first) == 2
|
|
assert "id" not in async_first.columns
|
|
assert "_rowid" not in async_first.columns
|
|
assert async_table._hybrid_pk_fusion_learned() is True
|
|
assert async_schema_calls == 1
|
|
|
|
async_schema_calls = 0
|
|
async_second = (
|
|
await async_table.vector_search([1.0, 0.0])
|
|
.nearest_to_text("alpha")
|
|
.select(["text"])
|
|
.limit(2)
|
|
.to_pandas()
|
|
)
|
|
assert len(async_second) == 2
|
|
assert async_schema_calls == 1
|