From 38573202026104f49c8c971383859c2f85212f42 Mon Sep 17 00:00:00 2001 From: Dmitry Molotkov Date: Wed, 2 Dec 2026 20:48:50 +0100 Subject: [PATCH] perf(python): avoid redundant output_schema planning and eager-path bypass in to_pandas (#5361) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### 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 --- python/python/lancedb/_lancedb.pyi | 13 +- python/python/lancedb/query.py | 542 +++++++++++--- python/python/tests/test_eager_collector.py | 329 +++++++++ python/python/tests/test_query.py | 686 +++++++++++++++++- python/python/tests/test_sync_query_direct.py | 144 ++++ python/python/tests/test_wal_hybrid.py | 202 +++++- 6 files changed, 1810 insertions(+), 106 deletions(-) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index eb6f38710..2a4d2aca8 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -1140,7 +1140,11 @@ class TakeQuery: async def execute_with_metadata( self, track: bool, cap: Optional[int] = None ) -> NativeQueryResult: ... - async def execute(self) -> RecordBatchStream: ... + async def execute( + self, + max_batch_length: Optional[int] = None, + timeout: Optional[timedelta] = None, + ) -> RecordBatchStream: ... async def execute_to_reader( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> pa.RecordBatchReader: ... @@ -1194,13 +1198,18 @@ class VectorQuery: async def execute_with_metadata( self, track: bool, cap: Optional[int] = None ) -> NativeQueryResult: ... - async def execute(self) -> RecordBatchStream: ... + async def execute( + self, + max_batch_length: Optional[int] = None, + timeout: Optional[timedelta] = None, + ) -> RecordBatchStream: ... async def execute_to_reader( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> pa.RecordBatchReader: ... def execute_to_reader_sync( self, max_batch_length: Optional[int], timeout: Optional[timedelta] ) -> pa.RecordBatchReader: ... + def with_row_id(self): ... def where(self, filter: str): ... def where_expr(self, expr: PyExpr): ... def select(self, columns: List[Tuple[str, str]]): ... diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index cf4336a10..1d988312e 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -4,6 +4,7 @@ from __future__ import annotations import asyncio +import inspect import math from abc import ABC, abstractmethod from concurrent.futures import ThreadPoolExecutor @@ -348,6 +349,21 @@ def _query_needs_lance_scanner(builder: Any) -> bool: ) +def _accepts_blob_mode(fn: Any) -> bool: + """Return whether a custom to_arrow override accepts a blob_mode keyword.""" + try: + params = inspect.signature(fn).parameters + except (TypeError, ValueError): + return True + blob_param = params.get("blob_mode") + if blob_param is not None and blob_param.kind in ( + inspect.Parameter.POSITIONAL_OR_KEYWORD, + inspect.Parameter.KEYWORD_ONLY, + ): + return True + return any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()) + + def _raise_unsupported_fragment_constraints( fragments: Optional[Any], fragment_ids: Optional[List[int]], @@ -1630,10 +1646,18 @@ class LanceQueryBuilder(ABC): **kwargs, ) + table_schema = self._table.schema + has_blob_columns = schema_has_blob_field(table_schema) output_schema = getattr(self, "output_schema", None) - if output_schema is not None and schema_has_blob_field(output_schema()): + if ( + has_blob_columns + and output_schema is not None + and schema_has_blob_field(output_schema()) + ): if (flatten is None or blob_mode != "lazy") and timeout is None: - df = self._plain_scan_to_pandas(blob_mode, flatten=flatten, **kwargs) + df = self._plain_scan_to_pandas( + blob_mode, flatten=flatten, _schema=table_schema, **kwargs + ) if df is not None: return df if _query_needs_lance_scanner(self): @@ -1641,12 +1665,15 @@ class LanceQueryBuilder(ABC): "this query shape cannot use Lance native pandas conversion" ) - arrow_mode = "descriptions" if blob_mode == "lazy" else blob_mode - tbl = self._to_arrow_in_mode(timeout, arrow_mode) + arrow_mode: BlobMode = "descriptions" if blob_mode == "lazy" else blob_mode + tbl = self._to_arrow_in_mode(timeout, arrow_mode, schema=table_schema) if ( blob_mode == "lazy" and schema_has_blob_field(tbl.schema) - and not blob_v2_projection_sources(self._table.schema, self._columns) + and not blob_v2_projection_sources( + table_schema if has_blob_columns else self._table.schema, + self._columns, + ) ): raise _unsupported_blob_pandas_error( "the query has no fetchable blob v2 source" @@ -1809,12 +1836,51 @@ class LanceQueryBuilder(ABC): validate_blob_mode(blob_mode) return self._to_arrow_in_mode(timeout, blob_mode).to_pylist() + def _uses_builtin_to_arrow(self) -> bool: + return ( + "to_arrow" not in self.__dict__ + and type(self).to_arrow in _BUILTIN_SYNC_TO_ARROW + ) + + def _to_arrow_with_schema( + self, + *, + timeout: Optional[timedelta] = None, + blob_mode: BlobMode = "lazy", + schema: Optional[pa.Schema] = None, + ) -> pa.Table: + return self.to_arrow(timeout=timeout, blob_mode=blob_mode) + def _to_arrow_in_mode( - self, timeout: Optional[timedelta], blob_mode: BlobMode + self, + timeout: Optional[timedelta], + blob_mode: BlobMode, + *, + schema: Optional[pa.Schema] = None, ) -> pa.Table: # Older subclasses may not accept blob_mode. Omit it when it has no effect. - if blob_mode == "lazy" or not schema_has_blob_field(self._table.schema): + if blob_mode == "lazy": + if schema is not None and self._uses_builtin_to_arrow(): + return self._to_arrow_with_schema( + timeout=timeout, blob_mode="lazy", schema=schema + ) return self.to_arrow(timeout=timeout) + if schema is None: + schema = self._table.schema + if not schema_has_blob_field(schema): + if self._uses_builtin_to_arrow(): + tbl = self._to_arrow_with_schema( + timeout=timeout, blob_mode="lazy", schema=schema + ) + else: + tbl = self.to_arrow(timeout=timeout) + if blob_mode == "bytes": + reject_unmatched_blob_outputs(tbl.schema, {}) + return tbl + if self._uses_builtin_to_arrow(): + return self._to_arrow_with_schema( + timeout=timeout, blob_mode=blob_mode, schema=schema + ) return self.to_arrow(timeout=timeout, blob_mode=blob_mode) def to_pydantic( @@ -2011,13 +2077,14 @@ class LanceQueryBuilder(ABC): return query def _prepare_blob_execution( - self, blob_mode: BlobMode + self, blob_mode: BlobMode, schema: Optional[pa.Schema] = None ) -> tuple[dict[str, str], Optional[pa.Schema]]: validate_blob_mode(blob_mode) - schema = self._table.schema + if schema is None: + schema = self._table.schema + if not schema_has_blob_field(schema): + return {}, schema if blob_mode == "lazy": - if not schema_has_blob_field(schema): - return {}, schema # Lazy results hide automatic row ids inside projected blob columns. return blob_v2_projection_sources(schema, self._columns), schema return self._validated_blob_sources(blob_mode, schema), schema @@ -2109,6 +2176,8 @@ class LanceQueryBuilder(ABC): return {} if schema is None: schema = self._table.schema + if not schema_has_blob_field(schema): + return {} blob_sources = blob_projection_sources( schema, self._columns, @@ -2136,7 +2205,9 @@ class LanceQueryBuilder(ABC): if blob_mode == "descriptions": return strip_auto_row_ids(tbl, blob_sources) reject_unmatched_blob_outputs(tbl.schema, blob_sources) - if _is_remote_query_table(self._table) and blob_sources: + if not blob_sources: + return tbl + if _is_remote_query_table(self._table): version, identity = _remote_blob_snapshot(tbl.schema) async def fetch_at_version(column, row_ids): @@ -2472,14 +2543,17 @@ class LanceQueryBuilder(ABC): self, blob_mode: BlobMode, flatten: Optional[Union[int, bool]] = None, + *, + _schema: Optional[pa.Schema] = None, **kwargs, ) -> Optional["pd.DataFrame"]: query = self.to_query_object() if not _query_is_plain_scan(query): return None + schema = self._table.schema if _schema is None else _schema blob_sources = ( blob_projection_sources( - self._table.schema, + schema, query.columns, include_legacy=self._can_fetch_plain_legacy_blobs(blob_mode), ) @@ -2498,7 +2572,7 @@ class LanceQueryBuilder(ABC): (blob_mode == "bytes" and blob_sources) or ( blob_mode == "descriptions" - and blob_v2_projection_sources(self._table.schema, query.columns) + and blob_v2_projection_sources(schema, query.columns) ) ): return None @@ -2506,11 +2580,9 @@ class LanceQueryBuilder(ABC): dataset = self._table.to_lance() except ImportError as err: raise _unsupported_blob_pandas_error(str(err)) from err - blob_auto_row_id = self._blob_auto_row_id_enabled() + blob_auto_row_id = self._blob_auto_row_id_enabled(schema) if blob_mode == "bytes": - reject_unfetchable_blob_columns( - self._table.schema, query.columns, blob_sources - ) + reject_unfetchable_blob_columns(schema, query.columns, blob_sources) scanner = dataset.scanner( **_scanner_kwargs_for_query( query, @@ -2875,8 +2947,17 @@ class LanceVectorQueryBuilder(_RankedResultOrder, LanceQueryBuilder): ``"bytes"`` returns payload bytes for supported row-addressable blob columns and raises for blobs inside lists. """ - blob_sources, schema = self._prepare_blob_execution(blob_mode) - if blob_mode != "lazy": + return self._to_arrow_with_schema(timeout=timeout, blob_mode=blob_mode) + + def _to_arrow_with_schema( + self, + *, + timeout: Optional[timedelta] = None, + blob_mode: BlobMode = "lazy", + schema: Optional[pa.Schema] = None, + ) -> pa.Table: + blob_sources, schema = self._prepare_blob_execution(blob_mode, schema=schema) + if blob_mode != "lazy" and (schema is None or schema_has_blob_field(schema)): # Materialize in lazy mode so reranking runs once over the full # result before the requested aggregate blob conversion. return self._finalize_blob_query_table( @@ -3298,12 +3379,23 @@ class LanceFtsQueryBuilder(_RankedResultOrder, LanceQueryBuilder): timeout: Optional[timedelta] = None, blob_mode: BlobMode = "lazy", ) -> pa.Table: - blob_sources, schema = self._prepare_blob_execution(blob_mode) + return self._to_arrow_with_schema(timeout=timeout, blob_mode=blob_mode) + + def _to_arrow_with_schema( + self, + *, + timeout: Optional[timedelta] = None, + blob_mode: BlobMode = "lazy", + schema: Optional[pa.Schema] = None, + ) -> pa.Table: + blob_sources, schema = self._prepare_blob_execution(blob_mode, schema=schema) self._table._ensure_no_legacy_fts_index() self._ensure_fragment_constraints_supported("to_arrow()") query = self._query_for_scan(blob_sources, schema) - if blob_mode == "lazy": + if blob_mode == "lazy" or ( + schema is not None and not schema_has_blob_field(schema) + ): results = self._execute_arrow_prepared(query, timeout=timeout) else: results = self._execute_query_prepared(query, timeout=timeout).read_all() @@ -3365,7 +3457,16 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder): timeout: Optional[timedelta] = None, blob_mode: BlobMode = "lazy", ) -> pa.Table: - blob_sources, schema = self._prepare_blob_execution(blob_mode) + return self._to_arrow_with_schema(timeout=timeout, blob_mode=blob_mode) + + def _to_arrow_with_schema( + self, + *, + timeout: Optional[timedelta] = None, + blob_mode: BlobMode = "lazy", + schema: Optional[pa.Schema] = None, + ) -> pa.Table: + blob_sources, schema = self._prepare_blob_execution(blob_mode, schema=schema) if blob_mode == "bytes" and blob_sources: return self._to_batches_prepared( batch_size=None, @@ -3374,7 +3475,7 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder): blob_sources=blob_sources, schema=schema, ).read_all() - if blob_mode != "lazy": + if blob_mode != "lazy" and (schema is None or schema_has_blob_field(schema)): return self._finalize_blob_query_table( self._to_batches_prepared( batch_size=None, @@ -3647,7 +3748,16 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): timeout: Optional[timedelta] = None, blob_mode: BlobMode = "lazy", ) -> pa.Table: - blob_sources, schema = self._prepare_blob_execution(blob_mode) + return self._to_arrow_with_schema(timeout=timeout, blob_mode=blob_mode) + + def _to_arrow_with_schema( + self, + *, + timeout: Optional[timedelta] = None, + blob_mode: BlobMode = "lazy", + schema: Optional[pa.Schema] = None, + ) -> pa.Table: + blob_sources, schema = self._prepare_blob_execution(blob_mode, schema=schema) # WAL-PK-FUSION: without the fallback, this body is `_run_hybrid`'s. return _wal_hybrid.with_pk_fallback( lambda: self._run_hybrid( @@ -3669,7 +3779,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): blob_sources: dict[str, str], schema: Optional[pa.Schema], ) -> pa.Table: - self._create_query_builders() + self._create_query_builders(schema=schema) fts_query, vector_query = self._fts_query, self._vector_query # WAL-PK-FUSION: without the fallback, both legs always ask for row ids. if self._pk_fusion is None: @@ -3687,12 +3797,16 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): fts = async_table._sync_query_to_async(fts_query.to_query_object()) vec = async_table._sync_query_to_async(vector_query.to_query_object()) fts_results, vector_results = LOOP.run( - _execute_hybrid_subquery_legs(fts, vec, timeout) + _execute_hybrid_subquery_legs(fts, vec, timeout, schema=schema) ) else: with ThreadPoolExecutor() as executor: - fts_future = executor.submit(fts_query.to_arrow, timeout=timeout) - vector_future = executor.submit(vector_query.to_arrow, timeout=timeout) + fts_future = executor.submit( + fts_query._to_arrow_in_mode, timeout, "lazy", schema=schema + ) + vector_future = executor.submit( + vector_query._to_arrow_in_mode, timeout, "lazy", schema=schema + ) fts_results = fts_future.result() vector_results = vector_future.result() if self._pk_fusion is not None: # WAL-PK-FUSION: delete. @@ -4272,7 +4386,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): self._create_query_builders() return self._vector_query.output_schema() - def _create_query_builders(self): + def _create_query_builders(self, *, schema: Optional[pa.Schema] = None): """Set up and configure the vector and FTS query builders.""" self._ensure_fragment_constraints_supported("this hybrid query") vector_query, fts_query = self._validate_query( @@ -4306,8 +4420,9 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): self._pk_fusion = None columns = self._columns if _wal_hybrid.pk_fusion_learned(self._table, self._use_rte): + pk_schema = schema if schema is not None else self._table.schema self._pk_fusion = _wal_hybrid.PkFusion.for_query( - self._table.schema, + pk_schema, self._columns, caller_requested_row_id=self._caller_requested_row_id, ) @@ -4364,6 +4479,16 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): self._reranker = RRFReranker() +_BUILTIN_SYNC_TO_ARROW = frozenset( + { + LanceVectorQueryBuilder.to_arrow, + LanceFtsQueryBuilder.to_arrow, + LanceEmptyQueryBuilder.to_arrow, + LanceHybridQueryBuilder.to_arrow, + } +) + + class AsyncQueryBase(object): """ Base class for all async queries (take, scan, vector, fts, hybrid) @@ -4432,14 +4557,20 @@ class AsyncQueryBase(object): blob_paths=self._blob_paths, ) - async def _maybe_add_blob_row_id(self) -> None: - if self._table is None: + async def _maybe_add_blob_row_id(self, schema: Optional[pa.Schema] = None) -> None: + if self._table is None or self._with_row_id is not None: + self._blob_auto_row_id = False + self._blob_paths = () + return + + if schema is None: + schema = await self._table.schema() + if not schema_has_blob_field(schema): self._blob_auto_row_id = False self._blob_paths = () return req = self._inner.to_query_request() - schema = await self._table.schema() projection = _query_request_projection(req) self._blob_auto_row_id = blob_auto_row_id_for_scan( schema, @@ -4452,14 +4583,20 @@ class AsyncQueryBase(object): self._blob_paths = tuple(blob_v2_projection_sources(schema, projection).keys()) self._inner.with_row_id() - def _maybe_add_blob_row_id_sync(self) -> None: - if self._table is None: + def _maybe_add_blob_row_id_sync(self, schema: Optional[pa.Schema] = None) -> None: + if self._table is None or self._with_row_id is not None: + self._blob_auto_row_id = False + self._blob_paths = () + return + + if schema is None: + schema = self._table._schema_sync() + if not schema_has_blob_field(schema): self._blob_auto_row_id = False self._blob_paths = () return req = self._inner.to_query_request() - schema = self._table._schema_sync() projection = _query_request_projection(req) self._blob_auto_row_id = blob_auto_row_id_for_scan( schema, @@ -4645,11 +4782,29 @@ class AsyncQueryBase(object): Use ``async for batch in await query.to_batches(blob_mode="bytes")`` to stream blob payloads and convert each batch with ``batch.to_pandas()``. """ - blob_sources = await self._validated_blob_sources(blob_mode) + blob_sources, schema, _ = await self._prepare_blob_execution(blob_mode) + return await self._to_batches_prepared( + max_batch_length=max_batch_length, + timeout=timeout, + blob_mode=blob_mode, + blob_sources=blob_sources, + schema=schema, + ) + + async def _to_batches_prepared( + self, + *, + max_batch_length: Optional[int] = None, + timeout: Optional[timedelta] = None, + blob_mode: BlobMode = "lazy", + blob_sources: dict[str, str], + schema: Optional[pa.Schema] = None, + ) -> AsyncRecordBatchReader: reader = await self._execute_batches( max_batch_length=max_batch_length, timeout=timeout, blob_sources=blob_sources, + schema=schema, ) if blob_mode == "lazy": return reader @@ -4662,7 +4817,9 @@ class AsyncQueryBase(object): tbl = tbl.drop_columns(["_rowid"]) return tbl - schema = (await convert(pa.Table.from_batches([], schema=reader.schema))).schema + result_schema = ( + await convert(pa.Table.from_batches([], schema=reader.schema)) + ).schema async def batches(): async for batch in reader: @@ -4670,17 +4827,18 @@ class AsyncQueryBase(object): for converted in tbl.to_batches(): yield converted - return AsyncRecordBatchReader._from_batches(schema, batches()) + return AsyncRecordBatchReader._from_batches(result_schema, batches()) async def _execute_eager( self, *, timeout: Optional[timedelta] = None, + schema: Optional[pa.Schema] = None, ) -> pa.Table: """Execute with the native eager collector used by ``to_arrow``.""" self._ensure_fragment_constraints_supported("to_arrow()") if not self._blob_row_id_prepared: - await self._maybe_add_blob_row_id() + await self._maybe_add_blob_row_id(schema=schema) reader = await self._inner.execute_to_reader(None, timeout) return pa.Table.from_batches(reader, schema=reader.schema) @@ -4702,6 +4860,7 @@ class AsyncQueryBase(object): max_batch_length: Optional[int] = None, timeout: Optional[timedelta] = None, blob_sources: Optional[dict[str, str]] = None, + schema: Optional[pa.Schema] = None, ) -> AsyncRecordBatchReader: self._ensure_fragment_constraints_supported("to_batches()") if ( @@ -4719,9 +4878,10 @@ class AsyncQueryBase(object): return await row_id_query._execute_batches( max_batch_length=max_batch_length, timeout=timeout, + schema=schema, ) if not self._blob_row_id_prepared: - await self._maybe_add_blob_row_id() + await self._maybe_add_blob_row_id(schema=schema) return AsyncRecordBatchReader( await self._inner.execute( max_batch_length=max_batch_length, timeout=timeout @@ -4736,7 +4896,23 @@ class AsyncQueryBase(object): """ return await self._inner.output_schema() - async def _validated_blob_sources(self, blob_mode: BlobMode) -> dict[str, str]: + def _uses_builtin_to_arrow(self) -> bool: + return ( + "to_arrow" not in self.__dict__ + and type(self).to_arrow is _BUILTIN_ASYNC_TO_ARROW + ) + + def _uses_builtin_to_batches(self) -> bool: + return ( + "to_batches" not in self.__dict__ + and type(self).to_batches is _BUILTIN_ASYNC_TO_BATCHES + ) + + async def _validated_blob_sources( + self, + blob_mode: BlobMode, + schema: Optional[pa.Schema] = None, + ) -> dict[str, str]: """Map projected blob outputs to their source columns. Bytes mode is checked here, before the query runs. @@ -4745,7 +4921,10 @@ class AsyncQueryBase(object): # Lazy needs no mapping, and skipping it saves remote tables a request. if blob_mode == "lazy" or self._table is None: return {} - schema = await self._table.schema() + if schema is None: + schema = await self._table.schema() + if not schema_has_blob_field(schema): + return {} projection = _query_request_projection(self._inner.to_query_request()) blob_sources = blob_projection_sources( schema, @@ -4765,6 +4944,30 @@ class AsyncQueryBase(object): ) return blob_sources + async def _prepare_blob_execution( + self, + blob_mode: BlobMode, + schema: Optional[pa.Schema] = None, + has_blob_columns: Optional[bool] = None, + ) -> tuple[dict[str, str], Optional[pa.Schema], Optional[bool]]: + validate_blob_mode(blob_mode) + # Lazy needs no mapping, and skipping it saves remote tables a request. + if blob_mode == "lazy" or self._table is None: + return {}, schema, has_blob_columns + if has_blob_columns is False: + return {}, schema, False + if schema is None: + schema = await self._table.schema() + if has_blob_columns is None: + has_blob_columns = schema_has_blob_field(schema) + if not has_blob_columns: + return {}, schema, False + return ( + await self._validated_blob_sources(blob_mode, schema=schema), + schema, + True, + ) + async def _blob_output_schema(self) -> pa.Schema: return await self.output_schema() @@ -4776,11 +4979,9 @@ class AsyncQueryBase(object): if blob_mode == "descriptions": return strip_auto_row_ids(tbl, blob_sources) reject_unmatched_blob_outputs(tbl.schema, blob_sources) - if ( - self._table is not None - and not self._table._inner._is_native() - and blob_sources - ): + if not blob_sources: + return tbl + if self._table is not None and not self._table._inner._is_native(): version, identity = _remote_blob_snapshot(tbl.schema) async def fetch_blobs(column, row_ids): @@ -4791,6 +4992,69 @@ class AsyncQueryBase(object): fetch_blobs = self._table.fetch_blobs return await replace_blob_columns_with_bytes(tbl, blob_sources, fetch_blobs) + async def _to_arrow_with_blob_sources( + self, + *, + timeout: Optional[timedelta] = None, + blob_mode: BlobMode = "lazy", + schema: Optional[pa.Schema] = None, + has_blob_columns: Optional[bool] = None, + ) -> tuple[pa.Table, dict[str, str]]: + blob_sources, schema, has_blob_columns = await self._prepare_blob_execution( + blob_mode, schema=schema, has_blob_columns=has_blob_columns + ) + if blob_mode == "bytes" and blob_sources: + if self._uses_builtin_to_batches(): + reader = await self._to_batches_prepared( + timeout=timeout, + blob_mode=blob_mode, + blob_sources=blob_sources, + schema=schema, + ) + else: + reader = await self.to_batches(timeout=timeout, blob_mode=blob_mode) + return ( + pa.Table.from_batches(await reader.read_all(), schema=reader.schema), + blob_sources, + ) + if blob_mode != "lazy" and ( + not self._uses_builtin_to_batches() or has_blob_columns is not False + ): + if self._uses_builtin_to_batches(): + batch_iter = await self._to_batches_prepared( + timeout=timeout, + blob_mode="lazy", + blob_sources={}, + schema=schema, + ) + else: + batch_iter = await self.to_batches(timeout=timeout) + tbl = self._finalize_blob_query_table( + pa.Table.from_batches( + await batch_iter.read_all(), schema=batch_iter.schema + ) + ) + else: + tbl = self._finalize_blob_query_table( + await self._execute_eager(timeout=timeout, schema=schema) + ) + return ( + await self._apply_arrow_blob_mode(tbl, blob_mode, blob_sources), + blob_sources, + ) + + async def _to_arrow_prepared( + self, + *, + timeout: Optional[timedelta] = None, + blob_mode: BlobMode = "lazy", + schema: Optional[pa.Schema] = None, + ) -> pa.Table: + tbl, _ = await self._to_arrow_with_blob_sources( + timeout=timeout, blob_mode=blob_mode, schema=schema + ) + return tbl + async def to_arrow( self, timeout: Optional[timedelta] = None, @@ -4818,22 +5082,7 @@ class AsyncQueryBase(object): Enterprise queries fetch bytes at the version reported by the query response. Namespace query pushdown refuses ``"bytes"``. """ - blob_sources = await self._validated_blob_sources(blob_mode) - if blob_mode == "bytes" and blob_sources: - reader = await self.to_batches(timeout=timeout, blob_mode=blob_mode) - return pa.Table.from_batches(await reader.read_all(), schema=reader.schema) - if blob_mode != "lazy": - batch_iter = await self.to_batches(timeout=timeout) - tbl = self._finalize_blob_query_table( - pa.Table.from_batches( - await batch_iter.read_all(), schema=batch_iter.schema - ) - ) - else: - tbl = self._finalize_blob_query_table( - await self._execute_eager(timeout=timeout) - ) - return await self._apply_arrow_blob_mode(tbl, blob_mode, blob_sources) + return await self._to_arrow_prepared(timeout=timeout, blob_mode=blob_mode) async def to_list( self, @@ -4922,12 +5171,16 @@ class AsyncQueryBase(object): flatten=flatten, timeout=timeout, blob_mode=blob_mode, **kwargs ) - if hasattr(self._inner, "output_schema") and schema_has_blob_field( - await self.output_schema() + table_schema = await self._table.schema() if self._table is not None else None + has_blob_columns = table_schema is None or schema_has_blob_field(table_schema) + if ( + has_blob_columns + and hasattr(self._inner, "output_schema") + and schema_has_blob_field(await self.output_schema()) ): if (flatten is None or blob_mode != "lazy") and timeout is None: df = await self._plain_scan_to_pandas( - blob_mode, flatten=flatten, **kwargs + blob_mode, flatten=flatten, _schema=table_schema, **kwargs ) if df is not None: return df @@ -4936,16 +5189,41 @@ class AsyncQueryBase(object): "this query shape cannot use Lance native pandas conversion" ) - arrow_mode = "descriptions" if blob_mode == "lazy" else blob_mode - tbl = await self.to_arrow(timeout=timeout, blob_mode=arrow_mode) - if ( - blob_mode == "lazy" - and schema_has_blob_field(tbl.schema) - and not await self._validated_blob_sources("descriptions") - ): - raise _unsupported_blob_pandas_error( - "the query has no fetchable blob v2 source" + arrow_mode: BlobMode = "descriptions" if blob_mode == "lazy" else blob_mode + validated_blob_sources: Optional[dict[str, str]] = None + if self._uses_builtin_to_arrow(): + tbl, validated_blob_sources = await self._to_arrow_with_blob_sources( + timeout=timeout, + blob_mode=arrow_mode, + schema=table_schema, + has_blob_columns=has_blob_columns, ) + elif not has_blob_columns and not _accepts_blob_mode(self.to_arrow): + # Older subclasses may not accept blob_mode. Omit it when the table + # has no blob columns, then still validate the actual result schema. + tbl = await self.to_arrow(timeout=timeout) + if arrow_mode == "bytes": + reject_unmatched_blob_outputs(tbl.schema, {}) + else: + tbl = await self.to_arrow(timeout=timeout, blob_mode=arrow_mode) + if blob_mode == "lazy" and schema_has_blob_field(tbl.schema): + if ( + validated_blob_sources is not None + and has_blob_columns + and arrow_mode == "descriptions" + ): + has_v2_source = bool(validated_blob_sources) + else: + has_v2_source = bool( + await self._validated_blob_sources( + "descriptions", + schema=table_schema if has_blob_columns else None, + ) + ) + if not has_v2_source: + raise _unsupported_blob_pandas_error( + "the query has no fetchable blob v2 source" + ) return flatten_columns(tbl, flatten).to_pandas(**kwargs) async def _remote_to_pandas( @@ -4969,6 +5247,8 @@ class AsyncQueryBase(object): self, blob_mode: BlobMode, flatten: Optional[Union[int, bool]] = None, + *, + _schema: Optional[pa.Schema] = None, **kwargs, ) -> Optional["pd.DataFrame"]: if self._table is None: @@ -4978,7 +5258,7 @@ class AsyncQueryBase(object): if not _query_is_plain_scan(query): return None - schema = await self._table.schema() + schema = await self._table.schema() if _schema is None else _schema blob_auto_row_id = blob_auto_row_id_for_scan( schema, query.columns, @@ -5141,6 +5421,10 @@ class AsyncQueryBase(object): return await self._inner.analyze_plan(distributed_metrics) +_BUILTIN_ASYNC_TO_ARROW = AsyncQueryBase.to_arrow +_BUILTIN_ASYNC_TO_BATCHES = AsyncQueryBase.to_batches + + class AsyncStandardQuery(AsyncQueryBase): """ Base class for "standard" async queries (all but take currently) @@ -5697,9 +5981,10 @@ class AsyncFTSQuery(_AsyncRankedResultOrder, AsyncStandardQuery): self, *, timeout: Optional[timedelta] = None, + schema: Optional[pa.Schema] = None, ) -> pa.Table: try: - results = await super()._execute_eager(timeout=timeout) + results = await super()._execute_eager(timeout=timeout, schema=schema) except Exception as error: _add_fts_position_error_note(error) raise @@ -5731,12 +6016,14 @@ class AsyncFTSQuery(_AsyncRankedResultOrder, AsyncStandardQuery): max_batch_length: Optional[int] = None, timeout: Optional[timedelta] = None, blob_sources: Optional[dict[str, str]] = None, + schema: Optional[pa.Schema] = None, ) -> AsyncRecordBatchReader: try: reader = await super()._execute_batches( max_batch_length=max_batch_length, timeout=timeout, blob_sources=blob_sources, + schema=schema, ) results = pa.Table.from_batches(await reader.read_all(), reader.schema) except Exception as error: @@ -6102,17 +6389,19 @@ class AsyncVectorQuery( return request.column, len(vectors[0]) return None - async def _check_rrf_vector_query(self) -> None: + async def _check_rrf_vector_query(self, schema: Optional[pa.Schema] = None) -> None: if (vector_input := self._rrf_multivector_input()) is not None: - schema = await self._table.schema() if self._table is not None else None + if schema is None and self._table is not None: + schema = await self._table.schema() _check_rrf_multivector_column(schema, *vector_input) async def _execute_eager( self, *, timeout: Optional[timedelta] = None, + schema: Optional[pa.Schema] = None, ) -> pa.Table: - await self._check_rrf_vector_query() + await self._check_rrf_vector_query(schema=schema) if self._force_local_namespace and self._table is not None: # Preserve local execution for the vector leg so it uses the same # embedded table snapshot as the FTS leg. @@ -6120,7 +6409,7 @@ class AsyncVectorQuery( query._force_local_namespace = True results = await self._table._execute_arrow(query, timeout=timeout) else: - results = await super()._execute_eager(timeout=timeout) + results = await super()._execute_eager(timeout=timeout, schema=schema) if self._reranker: source = results results = self._reranker.rerank_vector(self._query_string, results) @@ -6148,12 +6437,14 @@ class AsyncVectorQuery( max_batch_length: Optional[int] = None, timeout: Optional[timedelta] = None, blob_sources: Optional[dict[str, str]] = None, + schema: Optional[pa.Schema] = None, ) -> AsyncRecordBatchReader: - await self._check_rrf_vector_query() + await self._check_rrf_vector_query(schema=schema) reader = await super()._execute_batches( max_batch_length=max_batch_length, timeout=timeout, blob_sources=blob_sources, + schema=schema, ) if self._reranker is None: return reader @@ -6165,14 +6456,29 @@ class AsyncVectorQuery( return AsyncRecordBatchReader(results, max_batch_length=max_batch_length) +async def _execute_hybrid_leg_arrow( + leg: AsyncQueryBase, + timeout: Optional[timedelta], + schema: Optional[pa.Schema], +) -> pa.Table: + if leg._uses_builtin_to_arrow(): + return await leg._to_arrow_prepared(timeout=timeout, schema=schema) + return await leg.to_arrow(timeout=timeout) + + async def _execute_hybrid_subquery_legs( - fts: AsyncFTSQuery, vector: AsyncVectorQuery, timeout: Optional[timedelta] + fts: AsyncFTSQuery, + vector: AsyncVectorQuery, + timeout: Optional[timedelta], + *, + schema: Optional[pa.Schema] = None, ) -> tuple[pa.Table, pa.Table]: fts._inner, vector._inner = await _share_hybrid_subquery_filter( fts._inner, vector._inner ) fts_results, vector_results = await asyncio.gather( - fts.to_arrow(timeout=timeout), vector.to_arrow(timeout=timeout) + _execute_hybrid_leg_arrow(fts, timeout, schema), + _execute_hybrid_leg_arrow(vector, timeout, schema), ) return fts_results, vector_results @@ -6291,6 +6597,20 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): the hybrid query itself. The key the legs are fused on, if any, is left on `self._pk_fusion`. """ + ( + fts_query, + vec_query, + limit, + offset, + _, + ) = await self._create_child_queries_with_schema() + return fts_query, vec_query, limit, offset + + async def _create_child_queries_with_schema( + self, + *, + schema: Optional[pa.Schema] = None, + ) -> Tuple["AsyncFTSQuery", "AsyncVectorQuery", int, int, Optional[pa.Schema]]: self._ensure_fragment_constraints_supported("this hybrid query") fts_query = AsyncFTSQuery(self._inner.to_fts_query(), self._table) vec_query = AsyncVectorQuery(self._inner.to_vector_query(), self._table) @@ -6318,9 +6638,13 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): # WAL-PK-FUSION: without the fallback, keep only the two `with_row_id` # calls. self._pk_fusion = None - if _wal_hybrid.pk_fusion_learned(self._table, fts_req.use_rte): + if self._table is not None and _wal_hybrid.pk_fusion_learned( + self._table, fts_req.use_rte + ): + if schema is None: + schema = await self._table.schema() self._pk_fusion = _wal_hybrid.PkFusion.for_query( - await self._table.schema(), + schema, _query_request_projection(fts_req), caller_requested_row_id=self._user_requested_row_id(), ) @@ -6350,15 +6674,16 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): fts_query.offset(0) vec_query.offset(0) - return fts_query, vec_query, limit, offset + return fts_query, vec_query, limit, offset, schema async def _execute_eager( self, *, timeout: Optional[timedelta] = None, + schema: Optional[pa.Schema] = None, ) -> pa.Table: self._ensure_fragment_constraints_supported("to_arrow()") - reader = await self._execute_batches(timeout=timeout) + reader = await self._execute_batches(timeout=timeout, schema=schema) return pa.Table.from_batches(await reader.read_all(), schema=reader.schema) async def _execute_batches( @@ -6367,6 +6692,7 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): max_batch_length: Optional[int] = None, timeout: Optional[timedelta] = None, blob_sources: Optional[dict[str, str]] = None, + schema: Optional[pa.Schema] = None, ) -> AsyncRecordBatchReader: # WAL-PK-FUSION: without the fallback, this body is `_run_hybrid`'s. return await _wal_hybrid.with_pk_fallback_async( @@ -6374,6 +6700,7 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): max_batch_length=max_batch_length, timeout=timeout, blob_sources=blob_sources, + schema=schema, ), self._table, fused=lambda: self._pk_fusion is not None, @@ -6386,8 +6713,15 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): max_batch_length: Optional[int] = None, timeout: Optional[timedelta] = None, blob_sources: Optional[dict[str, str]] = None, + schema: Optional[pa.Schema] = None, ) -> AsyncRecordBatchReader: - fts_query, vec_query, limit, offset = await self._create_child_queries() + ( + fts_query, + vec_query, + limit, + offset, + schema, + ) = await self._create_child_queries_with_schema(schema=schema) if limit == 0: # An empty page needs no candidates. Reject it before anything # runs, whatever the offset: building an empty result would need @@ -6401,26 +6735,28 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): blob_auto_row_id = bool(blob_sources) blob_paths: tuple[str, ...] = () if self._table is not None: - schema = await self._table.schema() - projection = _query_request_projection(req) - blob_auto_row_id = blob_auto_row_id or blob_auto_row_id_for_scan( - schema, projection, with_row_id=self._with_row_id - ) - if blob_auto_row_id: - blob_paths = tuple( - blob_v2_projection_sources(schema, projection).keys() + if schema is None: + schema = await self._table.schema() + if schema_has_blob_field(schema): + projection = _query_request_projection(req) + blob_auto_row_id = blob_auto_row_id or blob_auto_row_id_for_scan( + schema, projection, with_row_id=self._with_row_id ) + if blob_auto_row_id: + blob_paths = tuple( + blob_v2_projection_sources(schema, projection).keys() + ) self._blob_auto_row_id = blob_auto_row_id self._blob_paths = blob_paths if isinstance(req.filter, str) and _uses_sql_subquery_filter(req.filter): fts_results, vector_results = await _execute_hybrid_subquery_legs( - fts_query, vec_query, timeout + fts_query, vec_query, timeout, schema=schema ) else: fts_results, vector_results = await asyncio.gather( - fts_query.to_arrow(timeout=timeout), - vec_query.to_arrow(timeout=timeout), + _execute_hybrid_leg_arrow(fts_query, timeout, schema), + _execute_hybrid_leg_arrow(vec_query, timeout, schema), ) if self._pk_fusion is not None: # WAL-PK-FUSION: delete. vector_results, fts_results = self._pk_fusion.stamp( @@ -6552,6 +6888,8 @@ class AsyncTakeQuery(AsyncQueryBase): self, blob_mode: BlobMode, flatten: Optional[Union[int, bool]] = None, + *, + _schema: Optional[pa.Schema] = None, **kwargs, ) -> Optional["pd.DataFrame"]: return None diff --git a/python/python/tests/test_eager_collector.py b/python/python/tests/test_eager_collector.py index 1eaed9678..89eee6052 100644 --- a/python/python/tests/test_eager_collector.py +++ b/python/python/tests/test_eager_collector.py @@ -7,6 +7,10 @@ import pyarrow as pa import pytest import lancedb +from lancedb import query as query_module +from lancedb.index import FTS +from lancedb.query import AsyncQueryBase +from lancedb.table import AsyncTable @pytest.mark.asyncio @@ -55,3 +59,328 @@ async def test_execute_to_reader_propagates_timeout(tmp_path): with pytest.raises(Exception, match="Query timeout"): await table._inner.query().execute_to_reader(None, timedelta(0)) + + +async def _async_multi_modal_table(path, rows: int = 5000): + db = await lancedb.connect_async(path) + data = pa.table( + { + "id": pa.array(range(rows), type=pa.int64()), + "text": pa.array([f"row {i}" for i in range(rows)], type=pa.utf8()), + "vector": pa.array( + [[float((i % 4) == j) for j in range(4)] for i in range(rows)], + type=pa.list_(pa.float32(), 4), + ), + } + ) + table = await db.create_table("multi_modal", data) + await table.create_index("text", config=FTS(with_position=True)) + return table + + +class _CountingInnerProxy: + def __init__(self, inner): + self._inner = inner + self.to_query_request_calls = 0 + self.output_schema_calls = 0 + self.execute_calls = 0 + self.batch_sizes: list[int] = [] + + def to_query_request(self): + self.to_query_request_calls += 1 + return self._inner.to_query_request() + + async def output_schema(self): + self.output_schema_calls += 1 + return await self._inner.output_schema() + + async def execute(self, *args, **kwargs): + self.execute_calls += 1 + return await self._inner.execute(*args, **kwargs) + + async def execute_to_reader(self, max_batch_length, timeout): + reader = await self._inner.execute_to_reader(max_batch_length, timeout) + batches = list(reader) + self.batch_sizes.extend(batch.num_rows for batch in batches) + return pa.RecordBatchReader.from_batches(reader.schema, batches) + + def __getattr__(self, name): + return getattr(self._inner, name) + + +@pytest.mark.asyncio +async def test_async_non_blob_to_arrow_and_batches_skip_blob_overhead( + tmp_path, monkeypatch +): + table = await _async_multi_modal_table(tmp_path, rows=64) + + counts = { + "output_schema": 0, + "to_batches_prepared": 0, + "execute_batches": 0, + "execute_eager": 0, + "schema": 0, + "projection": 0, + } + + orig_output_schema = AsyncQueryBase.output_schema + orig_to_batches_prepared = AsyncQueryBase._to_batches_prepared + orig_execute_batches = AsyncQueryBase._execute_batches + orig_execute_eager = AsyncQueryBase._execute_eager + orig_schema = AsyncTable.schema + orig_projection = query_module._query_request_projection + + async def counted_output_schema(self): + counts["output_schema"] += 1 + return await orig_output_schema(self) + + async def counted_to_batches_prepared(self, *args, **kwargs): + counts["to_batches_prepared"] += 1 + return await orig_to_batches_prepared(self, *args, **kwargs) + + async def counted_execute_batches(self, *args, **kwargs): + counts["execute_batches"] += 1 + return await orig_execute_batches(self, *args, **kwargs) + + async def counted_execute_eager(self, *args, **kwargs): + counts["execute_eager"] += 1 + return await orig_execute_eager(self, *args, **kwargs) + + async def counted_schema(self): + counts["schema"] += 1 + return await orig_schema(self) + + def counted_projection(req): + counts["projection"] += 1 + return orig_projection(req) + + monkeypatch.setattr(AsyncQueryBase, "output_schema", counted_output_schema) + monkeypatch.setattr( + AsyncQueryBase, "_to_batches_prepared", counted_to_batches_prepared + ) + monkeypatch.setattr(AsyncQueryBase, "_execute_batches", counted_execute_batches) + monkeypatch.setattr(AsyncQueryBase, "_execute_eager", counted_execute_eager) + monkeypatch.setattr(AsyncTable, "schema", counted_schema) + monkeypatch.setattr(query_module, "_query_request_projection", counted_projection) + + async def make_queries(): + return [ + table.query().limit(5), + table.vector_search([1.0, 0.0, 0.0, 0.0]).limit(5), + (await table.search("row", query_type="fts")).limit(5), + table.take_offsets([0, 1, 2]), + ] + + for blob_mode in ("descriptions", "bytes"): + for query in await make_queries(): + for key in counts: + counts[key] = 0 + proxy = _CountingInnerProxy(query._inner) + query._inner = proxy + + tbl = await query.to_arrow(blob_mode=blob_mode) + assert tbl.num_rows > 0 + assert counts["output_schema"] == 0 + assert proxy.output_schema_calls == 0 + assert counts["to_batches_prepared"] == 0 + assert counts["execute_batches"] == 0 + assert proxy.execute_calls == 0 + assert counts["execute_eager"] == 1 + assert proxy.to_query_request_calls == 0 + assert counts["projection"] == 0 + assert counts["schema"] == 1 + + for key in counts: + counts[key] = 0 + batch_query = table.query().limit(5) + proxy = _CountingInnerProxy(batch_query._inner) + batch_query._inner = proxy + reader = await batch_query.to_batches(blob_mode="descriptions") + batches = await reader.read_all() + assert sum(b.num_rows for b in batches) == 5 + assert counts["to_batches_prepared"] == 1 + assert counts["execute_batches"] == 1 + assert proxy.execute_calls == 1 + assert counts["schema"] == 1 + assert proxy.to_query_request_calls == 0 + assert counts["projection"] == 0 + + +@pytest.mark.asyncio +async def test_async_to_pandas_uses_eager_collector_and_skips_output_schema( + tmp_path, monkeypatch +): + pytest.importorskip("pandas") + table = await _async_multi_modal_table(tmp_path, rows=5000) + + counts = { + "output_schema": 0, + "to_batches_prepared": 0, + "execute_batches": 0, + "execute_eager": 0, + "schema": 0, + "projection": 0, + } + + orig_output_schema = AsyncQueryBase.output_schema + orig_to_batches_prepared = AsyncQueryBase._to_batches_prepared + orig_execute_batches = AsyncQueryBase._execute_batches + orig_execute_eager = AsyncQueryBase._execute_eager + orig_schema = AsyncTable.schema + orig_projection = query_module._query_request_projection + + async def counted_output_schema(self): + counts["output_schema"] += 1 + return await orig_output_schema(self) + + async def counted_to_batches_prepared(self, *args, **kwargs): + counts["to_batches_prepared"] += 1 + return await orig_to_batches_prepared(self, *args, **kwargs) + + async def counted_execute_batches(self, *args, **kwargs): + counts["execute_batches"] += 1 + return await orig_execute_batches(self, *args, **kwargs) + + async def counted_execute_eager(self, *args, **kwargs): + counts["execute_eager"] += 1 + return await orig_execute_eager(self, *args, **kwargs) + + async def counted_schema(self): + counts["schema"] += 1 + return await orig_schema(self) + + def counted_projection(req): + counts["projection"] += 1 + return orig_projection(req) + + monkeypatch.setattr(AsyncQueryBase, "output_schema", counted_output_schema) + monkeypatch.setattr( + AsyncQueryBase, "_to_batches_prepared", counted_to_batches_prepared + ) + monkeypatch.setattr(AsyncQueryBase, "_execute_batches", counted_execute_batches) + monkeypatch.setattr(AsyncQueryBase, "_execute_eager", counted_execute_eager) + monkeypatch.setattr(AsyncTable, "schema", counted_schema) + monkeypatch.setattr(query_module, "_query_request_projection", counted_projection) + + for blob_mode in ("lazy", "descriptions", "bytes"): + for key in counts: + counts[key] = 0 + scan_query = table.query() + proxy = _CountingInnerProxy(scan_query._inner) + scan_query._inner = proxy + + df = await scan_query.to_pandas(blob_mode=blob_mode) + assert len(df) == 5000 + assert counts["output_schema"] == 0 + assert proxy.output_schema_calls == 0 + assert counts["to_batches_prepared"] == 0 + assert counts["execute_batches"] == 0 + assert proxy.execute_calls == 0 + assert counts["execute_eager"] == 1 + assert max(proxy.batch_sizes) > 1024 + assert proxy.to_query_request_calls == 0 + assert counts["projection"] == 0 + assert counts["schema"] == 1 + + queries = [ + table.vector_search([1.0, 0.0, 0.0, 0.0]).limit(5), + (await table.search("row", query_type="fts")).limit(5), + table.take_offsets([0, 1, 2]), + ] + for query in queries: + for key in counts: + counts[key] = 0 + proxy = _CountingInnerProxy(query._inner) + query._inner = proxy + + df = await query.to_pandas() + assert len(df) > 0 + assert counts["output_schema"] == 0 + assert proxy.output_schema_calls == 0 + assert counts["to_batches_prepared"] == 0 + assert counts["execute_batches"] == 0 + assert proxy.execute_calls == 0 + assert counts["execute_eager"] == 1 + assert proxy.to_query_request_calls == 0 + assert counts["projection"] == 0 + assert counts["schema"] == 1 + + +@pytest.mark.asyncio +async def test_sync_take_and_async_hybrid_to_pandas_fast_paths(tmp_path, monkeypatch): + pytest.importorskip("pandas") + + counts = { + "output_schema": 0, + "to_batches_prepared": 0, + "execute_batches": 0, + "schema": 0, + "projection": 0, + } + orig_output_schema = AsyncQueryBase.output_schema + orig_to_batches_prepared = AsyncQueryBase._to_batches_prepared + orig_execute_batches = AsyncQueryBase._execute_batches + orig_schema = AsyncTable.schema + orig_projection = query_module._query_request_projection + + async def counted_output_schema(self): + counts["output_schema"] += 1 + return await orig_output_schema(self) + + async def counted_to_batches_prepared(self, *args, **kwargs): + counts["to_batches_prepared"] += 1 + return await orig_to_batches_prepared(self, *args, **kwargs) + + async def counted_execute_batches(self, *args, **kwargs): + counts["execute_batches"] += 1 + return await orig_execute_batches(self, *args, **kwargs) + + async def counted_schema(self): + counts["schema"] += 1 + return await orig_schema(self) + + def counted_projection(req): + counts["projection"] += 1 + return orig_projection(req) + + monkeypatch.setattr(AsyncQueryBase, "output_schema", counted_output_schema) + monkeypatch.setattr( + AsyncQueryBase, "_to_batches_prepared", counted_to_batches_prepared + ) + monkeypatch.setattr(AsyncQueryBase, "_execute_batches", counted_execute_batches) + monkeypatch.setattr(AsyncTable, "schema", counted_schema) + monkeypatch.setattr(query_module, "_query_request_projection", counted_projection) + + sync_db = lancedb.connect(tmp_path / "sync_take") + sync_table = sync_db.create_table( + "take_tbl", + pa.table({"id": pa.array([10, 20, 30], type=pa.int64())}), + ) + take_query = sync_table.take_offsets([0, 1]) + proxy = _CountingInnerProxy(take_query._inner._inner) + take_query._inner._inner = proxy + + for key in counts: + counts[key] = 0 + take_df = take_query.to_pandas() + assert sorted(take_df["id"].tolist()) == [10, 20] + assert counts["output_schema"] == 0 + assert proxy.output_schema_calls == 0 + assert counts["to_batches_prepared"] == 0 + assert counts["execute_batches"] == 0 + assert proxy.execute_calls == 0 + assert proxy.to_query_request_calls == 0 + assert counts["projection"] == 0 + assert counts["schema"] == 1 + + async_table = await _async_multi_modal_table(tmp_path / "async_hybrid", rows=16) + hybrid_query = ( + async_table.vector_search([1.0, 0.0, 0.0, 0.0]).nearest_to_text("row").limit(5) + ) + for key in counts: + counts[key] = 0 + hybrid_df = await hybrid_query.to_pandas() + assert len(hybrid_df) == 5 + assert counts["to_batches_prepared"] == 0 + assert counts["execute_batches"] == 0 + assert counts["schema"] == 1 diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index 47c4c7301..63b785987 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -8,12 +8,13 @@ from pathlib import Path import random import lancedb +from lancedb.arrow import AsyncRecordBatchReader from lancedb.db import AsyncConnection from lancedb.embeddings.base import TextEmbeddingFunction from lancedb.embeddings.registry import get_registry, register from lancedb.expr import col from lancedb.index import FTS, IvfPq -from lancedb.rerankers import RRFReranker +from lancedb.rerankers import RRFReranker, Reranker import lancedb.pydantic import numpy as np import pandas.testing as tm @@ -29,6 +30,8 @@ from lancedb.query import ( AsyncQueryBase, AsyncVectorQuery, ColumnOrdering, + LanceEmptyQueryBuilder, + LanceFtsQueryBuilder, LanceVectorQueryBuilder, MatchQuery, PhraseQuery, @@ -3862,3 +3865,684 @@ def test_query_result_count_error_after_last_page_batch(tmp_path): assert metadata.value is failure.value finally: offline.rename(dataset) + + +@pytest.mark.asyncio +async def test_to_pandas_non_blob_custom_to_arrow_override_still_called( + tmp_path, monkeypatch +): + data = pa.table( + { + "id": pa.array([1, 2], type=pa.int64()), + "text": pa.array(["alpha one", "alpha two"], type=pa.utf8()), + "vector": pa.array( + [[1.0, 0.0], [0.0, 1.0]], type=pa.list_(pa.float32(), 2) + ), + } + ) + + sync_db = lancedb.connect(tmp_path / "sync_override") + sync_table = sync_db.create_table("items", data) + sync_table.create_index("text", config=FTS(with_position=True)) + + # Sync instance-monkeypatched to_arrow + sync_query = sync_table.search().select(["id"]) + orig_sync_to_arrow = sync_query.to_arrow + sync_instance_calls = 0 + + def wrapped_sync_to_arrow(*args, **kwargs): + nonlocal sync_instance_calls + sync_instance_calls += 1 + return orig_sync_to_arrow(*args, **kwargs) + + monkeypatch.setattr(sync_query, "to_arrow", wrapped_sync_to_arrow) + assert sorted(sync_query.to_pandas()["id"].tolist()) == [1, 2] + assert sync_instance_calls == 1 + assert sorted(sync_query.to_pandas(blob_mode="descriptions")["id"].tolist()) == [ + 1, + 2, + ] + assert sync_instance_calls == 2 + + # Sync subclass overriding to_arrow(self, *, timeout=None) without blob_mode + sync_subclass_calls = 0 + + class CustomSyncQuery(LanceEmptyQueryBuilder): + def to_arrow(self, *, timeout=None): + nonlocal sync_subclass_calls + sync_subclass_calls += 1 + return super().to_arrow(timeout=timeout) + + custom_sync = CustomSyncQuery(sync_table).select(["id"]) + assert sorted(custom_sync.to_pandas()["id"].tolist()) == [1, 2] + assert sync_subclass_calls == 1 + assert sorted(custom_sync.to_pandas(blob_mode="descriptions")["id"].tolist()) == [ + 1, + 2, + ] + assert sync_subclass_calls == 2 + + # Async setup + async_db = await lancedb.connect_async(tmp_path / "async_override") + async_table = await async_db.create_table("items", data) + await async_table.create_index("text", config=FTS(with_position=True)) + + # Async instance-monkeypatched to_arrow + async_query = async_table.query().select(["id"]) + orig_async_to_arrow = async_query.to_arrow + async_instance_calls = 0 + + async def wrapped_async_to_arrow(*args, **kwargs): + nonlocal async_instance_calls + async_instance_calls += 1 + return await orig_async_to_arrow(*args, **kwargs) + + monkeypatch.setattr(async_query, "to_arrow", wrapped_async_to_arrow) + assert sorted((await async_query.to_pandas())["id"].tolist()) == [1, 2] + assert async_instance_calls == 1 + assert sorted( + (await async_query.to_pandas(blob_mode="descriptions"))["id"].tolist() + ) == [1, 2] + assert async_instance_calls == 2 + + # Async class-monkeypatched AsyncQuery.to_arrow + class_calls = 0 + orig_cls_to_arrow = AsyncQuery.to_arrow + + async def wrapped_cls_to_arrow(self, *args, **kwargs): + nonlocal class_calls + class_calls += 1 + return await orig_cls_to_arrow(self, *args, **kwargs) + + with monkeypatch.context() as mp: + mp.setattr(AsyncQuery, "to_arrow", wrapped_cls_to_arrow) + assert sorted( + (await async_table.query().select(["id"]).to_pandas())["id"].tolist() + ) == [1, 2] + assert class_calls == 1 + assert sorted( + ( + await async_table.query() + .select(["id"]) + .to_pandas(blob_mode="descriptions") + )["id"].tolist() + ) == [1, 2] + assert class_calls == 2 + + # Async subclass overriding async def to_arrow(self, timeout=None) without blob_mode + async_subclass_calls = 0 + + class CustomAsyncQuery(AsyncQuery): + async def to_arrow(self, timeout=None): + nonlocal async_subclass_calls + async_subclass_calls += 1 + return await super().to_arrow(timeout=timeout) + + custom_async = CustomAsyncQuery(async_table._inner.query(), async_table).select( + ["id"] + ) + assert sorted((await custom_async.to_pandas())["id"].tolist()) == [1, 2] + assert async_subclass_calls == 1 + assert sorted( + (await custom_async.to_pandas(blob_mode="descriptions"))["id"].tolist() + ) == [1, 2] + assert async_subclass_calls == 2 + + # Hybrid child-leg monkeypatch parity (sync and async) + with monkeypatch.context() as mp: + sync_legs = [] + orig_sync_fts = LanceFtsQueryBuilder.to_arrow + orig_sync_vec = LanceVectorQueryBuilder.to_arrow + + def counted_sync_fts(self, *args, **kwargs): + sync_legs.append("fts") + return orig_sync_fts(self, *args, **kwargs) + + def counted_sync_vec(self, *args, **kwargs): + sync_legs.append("vec") + return orig_sync_vec(self, *args, **kwargs) + + mp.setattr(LanceFtsQueryBuilder, "to_arrow", counted_sync_fts) + mp.setattr(LanceVectorQueryBuilder, "to_arrow", counted_sync_vec) + + sync_hybrid = ( + sync_table.search(query_type="hybrid") + .vector([1.0, 0.0]) + .text("alpha") + .limit(2) + ) + assert len(sync_hybrid.to_pandas()) == 2 + assert sorted(sync_legs) == ["fts", "vec"] + sync_legs.clear() + assert sync_hybrid.to_arrow().num_rows == 2 + assert sorted(sync_legs) == ["fts", "vec"] + + with monkeypatch.context() as mp: + async_legs = [] + orig_async_fts = AsyncFTSQuery.to_arrow + orig_async_vec = AsyncVectorQuery.to_arrow + + async def counted_async_fts(self, *args, **kwargs): + async_legs.append("fts") + return await orig_async_fts(self, *args, **kwargs) + + async def counted_async_vec(self, *args, **kwargs): + async_legs.append("vec") + return await orig_async_vec(self, *args, **kwargs) + + mp.setattr(AsyncFTSQuery, "to_arrow", counted_async_fts) + mp.setattr(AsyncVectorQuery, "to_arrow", counted_async_vec) + + async_hybrid = ( + async_table.vector_search([1.0, 0.0]).nearest_to_text("alpha").limit(2) + ) + assert len(await async_hybrid.to_pandas()) == 2 + assert sorted(async_legs) == ["fts", "vec"] + async_legs.clear() + assert (await async_hybrid.to_arrow()).num_rows == 2 + assert sorted(async_legs) == ["fts", "vec"] + + # Unbound AsyncQueryBase (table=None) conservatively falls back to output_schema() + unbound = AsyncQuery(async_table._inner.query(), table=None) + orig_unbound_output_schema = unbound.output_schema + unbound_output_schema_calls = 0 + + async def counted_unbound_output_schema(): + nonlocal unbound_output_schema_calls + unbound_output_schema_calls += 1 + return await orig_unbound_output_schema() + + monkeypatch.setattr(unbound, "output_schema", counted_unbound_output_schema) + unbound_df = await unbound.to_pandas() + assert sorted(unbound_df["id"].tolist()) == [1, 2] + assert unbound_output_schema_calls == 1 + + +@pytest.mark.asyncio +async def test_to_pandas_non_blob_subquery_skips_output_schema(tmp_path, monkeypatch): + items_data = pa.table( + { + "id": pa.array([1, 2, 3], type=pa.int64()), + "text": pa.array(["alpha one", "alpha two", "alpha three"], type=pa.utf8()), + "vector": pa.array( + [[1.0, 0.0], [0.5, 0.5], [0.0, 1.0]], type=pa.list_(pa.float32(), 2) + ), + } + ) + other_data = pa.table({"id": pa.array([2, 3], type=pa.int64())}) + filter_sql = "id IN (SELECT id FROM other)" + + def fail_output_schema(*_args, **_kwargs): + raise AssertionError("output_schema must not be called on non-blob to_pandas") + + async def fail_async_output_schema(*_args, **_kwargs): + raise AssertionError( + "async output_schema must not be called on non-blob to_pandas" + ) + + # Sync + sync_db = lancedb.connect(tmp_path / "sync_subquery") + sync_table = sync_db.create_table("items", items_data) + sync_table.create_index("text", config=FTS(with_position=True)) + sync_db.create_table("other", other_data) + + monkeypatch.setattr(sync_table, "_output_schema", fail_output_schema) + + sync_queries = [ + sync_table.search().where(filter_sql).select(["id"]), + sync_table.search([1.0, 0.0]).where(filter_sql).select(["id"]).limit(2), + sync_table.search("alpha", query_type="fts") + .where(filter_sql) + .select(["id"]) + .limit(2), + sync_table.search(query_type="hybrid") + .vector([1.0, 0.0]) + .text("alpha") + .where(filter_sql) + .select(["id"]) + .limit(2), + ] + for query in sync_queries: + expected = sorted(query.to_arrow()["id"].to_pylist()) + actual = sorted(query.to_pandas()["id"].tolist()) + assert expected == [2, 3] + assert actual == expected + + # Async + async_db = await lancedb.connect_async(tmp_path / "async_subquery") + async_table = await async_db.create_table("items", items_data) + await async_table.create_index("text", config=FTS(with_position=True)) + await async_db.create_table("other", other_data) + + monkeypatch.setattr(AsyncQueryBase, "output_schema", fail_async_output_schema) + + async_queries = [ + async_table.query().where(filter_sql).select(["id"]), + async_table.vector_search([1.0, 0.0]).where(filter_sql).select(["id"]).limit(2), + (await async_table.search("alpha", query_type="fts")) + .where(filter_sql) + .select(["id"]) + .limit(2), + async_table.vector_search([1.0, 0.0]) + .nearest_to_text("alpha") + .where(filter_sql) + .select(["id"]) + .limit(2), + ] + for query in async_queries: + expected = sorted((await query.to_arrow())["id"].to_pylist()) + actual = sorted((await query.to_pandas())["id"].tolist()) + assert expected == [2, 3] + assert actual == expected + + +@pytest.mark.asyncio +async def test_blob_to_pandas_does_not_add_extra_schema_fetches( + tmp_db, tmp_db_async, monkeypatch +): + pytest.importorskip("lance") + + v1_sync = tmp_db.create_table( + "blob_v1_sync", + _blob_query_data(), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, + ) + v1_async = await tmp_db_async.create_table( + "blob_v1_async", + _blob_query_data(), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, + ) + + v2_schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field("vector", pa.list_(pa.float32(), list_size=2)), + lancedb.blob("image"), + ] + ) + v2_rows = [ + {"id": 1, "vector": [1.0, 0.0], "image": b"one"}, + {"id": 2, "vector": [0.0, 1.0], "image": b"two"}, + ] + v2_sync = tmp_db.create_table("blob_v2_sync", schema=v2_schema) + v2_sync.add(v2_rows) + v2_async = await tmp_db_async.create_table("blob_v2_async", schema=v2_schema) + await v2_async.add(v2_rows) + + mem_sync_db = lancedb.connect("memory:///") + v2_mem_sync = mem_sync_db.create_table("blob_v2_mem_sync", schema=v2_schema) + v2_mem_sync.add(v2_rows) + mem_async_db = await lancedb.connect_async("memory:///") + v2_mem_async = await mem_async_db.create_table( + "blob_v2_mem_async", schema=v2_schema + ) + await v2_mem_async.add(v2_rows) + + schema_calls = 0 + validated_blob_sources_calls = 0 + blob_output_schema_calls = 0 + + orig_schema_sync = AsyncTable._schema_sync + orig_schema_async = AsyncTable.schema + orig_validated_blob_sources = AsyncQueryBase._validated_blob_sources + orig_blob_output_schema = AsyncQueryBase._blob_output_schema + + def counted_schema_sync(self): + nonlocal schema_calls + schema_calls += 1 + return orig_schema_sync(self) + + async def counted_schema_async(self): + nonlocal schema_calls + schema_calls += 1 + return await orig_schema_async(self) + + async def counted_validated_blob_sources(self, *args, **kwargs): + nonlocal validated_blob_sources_calls + validated_blob_sources_calls += 1 + return await orig_validated_blob_sources(self, *args, **kwargs) + + async def counted_blob_output_schema(self): + nonlocal blob_output_schema_calls + blob_output_schema_calls += 1 + return await orig_blob_output_schema(self) + + monkeypatch.setattr(AsyncTable, "_schema_sync", counted_schema_sync) + monkeypatch.setattr(AsyncTable, "schema", counted_schema_async) + monkeypatch.setattr( + AsyncQueryBase, "_validated_blob_sources", counted_validated_blob_sources + ) + monkeypatch.setattr( + AsyncQueryBase, "_blob_output_schema", counted_blob_output_schema + ) + + # 1. Plain-scan blob v1 and v2 to_pandas (sync & async, all modes): 1 schema fetch + for blob_mode in ("lazy", "descriptions", "bytes"): + schema_calls = 0 + df = ( + v1_sync.search() + .where("id = 1") + .select(["id", "blob"]) + .to_pandas(blob_mode=blob_mode) + ) + assert df["id"].tolist() == [1] + assert schema_calls == 1 + + schema_calls = 0 + df = ( + await v1_async.query() + .where("id = 1") + .select(["id", "blob"]) + .to_pandas(blob_mode=blob_mode) + ) + assert df["id"].tolist() == [1] + assert schema_calls == 1 + + schema_calls = 0 + df = ( + v2_sync.search() + .where("id = 1") + .select(["id", "image"]) + .to_pandas(blob_mode=blob_mode) + ) + assert df["id"].tolist() == [1] + assert schema_calls == 1 + + schema_calls = 0 + df = ( + await v2_async.query() + .where("id = 1") + .select(["id", "image"]) + .to_pandas(blob_mode=blob_mode) + ) + assert df["id"].tolist() == [1] + assert schema_calls == 1 + + # 2. Non-plain-scan / memory:// / flatten=True default blob_mode="lazy" + # blob v2 to_pandas: 1 schema fetch (sync & async), and async calls + # _validated_blob_sources 1 time. + sync_v2_fallbacks = [ + lambda: v2_sync.search([1.0, 0.0], vector_column_name="vector") + .select(["id", "image"]) + .limit(1) + .to_pandas(), + lambda: v2_sync.take_offsets([0]).select(["id", "image"]).to_pandas(), + lambda: v2_sync.search() + .where("id = 1") + .select(["id", "image"]) + .to_pandas(flatten=True), + lambda: v2_mem_sync.search() + .where("id = 1") + .select(["id", "image"]) + .to_pandas(), + ] + for run in sync_v2_fallbacks: + schema_calls = 0 + df = run() + assert len(df) == 1 + assert schema_calls == 1 + + async_v2_fallbacks = [ + lambda: v2_async.vector_search([1.0, 0.0]) + .select(["id", "image"]) + .limit(1) + .to_pandas(), + lambda: v2_async.take_offsets([0]).select(["id", "image"]).to_pandas(), + lambda: v2_async.query() + .where("id = 1") + .select(["id", "image"]) + .to_pandas(flatten=True), + lambda: v2_mem_async.query() + .where("id = 1") + .select(["id", "image"]) + .to_pandas(), + ] + for run in async_v2_fallbacks: + schema_calls = 0 + validated_blob_sources_calls = 0 + df = await run() + assert len(df) == 1 + assert schema_calls == 1 + assert validated_blob_sources_calls == 1 + + # 3. Async non-plain-scan blob to_arrow / to_pandas (blob_mode="bytes") + # calls _blob_output_schema == 1 time (not twice). + schema_calls = 0 + blob_output_schema_calls = 0 + tbl = ( + await v2_async.vector_search([1.0, 0.0]) + .select(["id", "image"]) + .limit(1) + .to_arrow(blob_mode="bytes") + ) + assert tbl["image"].to_pylist() == [b"one"] + assert schema_calls == 1 + assert blob_output_schema_calls == 1 + + schema_calls = 0 + blob_output_schema_calls = 0 + df = ( + await v2_async.vector_search([1.0, 0.0]) + .select(["id", "image"]) + .limit(1) + .to_pandas(blob_mode="bytes") + ) + assert df["image"].tolist() == [b"one"] + assert schema_calls == 1 + assert blob_output_schema_calls == 1 + + +@pytest.mark.asyncio +async def test_async_to_batches_override_preserved_on_non_blob_table( + tmp_path, monkeypatch +): + db = await lancedb.connect_async(tmp_path / "to_batches_override") + table = await db.create_table("items", data=[{"id": 1}, {"id": 2}]) + + def _filter_id_one(reader: AsyncRecordBatchReader) -> AsyncRecordBatchReader: + async def filtered_batches(): + async for batch in reader: + filtered = batch.filter(pc.equal(batch["id"], 1)) + if filtered.num_rows > 0: + yield filtered + + return AsyncRecordBatchReader._from_batches(reader.schema, filtered_batches()) + + class FilteringAsyncQuery(AsyncQuery): + async def to_batches( + self, + *, + max_batch_length=None, + timeout=None, + blob_mode="lazy", + ): + reader = await super().to_batches( + max_batch_length=max_batch_length, + timeout=timeout, + blob_mode=blob_mode, + ) + return _filter_id_one(reader) + + query = FilteringAsyncQuery(table._inner.query(), table) + assert (await query.to_arrow(blob_mode="descriptions"))["id"].to_pylist() == [1] + assert (await query.to_arrow(blob_mode="bytes"))["id"].to_pylist() == [1] + assert (await query.to_pandas())["id"].tolist() == [1] + assert (await query.to_pandas(blob_mode="descriptions"))["id"].tolist() == [1] + assert (await query.to_pandas(blob_mode="bytes"))["id"].tolist() == [1] + assert sorted((await query.to_arrow())["id"].to_pylist()) == [1, 2] + + instance_query = table.query() + orig_instance_to_batches = instance_query.to_batches + + async def instance_to_batches( + *, max_batch_length=None, timeout=None, blob_mode="lazy" + ): + reader = await orig_instance_to_batches( + max_batch_length=max_batch_length, + timeout=timeout, + blob_mode=blob_mode, + ) + return _filter_id_one(reader) + + monkeypatch.setattr(instance_query, "to_batches", instance_to_batches) + assert (await instance_query.to_arrow(blob_mode="descriptions"))[ + "id" + ].to_pylist() == [1] + assert (await instance_query.to_pandas())["id"].tolist() == [1] + + orig_class_to_batches = AsyncQuery.to_batches + + async def class_to_batches( + self, *, max_batch_length=None, timeout=None, blob_mode="lazy" + ): + reader = await orig_class_to_batches( + self, + max_batch_length=max_batch_length, + timeout=timeout, + blob_mode=blob_mode, + ) + return _filter_id_one(reader) + + with monkeypatch.context() as mp: + mp.setattr(AsyncQuery, "to_batches", class_to_batches) + assert (await table.query().to_arrow(blob_mode="descriptions"))[ + "id" + ].to_pylist() == [1] + assert (await table.query().to_pandas())["id"].tolist() == [1] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "blob_metadata", + [ + {"lance-encoding:blob": "true"}, + {"ARROW:extension:name": "lance.blob.v2"}, + ], +) +async def test_reranker_synthesized_blob_column_validated_in_to_pandas( + tmp_path, blob_metadata +): + blob_struct_type = pa.struct([("position", pa.uint64())]) + blob_field = pa.field("external_image", blob_struct_type, metadata=blob_metadata) + + class BlobSynthesizingReranker(Reranker): + def rerank_fts(self, query: str, fts_results: pa.Table) -> pa.Table: + n = len(fts_results) + return fts_results.append_column( + "_relevance_score", pa.array([1.0] * n, type=pa.float32()) + ).append_column( + blob_field, + pa.array([{"position": 1}] * n, type=blob_struct_type), + ) + + def rerank_hybrid( + self, + query: str, + vector_results: pa.Table, + fts_results: pa.Table, + ) -> pa.Table: + return fts_results + + reranker = BlobSynthesizingReranker() + rows = [{"id": 1, "text": "alpha"}, {"id": 2, "text": "beta"}] + + sync_db = lancedb.connect(tmp_path / "sync_rerank_blob") + sync_table = sync_db.create_table("docs", data=rows) + sync_table.create_index("text", config=FTS(with_position=True)) + + async_db = await lancedb.connect_async(tmp_path / "async_rerank_blob") + async_table = await async_db.create_table("docs", data=rows) + await async_table.create_index("text", config=FTS(with_position=True)) + + async_fts_query = (await async_table.search("alpha", query_type="fts")).rerank( + reranker + ) + with pytest.raises( + ValueError, match="could not match result columns.*external_image" + ): + await async_fts_query.to_pandas(blob_mode="bytes") + with pytest.raises( + ValueError, match="could not match result columns.*external_image" + ): + await async_fts_query.to_arrow(blob_mode="bytes") + with pytest.raises(RuntimeError, match="no fetchable blob v2 source"): + await async_fts_query.to_pandas() + async_desc_df = await async_fts_query.to_pandas(blob_mode="descriptions") + assert async_desc_df["external_image"].tolist() == [{"position": 1}] + + sync_fts_query = sync_table.search("alpha", query_type="fts").rerank(reranker) + with pytest.raises( + ValueError, match="could not match result columns.*external_image" + ): + sync_fts_query.to_pandas(blob_mode="bytes") + with pytest.raises( + ValueError, match="could not match result columns.*external_image" + ): + sync_fts_query.to_list(blob_mode="bytes") + with pytest.raises( + ValueError, match="could not match result columns.*external_image" + ): + sync_fts_query.to_arrow(blob_mode="bytes") + with pytest.raises(RuntimeError, match="no fetchable blob v2 source"): + sync_fts_query.to_pandas() + sync_desc_df = sync_fts_query.to_pandas(blob_mode="descriptions") + assert sync_desc_df["external_image"].tolist() == [{"position": 1}] + + assert list(sync_table.search().select(["id", "_rowid"]).to_pandas().columns) == [ + "id", + "_rowid", + ] + assert list( + sync_table.search() + .select(["id", "_rowid"]) + .to_pandas(blob_mode="bytes") + .columns + ) == ["id", "_rowid"] + assert list( + (await async_table.query().select(["id", "_rowid"]).to_pandas()).columns + ) == ["id", "_rowid"] + assert list( + ( + await async_table.query() + .select(["id", "_rowid"]) + .to_pandas(blob_mode="bytes") + ).columns + ) == ["id", "_rowid"] + + synthesized_tbl = pa.Table.from_arrays( + [ + pa.array([1], type=pa.int64()), + pa.array([{"position": 1}], type=blob_struct_type), + ], + schema=pa.schema([pa.field("id", pa.int64()), blob_field]), + ) + + class LegacyAsyncToArrowQuery(AsyncQuery): + async def to_arrow(self, timeout=None): + return synthesized_tbl + + custom_async = LegacyAsyncToArrowQuery(async_table._inner.query(), async_table) + with pytest.raises(ValueError, match="external_image"): + await custom_async.to_pandas(blob_mode="bytes") + + class LegacySyncToArrowQuery(LanceEmptyQueryBuilder): + def to_arrow(self, *, timeout=None): + return synthesized_tbl + + custom_sync = LegacySyncToArrowQuery(sync_table) + with pytest.raises(ValueError, match="external_image"): + custom_sync.to_pandas(blob_mode="bytes") + with pytest.raises(ValueError, match="external_image"): + custom_sync.to_list(blob_mode="bytes") + + recorded_modes: list[str] = [] + + class KeywordOnlyBlobModeAsyncQuery(AsyncQuery): + async def to_arrow(self, timeout=None, *, blob_mode="lazy"): + recorded_modes.append(blob_mode) + return await super().to_arrow(timeout=timeout, blob_mode=blob_mode) + + kw_async = KeywordOnlyBlobModeAsyncQuery(async_table._inner.query(), async_table) + await kw_async.to_pandas() + await kw_async.to_pandas(blob_mode="bytes") + assert recorded_modes == ["descriptions", "bytes"] diff --git a/python/python/tests/test_sync_query_direct.py b/python/python/tests/test_sync_query_direct.py index 9863f66c4..c1f694745 100644 --- a/python/python/tests/test_sync_query_direct.py +++ b/python/python/tests/test_sync_query_direct.py @@ -14,6 +14,7 @@ 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): @@ -48,10 +49,24 @@ def test_direct_sync_queries_do_not_use_background_loop(tmp_path, monkeypatch): 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() @@ -62,10 +77,22 @@ def test_direct_sync_queries_do_not_use_background_loop(tmp_path, monkeypatch): 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] @@ -78,6 +105,123 @@ def test_direct_sync_queries_do_not_use_background_loop(tmp_path, monkeypatch): 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""" diff --git a/python/python/tests/test_wal_hybrid.py b/python/python/tests/test_wal_hybrid.py index 372b1bd19..8afebcbff 100644 --- a/python/python/tests/test_wal_hybrid.py +++ b/python/python/tests/test_wal_hybrid.py @@ -9,8 +9,10 @@ import lancedb import pyarrow as pa import pytest from lancedb._wal_hybrid import WAL_ROW_ID_UNSUPPORTED, with_pk_fallback -from lancedb.query import LanceHybridQueryBuilder +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: @@ -219,3 +221,201 @@ def test_fallback_reraises_what_it_cannot_retry(error, fused): 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