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>
305 lines
9.4 KiB
Python
305 lines
9.4 KiB
Python
# SPDX-License-Identifier: Apache-2.0
|
|
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
|
|
|
import signal
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
from datetime import timedelta
|
|
|
|
import pyarrow as pa
|
|
import pytest
|
|
|
|
import lancedb
|
|
from lancedb import background_loop
|
|
from lancedb.index import BTree, FTS, IvfFlat
|
|
from lancedb.table import AsyncTable
|
|
|
|
|
|
def _direct_query_table(tmp_path):
|
|
table = lancedb.connect(tmp_path).create_table(
|
|
"direct",
|
|
pa.table(
|
|
{
|
|
"id": pa.array([1, 2, 3, 4], pa.int64()),
|
|
"text": ["alpha beta", "alpha gamma", "beta gamma", "delta epsilon"],
|
|
"vector": pa.array(
|
|
[
|
|
[1.0, 0.0, 0.0, 0.0],
|
|
[0.0, 1.0, 0.0, 0.0],
|
|
[0.0, 0.0, 1.0, 0.0],
|
|
[0.0, 0.0, 0.0, 1.0],
|
|
],
|
|
pa.list_(pa.float32(), 4),
|
|
),
|
|
}
|
|
),
|
|
)
|
|
table.create_index("id", config=BTree())
|
|
table.create_index("vector", config=IvfFlat(distance_type="l2", num_partitions=1))
|
|
table.create_index("text", config=FTS(with_position=True))
|
|
return table
|
|
|
|
|
|
def test_direct_sync_queries_do_not_use_background_loop(tmp_path, monkeypatch):
|
|
table = _direct_query_table(tmp_path)
|
|
expected_empty_schema = table.search().where("id < 0").output_schema()
|
|
|
|
def fail(*_args, **_kwargs):
|
|
raise AssertionError("LOOP.run must not be used by direct sync queries")
|
|
|
|
def fail_output_schema(*_args, **_kwargs):
|
|
raise AssertionError(
|
|
"_output_schema must not be called on direct non-blob sync queries"
|
|
)
|
|
|
|
monkeypatch.setattr(background_loop.LOOP, "run", fail)
|
|
monkeypatch.setattr(table, "_output_schema", fail_output_schema)
|
|
|
|
point = table.search().where("id = 1").select(["id", "text"]).to_arrow()
|
|
assert point.to_pylist() == [{"id": 1, "text": "alpha beta"}]
|
|
for blob_mode in ("descriptions", "bytes"):
|
|
mode_point = (
|
|
table.search()
|
|
.where("id = 1")
|
|
.select(["id", "text"])
|
|
.to_arrow(blob_mode=blob_mode)
|
|
)
|
|
assert mode_point.to_pylist() == [{"id": 1, "text": "alpha beta"}]
|
|
|
|
with_row_id = (
|
|
table.search().where("id = 1").select(["id"]).with_row_id(True).to_arrow()
|
|
)
|
|
assert with_row_id["_rowid"].to_pylist() == [0]
|
|
|
|
# The vector column is inferred from the sync schema binding.
|
|
vector = table.search([0.9, 0.1, 0.0, 0.0]).limit(2).to_arrow()
|
|
assert vector["id"].to_pylist() == [1, 2]
|
|
assert "_distance" in vector.column_names
|
|
for blob_mode in ("descriptions", "bytes"):
|
|
mode_vector = (
|
|
table.search([0.9, 0.1, 0.0, 0.0]).limit(2).to_arrow(blob_mode=blob_mode)
|
|
)
|
|
assert mode_vector["id"].to_pylist() == [1, 2]
|
|
|
|
fts = table.search("alpha", query_type="fts").select(["id"]).to_arrow()
|
|
assert sorted(fts["id"].to_pylist()) == [1, 2]
|
|
assert "_score" in fts.column_names
|
|
for blob_mode in ("descriptions", "bytes"):
|
|
mode_fts = (
|
|
table.search("alpha", query_type="fts")
|
|
.select(["id"])
|
|
.to_arrow(blob_mode=blob_mode)
|
|
)
|
|
assert sorted(mode_fts["id"].to_pylist()) == [1, 2]
|
|
|
|
phrase = table.search('"alpha beta"', query_type="fts").select(["id"]).to_arrow()
|
|
assert phrase["id"].to_pylist() == [1]
|
|
|
|
empty = table.search().where("id < 0").to_arrow()
|
|
assert empty.num_rows == 0
|
|
assert empty.schema == expected_empty_schema
|
|
|
|
with pytest.raises(Exception, match="Query timeout"):
|
|
table.search([1.0, 0.0, 0.0, 0.0]).to_arrow(timeout=timedelta(0))
|
|
|
|
|
|
def test_direct_sync_to_pandas_skips_output_schema_and_background_loop(
|
|
tmp_path, monkeypatch
|
|
):
|
|
pytest.importorskip("pandas")
|
|
table = _direct_query_table(tmp_path)
|
|
expected_columns = table.schema.names
|
|
|
|
def fail_loop(*_args, **_kwargs):
|
|
raise AssertionError("LOOP.run must not be used by direct sync to_pandas")
|
|
|
|
def fail_output_schema(*_args, **_kwargs):
|
|
raise AssertionError("_output_schema must not be called on non-blob to_pandas")
|
|
|
|
monkeypatch.setattr(background_loop.LOOP, "run", fail_loop)
|
|
monkeypatch.setattr(table, "_output_schema", fail_output_schema)
|
|
|
|
schema_calls = 0
|
|
original_schema_sync = AsyncTable._schema_sync
|
|
|
|
def counted_schema_sync(self):
|
|
nonlocal schema_calls
|
|
schema_calls += 1
|
|
return original_schema_sync(self)
|
|
|
|
monkeypatch.setattr(AsyncTable, "_schema_sync", counted_schema_sync)
|
|
|
|
for blob_mode in ("lazy", "descriptions", "bytes"):
|
|
schema_calls = 0
|
|
df = (
|
|
table.search()
|
|
.where("id = 1")
|
|
.select(["id", "text"])
|
|
.to_pandas(blob_mode=blob_mode)
|
|
)
|
|
assert df.to_dict(orient="records") == [{"id": 1, "text": "alpha beta"}]
|
|
assert schema_calls == 1
|
|
|
|
schema_calls = 0
|
|
vec_df = (
|
|
table.search([0.9, 0.1, 0.0, 0.0], vector_column_name="vector")
|
|
.limit(2)
|
|
.to_pandas()
|
|
)
|
|
assert vec_df["id"].tolist() == [1, 2]
|
|
assert "_distance" in vec_df.columns
|
|
assert schema_calls == 1
|
|
|
|
schema_calls = 0
|
|
inferred_query = table.search([0.9, 0.1, 0.0, 0.0]).limit(2)
|
|
assert schema_calls == 1
|
|
schema_calls = 0
|
|
inferred_df = inferred_query.to_pandas()
|
|
assert inferred_df["id"].tolist() == [1, 2]
|
|
assert schema_calls == 1
|
|
|
|
schema_calls = 0
|
|
inferred_e2e_df = table.search([0.9, 0.1, 0.0, 0.0]).limit(2).to_pandas()
|
|
assert inferred_e2e_df["id"].tolist() == [1, 2]
|
|
assert schema_calls == 2
|
|
|
|
schema_calls = 0
|
|
fts_df = table.search("alpha", query_type="fts").select(["id"]).to_pandas()
|
|
assert sorted(fts_df["id"].tolist()) == [1, 2]
|
|
assert "_score" in fts_df.columns
|
|
assert schema_calls == 1
|
|
|
|
empty_df = table.search().where("id < 0").to_pandas()
|
|
assert len(empty_df) == 0
|
|
assert list(empty_df.columns) == expected_columns
|
|
|
|
with pytest.raises(Exception, match="Query timeout"):
|
|
table.search([1.0, 0.0, 0.0, 0.0]).to_pandas(timeout=timedelta(0))
|
|
|
|
with pytest.raises(ValueError, match="blob_mode must be one of"):
|
|
table.search().to_pandas(blob_mode="invalid")
|
|
|
|
with pytest.raises(NotImplementedError, match="fragment selection"):
|
|
table.search().fragment_ids([0]).to_pandas()
|
|
|
|
|
|
def test_sync_hybrid_to_pandas_fetches_schema_once(tmp_path, monkeypatch):
|
|
pytest.importorskip("pandas")
|
|
table = _direct_query_table(tmp_path)
|
|
|
|
schema_calls = 0
|
|
original_schema_sync = AsyncTable._schema_sync
|
|
|
|
def counted_schema_sync(self):
|
|
nonlocal schema_calls
|
|
schema_calls += 1
|
|
return original_schema_sync(self)
|
|
|
|
monkeypatch.setattr(AsyncTable, "_schema_sync", counted_schema_sync)
|
|
|
|
query = (
|
|
table.search(query_type="hybrid")
|
|
.vector([0.9, 0.1, 0.0, 0.0])
|
|
.text("alpha")
|
|
.limit(2)
|
|
)
|
|
schema_calls = 0
|
|
df = query.to_pandas()
|
|
assert len(df) == 2
|
|
assert schema_calls == 1
|
|
|
|
schema_calls = 0
|
|
df_explicit = (
|
|
table.search(query_type="hybrid", vector_column_name="vector")
|
|
.vector([0.9, 0.1, 0.0, 0.0])
|
|
.text("alpha")
|
|
.limit(2)
|
|
.to_pandas()
|
|
)
|
|
assert len(df_explicit) == 2
|
|
assert schema_calls == 1
|
|
|
|
|
|
@pytest.mark.skipif(sys.platform != "linux", reason="needs sched_setaffinity")
|
|
def test_direct_sync_query_from_single_worker_progress_callback(tmp_path):
|
|
script = r"""
|
|
import os
|
|
import sys
|
|
|
|
try:
|
|
cpus = sorted(os.sched_getaffinity(0))
|
|
if not cpus:
|
|
print("SKIP")
|
|
sys.exit(0)
|
|
os.sched_setaffinity(0, {cpus[0]})
|
|
except OSError:
|
|
print("SKIP")
|
|
sys.exit(0)
|
|
|
|
import lancedb
|
|
|
|
db = lancedb.connect("memory:///")
|
|
target = db.create_table(
|
|
"target",
|
|
[{"id": 1, "value": "one"}, {"id": 2, "value": "two"}],
|
|
)
|
|
source = db.create_table("source", [{"id": 1}])
|
|
seen = []
|
|
|
|
def progress(_update):
|
|
if not seen:
|
|
seen.append(
|
|
target.search()
|
|
.where("id = 1")
|
|
.select(["value"])
|
|
.to_arrow()
|
|
.to_pylist()
|
|
)
|
|
|
|
source.add([{"id": 2}], progress=progress)
|
|
assert seen == [[{"value": "one"}]], seen
|
|
print("OK")
|
|
"""
|
|
result = subprocess.run(
|
|
[sys.executable, "-c", script],
|
|
cwd=tmp_path,
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=30,
|
|
)
|
|
if "SKIP" in result.stdout:
|
|
pytest.skip("sched_setaffinity did not leave a usable CPU")
|
|
assert result.returncode == 0, result.stdout + result.stderr
|
|
assert "OK" in result.stdout
|
|
|
|
|
|
@pytest.mark.slow
|
|
def test_direct_sync_query_sigint_aborts_and_reuses_runtime(tmp_path):
|
|
rows = 500_000
|
|
table = lancedb.connect(tmp_path).create_table(
|
|
"sigint",
|
|
pa.table(
|
|
{
|
|
"id": pa.array(range(rows), pa.int64()),
|
|
"text": pa.array([f"row-{row}" for row in range(rows)]),
|
|
}
|
|
),
|
|
)
|
|
# Warm the runtime and page cache so the timed call is long enough to observe.
|
|
table.search().select(["id"]).to_arrow()
|
|
|
|
timer = threading.Timer(0.001, os.kill, args=(os.getpid(), signal.SIGINT))
|
|
timer.start()
|
|
try:
|
|
with pytest.raises(KeyboardInterrupt):
|
|
table.search().select(["id", "text"]).to_arrow()
|
|
finally:
|
|
timer.cancel()
|
|
timer.join()
|
|
|
|
# The shared runtime and its generation counter remain usable.
|
|
after = table.search().where("id = 1").select(["id", "text"]).to_arrow()
|
|
assert after.to_pylist() == [{"id": 1, "text": "row-1"}]
|