Merge main into gatekeeper/fix-5025-1

This commit is contained in:
Gatefixer
2026-11-20 20:56:44 +00:00
61 changed files with 4889 additions and 318 deletions
+3 -1
View File
@@ -38,7 +38,7 @@ from .db import AsyncConnection, DBConnection, LanceDBConnection
from .remote import ClientConfig
from .remote.db import RemoteDBConnection
from .expr import Expr, col, lit, func
from .schema import blob, vector
from .schema import BasePath, blob, blob_uri_array, vector
from ._blob_reader import BlobReader as BlobReader
from .job import AsyncJob, Job
from .sql import AsyncQuery as AsyncSqlQuery
@@ -696,6 +696,8 @@ __all__ = [
"sanitize_uri",
"blob",
"BlobType",
"BasePath",
"blob_uri_array",
"vector",
"DBConnection",
"Job",
+65 -4
View File
@@ -7,7 +7,9 @@ from __future__ import annotations
import io
import operator
import re
from collections.abc import Awaitable, Callable, Iterable, Mapping
from dataclasses import dataclass
from typing import TYPE_CHECKING, Optional, Union
import pyarrow as pa
@@ -30,10 +32,47 @@ BLOB_MODE_TO_HANDLING = {
}
ROW_ID_FIELD_NAME = "_lance_row_id"
QUERY_VERSION_METADATA_KEY = b"lancedb:query_version"
QUERY_SNAPSHOT_METADATA_KEY = b"lancedb:query_snapshot"
FetchBlobsSync = Callable[[str, list[int]], pa.Array | pa.ChunkedArray]
FetchBlobsAsync = Callable[[str, list[int]], Awaitable[pa.Array | pa.ChunkedArray]]
_POSITION_HELP = (
"If you only have row positions, call "
"table.take_offsets(offsets, with_row_id=True) first and pass the resulting "
"'_rowid' values."
)
def _remote_blob_snapshot(
schema: pa.Schema, *, operation: str = "blob_mode='bytes'"
) -> tuple[int, str]:
"""Validate the snapshot metadata a remote query attaches to its result."""
value = (schema.metadata or {}).get(QUERY_VERSION_METADATA_KEY, b"")
if not value.isdigit() or not 0 < int(value) < 2**64:
raise NotImplementedError(
f"{operation} requires a stable table snapshot: the query response "
"has a missing, invalid, or inconsistent x-lancedb-query-version header. "
"Upgrade the server and use a table without Realtime/MemWAL, or use "
"blob_mode='descriptions'."
)
identity = (schema.metadata or {}).get(QUERY_SNAPSHOT_METADATA_KEY, b"")
if not re.fullmatch(rb"v1:[0-9a-f]{64}", identity):
raise NotImplementedError(
f"{operation} requires a trustworthy query snapshot identity: "
"missing or unsupported x-lancedb-query-snapshot. Upgrade the server "
"on every serving node, or use blob_mode='descriptions'."
)
return int(value), identity.decode("ascii")
@dataclass(frozen=True)
class _BlobRowIdSelection:
row_ids: list[int]
version: Optional[int] = None
snapshot_identity: Optional[str] = None
def _validate_blob_buffer_size(size: Optional[int]) -> Optional[int]:
if size is None:
@@ -376,7 +415,7 @@ def _hit_row_ids(tbl: pa.Table, blob_sources: dict[str, str]) -> list[int]:
raise ValueError(
f"query result has no '_rowid' column and no '{ROW_ID_FIELD_NAME}' "
f"field on blob columns {list(blob_sources)}. Call .with_row_id(True) "
"to fetch blob bytes for this query."
f"to fetch blob bytes for this query. {_POSITION_HELP}"
)
@@ -417,7 +456,8 @@ def read_row_ids_from_hits(hits: pa.Table, blob_column: str) -> list[int]:
raise ValueError(
f"query result has no '_rowid' column and no '{ROW_ID_FIELD_NAME}' "
f"field on blob column '{blob_column}'. Pass fresh blob query "
"results, call .with_row_id(True), or pass a list of row ids."
f"results, call .with_row_id(True), or pass a list of row ids. "
f"{_POSITION_HELP}"
)
@@ -638,11 +678,31 @@ def _walk_struct_fields(
return data_type
def _query_snapshot_for_blob_fetch(
schema: pa.Schema,
) -> Optional[tuple[int, str]]:
"""Use the query snapshot when a result table carries one.
A table without either metadata key came from a local table or a server
that cannot pin deferred reads, so row ids keep their existing
current-snapshot behavior.
"""
metadata = schema.metadata or {}
if not any(
key in metadata
for key in (QUERY_VERSION_METADATA_KEY, QUERY_SNAPSHOT_METADATA_KEY)
):
return None
return _remote_blob_snapshot(schema, operation="fetching blobs for a query result")
def _normalize_blob_row_ids(
row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table], blob_column: str
) -> list[int]:
) -> _BlobRowIdSelection:
snapshot = None
if isinstance(row_ids, pa.Table):
values = read_row_ids_from_hits(row_ids, blob_column)
snapshot = _query_snapshot_for_blob_fetch(row_ids.schema)
elif isinstance(row_ids, (pa.Array, pa.ChunkedArray)):
if not pa.types.is_integer(row_ids.type):
raise ValueError(
@@ -662,7 +722,8 @@ def _normalize_blob_row_ids(
if row_id < 0:
raise ValueError("row ids must be non-negative")
normalized.append(row_id)
return normalized
version, snapshot_identity = snapshot if snapshot else (None, None)
return _BlobRowIdSelection(normalized, version, snapshot_identity)
def _wrap_blob_files(handles: Iterable[object]) -> list[Optional[BlobFile]]:
+24 -1
View File
@@ -334,6 +334,9 @@ class Connection(object):
namespace_path: Optional[List[str]] = None,
storage_options: Optional[Dict[str, str]] = None,
location: Optional[str] = None,
namespace_client: Optional[Any] = None,
initial_bases: Optional[List[Any]] = None,
allow_external_blob_outside_bases: bool = False,
) -> Table: ...
async def create_empty_table(
self,
@@ -343,6 +346,8 @@ class Connection(object):
namespace_path: Optional[List[str]] = None,
storage_options: Optional[Dict[str, str]] = None,
location: Optional[str] = None,
namespace_client: Optional[Any] = None,
initial_bases: Optional[List[Any]] = None,
) -> Table: ...
async def open_table(
self,
@@ -570,6 +575,7 @@ class Table:
def _is_native(self) -> bool: ...
def close(self) -> None: ...
async def schema(self) -> pa.Schema: ...
def schema_sync(self) -> pa.Schema: ...
async def add(
self,
data: pa.RecordBatchReader,
@@ -857,7 +863,13 @@ class Table:
requests: Sequence[Sequence[int]],
) -> pa.LargeBinaryArray: ...
async def fetch_blob_files(
self, column: str, row_ids: list[int], buffer_size: Optional[int] = None
self,
column: str,
row_ids: list[int],
buffer_size: Optional[int] = None,
*,
version: Optional[int] = None,
snapshot_identity: Optional[str] = None,
) -> list[Optional[BlobFile]]: ...
async def open_blob_file(
self, descriptor: str, buffer_size: Optional[int] = None
@@ -965,6 +977,9 @@ class Query:
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: ...
async def explain_plan(self, verbose: Optional[bool]) -> str: ...
async def analyze_plan(
self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None
@@ -974,6 +989,7 @@ class Query:
class TakeQuery:
def select(self, columns: List[str]): ...
def with_row_id(self): ...
def preserve_order(self): ...
def use_rte(self, enable: bool): ...
async def output_schema(self) -> pa.Schema: ...
async def execute(self) -> RecordBatchStream: ...
@@ -1009,6 +1025,9 @@ class FTSQuery:
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: ...
async def explain_plan(self, verbose: Optional[bool]) -> str: ...
async def analyze_plan(
self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None
@@ -1021,6 +1040,9 @@ class VectorQuery:
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 where(self, filter: str): ...
def where_expr(self, expr: PyExpr): ...
def select(self, columns: List[Tuple[str, str]]): ...
@@ -1081,6 +1103,7 @@ class PyQueryRequest:
offset: Optional[int]
take_offsets: Optional[List[int]]
take_row_ids: Optional[List[int]]
preserve_order: Optional[bool]
filter: Optional[Union[str, bytes]]
full_text_search: Optional[FullTextQuery]
select: Optional[Union[str, List[str]]]
+70
View File
@@ -507,6 +507,8 @@ class DBConnection(EnforceOverrides):
storage_options: Optional[Dict[str, str]] = None,
data_storage_version: Optional[str] = None,
enable_v2_manifest_paths: Optional[bool] = None,
initial_bases: Optional[List[Any]] = None,
allow_external_blob_outside_bases: bool = False,
) -> Table:
"""Create a [Table][lancedb.table.Table] in the database.
@@ -570,6 +572,23 @@ class DBConnection(EnforceOverrides):
enable_v2_manifest_paths: optional, bool, default False
Deprecated. Set `storage_options` when connecting to the database and set
`new_table_enable_v2_manifest_paths` in the options.
initial_bases: list, optional
Storage bases to register in the table's manifest in the same
commit that creates it, so a create with data stays atomic. Each
entry can be a [BasePath][lancedb.schema.BasePath], a dict with
`path`, `name`, `is_dataset_root`, and `id` keys, or a
`lance.DatasetBasePath`. Blob URIs that fall under a registered
base are stored relative to it; other URIs need
`allow_external_blob_outside_bases=True`. `None` and an empty
list are equivalent. When supplying IDs for multiple bases, use
distinct explicit non-zero IDs; [BasePath][lancedb.schema.BasePath]
describes the pinned-Lance limitation.
allow_external_blob_outside_bases: bool, default False
Store blob URIs that do not fall under a registered base. The row
keeps a reference, so the objects have to stay readable. Set
`initial_bases` instead when the URIs share a registered prefix.
Defaults to rejecting such URIs. The opt-in applies only to the
initial data; a later `add()` must enable it again.
Returns
-------
LanceTable
@@ -2156,6 +2175,8 @@ class LanceDBConnection(DBConnection):
storage_options: Optional[Dict[str, str]] = None,
data_storage_version: Optional[str] = None,
enable_v2_manifest_paths: Optional[bool] = None,
initial_bases: Optional[List[Any]] = None,
allow_external_blob_outside_bases: bool = False,
) -> LanceTable:
"""Create a table in the database.
@@ -2186,6 +2207,8 @@ class LanceDBConnection(DBConnection):
storage_options=storage_options,
data_storage_version=data_storage_version,
enable_v2_manifest_paths=enable_v2_manifest_paths,
initial_bases=initial_bases,
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
)
return tbl
@@ -2197,6 +2220,7 @@ class LanceDBConnection(DBConnection):
namespace_path: Optional[List[str]] = None,
storage_options: Optional[Dict[str, str]] = None,
index_cache_size: Optional[int] = None,
location: Optional[str] = None,
branch: Optional[str] = None,
version: Optional[int] = None,
) -> LanceTable:
@@ -2209,6 +2233,10 @@ class LanceDBConnection(DBConnection):
namespace_path: List[str], optional
The namespace to open the table from. When non-empty, the
table is resolved through the directory namespace client.
location: str, optional
The explicit location (URI) of the table. If provided, the table will be
opened from this location instead of deriving it from the database URI
and table name.
branch: str, optional
If provided, open a handle scoped to this branch instead of the
default branch. Reads and writes operate in the branch's context.
@@ -2242,6 +2270,7 @@ class LanceDBConnection(DBConnection):
namespace_path=namespace_path,
storage_options=storage_options,
index_cache_size=index_cache_size,
location=location,
)
except (RuntimeError, ValueError) as e:
if namespace_path and (
@@ -3290,6 +3319,8 @@ class AsyncConnection(object):
embedding_functions: Optional[List[EmbeddingFunctionConfig]] = None,
location: Optional[str] = None,
namespace_client: Optional[Any] = None,
initial_bases: Optional[List[Any]] = None,
allow_external_blob_outside_bases: bool = False,
) -> AsyncTable:
"""Create an [AsyncTable][lancedb.table.AsyncTable] in the database.
@@ -3347,6 +3378,23 @@ class AsyncConnection(object):
To enable stable row IDs (row IDs remain stable after compaction,
update, delete, and merges), set `new_table_enable_stable_row_ids`
to `"true"` in storage_options when connecting to the database.
initial_bases: list, optional
Storage bases to register in the table's manifest in the same
commit that creates it, so a create with data stays atomic. Each
entry can be a [BasePath][lancedb.schema.BasePath], a dict with
`path`, `name`, `is_dataset_root`, and `id` keys, or a
`lance.DatasetBasePath`. Blob URIs that fall under a registered
base are stored relative to it; other URIs need
`allow_external_blob_outside_bases=True`. `None` and an empty
list are equivalent. When supplying IDs for multiple bases, use
distinct explicit non-zero IDs; [BasePath][lancedb.schema.BasePath]
describes the pinned-Lance limitation.
allow_external_blob_outside_bases: bool, default False
Store blob URIs that do not fall under a registered base. The row
keeps a reference, so the objects have to stay readable. Requires
initial `data`; the opt-in applies only to that initial write, and
a later `add()` must enable it again. Defaults to rejecting such
URIs.
Returns
-------
@@ -3458,6 +3506,25 @@ class AsyncConnection(object):
"""
if namespace_path is None:
namespace_path = []
if get_uri_scheme(self.uri) == "db":
# The Enterprise create endpoint has no way to express either
# option. Reject before sanitizing or reading `data`, and do not
# point at a local-only or remote `add` path.
if initial_bases:
raise NotImplementedError(
"initial_bases is not supported for table creation in "
"LanceDB Enterprise"
)
if allow_external_blob_outside_bases:
raise NotImplementedError(
"allow_external_blob_outside_bases is not supported for table "
"creation in LanceDB Enterprise"
)
if data is None and allow_external_blob_outside_bases:
raise ValueError(
"allow_external_blob_outside_bases requires initial data; "
"pass it to add() for later writes"
)
metadata = None
if embedding_functions is not None:
@@ -3504,6 +3571,7 @@ class AsyncConnection(object):
storage_options=storage_options,
location=location,
namespace_client=namespace_client,
initial_bases=initial_bases,
)
else:
data = data_to_reader(data, schema)
@@ -3515,6 +3583,8 @@ class AsyncConnection(object):
storage_options=storage_options,
location=location,
namespace_client=namespace_client,
initial_bases=initial_bases,
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
)
return AsyncTable(new_table)
+8
View File
@@ -642,6 +642,8 @@ class LanceNamespaceDBConnection(DBConnection):
storage_options: Optional[Dict[str, str]] = None,
data_storage_version: Optional[str] = None,
enable_v2_manifest_paths: Optional[bool] = None,
initial_bases: Optional[List[Any]] = None,
allow_external_blob_outside_bases: bool = False,
) -> Table:
if namespace_path is None:
namespace_path = []
@@ -663,6 +665,8 @@ class LanceNamespaceDBConnection(DBConnection):
embedding_functions=embedding_functions,
namespace_path=namespace_path,
storage_options=storage_options,
initial_bases=initial_bases,
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
)
)
@@ -1309,6 +1313,8 @@ class AsyncLanceNamespaceDBConnection:
storage_options: Optional[Dict[str, str]] = None,
data_storage_version: Optional[str] = None,
enable_v2_manifest_paths: Optional[bool] = None,
initial_bases: Optional[List[Any]] = None,
allow_external_blob_outside_bases: bool = False,
) -> AsyncTable:
"""Create a new table in the namespace."""
if namespace_path is None:
@@ -1330,6 +1336,8 @@ class AsyncLanceNamespaceDBConnection:
namespace_path=namespace_path,
embedding_functions=embedding_functions,
storage_options=storage_options,
initial_bases=initial_bases,
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
)
return table._set_namespace_context(
namespace_path=namespace_path,
+49 -15
View File
@@ -11,7 +11,12 @@ import pyarrow as pa
from ._lancedb import async_permutation_builder, PermutationReader
from .table import LanceTable, Table
from .background_loop import LOOP
from .util import batch_to_tensor, batch_to_tensor_dict, batch_to_tensor_rows
from .util import (
batch_to_tensor,
batch_to_tensor_columns,
batch_to_tensor_dict,
batch_to_tensor_rows,
)
from typing import Any, Callable, Iterator, Literal, Optional, TYPE_CHECKING, Union
if TYPE_CHECKING:
@@ -1031,6 +1036,7 @@ class Permutation:
"pandas",
"arrow",
"torch",
"torch_dict",
"torch_row",
"torch_col",
"polars",
@@ -1042,28 +1048,54 @@ class Permutation:
If this method is not called, the "python" format will be used.
The format can be one of:
- "numpy" - the batch will be a dict of numpy arrays (one per column)
- "numpy" - a single NumPy ndarray built with
``batch.to_pandas().to_numpy()``. This conversion may copy data and
may promote mixed numeric columns to a common numeric dtype, for
example int64 and float32 to float64. Nested or incompatible columns
produce an object array.
- "python" - the batch will be a list of dicts (one per row)
- "python_col" - the batch will be a dict of lists (one entry per column)
- "pandas" - the batch will be a pandas DataFrame
- "arrow" - the batch will be a pyarrow RecordBatch
- "torch" - the batch will be a list of per-row dicts mapping column
name to a 0-D torch tensor. Works with the default
``torch.utils.data.DataLoader`` collate, which stacks the per-row
dicts back into a dict of batched tensors.
- "torch_row" - the batch will be a list of tensors, one per row
- "torch_col" - the batch will be a 2D torch tensor (first dim indexes columns)
- "torch" - a list of per-row dicts mapping column names to tensors with
shape ``(*S)``. The default DataLoader collate stacks these into a
dict of ``(B, *S)`` tensors.
- "torch_dict" - a dict mapping each column name to one tensor with
shape ``(B, *S)``. Columns may have different sample shapes ``S``.
Use an identity collate to consume the batch directly. Tensors share
Arrow storage where the layout allows.
- "torch_row" - a list of per-row tensors with shape ``(C, *S)``. All
columns must have the same sample shape ``S``. A single scalar column
produces ``(1,)`` tensors. Numeric dtypes are combined with
``torch.promote_types``.
- "torch_col" - one tensor with shape ``(C, B, *S)``. All columns must
have the same sample shape ``S``. For one column this is an
``unsqueeze(0)`` view of the column tensor.
- "polars" - the batch will be a polars DataFrame
Conversion may or may not involve a data copy. Lance uses Arrow internally
and so it is able to zero-copy to the arrow and polars formats.
For torch formats, ``S`` is the shape of one sample. Scalar columns have
``S = ()``. A fixed-size-list column of width ``D`` contributes a
dimension ``D``, and nested fixed-size lists contribute one dimension
per level. Fixed-shape tensors use their logical shape, including any
axis permutation. "torch_dict", "torch", and "torch_col" reject nulls;
use the "python" or "arrow" format for nullable columns. "torch_row"
preserves the previous NaN behavior for nullable scalar integer and
floating columns, but rejects nulls in nested fixed-size-list and tensor
columns.
Conversion to torch and torch_col will be zero-copy but will only support a
subset of data types (numeric types).
``lance.bfloat16`` values become ``torch.bfloat16`` tensors when the
leaf field is ``fixed_size_binary[2]`` and carries the
``ARROW:extension:name`` metadata value ``lance.bfloat16``. Unmarked
binary columns are rejected.
Conversion to numpy and/or pandas will typically be zero-copy for numeric
types. Conversion of strings, lists, and structs will require creating python
objects and this is not zero-copy.
Conversion may or may not involve a data copy. Lance uses Arrow
internally and can zero-copy to the arrow and polars formats.
"torch_dict", "torch", and a single-column "torch_col" produce
numeric and fixed-size-list tensors without copying where the Arrow
layout allows. Multi-column "torch_col" and "torch_row" stack columns
and therefore copy. Conversion to numpy and/or pandas can copy even
homogeneous numeric columns. Conversion of strings, lists, and structs
will require creating Python objects and this is not zero-copy.
For custom formatting, use
[with_transform][lancedb.permutation.Permutation.with_transform] which
@@ -1082,6 +1114,8 @@ class Permutation:
return self.with_transform(Transforms.arrow2arrow)
elif format == "torch":
return self.with_transform(batch_to_tensor_dict)
elif format == "torch_dict":
return self.with_transform(batch_to_tensor_columns)
elif format == "torch_row":
return self.with_transform(batch_to_tensor_rows)
elif format == "torch_col":
+257 -77
View File
@@ -4,7 +4,6 @@
from __future__ import annotations
import asyncio
import re
from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor
from datetime import timedelta
@@ -48,6 +47,7 @@ from ._blob import (
BLOB_MODE_TO_HANDLING,
FetchBlobsAsync,
FetchBlobsSync,
_remote_blob_snapshot,
blob_auto_row_id_for_scan,
blob_projection_sources,
blob_v2_projection_sources,
@@ -205,25 +205,6 @@ def _supports_blob_fetch(
)
def _remote_blob_snapshot(schema: pa.Schema) -> tuple[int, str]:
value = (schema.metadata or {}).get(b"lancedb:query_version", b"")
if not value.isdigit() or not 0 < int(value) < 2**64:
raise NotImplementedError(
"blob_mode='bytes' requires a stable table snapshot: the query response "
"has a missing, invalid, or inconsistent x-lancedb-query-version header. "
"Upgrade the server and use a table without Realtime/MemWAL, or use "
"blob_mode='descriptions'."
)
identity = (schema.metadata or {}).get(b"lancedb:query_snapshot", b"")
if not re.fullmatch(rb"v1:[0-9a-f]{64}", identity):
raise NotImplementedError(
"blob_mode='bytes' requires a trustworthy query snapshot identity: "
"missing or unsupported x-lancedb-query-snapshot. Upgrade the server "
"on every serving node, or use blob_mode='descriptions'."
)
return int(value), identity.decode("ascii")
def _merge_query_snapshot(result: pa.Table, *sources: pa.Table) -> pa.Table:
"""Preserve a snapshot only when every query leg used the same identity."""
keys = (b"lancedb:query_version", b"lancedb:query_snapshot")
@@ -1124,6 +1105,9 @@ class Query(pydantic.BaseModel):
The default is False
"""
# Internal: the sync query layer already prepared blob row ids.
_blob_row_id_prepared: bool = pydantic.PrivateAttr(default=False)
# The name of the vector column to use for vector search.
vector_column: Optional[str] = None
@@ -1202,6 +1186,9 @@ class Query(pydantic.BaseModel):
# Row IDs whose requested order and duplicate occurrences must be restored.
take_row_ids: Optional[List[int]] = None
# Restore take-offset duplicates in the exact input order.
preserve_order: Optional[bool] = None
# if true, will only search the indexed data
fast_search: Optional[bool] = None
@@ -1228,6 +1215,7 @@ class Query(pydantic.BaseModel):
query.offset = req.offset
query.take_offsets = req.take_offsets
query.take_row_ids = req.take_row_ids
query.preserve_order = req.preserve_order
query.filter = req.filter
query.full_text_query = req.full_text_search
query.columns = req.select
@@ -1789,23 +1777,85 @@ class LanceQueryBuilder(ABC):
def _user_requested_row_id(self) -> bool:
return self._with_row_id is True
def _blob_auto_row_id_enabled(self) -> bool:
def _blob_auto_row_id_enabled(self, schema: Optional[pa.Schema] = None) -> bool:
if self._with_row_id is not None:
return False
if schema is None:
schema = self._table.schema
return blob_auto_row_id_for_scan(
self._table.schema,
schema,
self._columns,
with_row_id=self._with_row_id,
)
def _scan_needs_row_id(self) -> bool:
return self._user_requested_row_id() or self._blob_auto_row_id_enabled()
def _row_id_schema(self) -> Optional[pa.Schema]:
if self._with_row_id is not None:
return None
return self._table.schema
def _query_for_scan(self, blob_sources: Optional[dict[str, str]] = None) -> Query:
def _scan_needs_row_id(self, schema: Optional[pa.Schema] = None) -> bool:
if self._user_requested_row_id():
return True
return self._blob_auto_row_id_enabled(schema)
def _query_for_scan(
self,
blob_sources: Optional[dict[str, str]] = None,
schema: Optional[pa.Schema] = None,
) -> Query:
self._ensure_fragment_constraints_supported("this query")
query = self.to_query_object()
if self._scan_needs_row_id() or blob_sources:
if schema is None:
schema = self._row_id_schema()
if self._scan_needs_row_id(schema) or blob_sources:
query.with_row_id = True
return query
def _prepare_blob_execution(
self, blob_mode: BlobMode
) -> tuple[dict[str, str], Optional[pa.Schema]]:
validate_blob_mode(blob_mode)
schema = self._table.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
def _to_batches_prepared(
self,
*,
batch_size: Optional[int],
timeout: Optional[timedelta],
blob_mode: BlobMode,
blob_sources: dict[str, str],
schema: Optional[pa.Schema],
) -> pa.RecordBatchReader:
query = self._query_for_scan(blob_sources, schema)
reader = self._execute_query_prepared(
query, batch_size=batch_size, timeout=timeout
)
return self._batches_in_mode(reader, blob_mode, blob_sources, schema)
def _execute_query_prepared(
self,
query: Query,
*,
batch_size: Optional[int] = None,
timeout: Optional[timedelta] = None,
) -> pa.RecordBatchReader:
if not _is_remote_query_table(self._table):
query._blob_row_id_prepared = True
return self._table._execute_query(query, batch_size=batch_size, timeout=timeout)
def _execute_arrow_prepared(
self, query: Query, *, timeout: Optional[timedelta] = None
) -> pa.Table:
if not _is_remote_query_table(self._table):
query._blob_row_id_prepared = True
return self._table._execute_arrow(query, timeout=timeout)
def _ensure_fragment_constraints_supported(self, operation: str) -> None:
_raise_unsupported_fragment_constraints(
self._fragments,
@@ -1831,13 +1881,18 @@ class LanceQueryBuilder(ABC):
)
)
def _validated_blob_sources(self, blob_mode: BlobMode) -> dict[str, str]:
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.
"""
validate_blob_mode(blob_mode)
schema = self._table.schema
if blob_mode == "lazy":
return {}
if schema is None:
schema = self._table.schema
blob_sources = blob_projection_sources(
schema,
self._columns,
@@ -1885,8 +1940,9 @@ class LanceQueryBuilder(ABC):
*,
blob_mode: BlobMode,
blob_sources: dict[str, str],
schema: Optional[pa.Schema] = None,
) -> pa.Table:
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" and blob_sources:
# Bytes conversion reads _rowid directly, including when the
# projection mixes legacy and v2 columns.
@@ -1914,22 +1970,26 @@ class LanceQueryBuilder(ABC):
reader: pa.RecordBatchReader,
blob_mode: BlobMode,
blob_sources: dict[str, str],
schema: Optional[pa.Schema] = None,
) -> pa.RecordBatchReader:
if blob_mode == "lazy":
return reader
def convert(tbl: pa.Table) -> pa.Table:
return self._finalize_blob_query_table(
tbl, blob_mode=blob_mode, blob_sources=blob_sources
tbl,
blob_mode=blob_mode,
blob_sources=blob_sources,
schema=schema,
)
schema = convert(pa.Table.from_batches([], schema=reader.schema)).schema
result_schema = convert(pa.Table.from_batches([], schema=reader.schema)).schema
def batches():
for batch in reader:
yield from convert(pa.Table.from_batches([batch])).to_batches()
return pa.RecordBatchReader.from_batches(schema, batches())
return pa.RecordBatchReader.from_batches(result_schema, batches())
def with_row_address(self, with_row_address: bool = True) -> Self:
"""Set whether to return row addresses.
@@ -2566,17 +2626,26 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
``"bytes"`` returns payload bytes for supported row-addressable blob
columns and raises for blobs inside lists.
"""
blob_sources = self._validated_blob_sources(blob_mode)
blob_sources, schema = self._prepare_blob_execution(blob_mode)
if blob_mode != "lazy":
# Materialize in lazy mode so reranking runs once over the full
# result before the requested aggregate blob conversion.
return self._finalize_blob_query_table(
self.to_batches(timeout=timeout).read_all(),
self._to_batches_prepared(
batch_size=None,
timeout=timeout,
blob_mode="lazy",
blob_sources=blob_sources,
schema=schema,
).read_all(),
blob_mode=blob_mode,
blob_sources=blob_sources,
schema=schema,
)
self._ensure_fragment_constraints_supported("to_arrow()")
results = self._table._execute_arrow(
self._query_for_scan(blob_sources), timeout=timeout
results = self._execute_arrow_prepared(
self._query_for_scan(blob_sources, schema), timeout=timeout
)
if self._reranker is not None:
source = results
@@ -2584,7 +2653,10 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
check_reranker_result(results)
results = _merge_query_snapshot(results, source)
return self._finalize_blob_query_table(
results, blob_mode=blob_mode, blob_sources=blob_sources
results,
blob_mode=blob_mode,
blob_sources=blob_sources,
schema=schema,
)
def to_query_object(self) -> Query:
@@ -2624,6 +2696,31 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
order_by=self._order_by,
)
def _to_batches_prepared(
self,
*,
batch_size: Optional[int],
timeout: Optional[timedelta],
blob_mode: BlobMode,
blob_sources: dict[str, str],
schema: Optional[pa.Schema],
) -> pa.RecordBatchReader:
query = self._query_for_scan(blob_sources, schema)
result_set = self._execute_query_prepared(
query, batch_size=batch_size, timeout=timeout
)
if self._reranker is not None:
rs_table = result_set.read_all()
result_set = self._reranker.rerank_vector(self._str_query, rs_table)
check_reranker_result(result_set)
result_set = _merge_query_snapshot(result_set, rs_table)
# convert result_set back to RecordBatchReader
result_set = pa.RecordBatchReader.from_batches(
result_set.schema, result_set.to_batches()
)
return self._batches_in_mode(result_set, blob_mode, blob_sources, schema)
def to_batches(
self,
/,
@@ -2652,25 +2749,14 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
-------
pa.RecordBatchReader
"""
blob_sources = self._validated_blob_sources(blob_mode)
vector = self._query if isinstance(self._query, list) else self._query.tolist()
if isinstance(vector[0], np.ndarray):
vector = [v.tolist() for v in vector]
query = self._query_for_scan(blob_sources)
result_set = self._table._execute_query(
query, batch_size=batch_size, timeout=timeout
blob_sources, schema = self._prepare_blob_execution(blob_mode)
return self._to_batches_prepared(
batch_size=batch_size,
timeout=timeout,
blob_mode=blob_mode,
blob_sources=blob_sources,
schema=schema,
)
if self._reranker is not None:
rs_table = result_set.read_all()
result_set = self._reranker.rerank_vector(self._str_query, rs_table)
check_reranker_result(result_set)
result_set = _merge_query_snapshot(result_set, rs_table)
# convert result_set back to RecordBatchReader
result_set = pa.RecordBatchReader.from_batches(
result_set.schema, result_set.to_batches()
)
return self._batches_in_mode(result_set, blob_mode, blob_sources)
def where(
self, where: Union[str, Expr], prefilter: bool = None
@@ -2906,22 +2992,25 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
timeout: Optional[timedelta] = None,
blob_mode: BlobMode = "lazy",
) -> pa.Table:
blob_sources = self._validated_blob_sources(blob_mode)
blob_sources, schema = self._prepare_blob_execution(blob_mode)
self._table._ensure_no_legacy_fts_index()
self._ensure_fragment_constraints_supported("to_arrow()")
query = self._query_for_scan(blob_sources)
query = self._query_for_scan(blob_sources, schema)
if blob_mode == "lazy":
results = self._table._execute_arrow(query, timeout=timeout)
results = self._execute_arrow_prepared(query, timeout=timeout)
else:
results = self._table._execute_query(query, timeout=timeout).read_all()
results = self._execute_query_prepared(query, timeout=timeout).read_all()
if self._reranker is not None:
source = results
results = self._reranker.rerank_fts(self._query, results)
check_reranker_result(results)
results = _merge_query_snapshot(results, source)
return self._finalize_blob_query_table(
results, blob_mode=blob_mode, blob_sources=blob_sources
results,
blob_mode=blob_mode,
blob_sources=blob_sources,
schema=schema,
)
def to_batches(
@@ -2960,23 +3049,37 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder):
timeout: Optional[timedelta] = None,
blob_mode: BlobMode = "lazy",
) -> pa.Table:
blob_sources = self._validated_blob_sources(blob_mode)
blob_sources, schema = self._prepare_blob_execution(blob_mode)
if blob_mode == "bytes" and blob_sources:
return self.to_batches(timeout=timeout, blob_mode=blob_mode).read_all()
return self._to_batches_prepared(
batch_size=None,
timeout=timeout,
blob_mode="bytes",
blob_sources=blob_sources,
schema=schema,
).read_all()
if blob_mode != "lazy":
return self._finalize_blob_query_table(
self.to_batches(timeout=timeout).read_all(),
self._to_batches_prepared(
batch_size=None,
timeout=timeout,
blob_mode="lazy",
blob_sources=blob_sources,
schema=schema,
).read_all(),
blob_mode=blob_mode,
blob_sources=blob_sources,
schema=schema,
)
self._ensure_fragment_constraints_supported("to_arrow()")
return self._finalize_blob_query_table(
self._table._execute_arrow(
self._query_for_scan(blob_sources), timeout=timeout
self._execute_arrow_prepared(
self._query_for_scan(blob_sources, schema), timeout=timeout
),
blob_mode=blob_mode,
blob_sources=blob_sources,
schema=schema,
)
def to_query_object(self) -> Query:
@@ -3005,12 +3108,14 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder):
*,
blob_mode: BlobMode = "lazy",
) -> pa.RecordBatchReader:
blob_sources = self._validated_blob_sources(blob_mode)
query = self._query_for_scan(blob_sources)
reader = self._table._execute_query(
query, batch_size=batch_size, timeout=timeout
blob_sources, schema = self._prepare_blob_execution(blob_mode)
return self._to_batches_prepared(
batch_size=batch_size,
timeout=timeout,
blob_mode=blob_mode,
blob_sources=blob_sources,
schema=schema,
)
return self._batches_in_mode(reader, blob_mode, blob_sources)
def rerank(self, reranker: Reranker) -> LanceEmptyQueryBuilder:
"""Rerank the results using the specified reranker.
@@ -3155,11 +3260,14 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
timeout: Optional[timedelta] = None,
blob_mode: BlobMode = "lazy",
) -> pa.Table:
blob_sources = self._validated_blob_sources(blob_mode)
blob_sources, schema = self._prepare_blob_execution(blob_mode)
# WAL-PK-FUSION: without the fallback, this body is `_run_hybrid`'s.
return _wal_hybrid.with_pk_fallback(
lambda: self._run_hybrid(
timeout=timeout, blob_mode=blob_mode, blob_sources=blob_sources
timeout=timeout,
blob_mode=blob_mode,
blob_sources=blob_sources,
schema=schema,
),
self._table,
fused=lambda: self._pk_fusion is not None,
@@ -3172,6 +3280,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
timeout: Optional[timedelta] = None,
blob_mode: BlobMode,
blob_sources: dict[str, str],
schema: Optional[pa.Schema],
) -> pa.Table:
self._create_query_builders()
fts_query, vector_query = self._fts_query, self._vector_query
@@ -3201,7 +3310,10 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
)
results = _merge_query_snapshot(results, fts_results, vector_results)
return self._finish_hybrid_results(
results, blob_mode=blob_mode, blob_sources=blob_sources
results,
blob_mode=blob_mode,
blob_sources=blob_sources,
schema=schema,
)
def _finish_hybrid_results(
@@ -3210,6 +3322,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
*,
blob_mode: BlobMode,
blob_sources: dict[str, str],
schema: Optional[pa.Schema],
) -> pa.Table:
if self._pk_fusion is not None: # WAL-PK-FUSION: delete.
return self._apply_arrow_blob_mode(
@@ -3217,9 +3330,12 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
)
if self._user_requested_row_id():
return self._apply_arrow_blob_mode(results, blob_mode, blob_sources)
if self._blob_auto_row_id_enabled():
if self._blob_auto_row_id_enabled(schema):
return self._finalize_blob_query_table(
results, blob_mode=blob_mode, blob_sources=blob_sources
results,
blob_mode=blob_mode,
blob_sources=blob_sources,
schema=schema,
)
if "_rowid" in results.column_names:
# Fetch bytes before dropping _rowid.
@@ -3853,6 +3969,8 @@ class AsyncQueryBase(object):
self._with_row_id = None
self._blob_auto_row_id = False
self._blob_paths: tuple[str, ...] = ()
# Set by the sync table path, which has already prepared blob row ids.
self._blob_row_id_prepared = False
def to_query_object(self) -> Query:
"""
@@ -3915,6 +4033,26 @@ 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:
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,
projection,
with_row_id=self._with_row_id,
)
if not self._blob_auto_row_id:
self._blob_paths = ()
return
self._blob_paths = tuple(blob_v2_projection_sources(schema, projection).keys())
self._inner.with_row_id()
async def _can_fetch_plain_legacy_blobs(self, blob_mode: BlobMode) -> bool:
if blob_mode != "bytes" or self._table is None:
return False
@@ -4097,10 +4235,23 @@ class AsyncQueryBase(object):
) -> pa.Table:
"""Execute with the native eager collector used by ``to_arrow``."""
self._ensure_fragment_constraints_supported("to_arrow()")
await self._maybe_add_blob_row_id()
if not self._blob_row_id_prepared:
await self._maybe_add_blob_row_id()
reader = await self._inner.execute_to_reader(None, timeout)
return pa.Table.from_batches(reader, schema=reader.schema)
def _execute_eager_sync(
self,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
"""Execute with the synchronous native eager collector."""
self._ensure_fragment_constraints_supported("to_arrow()")
if not self._blob_row_id_prepared:
self._maybe_add_blob_row_id_sync()
reader = self._inner.execute_to_reader_sync(None, timeout)
return pa.Table.from_batches(reader, schema=reader.schema)
async def _execute_batches(
self,
*,
@@ -4125,7 +4276,8 @@ class AsyncQueryBase(object):
max_batch_length=max_batch_length,
timeout=timeout,
)
await self._maybe_add_blob_row_id()
if not self._blob_row_id_prepared:
await self._maybe_add_blob_row_id()
return AsyncRecordBatchReader(
await self._inner.execute(
max_batch_length=max_batch_length, timeout=timeout
@@ -4998,6 +5150,22 @@ class AsyncFTSQuery(AsyncStandardQuery):
results = _merge_query_snapshot(results, source)
return results
def _execute_eager_sync(
self,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
try:
results = super()._execute_eager_sync(timeout=timeout)
except Exception as error:
_add_fts_position_error_note(error)
raise
if self._reranker:
source = results
results = self._reranker.rerank_fts(self.get_query(), results)
results = _merge_query_snapshot(results, source)
return results
async def _execute_batches(
self,
*,
@@ -5360,6 +5528,18 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
results = _merge_query_snapshot(results, source)
return results
def _execute_eager_sync(
self,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
results = super()._execute_eager_sync(timeout=timeout)
if self._reranker:
source = results
results = self._reranker.rerank_vector(self._query_string, results)
results = _merge_query_snapshot(results, source)
return results
async def _execute_batches(
self,
*,
+16
View File
@@ -641,6 +641,8 @@ class RemoteDBConnection(DBConnection):
storage_options: Optional[Dict[str, str]] = None,
data_storage_version: Optional[str] = None,
enable_v2_manifest_paths: Optional[bool] = None,
initial_bases: Optional[List[Any]] = None,
allow_external_blob_outside_bases: bool = False,
) -> Table:
"""Create a [Table][lancedb.table.Table] in the database.
@@ -686,6 +688,10 @@ class RemoteDBConnection(DBConnection):
Not supported in LanceDB Enterprise. Raises NotImplementedError.
enable_v2_manifest_paths: bool, optional
Not supported in LanceDB Enterprise. Raises NotImplementedError.
initial_bases: list, optional
Not supported in LanceDB Enterprise. Raises NotImplementedError.
allow_external_blob_outside_bases: bool, default False
Not supported in LanceDB Enterprise. Raises NotImplementedError.
Returns
-------
@@ -761,6 +767,16 @@ class RemoteDBConnection(DBConnection):
f"{option} is not supported for table creation in "
"LanceDB Enterprise"
)
if initial_bases:
raise NotImplementedError(
"initial_bases is not supported for table creation in "
"LanceDB Enterprise"
)
if allow_external_blob_outside_bases:
raise NotImplementedError(
"allow_external_blob_outside_bases is not supported for table "
"creation in LanceDB Enterprise"
)
if exist_ok:
if mode == "create":
mode = "exist_ok"
+8 -2
View File
@@ -1556,9 +1556,15 @@ class RemoteTable(Table):
return LOOP.run(self._table.uri())
def take_offsets(
self, offsets: list[int], *, with_row_id: bool = False
self,
offsets: list[int],
*,
with_row_id: bool = False,
preserve_order: bool = False,
) -> LanceTakeQueryBuilder:
builder = LanceTakeQueryBuilder(self._table.take_offsets(offsets))
builder = LanceTakeQueryBuilder(
self._table.take_offsets(offsets, preserve_order=preserve_order)
)
if with_row_id:
builder.with_row_id()
return builder
+199
View File
@@ -6,6 +6,7 @@
import ctypes
import importlib
from dataclasses import dataclass
from typing import TYPE_CHECKING, Iterable, Optional
import pyarrow as pa
@@ -27,6 +28,78 @@ _BLOB_V2_STORAGE_TYPE = pa.struct(
]
)
_resolved_blob_type = None
_UINT32_MAX = 0xFFFF_FFFF
_UINT64_MAX = 0xFFFF_FFFF_FFFF_FFFF
@dataclass(frozen=True)
class BasePath:
"""A storage base registered on a table at creation time.
Use with the ``initial_bases`` argument of
[create_table][lancedb.db.DBConnection.create_table] to make
external blob URIs resolve under a shared prefix: descriptors that fall
under ``path`` are stored relative to it instead of as absolute URIs.
This is a lightweight stand-in for ``lance.DatasetBasePath`` that does
not require pylance. Both classes, and equivalent dictionaries, are
accepted by the create APIs.
Parameters
----------
path:
Full URI of the base (for example ``s3://bucket/prefix`` or a
``file://`` URI). A blob URI under this prefix is stored relative to
it.
name:
Optional human-readable name for the base.
is_dataset_root:
Whether the base uses the dataset-root layout. Defaults to ``False``.
Bases registered here must leave this ``False``: Lance only resolves
external blob URIs against non-root bases.
id:
Base ID used by scoped storage options such as ``base_<id>.region``.
``None`` lets Lance assign a non-zero ID. ``0`` is reserved for
absolute (unregistered) URIs and is rejected.
When supplying IDs for multiple bases, use distinct explicit non-zero
IDs. The pinned Lance release can collide when one base uses automatic
allocation and another supplies an explicit ID; the create fails, the
table name can remain listed but unopenable, and retrying with distinct
explicit IDs succeeds. Automatic allocation for every base is
supported.
"""
path: str
name: Optional[str] = None
is_dataset_root: bool = False
id: Optional[int] = None
def __post_init__(self) -> None:
if not isinstance(self.path, str):
raise TypeError(f"path must be a string, got {type(self.path).__name__}")
if not self.path:
raise ValueError("path must not be empty")
if self.name is not None and not isinstance(self.name, str):
raise TypeError(f"name must be a string, got {type(self.name).__name__}")
if not isinstance(self.is_dataset_root, bool):
raise TypeError(
"is_dataset_root must be a bool, got "
f"{type(self.is_dataset_root).__name__}"
)
if self.id is None:
return
if isinstance(self.id, bool) or not isinstance(self.id, int):
raise TypeError(f"id must be an int or None, got {type(self.id).__name__}")
if self.id == 0:
raise ValueError(
"id=0 is reserved for unregistered blob URIs; "
"pass id=None to let Lance assign an ID"
)
if self.id < 0:
raise ValueError("id must be a positive integer")
if self.id > _UINT32_MAX:
raise ValueError("id must fit in a 32-bit unsigned integer")
class _FallbackBlobType(pa.ExtensionType):
@@ -344,6 +417,132 @@ def blob_array(payloads: Iterable[Optional[bytes]]) -> pa.ExtensionArray:
return pa.ExtensionArray.from_storage(blob_type, storage)
def _blob_uint64(value: object, what: str) -> int:
if isinstance(value, bool) or not isinstance(value, int):
raise TypeError(f"{what} must be an int, got {type(value).__name__}")
if value < 0:
raise ValueError(f"{what} must be non-negative")
if value > _UINT64_MAX:
raise OverflowError(f"{what} must fit in a uint64")
return value
def blob_uri_array(
uris: Iterable[Optional[str]],
*,
positions: Optional[Iterable[Optional[int]]] = None,
sizes: Optional[Iterable[Optional[int]]] = None,
) -> pa.ExtensionArray:
"""Build a Lance blob v2 extension array from external URIs.
Produces the standard four-field blob v2 storage (``data=None``, ``uri``,
nullable ``position`` and ``size``) without requiring pylance, so the
result can be used directly in Arrow record batches and combined with
field metadata such as ``lancedb:logical_type="mp4"``.
A row without ``position`` and ``size`` references the whole object; a
row with both reads exactly that byte range. Register the object prefix
with [BasePath][lancedb.schema.BasePath] at table creation to store a
matched URI relative to a base, or enable
``allow_external_blob_outside_bases`` on the write that inserts the row to
keep the absolute URI when no base matches. The opt-in covers that one
write; a later ``add()`` must enable it again.
Parameters
----------
uris:
An iterable of absolute URI strings or ``None`` for a null blob. A
URI under a registered base is matched and stored in the descriptor
relative to that base. An unmatched URI requires the write that
inserts the row to opt in with
``allow_external_blob_outside_bases``, and must always be a valid
absolute URI.
positions:
Optional byte offsets, one per URI. Provide together with ``sizes``;
each entry is an ``int`` or ``None``. A range requires both fields.
sizes:
Optional range lengths in bytes, one per URI. Must be positive when
``position`` is set.
Returns
-------
pa.ExtensionArray
external blob values ready to use in Arrow tables or record batches.
Raises
------
TypeError
If a URI, position, or size has the wrong type.
ValueError
If lengths differ, only one of ``positions``/``sizes`` is given, a
range is incomplete, a size is not positive, or a range is given for
a null URI.
OverflowError
If a position or size does not fit in a uint64.
Examples
--------
>>> import pyarrow as pa
>>> from lancedb.schema import blob, blob_uri_array
>>> schema = pa.schema([blob("video")])
>>> videos = blob_uri_array(
... ["s3://bucket/a.mp4", "hf://datasets/org/repo@abc/b.mp4"],
... positions=[0, 8],
... sizes=[4, 4],
... )
>>> batch = pa.RecordBatch.from_arrays([videos], schema=schema)
>>> batch.num_rows
2
"""
uri_list = list(uris)
if positions is None and sizes is None:
ranges = [(None, None)] * len(uri_list)
elif positions is None or sizes is None:
raise ValueError("positions and sizes must be provided together")
else:
position_list = list(positions)
size_list = list(sizes)
if len(position_list) != len(uri_list):
raise ValueError(
"positions must have the same length as uris, got "
f"{len(position_list)} and {len(uri_list)}"
)
if len(size_list) != len(uri_list):
raise ValueError(
"sizes must have the same length as uris, got "
f"{len(size_list)} and {len(uri_list)}"
)
ranges = list(zip(position_list, size_list, strict=True))
descriptors = []
for index, (uri, (position, size)) in enumerate(zip(uri_list, ranges, strict=True)):
if uri is None:
if position is not None or size is not None:
raise ValueError(
f"uris[{index}] is None but a position or size was provided"
)
descriptors.append(None)
continue
if not isinstance(uri, str):
raise TypeError(f"uris[{index}] must be a string, got {type(uri).__name__}")
if position is None and size is None:
descriptors.append({"uri": uri})
continue
if position is None or size is None:
raise ValueError(
f"uris[{index}] must set both position and size or neither"
)
position = _blob_uint64(position, f"positions[{index}]")
size = _blob_uint64(size, f"sizes[{index}]")
if size == 0:
raise ValueError(f"sizes[{index}] must be positive to read a byte range")
descriptors.append({"uri": uri, "position": position, "size": size})
blob_type = _resolve_blob_type()()
storage = pa.array(descriptors, type=blob_type.storage_type)
return pa.ExtensionArray.from_storage(blob_type, storage)
def vector(dimension: int, value_type: pa.DataType = pa.float32()) -> pa.DataType:
"""A help function to create a vector type.
+125 -14
View File
@@ -2660,7 +2660,11 @@ class Table(ABC):
@abstractmethod
def take_offsets(
self, offsets: list[int], *, with_row_id: bool = False
self,
offsets: list[int],
*,
with_row_id: bool = False,
preserve_order: bool = False,
) -> LanceTakeQueryBuilder:
"""
Take a list of offsets from the table.
@@ -2672,9 +2676,13 @@ class Table(ABC):
Offsets are mostly useful for sampling as the set of all valid offsets is easily
known in advance to be [0, len(table)).
No guarantees are made regarding the order in which results are returned.
Repeated offsets produce repeated rows, which makes this method suitable for
sampling with replacement.
By default, no guarantees are made regarding the order in which results
are returned. Repeated offsets produce repeated rows, which makes this
method suitable for sampling with replacement. Set ``preserve_order=True``
to return found rows in input order, including repeated offsets. Missing
non-negative offsets are omitted. Negative offsets are rejected and are
not Python-style relative indices. ``preserve_order`` cannot be combined
with an explicit ``order_by``.
Parameters
----------
@@ -2682,6 +2690,10 @@ class Table(ABC):
The offsets to take.
with_row_id: bool, default False
If True, include the "_rowid" column in the results.
preserve_order: bool, default False
If True, return found rows in input order. Rust take queries apply
limit/offset after restoration; Python take builders and Query
conversion do not expose pagination.
Returns
-------
@@ -2802,6 +2814,15 @@ class Table(ABC):
One missing or deleted row ID rejects the entire batch; no partial
results are returned.
A query result table that carries snapshot metadata keeps the snapshot
that produced it on LanceDB Enterprise. A query result without that
metadata, including a legacy query response, and a plain list are read
from the table's current snapshot; keep the source unchanged between
selection and fetching. Partial snapshot metadata is rejected. Row
positions are not row IDs: to read by position, call
``table.take_offsets(offsets, with_row_id=True)`` first and pass the
resulting ``_rowid`` values.
Blobs inside lists cannot be fetched by row id yet.
LanceDB Enterprise limits each request to 1024 row IDs and 64 MiB of blob
@@ -2868,6 +2889,17 @@ class Table(ABC):
row ids.
One missing or deleted row ID rejects the entire batch; no partial
handles are returned.
A query result table that carries snapshot metadata keeps the snapshot
that produced it on LanceDB Enterprise, so every returned handle reads
that snapshot. Metadata-free query results, including legacy server
responses, and plain lists are read from the table's current snapshot.
Partial snapshot metadata is rejected. A snapshot-bound handle fails
explicitly when the serving node cannot echo the query snapshot
identity; the 0.5.0 floor covers the basic remote Blob API but not that
echo. Row positions are not row IDs: call
``table.take_offsets(offsets, with_row_id=True)`` first and pass the
resulting ``_rowid`` values.
"""
@abstractmethod
@@ -4501,7 +4533,10 @@ class LanceTable(Table):
-------
pa.Schema
A PyArrow schema object."""
return LOOP.run(self._table.schema())
schema_sync = getattr(self._table, "_schema_sync", None)
if schema_sync is None:
return LOOP.run(self._table.schema())
return schema_sync()
def list_versions(self) -> List[Dict[str, Any]]:
"""List all versions of the table"""
@@ -4513,9 +4548,15 @@ class LanceTable(Table):
return LOOP.run(self._table.version())
def take_offsets(
self, offsets: list[int], *, with_row_id: bool = False
self,
offsets: list[int],
*,
with_row_id: bool = False,
preserve_order: bool = False,
) -> LanceTakeQueryBuilder:
builder = LanceTakeQueryBuilder(self._table.take_offsets(offsets))
builder = LanceTakeQueryBuilder(
self._table.take_offsets(offsets, preserve_order=preserve_order)
)
if with_row_id:
builder.with_row_id()
return builder
@@ -5727,8 +5768,16 @@ class LanceTable(Table):
"""
if isinstance(query, FullTextQuery):
query_type = "fts"
if (
vector_column_name is None
and query_type != "fts"
and not (query is None and query_type != "hybrid")
):
schema = self.schema
else:
schema = None
vector_column_name = infer_vector_column_name(
schema=self.schema,
schema=schema,
query_type=query_type,
query=query,
vector_column_name=vector_column_name,
@@ -5766,6 +5815,8 @@ class LanceTable(Table):
namespace_client: Optional[Any] = None,
pushdown_operations: Optional[set] = None,
route_pushdown_to_rust: bool = False,
initial_bases: Optional[List[Any]] = None,
allow_external_blob_outside_bases: bool = False,
):
"""
Create a new table.
@@ -5819,6 +5870,20 @@ class LanceTable(Table):
enable_v2_manifest_paths: optional, bool, default False
Deprecated. Set `storage_options` when connecting to the database and set
`new_table_enable_v2_manifest_paths` in the options.
initial_bases: list, optional
Storage bases to register in the table's manifest in the same
commit that creates it. Each entry can be a
[BasePath][lancedb.schema.BasePath], a dict with `path`, `name`,
`is_dataset_root`, and `id` keys, or a `lance.DatasetBasePath`.
Blob URIs under a registered base are stored relative to it. When
supplying IDs for multiple bases, use distinct explicit non-zero
IDs; [BasePath][lancedb.schema.BasePath] describes the pinned-Lance
limitation.
allow_external_blob_outside_bases: bool, default False
Store blob URIs that do not fall under a registered base. The row
keeps a reference, so the objects have to stay readable. The
opt-in applies only to the initial data; a later `add()` must
enable it again.
"""
if namespace_path is None:
namespace_path = []
@@ -5870,6 +5935,8 @@ class LanceTable(Table):
storage_options=storage_options,
location=location,
namespace_client=namespace_client,
initial_bases=initial_bases,
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
)
)
self._branch = self._table.current_branch()
@@ -5995,6 +6062,14 @@ class LanceTable(Table):
return self._execute_query(query, timeout=timeout).read_all()
async_query = self._table._sync_query_to_async(query)
async_query._blob_row_id_prepared = query._blob_row_id_prepared
if (
self._table._inner._is_native()
and self._namespace_client is None
and not self._route_pushdown_to_rust
and isinstance(async_query, (AsyncQuery, AsyncVectorQuery, AsyncFTSQuery))
):
return async_query._execute_eager_sync(timeout=timeout)
return LOOP.run(async_query._execute_eager(timeout=timeout))
def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str:
@@ -7365,6 +7440,9 @@ class AsyncTable:
"""
return _restore_blob_extensions(await self._inner.schema())
def _schema_sync(self) -> pa.Schema:
return _restore_blob_extensions(self._inner.schema_sync())
async def embedding_functions(self) -> Dict[str, EmbeddingFunctionConfig]:
"""
Get the embedding functions for the table
@@ -8402,10 +8480,18 @@ class AsyncTable:
if query.take_offsets is not None or query.take_row_ids is not None:
if query.take_offsets is not None and query.take_row_ids is not None:
raise ValueError("Only one of take_offsets and take_row_ids may be set")
if query.preserve_order is True and query.take_offsets is None:
raise ValueError("preserve_order only supports take_offsets")
if query.preserve_order is True and query.order_by:
raise ValueError(
"preserve_order cannot be combined with an explicit order_by"
)
take_query = (
self.take_row_ids(query.take_row_ids)
if query.take_row_ids is not None
else self.take_offsets(query.take_offsets)
else self.take_offsets(
query.take_offsets, preserve_order=query.preserve_order is True
)
)
if query.columns is not None:
columns = query.columns
@@ -8509,6 +8595,7 @@ class AsyncTable:
# used for that code path right now.
async_query = self._sync_query_to_async(query)
async_query._blob_row_id_prepared = query._blob_row_id_prepared
return await async_query.to_batches(
max_batch_length=batch_size, timeout=timeout
@@ -8530,6 +8617,7 @@ class AsyncTable:
return (await self._execute_query(query, timeout=timeout)).read_all()
async_query = self._sync_query_to_async(query)
async_query._blob_row_id_prepared = query._blob_row_id_prepared
return await async_query._execute_eager(timeout=timeout)
async def _explain_plan(self, query: Query, verbose: Optional[bool]) -> str:
@@ -9613,7 +9701,11 @@ class AsyncTable:
await self._inner.restore(version)
def take_offsets(
self, offsets: list[int], *, with_row_id: bool = False
self,
offsets: list[int],
*,
with_row_id: bool = False,
preserve_order: bool = False,
) -> AsyncTakeQuery:
"""
Take a list of offsets from the table.
@@ -9625,8 +9717,12 @@ class AsyncTable:
Offsets are mostly useful for sampling as the set of all valid offsets is easily
known in advance to be [0, len(table)).
No guarantees are made regarding the order in which results are returned.
Repeated offsets produce repeated rows.
By default, no guarantees are made regarding the order in which results
are returned. Repeated offsets produce repeated rows. Set
``preserve_order=True`` to return found rows in input order, including
repeated offsets. Missing non-negative offsets are omitted. Negative
offsets are rejected and are not Python-style relative indices.
``preserve_order`` cannot be combined with an explicit ``order_by``.
Parameters
----------
@@ -9634,6 +9730,10 @@ class AsyncTable:
The offsets to take.
with_row_id: bool, default False
If True, include the "_rowid" column in the results.
preserve_order: bool, default False
If True, return found rows in input order. Rust take queries apply
limit/offset after restoration; Python take builders and Query
conversion do not expose pagination.
Returns
-------
@@ -9642,6 +9742,8 @@ class AsyncTable:
offsets.
"""
query = AsyncTakeQuery(self._inner.take_offsets(offsets), self)
if preserve_order:
query._inner.preserve_order()
if with_row_id:
query.with_row_id()
return query
@@ -9693,8 +9795,12 @@ class AsyncTable:
column: str,
row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table],
) -> pa.LargeBinaryArray:
selection = _normalize_blob_row_ids(row_ids, column)
return await self._inner.fetch_blobs(
column, _normalize_blob_row_ids(row_ids, column)
column,
selection.row_ids,
version=selection.version,
snapshot_identity=selection.snapshot_identity,
)
async def fetch_blob_ranges(
@@ -9720,8 +9826,13 @@ class AsyncTable:
See [Table.fetch_blob_files][lancedb.table.Table.fetch_blob_files].
"""
buffer_size = _validate_blob_buffer_size(buffer_size)
selection = _normalize_blob_row_ids(row_ids, column)
handles = await self._inner.fetch_blob_files(
column, _normalize_blob_row_ids(row_ids, column), buffer_size
column,
selection.row_ids,
buffer_size=buffer_size,
version=selection.version,
snapshot_identity=selection.snapshot_identity,
)
return _wrap_blob_files(handles)
+332 -32
View File
@@ -8,9 +8,11 @@ import importlib
import math
import os
import pathlib
import sys
import warnings
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from enum import Enum
from functools import singledispatch
from typing import Tuple, Union, Optional, Any, List
from urllib.parse import urlparse
@@ -328,7 +330,7 @@ def _query_vector_dim(query: Optional[Any]) -> Optional[int]:
def infer_vector_column_name(
schema: pa.Schema,
schema: Optional[pa.Schema],
query_type: str,
query: Optional[Any], # inferred later in query builder
vector_column_name: Optional[str],
@@ -348,6 +350,8 @@ def infer_vector_column_name(
# nothing to infer.
return None
if schema is None:
raise ValueError("schema is required to infer a vector column")
vector_column_name = inf_vector_column_query(schema, dim=_query_vector_dim(query))
if vector_column_name is None:
@@ -382,7 +386,8 @@ def _(value: bytes):
@value_to_sql.register(int)
def _(value: int):
return str(value)
# int() first: str() of an int-valued Enum member is its name, e.g. "P.HIGH".
return str(int(value))
@value_to_sql.register(float)
@@ -394,7 +399,7 @@ def _(value: float):
return (
"CAST('Infinity' AS DOUBLE)" if value > 0 else "CAST('-Infinity' AS DOUBLE)"
)
return str(value)
return str(float(value))
@value_to_sql.register(Decimal)
@@ -415,6 +420,12 @@ def _(value: type(None)):
return "NULL"
@value_to_sql.register(Enum)
def _(value: Enum):
# Write the member's value, as model_to_dict does for a LanceModel field.
return value_to_sql(value.value)
@value_to_sql.register(datetime)
def _(value: datetime):
return f"'{value.isoformat()}'"
@@ -601,15 +612,253 @@ def tbl_to_tensor(tbl: pa.Table):
return torch.stack([to_tensor(tbl.column(i)) for i in range(tbl.num_columns)])
_BFLOAT16_EXTENSION_NAME = "lance.bfloat16"
_ARROW_EXTENSION_NAME_KEY = "ARROW:extension:name"
def _field_metadata_value(field: pa.Field, key: str):
metadata = field.metadata or {}
value = metadata.get(key.encode()) or metadata.get(key)
if isinstance(value, bytes):
return value.decode()
return value
def _field_extension_name(field: pa.Field) -> Optional[str]:
extension_name = _field_metadata_value(field, _ARROW_EXTENSION_NAME_KEY)
if extension_name is not None:
return extension_name
if isinstance(field.type, pa.ExtensionType):
return field.type.extension_name
return None
def _field_storage_type(field: pa.Field) -> pa.DataType:
if isinstance(field.type, pa.ExtensionType):
return field.type.storage_type
return field.type
def _is_bfloat16_field(field: pa.Field) -> bool:
if _field_extension_name(field) != _BFLOAT16_EXTENSION_NAME:
return False
storage_type = _field_storage_type(field)
return pa.types.is_fixed_size_binary(storage_type) and storage_type.byte_width == 2
def _check_torch_nulls(array: pa.Array, column_name: str) -> None:
if array.null_count:
raise ValueError(
f"Cannot convert column `{column_name}` to a torch tensor because it "
f"contains {array.null_count} null value(s). Drop or fill nulls before "
"using a torch format."
)
def _bfloat16_to_tensor(array: pa.Array, torch, column_name: str):
storage = array.storage if isinstance(array.type, pa.ExtensionType) else array
storage_type = storage.type
if not (
pa.types.is_fixed_size_binary(storage_type) and storage_type.byte_width == 2
):
raise ValueError(
f"Column `{column_name}` is marked as {_BFLOAT16_EXTENSION_NAME!r} but "
f"has storage type {storage_type}. The lance.bfloat16 extension requires "
"fixed_size_binary[2] storage."
)
_check_torch_nulls(storage, column_name)
if len(storage) == 0:
return torch.empty((0,), dtype=torch.bfloat16)
buffer = storage.buffers()[1]
if buffer is None:
return torch.empty((0,), dtype=torch.bfloat16)
offset = storage.offset * 2
byte_length = len(storage) * 2
if buffer.size < offset + byte_length:
raise ValueError(
f"Column `{column_name}` has a truncated bfloat16 value buffer."
)
# Arrow stores bfloat16 as two little-endian bytes. Copy only on big-endian
# hosts before viewing the same bits as torch.bfloat16.
values = np.frombuffer(
buffer, dtype=np.dtype("<u2"), count=len(storage), offset=offset
)
if sys.byteorder != "little":
values = values.astype(np.uint16)
# Older torch releases cannot create a tensor from np.uint16, so view the
# same bits as signed 16-bit values before interpreting them as bfloat16.
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
message="The given NumPy array is not writable",
category=UserWarning,
)
return torch.from_numpy(values.view(np.int16)).view(torch.bfloat16)
def _leaf_to_tensor(array: pa.Array, field: pa.Field, torch, column_name: str):
_check_torch_nulls(array, column_name)
if _is_bfloat16_field(field):
return _bfloat16_to_tensor(array, torch, column_name)
data_type = array.type
if isinstance(data_type, pa.ExtensionType):
raise ValueError(
f"Unsupported PyTorch column type {data_type} for column "
f"`{column_name}`. Supported extension types are "
f"{_BFLOAT16_EXTENSION_NAME!r} and arrow.fixed_shape_tensor."
)
if (
pa.types.is_boolean(data_type)
or pa.types.is_integer(data_type)
or pa.types.is_floating(data_type)
):
# Arrow packs booleans as bits while torch uses one byte per value, so
# boolean columns always need a copy. Other numeric columns share the
# Arrow buffer.
zero_copy_only = not pa.types.is_boolean(data_type)
try:
numpy_values = array.to_numpy(zero_copy_only=zero_copy_only)
except pa.ArrowInvalid as err:
raise ValueError(
f"Cannot convert column `{column_name}` of type {data_type} to a "
f"torch tensor without copying: {err}"
) from err
try:
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
message="The given NumPy array is not writable",
category=UserWarning,
)
return torch.from_numpy(numpy_values)
except (TypeError, RuntimeError) as err:
raise ValueError(
f"Cannot convert column `{column_name}` of type {data_type} to a "
f"torch tensor: {err}"
) from err
if pa.types.is_fixed_size_binary(data_type) and data_type.byte_width == 2:
raise ValueError(
f"Column `{column_name}` has type fixed_size_binary[2] but is not "
f"marked with {_ARROW_EXTENSION_NAME_KEY!r} = "
f"{_BFLOAT16_EXTENSION_NAME!r}. An unmarked binary column is not "
"treated as bfloat16."
)
raise ValueError(
f"Unsupported PyTorch column type {data_type} for column `{column_name}`. "
"Supported leaf types are boolean, integer, floating point, and "
f"{_BFLOAT16_EXTENSION_NAME!r} fixed_size_binary[2] values."
)
def _fixed_size_list_to_tensor(array: pa.FixedSizeListArray, torch, column_name: str):
_check_torch_nulls(array, column_name)
width = array.type.list_size
values = array.values.slice(array.offset * width, len(array) * width)
child_tensor = _arrow_column_to_tensor(
values, array.type.value_field, torch, column_name
)
return child_tensor.reshape((len(array), width, *child_tensor.shape[1:]))
def _fixed_shape_tensor_to_tensor(array: pa.Array, torch, column_name: str):
_check_torch_nulls(array, column_name)
tensor_type = array.type
storage = array.storage
physical_shape = list(tensor_type.shape)
permutation = list(getattr(tensor_type, "permutation", None) or [])
storage_tensor = _arrow_column_to_tensor(
storage, storage.type.value_field, torch, column_name
)
tensor = storage_tensor.reshape((len(array), *physical_shape))
if permutation:
# Arrow's ``shape`` is the physical row-major shape, and
# ``permutation`` maps a logical axis to its physical axis. Transposing
# by it restores the logical shape as a view.
tensor = tensor.permute([0] + [axis + 1 for axis in permutation])
return tensor
def _arrow_column_to_tensor(array: pa.Array, field: pa.Field, torch, column_name: str):
if isinstance(array.type, pa.FixedShapeTensorType):
return _fixed_shape_tensor_to_tensor(array, torch, column_name)
if pa.types.is_fixed_size_list(array.type):
return _fixed_size_list_to_tensor(array, torch, column_name)
return _leaf_to_tensor(array, field, torch, column_name).reshape((len(array),))
def _is_nullable_numeric_scalar(array: pa.Array) -> bool:
data_type = array.type
if isinstance(data_type, pa.ExtensionType) or array.null_count == 0:
return False
return pa.types.is_integer(data_type) or pa.types.is_floating(data_type)
def _nullable_numeric_scalar_to_tensor(array: pa.Array, torch, column_name: str):
try:
numpy_values = array.to_numpy(zero_copy_only=False)
except pa.ArrowInvalid as err:
raise ValueError(
f"Cannot convert nullable column `{column_name}` of type {array.type} "
f"to a torch tensor: {err}"
) from err
try:
return torch.from_numpy(numpy_values)
except (TypeError, RuntimeError) as err:
raise ValueError(
f"Cannot convert nullable column `{column_name}` of type {array.type} "
f"to a torch tensor: {err}"
) from err
def _batch_column_tensors(batch: pa.RecordBatch, allow_scalar_nulls: bool = False):
torch = attempt_import_or_raise("torch", "torch")
columns = []
for field, column in zip(batch.schema, batch.columns):
if allow_scalar_nulls and _is_nullable_numeric_scalar(column):
tensor = _nullable_numeric_scalar_to_tensor(column, torch, field.name)
else:
tensor = _arrow_column_to_tensor(column, field, torch, field.name)
columns.append((field.name, tensor))
return torch, columns
def _uniform_column_tensors(
batch: pa.RecordBatch, format_name: str, allow_scalar_nulls: bool = False
):
torch, columns = _batch_column_tensors(batch, allow_scalar_nulls=allow_scalar_nulls)
if len(columns) <= 1:
return torch, columns
first_name, first = columns[0]
first_shape = tuple(first.shape[1:])
for name, tensor in columns[1:]:
shape = tuple(tensor.shape[1:])
if shape != first_shape:
raise ValueError(
f"Cannot use the {format_name!r} format because column `{name}` "
f"has sample shape {shape} while column `{first_name}` has sample "
f'shape {first_shape}. Use with_format("torch_dict") for columns '
'with different shapes, or with_format("torch") for a list of '
"per-row dicts."
)
return torch, columns
def batch_to_tensor(batch: pa.RecordBatch):
"""
Convert a PyArrow RecordBatch to a PyTorch Tensor.
Each column is converted to a tensor (using zero-copy via DLPack)
and the columns are then stacked into a single tensor.
Each column is converted to a tensor with shape ``(rows, *sample_shape)``
and the columns are stacked along a new leading dimension. Scalar columns
have sample shape ``()`` and fixed-size-list columns contribute each list
dimension. All columns must have the same sample shape.
Fails if torch is not installed.
Fails if a column's data type is not supported by PyTorch.
Fails if a column contains nulls.
Parameters
----------
@@ -618,43 +867,99 @@ def batch_to_tensor(batch: pa.RecordBatch):
Returns
-------
torch.Tensor: The tensor containing the columns of the record batch.
torch.Tensor: A tensor with shape ``(columns, rows, *sample_shape)``. A
one-column batch returns an ``unsqueeze(0)`` view of that column.
"""
torch = attempt_import_or_raise("torch", "torch")
return torch.stack([torch.from_dlpack(col) for col in batch.columns])
torch, columns = _uniform_column_tensors(batch, "torch_col")
if not columns:
return torch.empty((0, batch.num_rows))
if len(columns) == 1:
return columns[0][1].unsqueeze(0)
return torch.stack([tensor for _, tensor in columns], dim=0)
def batch_to_tensor_rows(batch: pa.RecordBatch):
"""
Convert a PyArrow RecordBatch to a list of PyTorch Tensor, one per row
Convert a PyArrow RecordBatch to a list of PyTorch Tensors, one per row.
Each column is converted to a tensor (using zero-copy via DLPack)
and the columns are then stacked into a single tensor. The 2D tensor
is then converted to a list of tensors, one per row
Each row tensor has shape ``(columns, *sample_shape)``. All columns must
have the same sample shape, so a table mixing scalar and vector columns
should use ``torch_dict`` or ``torch`` instead. Dtypes are combined with
``torch.promote_types``, matching PyTorch's numeric promotion rules.
Fails if torch or numpy is not installed.
Fails if torch is not installed.
Fails if a column's data type is not supported by PyTorch.
Nulls in ordinary integer or floating scalar columns become ``NaN``.
Nulls in nested fixed-size-list or tensor columns are rejected.
Parameters
----------
batch : pa.RecordBatch
The record batch to convert.
Returns
-------
list[torch.Tensor]
One tensor per row, each with shape ``(columns, *sample_shape)``. A
one-column scalar batch produces ``(1,)`` tensors.
"""
torch = attempt_import_or_raise("torch", "torch")
numpy = attempt_import_or_raise("numpy", "numpy")
columns = [col.to_numpy(zero_copy_only=False) for col in batch.columns]
stacked = torch.tensor(numpy.column_stack(columns))
rows = list(stacked.unbind(dim=0))
return rows
torch, columns = _uniform_column_tensors(
batch, "torch_row", allow_scalar_nulls=True
)
if not columns:
return [torch.empty((0,)) for _ in range(batch.num_rows)]
dtype = columns[0][1].dtype
for _, tensor in columns[1:]:
dtype = torch.promote_types(dtype, tensor.dtype)
tensors = [
tensor if tensor.dtype == dtype else tensor.to(dtype) for _, tensor in columns
]
stacked = torch.stack(tensors, dim=1)
return list(stacked.unbind(dim=0))
def batch_to_tensor_columns(batch: pa.RecordBatch):
"""
Convert a PyArrow RecordBatch to a dict of per-column PyTorch Tensors.
Each tensor has shape ``(rows, *sample_shape)`` and shares Arrow storage
where the layout allows it. Unlike ``torch_col`` and ``torch_row``, columns
may have different sample shapes. This is the transform behind
``Permutation.with_format("torch_dict")`` and can be consumed directly by
a ``DataLoader`` with an identity ``collate_fn``.
Fails if torch is not installed.
Fails if a column's data type is not supported by PyTorch.
Fails if a column contains nulls.
Parameters
----------
batch : pa.RecordBatch
The record batch to convert.
Returns
-------
dict[str, torch.Tensor]
A tensor per column, each with shape ``(rows, *sample_shape)``.
"""
_, columns = _batch_column_tensors(batch)
return dict(columns)
def batch_to_tensor_dict(batch: pa.RecordBatch):
"""
Convert a PyArrow RecordBatch to a list of per-row dicts of PyTorch Tensors.
Each column is first converted to a 1-D tensor (zero-copy via DLPack), then
sliced per row. The result is a list whose length is ``batch.num_rows`` and
whose items are dicts keyed by column name. This shape composes directly
with PyTorch's default ``DataLoader`` collate, which stacks the per-row
dicts back into a dict of batched tensors.
Each column is converted to a tensor with shape ``(rows, *sample_shape)``,
then sliced per row. The result is a list whose length is
``batch.num_rows`` and whose items are dicts keyed by column name. This
shape composes directly with PyTorch's default ``DataLoader`` collate,
which stacks the per-row dicts back into a dict of batched tensors.
Fails if torch is not installed.
Fails if a column's data type is not supported by PyTorch.
Fails if a column contains nulls.
Parameters
----------
@@ -665,14 +970,9 @@ def batch_to_tensor_dict(batch: pa.RecordBatch):
-------
list[dict[str, torch.Tensor]]
One per-row dict per row in the batch. Each dict maps column name to a
0-D tensor view into the column.
tensor view into the column.
"""
torch = attempt_import_or_raise("torch", "torch")
tensors = {
name: torch.from_dlpack(col)
for name, col in zip(batch.schema.names, batch.columns)
}
_, columns = _batch_column_tensors(batch)
return [
{name: tensor[i] for name, tensor in tensors.items()}
for i in range(batch.num_rows)
{name: tensor[i] for name, tensor in columns} for i in range(batch.num_rows)
]
+482 -1
View File
@@ -1017,6 +1017,11 @@ def test_take_queries_honor_blob_mode():
1: b"one",
2: b"two",
}
ordered = table.take_offsets([1, 0], preserve_order=True).to_arrow(
blob_mode="bytes"
)
assert ordered["id"].to_pylist() == [2, 1]
assert ordered["image"].to_pylist() == [b"two", b"one"]
assert [
row["image"] for row in table.take_row_ids([0]).to_list(blob_mode="bytes")
] == [b"one"]
@@ -1958,6 +1963,18 @@ def test_fetch_blob_apis_reject_missing_fragment_row_addr():
_assert_fetch_apis_reject_missing_row_ids(table, [1 << 32, live])
def test_fetch_blobs_missing_row_ids_suggest_take_offsets():
table = _blob_table(
"position_hint",
[{"id": i, "image": b"x"} for i in range(3)],
)
with pytest.raises(ValueError, match="take_offsets") as exc:
table.fetch_blobs("image", [10])
message = str(exc.value)
assert "first missing row ids: [10]" in message
assert "with_row_id=True" in message
def test_fetch_blob_apis_reject_deleted_row_ids():
table = _blob_table(
"deleted_rows",
@@ -2216,8 +2233,11 @@ def test_fetch_blobs_from_query_result_without_row_id_raises():
table = _blob_table("no_rowid", [{"id": 1, "image": b"x"}])
hits = table.search().select(["id"]).to_arrow()
assert "_rowid" not in hits.column_names
with pytest.raises(ValueError, match="_rowid"):
with pytest.raises(ValueError, match="take_offsets") as exc:
table.fetch_blobs("image", hits)
message = str(exc.value)
assert "with_row_id=True" in message
assert "list of row ids" in message
_HYBRID_BLOB_SCHEMA = pa.schema(
@@ -2384,6 +2404,77 @@ class _KeepAllScoresReranker(Reranker):
return combined.append_column("_relevance_score", scores)
class _RecordingVectorReranker(Reranker):
def __init__(self):
super().__init__(return_score="all")
self.calls = []
def rerank_hybrid(self, query, vector_results, fts_results):
raise AssertionError("vector queries must not call rerank_hybrid")
def rerank_vector(self, query, vector_results):
self.calls.append((query, vector_results))
return vector_results.append_column(
"_relevance_score",
pa.array([1.0] * len(vector_results), type=pa.float32()),
)
@pytest.mark.parametrize("blob_mode", ["descriptions", "bytes"])
def test_vector_to_arrow_reranks_before_blob_conversion(blob_mode, monkeypatch):
db = lancedb.connect("memory:///")
schema = pa.schema(
[
pa.field("id", pa.int64()),
pa.field("vector", pa.list_(pa.float32(), list_size=2)),
lancedb.blob("image"),
]
)
table = db.create_table(f"vector_rerank_{blob_mode}", schema=schema)
rows = 1100
table.add(
[
{
"id": row_id,
"vector": [1.0, float(row_id % 2)],
"image": f"image-{row_id}".encode(),
}
for row_id in range(rows)
]
)
fetched = []
fetch_blobs = table.fetch_blobs
def fetch(column, row_ids):
fetched.append((column, len(row_ids)))
return fetch_blobs(column, row_ids)
monkeypatch.setattr(table, "fetch_blobs", fetch)
reranker = _RecordingVectorReranker()
hits = (
table.search([1.0, 0.0])
.limit(rows)
.select(["id", "image"])
.rerank(reranker, "hello")
.to_arrow(blob_mode=blob_mode)
)
assert len(reranker.calls) == 1
query, source = reranker.calls[0]
assert query == "hello"
# The reranker sees descriptors, not already-converted payload bytes.
assert not pa.types.is_large_binary(source.schema.field("image").type)
assert "_relevance_score" in hits.column_names
assert len(hits) == rows
if blob_mode == "bytes":
# The whole lazy result is materialized before one aggregate conversion.
assert fetched == [("image", rows)]
assert pa.types.is_large_binary(hits.schema.field("image").type)
else:
assert fetched == []
assert not pa.types.is_large_binary(hits.schema.field("image").type)
def test_bytes_mode_rejects_legacy_blob_after_reranker_drops_metadata(tmp_path):
db = lancedb.connect(tmp_path)
table = db.create_table(
@@ -3176,3 +3267,393 @@ async def test_open_blob_files_async_iterates_snapshot_handles(tmp_path):
with file:
actual.append(await file.aread())
assert actual == [None, b"alpha", b"alpha"]
def _initial_base_payloads(tmp_path):
base_dir = tmp_path / "videos"
base_dir.mkdir(exist_ok=True)
payload = b"0123456789abcdef"
clip = base_dir / "clip.mp4"
clip.write_bytes(payload)
return base_dir, clip, payload
@pytest.mark.parametrize("base_spec", ["lightweight", "dict", "dataset_base_path"])
@pytest.mark.parametrize("use_async", [False, True])
@pytest.mark.asyncio
async def test_create_table_initial_bases_store_relative_blob_ranges(
tmp_path, base_spec, use_async
):
lance = None
if base_spec == "dataset_base_path":
lance = pytest.importorskip("lance")
base_dir, clip, payload = _initial_base_payloads(tmp_path)
field = lancedb.blob("video").with_metadata({"lancedb:logical_type": "mp4"})
schema = pa.schema([pa.field("id", pa.int64()), field])
videos = lancedb.blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
batch = pa.RecordBatch.from_arrays(
[pa.array([1], pa.int64()), videos], schema=schema
)
base_kwargs = {"path": base_dir.as_uri(), "name": "source", "id": 1}
if base_spec == "lightweight":
bases = [lancedb.BasePath(**base_kwargs)]
elif base_spec == "dict":
bases = [base_kwargs]
else:
bases = [lance.DatasetBasePath(**base_kwargs)]
if use_async:
db = await lancedb.connect_async(tmp_path / "db")
table = await db.create_table("videos", data=batch, initial_bases=bases)
assert await table.version() == 1
created_schema = await table.schema()
reopened = await db.open_table("videos")
hits = await reopened.query().with_row_id().to_arrow()
row_id = hits["_rowid"][0].as_py()
assert (await reopened.fetch_blobs("video", hits)).to_pylist() == [payload[:6]]
assert (
await reopened.fetch_blob_ranges("video", [(row_id, 1, 3)])
).to_pylist() == [payload[1:4]]
else:
db = lancedb.connect(tmp_path / "db")
table = db.create_table("videos", data=batch, initial_bases=bases)
assert table.version == 1
created_schema = table.schema
# Manifest introspection needs pylance; the lightweight and dict
# variants must still prove registration through the reopen and bytes.
if lance is not None:
registered = table.to_lance().base_paths()[1]
assert registered.path == base_dir.as_uri()
assert registered.is_dataset_root is False
reopened = db.open_table("videos")
hits = reopened.search().with_row_id(True).to_arrow()
row_id = hits["_rowid"][0].as_py()
assert reopened.fetch_blobs("video", hits).to_pylist() == [payload[:6]]
assert reopened.fetch_blob_ranges("video", [(row_id, 1, 3)]).to_pylist() == [
payload[1:4]
]
assert created_schema.field("video").metadata[b"lancedb:logical_type"] == b"mp4"
def test_create_table_initial_bases_bootstrap_empty_table_with_auto_id(tmp_path):
pytest.importorskip("lance")
base_dir, clip, payload = _initial_base_payloads(tmp_path)
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
db = lancedb.connect(tmp_path / "db")
table = db.create_table(
"videos",
schema=schema,
initial_bases=[lancedb.BasePath(path=base_dir.as_uri(), name="source")],
)
assert table.version == 1
registered = list(table.to_lance().base_paths().values())
assert len(registered) == 1
assert registered[0].id > 0
assert registered[0].path == base_dir.as_uri()
assert registered[0].is_dataset_root is False
videos = lancedb.blob_uri_array([clip.as_uri()])
rows = pa.RecordBatch.from_arrays(
[pa.array([1], pa.int64()), videos], schema=schema
)
table.add(rows)
reopened = db.open_table("videos")
by_id = _row_ids_by_id(reopened)
assert reopened.fetch_blobs("video", [by_id[1]]).to_pylist() == [payload]
def test_create_table_initial_bases_reject_bad_input(tmp_path):
base_dir, _, _ = _initial_base_payloads(tmp_path)
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
db = lancedb.connect("memory:///")
path = base_dir.as_uri()
with pytest.raises(ValueError, match="id=0"):
lancedb.BasePath(path=path, id=0)
with pytest.raises(ValueError, match="id=0"):
db.create_table("zero", schema=schema, initial_bases=[{"path": path, "id": 0}])
with pytest.raises(ValueError, match="unique"):
db.create_table(
"duplicates",
schema=schema,
initial_bases=[
lancedb.BasePath(path=path, id=1),
lancedb.BasePath(path=f"{path}/other", id=1),
],
)
with pytest.raises(ValueError, match="missing 'path'"):
db.create_table("missing_path", schema=schema, initial_bases=[{"id": 1}])
with pytest.raises(TypeError, match="must be a BasePath, dict, or DatasetBasePath"):
db.create_table("not_a_base", schema=schema, initial_bases=[object()])
def test_create_table_allow_external_blob_outside_bases_is_atomic(tmp_path):
payload = b"0123456789abcdef"
clip = tmp_path / "clip.mp4"
clip.write_bytes(payload)
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
videos = lancedb.blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
rows = pa.RecordBatch.from_arrays(
[pa.array([1], pa.int64()), videos], schema=schema
)
db = lancedb.connect(tmp_path / "db")
with pytest.raises(ValueError, match="allow_external_blob_outside_bases"):
db.create_table("rejected", data=rows, schema=schema)
with pytest.raises(ValueError, match="requires initial data"):
db.create_table(
"empty_opt_in", schema=schema, allow_external_blob_outside_bases=True
)
table = db.create_table(
"videos", data=rows, schema=schema, allow_external_blob_outside_bases=True
)
assert table.version == 1
reopened = db.open_table("videos")
hits = reopened.search().with_row_id(True).to_arrow()
assert reopened.fetch_blobs("video", hits).to_pylist() == [payload[:6]]
row_id = hits["_rowid"][0].as_py()
assert reopened.fetch_blob_ranges("video", [(row_id, 0, 6)]).to_pylist() == [
payload[:6]
]
def test_create_table_initial_bases_keep_scoped_options_on_reopen(tmp_path):
pytest.importorskip("lance")
payload = b"scoped-payload"
dir_a = tmp_path / "base-a"
dir_b = tmp_path / "base-b"
dir_a.mkdir()
dir_b.mkdir()
clip_a = dir_a / "clip.mp4"
clip_b = dir_b / "clip.mp4"
clip_a.write_bytes(payload)
clip_b.write_bytes(payload)
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
videos = lancedb.blob_uri_array([clip_a.as_uri(), clip_b.as_uri()])
rows = pa.RecordBatch.from_arrays(
[pa.array([1, 2], pa.int64()), videos], schema=schema
)
storage_options = {
"timeout": "7s",
"base_1.region": "base-one",
"base_2.region": "base-two",
}
db = lancedb.connect(tmp_path / "db")
table = db.create_table(
"videos",
data=rows,
schema=schema,
initial_bases=[
lancedb.BasePath(path=dir_a.as_uri(), name="a", id=1),
lancedb.BasePath(path=dir_b.as_uri(), name="b", id=2),
],
storage_options=storage_options,
)
assert table.version == 1
assert {base.id for base in table.to_lance().base_paths().values()} == {1, 2}
reopened = db.open_table("videos", storage_options=storage_options)
by_id = _row_ids_by_id(reopened)
assert reopened.fetch_blobs("video", [by_id[1], by_id[2]]).to_pylist() == [
payload,
payload,
]
def test_create_table_initial_bases_through_namespace(tmp_path):
pytest.importorskip("lance")
base_dir, clip, payload = _initial_base_payloads(tmp_path)
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
videos = lancedb.blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
rows = pa.RecordBatch.from_arrays(
[pa.array([1], pa.int64()), videos], schema=schema
)
db = lancedb.connect_namespace("dir", {"root": str(tmp_path / "ns")})
table = db.create_table(
"videos",
data=rows,
schema=schema,
initial_bases=[lancedb.BasePath(path=base_dir.as_uri(), name="source", id=1)],
)
assert table.version == 1
reopened = db.open_table("videos")
hits = reopened.search().with_row_id(True).to_arrow()
row_id = hits["_rowid"][0].as_py()
assert reopened.fetch_blobs("video", hits).to_pylist() == [payload[:6]]
assert reopened.fetch_blob_ranges("video", [(row_id, 1, 3)]).to_pylist() == [
payload[1:4]
]
def test_namespace_create_keeps_scoped_options_over_connection_defaults(tmp_path):
pytest.importorskip("lance")
base_dir, clip, _ = _initial_base_payloads(tmp_path)
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
videos = lancedb.blob_uri_array([clip.as_uri()])
rows = pa.RecordBatch.from_arrays(
[pa.array([1], pa.int64()), videos], schema=schema
)
db = lancedb.connect_namespace(
"dir",
{"root": str(tmp_path / "ns")},
storage_options={"timeout": "7s"},
)
# The invalid scoped option belongs to base 1. It must survive the merge
# with connection defaults instead of being replaced by them.
with pytest.raises(ValueError, match="scheduler_error_mode"):
db.create_table(
"videos",
data=rows,
schema=schema,
initial_bases=[
lancedb.BasePath(path=base_dir.as_uri(), name="source", id=1)
],
storage_options={"base_1.scheduler_error_mode": "invalid"},
)
def test_namespace_reopen_applies_scoped_options_per_base(tmp_path):
pytest.importorskip("lance")
payload_a = b"namespace-base-a"
payload_b = b"namespace-base-b"
dir_a = tmp_path / "base-a"
dir_b = tmp_path / "base-b"
dir_a.mkdir()
dir_b.mkdir()
clip_a = dir_a / "clip.mp4"
clip_b = dir_b / "clip.mp4"
clip_a.write_bytes(payload_a)
clip_b.write_bytes(payload_b)
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
videos = lancedb.blob_uri_array([clip_a.as_uri(), clip_b.as_uri()])
rows = pa.RecordBatch.from_arrays(
[pa.array([1, 2], pa.int64()), videos], schema=schema
)
db = lancedb.connect_namespace(
"dir",
{"root": str(tmp_path / "ns")},
storage_options={"timeout": "7s"},
)
table = db.create_table(
"videos",
data=rows,
schema=schema,
initial_bases=[
lancedb.BasePath(path=dir_a.as_uri(), name="a", id=1),
lancedb.BasePath(path=dir_b.as_uri(), name="b", id=2),
],
)
assert table.version == 1
reopened = db.open_table(
"videos", storage_options={"base_1.scheduler_error_mode": "invalid"}
)
by_id = _row_ids_by_id(reopened)
with pytest.raises(ValueError, match="scheduler_error_mode"):
reopened.fetch_blobs("video", [by_id[1]])
assert reopened.fetch_blobs("video", [by_id[2]]).to_pylist() == [payload_b]
@pytest.mark.asyncio
async def test_create_table_initial_bases_through_async_namespace(tmp_path):
pytest.importorskip("lance")
base_dir, clip, payload = _initial_base_payloads(tmp_path)
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
videos = lancedb.blob_uri_array([clip.as_uri()])
rows = pa.RecordBatch.from_arrays(
[pa.array([1], pa.int64()), videos], schema=schema
)
db = lancedb.connect_namespace_async("dir", {"root": str(tmp_path / "ns")})
table = await db.create_table(
"videos",
data=rows,
schema=schema,
initial_bases=[lancedb.BasePath(path=base_dir.as_uri(), name="source", id=1)],
)
assert await table.version() == 1
reopened = await db.open_table("videos")
hits = await reopened.query().with_row_id().to_arrow()
assert (await reopened.fetch_blobs("video", hits)).to_pylist() == [payload]
def test_namespace_refresh_layers_caller_scoped_options(tmp_path):
from lance_namespace import (
DeclareTableResponse,
DescribeTableResponse,
LanceNamespace,
)
from lancedb.namespace import LanceNamespaceDBConnection
class RefreshingNamespace(LanceNamespace):
def __init__(self, location):
self.location = location
self.refreshes = 0
def namespace_id(self):
return self.location
def declare_table(self, request):
return DeclareTableResponse(
location=self.location,
storage_options={
"timeout": "7s",
# Expired immediately so the next read must refresh.
"expires_at_millis": "1",
},
)
def describe_table(self, request):
self.refreshes += 1
return DescribeTableResponse(
location=self.location,
storage_options={"timeout": "8s", "namespace_vended": "fresh"},
)
payload = b"0123456789abcdef"
base_dir = tmp_path / "base"
base_dir.mkdir()
clip = base_dir / "clip.mp4"
clip.write_bytes(payload)
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
videos = lancedb.blob_uri_array([clip.as_uri()])
rows = pa.RecordBatch.from_arrays(
[pa.array([1], pa.int64()), videos], schema=schema
)
namespace = RefreshingNamespace((tmp_path / "table.lance").as_uri())
db = LanceNamespaceDBConnection(namespace)
table = db.create_table(
"videos",
data=rows,
schema=schema,
initial_bases=[lancedb.BasePath(base_dir.as_uri(), name="base", id=1)],
storage_options={"base_1.caller_scoped": "keep-me"},
)
initial = table.initial_storage_options()
assert initial["base_1.caller_scoped"] == "keep-me"
assert initial["timeout"] == "7s"
latest = table.latest_storage_options()
assert namespace.refreshes > 0, "expired seed did not trigger a refresh"
assert latest["base_1.caller_scoped"] == "keep-me"
assert latest["timeout"] == "8s"
assert latest["namespace_vended"] == "fresh"
assert table.version == 1
reopened = db.open_table(
"videos", storage_options={"base_1.caller_scoped": "keep-me"}
)
assert reopened.latest_storage_options()["base_1.caller_scoped"] == "keep-me"
hits = reopened.search().with_row_id(True).to_arrow()
row_id = hits["_rowid"][0].as_py()
assert reopened.fetch_blobs("video", [row_id]).to_pylist() == [payload]
assert reopened.fetch_blob_ranges("video", [(row_id, 4, 6)]).to_pylist() == [
payload[4:10]
]
+130
View File
@@ -85,3 +85,133 @@ def test_blob_array(with_pylance):
text=True,
)
assert result.returncode == 0, result.stderr
@pytest.mark.parametrize("with_pylance", [False, True])
def test_blob_uri_array(with_pylance):
if with_pylance:
pytest.importorskip("lance")
# Use fresh processes so each extension class can own Arrow's registry.
script = textwrap.dedent(
"""\
import importlib.abc
import pathlib
import sys
import tempfile
if sys.argv[1] == "False":
class MissingLance(importlib.abc.MetaPathFinder):
def find_spec(self, fullname, path, target=None):
if fullname == "lance" or fullname.startswith("lance."):
raise ModuleNotFoundError(fullname, name="lance")
sys.meta_path.insert(0, MissingLance())
import lancedb
import pyarrow as pa
from lancedb import BasePath, blob_uri_array
from lancedb.schema import blob
if sys.argv[1] == "True":
from lance import DatasetBasePath
from lance.blob import BlobType
else:
from lancedb.schema import _FallbackBlobType as BlobType
DatasetBasePath = None
schema = pa.schema([blob("video")])
array = blob_uri_array(
["s3://bucket/a.mp4", None, "b.mp4"],
positions=[0, None, None],
sizes=[4, None, None],
)
assert isinstance(array, pa.ExtensionArray)
assert type(array.type) is BlobType
assert array.type == schema.field("video").type
assert array.storage.to_pylist() == [
{"data": None, "uri": "s3://bucket/a.mp4", "position": 0, "size": 4},
None,
{"data": None, "uri": "b.mp4", "position": None, "size": None},
]
whole = blob_uri_array(iter(["s3://bucket/a.mp4"]))
assert whole.storage.to_pylist() == [
{"data": None, "uri": "s3://bucket/a.mp4", "position": None, "size": None}
]
checks = [
(lambda: blob_uri_array(["u"], positions=[0]), "provided together"),
(
lambda: blob_uri_array(["u"], positions=[0, 0], sizes=[1, 1]),
"same length",
),
(
lambda: blob_uri_array(["u"], sizes=[1, 1], positions=[0, 0]),
"same length",
),
(
lambda: blob_uri_array(["u"], positions=[0], sizes=[None]),
"both position and size",
),
(lambda: blob_uri_array(["u"], positions=[0], sizes=[0]), "positive"),
(lambda: blob_uri_array(["u"], positions=[-1], sizes=[1]), "non-negative"),
(lambda: blob_uri_array([None], positions=[0], sizes=[1]), "None but"),
(lambda: blob_uri_array(["u"], positions=[0], sizes=[2**64]), "uint64"),
(lambda: blob_uri_array([b"u"]), "must be a string"),
]
for call, fragment in checks:
try:
call()
except (TypeError, ValueError, OverflowError) as error:
assert fragment in str(error), (fragment, error)
else:
raise AssertionError(f"accepted invalid input: {fragment}")
try:
BasePath("s3://bucket", id=0)
except ValueError as error:
assert "id=None" in str(error)
else:
raise AssertionError("accepted explicit id=0")
# The public create route must accept the helper and register the base
# in the same commit as the data, with or without pylance.
root = pathlib.Path(tempfile.mkdtemp())
base_dir = root / "videos"
base_dir.mkdir()
payload = b"0123456789abcdef"
clip = base_dir / "clip.mp4"
clip.write_bytes(payload)
db = lancedb.connect(root / "db")
field = blob("video").with_metadata({"lancedb:logical_type": "mp4"})
table_schema = pa.schema([pa.field("id", pa.int64()), field])
videos = blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
batch = pa.RecordBatch.from_arrays(
[pa.array([1], pa.int64()), videos], schema=table_schema
)
if DatasetBasePath is not None:
bases = [DatasetBasePath(path=base_dir.as_uri(), name="source")]
else:
bases = [BasePath(path=base_dir.as_uri(), name="source")]
table = db.create_table("videos", data=batch, initial_bases=bases)
assert table.version == 1
assert (
table.schema.field("video").metadata[b"lancedb:logical_type"] == b"mp4"
)
row_ids = table.search().with_row_id(True).to_arrow()["_rowid"]
assert table.fetch_blobs("video", row_ids).to_pylist() == [payload[:6]]
assert table.fetch_blob_ranges(
"video", [(row_ids[0].as_py(), 1, 3)]
).to_pylist() == [payload[1:4]]
if DatasetBasePath is not None:
base_paths = table.to_lance().base_paths()
assert base_paths[1].path == base_dir.as_uri()
assert base_paths[1].is_dataset_root is False
if sys.argv[1] == "False":
assert "lance" not in sys.modules
"""
)
result = subprocess.run(
[sys.executable, "-c", script, str(with_pylance)],
capture_output=True,
text=True,
)
assert result.returncode == 0, result.stderr
+29
View File
@@ -869,6 +869,35 @@ def test_open_table_sync(tmp_db: lancedb.DBConnection):
tmp_db.open_table("does_not_exist")
def test_open_table_sync_with_location(tmp_path):
db = lancedb.connect(tmp_path / "db")
db.create_table("test", data=[{"id": 0}])
dataset_path = tmp_path / "db" / "test.lance"
other_db = lancedb.connect(tmp_path / "other")
opened = other_db.open_table("test", location=str(dataset_path))
assert opened.name == "test"
assert opened.count_rows() == 1
def test_open_table_sync_lance_dataset_path_hint(tmp_path):
data_dir = tmp_path / "data"
lancedb.connect(data_dir).create_table("embeddings", data=[{"id": 0}])
dataset_db = lancedb.connect(data_dir / "embeddings.lance")
with pytest.raises(ValueError) as exc_info:
dataset_db.open_table("embeddings")
message = str(exc_info.value)
assert "Table 'embeddings' was not found" in message
assert "points to a Lance dataset rather than a database directory" in message
assert f"parent directory '{data_dir}'" in message
assert "open table 'embeddings' instead" in message
with pytest.raises(ValueError) as exc_info:
dataset_db.open_table("missing", location=str(tmp_path / "missing.lance"))
assert "points to a Lance dataset" not in str(exc_info.value)
@pytest.mark.asyncio
async def test_open_table(tmp_path):
from conftest import pandas_string_type
+25
View File
@@ -1224,6 +1224,31 @@ def test_transform_fn_pandas(mem_db):
assert isinstance(result, pd.DataFrame)
def test_numpy_format_mixed_columns_is_object_ndarray(mem_db):
pytest.importorskip("pandas")
import numpy as np
tbl = mem_db.create_table(
"test_table",
pa.table(
{
"id": range(3),
"vector": pa.array(
[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],
type=pa.list_(pa.float32(), 2),
),
}
),
)
permutation = Permutation.identity(tbl).with_format("numpy")
result = next(permutation.iter(2, skip_last_batch=False))
assert isinstance(result, np.ndarray)
assert result.dtype == object
assert result.shape == (2, 2)
np.testing.assert_array_equal(result[0, 1], [1.0, 2.0])
def test_custom_transform(mem_db):
tbl = mem_db.create_table(
"test_table", pa.table({"id": range(10), "value": range(10)})
+155 -10
View File
@@ -975,6 +975,10 @@ async def test_async_take_query_to_pandas_blob_v2_bytes(tmp_db_async):
df = await table.take_offsets([1, 2]).to_pandas(blob_mode="bytes")
assert set(df["blob"]) == {b"two", b"three"}
ordered = await table.take_offsets([2, 1], preserve_order=True).to_pandas(
blob_mode="bytes"
)
assert ordered["blob"].tolist() == [b"three", b"two"]
def test_order_by_plain_query(mem_db):
@@ -1739,17 +1743,16 @@ def test_query_builder_with_different_vector_column():
ds = mock.Mock()
table.to_lance.return_value = ds
builder.to_arrow()
table._execute_arrow.assert_called_once_with(
Query(
vector=query,
filter="b < 10",
limit=2,
distance_type="cosine",
columns=["b"],
vector_column="foo_vector",
),
timeout=None,
expected = Query(
vector=query,
filter="b < 10",
limit=2,
distance_type="cosine",
columns=["b"],
vector_column="foo_vector",
)
expected._blob_row_id_prepared = True
table._execute_arrow.assert_called_once_with(expected, timeout=None)
def cosine_distance(vec1, vec2):
@@ -2657,6 +2660,61 @@ def test_query_schema(tmp_path):
)
def test_sync_query_prepares_schema_once_per_execution(tmp_path, monkeypatch):
db = lancedb.connect(tmp_path)
table = db.create_table(
"test",
pa.table(
{
"id": [1, 2, 3],
"vector": pa.array(
[[1, 2], [3, 4], [5, 6]],
pa.list_(pa.float32(), list_size=2),
),
}
),
)
calls = 0
original = AsyncTable._schema_sync
def counted(self):
nonlocal calls
calls += 1
return original(self)
monkeypatch.setattr(AsyncTable, "_schema_sync", counted)
table.search().where("id = 1").select(["id"]).to_arrow()
assert calls <= 1
calls = 0
table.search([1, 2], vector_column_name="vector").limit(1).to_arrow()
assert calls <= 1
calls = 0
table.search([1, 2]).limit(1).to_arrow()
# At most one lookup infers the vector column, one prepares execution.
assert calls <= 2
calls = 0
table.search().where("id = 1").select(["id"]).to_batches().read_all()
assert calls <= 1
builder = table.search().where("id = 1")
before = builder.to_arrow()
assert "extra" not in before.column_names
assert "image" not in before.column_names
table.add_columns(pa.schema([pa.field("extra", pa.int64()), lancedb.blob("image")]))
calls = 0
after = builder.to_arrow()
assert calls <= 1
assert after["extra"].to_pylist() == [None]
assert "_lance_row_id" in str(after.schema)
assert "_rowid" not in after.column_names
@pytest.mark.asyncio
async def test_query_schema_async(tmp_path):
db = await lancedb.connect_async(tmp_path)
@@ -2761,6 +2819,86 @@ def test_take_queries(tmp_path):
assert table.take_row_ids([5, 2, 17]).to_pandas()["idx"].to_list() == [5, 2, 17]
def test_take_offsets_preserve_order_sync(tmp_path):
db = lancedb.connect(tmp_path)
table = db.create_table("test", pa.table({"idx": range(4)}))
table.add(pa.table({"idx": range(4, 8)}))
table.delete("idx IN (1, 6)")
requested = [5, 0, 5, 2, 99, 4, 0]
expected = [7, 0, 7, 3, 5, 0]
actual = (
table.take_offsets(requested, preserve_order=True).select(["idx"]).to_arrow()
)
assert actual.column_names == ["idx"]
assert actual["idx"].to_pylist() == expected
batches = list(
table.take_offsets(requested, preserve_order=True)
.select(["idx"])
.to_batches(max_batch_length=1)
)
assert all(batch.num_rows <= 1 for batch in batches)
assert [row for batch in batches for row in batch["idx"].to_pylist()] == expected
# The default path keeps its unspecified-order behavior.
default = table.take_offsets(requested).select(["idx"]).to_arrow()
assert sorted(default["idx"].to_pylist()) == sorted(expected)
assert table.take_offsets(requested).to_query_object().preserve_order is None
query = (
table.take_offsets(requested, preserve_order=True)
.select(["idx"])
.to_query_object()
)
assert query.preserve_order is True
assert table._execute_query(query).read_all()["idx"].to_pylist() == expected
empty = table.take_offsets([], preserve_order=True).select(["idx"]).to_arrow()
assert empty.num_rows == 0
assert empty.column_names == ["idx"]
query.order_by = [ColumnOrdering(column_name="idx")]
with pytest.raises(
ValueError, match="preserve_order cannot be combined with an explicit order_by"
):
table._execute_query(query)
@pytest.mark.asyncio
async def test_take_offsets_preserve_order_async(tmp_path):
db = await lancedb.connect_async(tmp_path)
table = await db.create_table("test", pa.table({"idx": range(4)}))
await table.add(pa.table({"idx": range(4, 8)}))
await table.delete("idx IN (1, 6)")
requested = [5, 0, 5, 2, 99, 4, 0]
expected = [7, 0, 7, 3, 5, 0]
actual = (
await table.take_offsets(requested, preserve_order=True)
.select(["idx"])
.to_arrow()
)
assert actual.column_names == ["idx"]
assert actual["idx"].to_pylist() == expected
reader = (
await table.take_offsets(requested, preserve_order=True)
.select(["idx"])
.to_batches(max_batch_length=1)
)
batches = [batch async for batch in reader]
assert all(batch.num_rows <= 1 for batch in batches)
assert [row for batch in batches for row in batch["idx"].to_pylist()] == expected
query = (
table.take_offsets(requested, preserve_order=True)
.select(["idx"])
.to_query_object()
)
assert query.preserve_order is True
@pytest.mark.parametrize("selection", [None, [], ["idx"], {"_rowid": "100 - idx"}])
@pytest.mark.parametrize("empty", [False, True])
def test_take_row_ids_order_and_roundtrip(tmp_path, selection, empty):
@@ -2867,6 +3005,13 @@ def test_getitems(tmp_path):
assert table.__getitems__(offsets) == pa.table({"idx": offsets})
def test_getitems_rejects_missing_offsets(tmp_path):
table = lancedb.connect(tmp_path).create_table("test", pa.table({"idx": range(3)}))
with pytest.raises(pa.ArrowIndexError, match="out of bounds"):
table.__getitems__([0, 99])
@pytest.mark.asyncio
async def test_query_timeout_async(tmp_path):
db = await lancedb.connect_async(tmp_path)
+267 -10
View File
@@ -1404,6 +1404,12 @@ def test_remote_permutation_is_picklable():
{"a": 2},
{"a": 4},
]
assert table.take_offsets([0, 2, 0, 4], preserve_order=True).to_list() == [
{"a": 0},
{"a": 2},
{"a": 0},
{"a": 4},
]
permutation = Permutation.identity(table)
restored = pickle.loads(pickle.dumps(permutation))
@@ -1530,6 +1536,126 @@ def test_create_table_positional_parameters_match_base_contract():
assert actual == expected
def _unconsumed_create_input():
raise AssertionError("create_table consumed input before rejecting the option")
yield # pragma: no cover
def _assert_enterprise_rejection(error):
message = str(error)
assert "not supported for table creation in LanceDB Enterprise" in message
assert "Embedded" not in message
assert "add(" not in message
def test_create_table_rejects_blob_base_options_before_request():
def handler(request):
raise AssertionError(f"unexpected request: {request.path}")
schema = pa.schema([pa.field("id", pa.int64())])
with mock_lancedb_connection(handler) as db:
with pytest.raises(NotImplementedError, match="initial_bases") as error:
db.create_table(
"test",
data=_unconsumed_create_input(),
initial_bases=[{"path": "s3://bucket/prefix"}],
)
_assert_enterprise_rejection(error.value)
with pytest.raises(
NotImplementedError, match="allow_external_blob_outside_bases"
) as error:
db.create_table(
"test",
data=_unconsumed_create_input(),
allow_external_blob_outside_bases=True,
)
_assert_enterprise_rejection(error.value)
with pytest.raises(
NotImplementedError, match="allow_external_blob_outside_bases"
) as error:
db.create_table(
"test",
schema=schema,
allow_external_blob_outside_bases=True,
)
_assert_enterprise_rejection(error.value)
def test_create_table_accepts_empty_blob_base_options():
def handler(request):
assert request.path == "/v1/table/test/create/?mode=create"
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(b"{}")
schema = pa.schema([pa.field("id", pa.int64())])
with mock_lancedb_connection(handler) as db:
table = db.create_table(
"test",
schema=schema,
initial_bases=[],
allow_external_blob_outside_bases=False,
)
assert table is not None
@pytest.mark.asyncio
async def test_create_table_rejects_blob_base_options_before_request_async():
def handler(request):
raise AssertionError(f"unexpected request: {request.path}")
def reader():
schema = pa.schema([pa.field("id", pa.int64())])
return pa.RecordBatchReader.from_batches(schema, [])
schema = pa.schema([pa.field("id", pa.int64())])
async with mock_lancedb_connection_async(handler) as db:
with pytest.raises(NotImplementedError, match="initial_bases") as error:
await db.create_table(
"test",
data=_unconsumed_create_input(),
initial_bases=[{"path": "s3://bucket/prefix"}],
)
_assert_enterprise_rejection(error.value)
with pytest.raises(
NotImplementedError, match="allow_external_blob_outside_bases"
) as error:
await db.create_table(
"test",
data=_unconsumed_create_input(),
allow_external_blob_outside_bases=True,
)
_assert_enterprise_rejection(error.value)
with pytest.raises(
NotImplementedError, match="allow_external_blob_outside_bases"
) as error:
await db.create_table(
"test",
schema=schema,
allow_external_blob_outside_bases=True,
)
_assert_enterprise_rejection(error.value)
# The lower-layer guard still maps Error::NotSupported for direct native
# calls that bypass the Python entrypoint.
with pytest.raises(NotImplementedError, match="initial_bases"):
await db._inner.create_table(
"test",
"create",
reader(),
initial_bases=[{"path": "s3://bucket/prefix"}],
)
with pytest.raises(
NotImplementedError, match="allow_external_blob_outside_bases"
):
await db._inner.create_table(
"test",
"create",
reader(),
allow_external_blob_outside_bases=True,
)
def test_create_table_exist_ok():
def handler(request):
if request.path == "/v1/table/test/create/?mode=exist_ok":
@@ -5887,6 +6013,9 @@ def blob_descriptor_take_table():
)
_DEFAULT_DESCRIPTOR_IDENTITY = object()
@contextlib.contextmanager
def blob_remote_table(
*,
@@ -5902,6 +6031,7 @@ def blob_remote_table(
search_scores=False,
snapshot_supported=True,
identity_header="v1:" + "a" * 64,
descriptor_identity_header=_DEFAULT_DESCRIPTOR_IDENTITY,
verify_identity=True,
):
if state is None:
@@ -5946,6 +6076,11 @@ def blob_remote_table(
request.send_header(
"x-lancedb-version", str(BLOB_DESCRIBE_RESPONSE["version"])
)
if verify_identity and request.headers.get("x-lancedb-query-snapshot"):
request.send_header(
"x-lancedb-query-snapshot",
request.headers["x-lancedb-query-snapshot"],
)
request.end_headers()
request.wfile.write(chunk)
elif request.path == "/v1/table/test/query/":
@@ -5954,14 +6089,26 @@ def blob_remote_table(
if requests is not None:
requests.append(("query", body))
columns = body.get("columns")
assert columns in (
take_offsets_query = isinstance(columns, list) and "_rowoffset" in columns
assert take_offsets_query or columns in (
None,
["id", "image"],
["id"],
["image"],
{"payload": "image"},
)
if isinstance(columns, dict):
if take_offsets_query:
response_table = blob_query_response_table().append_column(
"_rowoffset", pa.array(range(3), type=pa.uint64())
)
response_table = response_table.select(
[name for name in columns if name != "_rowid"]
)
if body.get("with_row_id", False):
response_table = response_table.append_column(
"_rowid", blob_query_response_table()["_rowid"]
)
elif isinstance(columns, dict):
response_table = blob_query_response_table().select(["image", "_rowid"])
response_table = response_table.rename_columns(["payload", "_rowid"])
if not body.get("with_row_id", False):
@@ -6012,11 +6159,20 @@ def blob_remote_table(
request.send_header("x-lancedb-version", header)
if snapshot_supported:
request.send_header("x-lancedb-query-version", header)
identity = (
identity_header(body)
if callable(identity_header)
else identity_header
descriptor_query = body.get("filter", "").startswith("_rowid IN")
use_descriptor_identity = (
descriptor_query
and descriptor_identity_header
is not _DEFAULT_DESCRIPTOR_IDENTITY
)
if use_descriptor_identity:
identity = descriptor_identity_header
else:
identity = (
identity_header(body)
if callable(identity_header)
else identity_header
)
if identity is not None:
request.send_header("x-lancedb-query-snapshot", identity)
request.end_headers()
@@ -6564,13 +6720,114 @@ def test_remote_blob_file_matches_file_error_and_range_contract():
handle.read(1)
def test_remote_blob_fetch_accepts_query_table():
@pytest.mark.parametrize("api", ["fetch_blobs", "fetch_blob_files"])
def test_remote_blob_fetch_accepts_metadata_free_query_table(api):
hits = pa.table({"_rowid": pa.array([10, 20, 30], type=pa.uint64())})
with blob_remote_table() as table:
blobs = table.fetch_blobs("image", hits)
with blob_remote_table(descriptor_identity_header=None) as table:
if api == "fetch_blobs":
assert table.fetch_blobs("image", hits).to_pylist() == [
b"alpha",
None,
b"gamma",
]
else:
handles = table.fetch_blob_files("image", hits)
try:
assert [
handle.read() if handle is not None else None for handle in handles
] == [b"alpha", None, b"gamma"]
finally:
for handle in handles:
if handle is not None:
handle.close()
assert blobs.to_pylist() == [b"alpha", None, b"gamma"]
def test_remote_take_offsets_preserve_order_with_blob_bytes():
with blob_remote_table() as table:
hits = (
table.take_offsets([2, 0, 2], preserve_order=True)
.select(["id", "image"])
.to_arrow(blob_mode="bytes")
)
assert hits["id"].to_pylist() == [3, 1, 3]
assert hits["image"].to_pylist() == [b"gamma", b"alpha", b"gamma"]
@pytest.mark.parametrize("api", ["fetch_blobs", "fetch_blob_files"])
def test_remote_blob_fetch_from_query_result_keeps_query_snapshot(api):
requests = []
state = {"version": 1}
with blob_remote_table(requests=requests, state=state) as table:
hits = table.search().select(["id", "image"]).limit(3).to_arrow()
assert hits.schema.metadata[b"lancedb:query_version"] == b"1"
table.add([{"id": 4, "image": b"new-version"}])
assert table.version == 2
if api == "fetch_blobs":
assert table.fetch_blobs("image", hits).to_pylist() == [
b"alpha",
None,
b"gamma",
]
fetches = [body for path, body in requests if path == "fetch_blobs"]
assert fetches
assert all(body["version"] == 1 for body in fetches)
else:
handles = table.fetch_blob_files("image", hits)
try:
assert [
handle.read() if handle is not None else None for handle in handles
] == [b"alpha", None, b"gamma"]
finally:
for handle in handles:
if handle is not None:
handle.close()
descriptor_queries = [
body
for path, body in requests
if path == "query" and body.get("filter", "").startswith("_rowid IN")
]
assert descriptor_queries
assert all(body["version"] == 1 for body in descriptor_queries)
@pytest.mark.parametrize("descriptor_identity", [None, "v1:" + "b" * 64])
def test_remote_blob_files_reject_unverified_descriptor_identity(descriptor_identity):
requested = "v1:" + "a" * 64
hits = pa.table(
{"_rowid": pa.array([20, 40], type=pa.uint64())}
).replace_schema_metadata(
{
b"lancedb:query_version": b"1",
b"lancedb:query_snapshot": requested.encode(),
}
)
requests = []
with blob_remote_table(
requests=requests, descriptor_identity_header=descriptor_identity
) as table:
with pytest.raises(
NotImplementedError, match="did not verify the query snapshot identity"
):
table.fetch_blob_files("image", hits)
assert not any(path.startswith("/v1/table/test/blob/") for path, _ in requests)
assert not any(path == "/v1/table/test/fetch_blobs/" for path, _ in requests)
@pytest.mark.parametrize("api", ["fetch_blobs", "fetch_blob_files"])
def test_remote_blob_fetch_rejects_incomplete_query_snapshot(api):
requests = []
hits = pa.table(
{"_rowid": pa.array([10], type=pa.uint64())}
).replace_schema_metadata({b"lancedb:query_version": b"1"})
with blob_remote_table(requests=requests) as table:
with pytest.raises(NotImplementedError, match="x-lancedb-query-snapshot"):
getattr(table, api)("image", hits)
assert not any(path == "fetch_blobs" for path, _ in requests)
def test_remote_blob_query_stashes_row_ids_for_fetch():
@@ -0,0 +1,160 @@
# 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
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")
monkeypatch.setattr(background_loop.LOOP, "run", fail)
point = table.search().where("id = 1").select(["id", "text"]).to_arrow()
assert 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
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
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))
@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"}]
+509 -1
View File
@@ -8,13 +8,15 @@ import json
import multiprocessing as mp
import pickle
import re
import struct
import sys
import lancedb
import numpy as np
import pyarrow as pa
import pytest
from lancedb.permutation import Permutation, Permutations, permutation_builder
from lancedb.util import tbl_to_tensor
from lancedb.util import batch_to_tensor, batch_to_tensor_columns, tbl_to_tensor
from utils import start_server_thread
torch = pytest.importorskip("torch")
@@ -23,6 +25,43 @@ torch = pytest.importorskip("torch")
REMOTE_ROWS = list(range(100))
def _identity_collate(batch):
return batch
class _LanceBFloat16Type(pa.ExtensionType):
def __init__(self):
pa.ExtensionType.__init__(self, pa.binary(2), "lance.bfloat16")
def __arrow_ext_serialize__(self):
return b""
@classmethod
def __arrow_ext_deserialize__(cls, storage_type, serialized):
return cls()
def _bf16_storage(values):
bits = torch.tensor(values, dtype=torch.bfloat16).view(torch.int16).tolist()
return [struct.pack("<H", bit & 0xFFFF) for bit in bits]
def _bf16_array(values):
storage = pa.array(_bf16_storage(values), type=pa.binary(2))
return pa.ExtensionArray.from_storage(_LanceBFloat16Type(), storage)
def _fixed_shape_tensor_array(physical_values, shape, permutation=None):
tensor_type = pa.fixed_shape_tensor(
pa.float32(), shape, permutation=permutation or []
)
flat_values = np.asarray(physical_values, dtype=np.float32).reshape(-1)
storage = pa.FixedSizeListArray.from_arrays(
pa.array(flat_values), int(np.prod(shape))
)
return pa.ExtensionArray.from_storage(tensor_type, storage)
def _make_mock_http_handler(handler):
class MockLanceDBHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
@@ -496,3 +535,472 @@ def test_remote_permutation_dataloader_fork_workers():
finally:
server.shutdown()
handle.join()
def test_permutation_torch_dict_mixed_columns(mem_db):
vectors = [[float(i), float(i) + 0.5, float(i) + 1.0] for i in range(5)]
grids = [
[[float(row), float(row) + 1.0], [float(row) + 2.0, float(row) + 3.0]]
for row in range(5)
]
table = mem_db.create_table(
"mixed",
pa.table(
{
"id": pa.array(range(5), type=pa.int32()),
"score": pa.array([i / 2 for i in range(5)], type=pa.float32()),
"vector": pa.array(vectors, type=pa.list_(pa.float32(), 3)),
"grid": pa.array(grids, type=pa.list_(pa.list_(pa.float32(), 2), 2)),
}
),
)
permutation = Permutation.identity(table).with_format("torch_dict")
batch = next(permutation.iter(5, skip_last_batch=False))
assert set(batch) == {"id", "score", "vector", "grid"}
assert batch["id"].shape == (5,)
assert batch["id"].dtype == torch.int32
assert batch["score"].dtype == torch.float32
assert batch["vector"].shape == (5, 3)
assert batch["grid"].shape == (5, 2, 2)
assert torch.equal(batch["vector"], torch.tensor(vectors))
assert torch.equal(batch["grid"], torch.tensor(grids))
items = permutation.__getitems__([0, 2, 4])
assert items["id"].shape == (3,)
assert items["score"].shape == (3,)
assert items["vector"].shape == (3, 3)
assert items["grid"].shape == (3, 2, 2)
dataloader = torch.utils.data.DataLoader(
permutation,
batch_size=2,
shuffle=False,
collate_fn=_identity_collate,
)
batches = list(dataloader)
assert [batch["id"].shape[0] for batch in batches] == [2, 2, 1]
assert batches[0]["vector"].shape == (2, 3)
assert batches[-1]["grid"].shape == (1, 2, 2)
empty = permutation.take_offsets([])
assert empty["id"].shape == (0,)
assert empty["vector"].shape == (0, 3)
assert empty["grid"].shape == (0, 2, 2)
torch_permutation = Permutation.identity(table).with_format("torch")
per_row = next(torch_permutation.iter(2, skip_last_batch=False))
assert isinstance(per_row, list)
assert per_row[0]["vector"].shape == (3,)
assert per_row[0]["grid"].shape == (2, 2)
torch_loader = torch.utils.data.DataLoader(
torch_permutation, batch_size=2, shuffle=False
)
collated = next(iter(torch_loader))
assert collated["vector"].shape == (2, 3)
assert collated["grid"].shape == (2, 2, 2)
def test_permutation_torch_dict_dataloader_spawn(tmp_db):
vectors = [[float(i), float(i) + 0.5] for i in range(11)]
table = tmp_db.create_table(
"spawn",
pa.table(
{
"id": range(11),
"vector": pa.array(vectors, type=pa.list_(pa.float32(), 2)),
}
),
)
permutation = Permutation.identity(table).with_format("torch_dict")
dataloader = torch.utils.data.DataLoader(
permutation,
batch_size=4,
shuffle=False,
num_workers=2,
multiprocessing_context="spawn",
collate_fn=_identity_collate,
)
seen = []
for batch in dataloader:
assert isinstance(batch, dict)
assert batch["id"].shape == (batch["id"].shape[0],)
assert batch["vector"].shape == (batch["id"].shape[0], 2)
seen.extend(batch["id"].tolist())
assert sorted(seen) == list(range(11))
def test_batch_to_tensor_columns_zero_copy_and_slice_offsets():
vectors = [[float(i), float(i) + 0.5, float(i) + 1.0] for i in range(5)]
nested_values = np.arange(5 * 3 * 2, dtype=np.float32).reshape(5, 3, 2)
batch = pa.record_batch(
[
pa.array(range(5), type=pa.int64()),
pa.array(vectors, type=pa.list_(pa.float32(), 3)),
pa.array(
nested_values.tolist(),
type=pa.list_(pa.list_(pa.float32(), 2), 3),
),
pa.array([True, False, True, False, True]),
],
names=["id", "vector", "nested", "active"],
).slice(2, 2)
tensors = batch_to_tensor_columns(batch)
assert tensors["id"].tolist() == [2, 3]
assert torch.equal(tensors["vector"], torch.tensor(vectors[2:4]))
assert torch.equal(tensors["nested"], torch.from_numpy(nested_values[2:4].copy()))
assert tensors["active"].dtype == torch.bool
assert tensors["active"].tolist() == [True, False]
id_array = batch.column("id")
assert tensors["id"].data_ptr() == (
id_array.buffers()[1].address + id_array.offset * 8
)
vector_array = batch.column("vector")
vector_values = vector_array.values
expected_vector_offset = (vector_array.offset * 3 + vector_values.offset) * 4
assert tensors["vector"].data_ptr() == (
vector_values.buffers()[1].address + expected_vector_offset
)
single_column = pa.record_batch([batch.column("vector")], names=["vector"])
column_tensor = batch_to_tensor(single_column)
assert column_tensor.shape == (1, 2, 3)
assert column_tensor.data_ptr() == tensors["vector"].data_ptr()
def test_permutation_torch_col_and_row_vector_layouts(mem_db):
left = [[float(i), float(i) + 0.5] for i in range(4)]
right = [[float(i) + 1.0, float(i) + 1.5] for i in range(4)]
table = mem_db.create_table(
"uniform",
pa.table(
{
"left": pa.array(left, type=pa.list_(pa.float32(), 2)),
"right": pa.array(right, type=pa.list_(pa.float32(), 2)),
}
),
)
permutation = Permutation.identity(table)
column_batch = next(
permutation.with_format("torch_col").iter(4, skip_last_batch=False)
)
assert column_batch.shape == (2, 4, 2)
assert column_batch.dtype == torch.float32
assert torch.equal(column_batch[0], torch.tensor(left))
row_batch = next(
permutation.with_format("torch_row").iter(4, skip_last_batch=False)
)
assert len(row_batch) == 4
assert row_batch[0].shape == (2, 2)
assert torch.equal(
row_batch[0], torch.stack([torch.tensor(left[0]), torch.tensor(right[0])])
)
dataloader = torch.utils.data.DataLoader(
permutation.with_format("torch_row"), batch_size=4, shuffle=False
)
stacked = next(iter(dataloader))
assert stacked.shape == (4, 2, 2)
scalar_table = mem_db.create_table(
"single_scalar", pa.table({"x": pa.array(range(4), type=pa.int64())})
)
scalar_rows = next(
Permutation.identity(scalar_table)
.with_format("torch_row")
.iter(4, skip_last_batch=False)
)
assert scalar_rows[0].shape == (1,)
assert scalar_rows[0].dtype == torch.int64
vector_table = mem_db.create_table(
"single_vector",
pa.table({"v": pa.array(left, type=pa.list_(pa.float32(), 2))}),
)
vector_rows = next(
Permutation.identity(vector_table)
.with_format("torch_row")
.iter(4, skip_last_batch=False)
)
assert vector_rows[0].shape == (1, 2)
vector_column = next(
Permutation.identity(vector_table)
.with_format("torch_col")
.iter(4, skip_last_batch=False)
)
assert vector_column.shape == (1, 4, 2)
def test_torch_col_and_row_reject_heterogeneous_shapes(mem_db):
table = mem_db.create_table(
"heterogeneous",
pa.table(
{
"id": pa.array(range(4), type=pa.int64()),
"vector": pa.array(
[[float(i), float(i) + 1.0, float(i) + 2.0] for i in range(4)],
type=pa.list_(pa.float32(), 3),
),
}
),
)
permutation = Permutation.identity(table)
for format_name in ("torch_col", "torch_row"):
with pytest.raises(ValueError, match="torch_dict") as exc_info:
next(permutation.with_format(format_name).iter(2, skip_last_batch=False))
message = str(exc_info.value)
assert "`vector`" in message
assert "(3,)" in message
assert "`id`" in message
assert "()" in message
different_dims = mem_db.create_table(
"different_dims",
pa.table(
{
"left": pa.array(
[[1.0, 2.0] for _ in range(4)],
type=pa.list_(pa.float32(), 2),
),
"right": pa.array(
[[1.0, 2.0, 3.0] for _ in range(4)],
type=pa.list_(pa.float32(), 3),
),
}
),
)
with pytest.raises(ValueError, match="torch_dict") as exc_info:
next(
Permutation.identity(different_dims)
.with_format("torch_row")
.iter(2, skip_last_batch=False)
)
message = str(exc_info.value)
assert "`right`" in message and "(3,)" in message
assert "`left`" in message and "(2,)" in message
def test_torch_row_uses_pytorch_numeric_promotion(mem_db):
table = mem_db.create_table(
"promotion",
pa.table(
{
"id": pa.array(range(4), type=pa.int64()),
"score": pa.array([i / 2 for i in range(4)], type=pa.float32()),
"count": pa.array(range(4), type=pa.int32()),
}
),
)
rows = next(
Permutation.identity(table)
.with_format("torch_row")
.iter(4, skip_last_batch=False)
)
assert rows[0].shape == (3,)
assert rows[0].dtype == torch.float32
assert rows[0].tolist() == [0.0, 0.0, 0.0]
assert rows[2].tolist() == [2.0, 1.0, 2.0]
def test_torch_row_preserves_nullable_numeric_scalar_nan(mem_db):
nullable_int = mem_db.create_table(
"nullable_int",
pa.table({"value": pa.array([1, None, 3], type=pa.int64())}),
)
rows = next(
Permutation.identity(nullable_int)
.with_format("torch_row")
.iter(3, skip_last_batch=False)
)
assert rows[0].shape == (1,)
assert rows[0].dtype == torch.float64
assert rows[0].tolist() == [1.0]
assert torch.isnan(rows[1]).all()
assert rows[2].tolist() == [3.0]
nullable_float = mem_db.create_table(
"nullable_float",
pa.table({"value": pa.array([0.5, None, 2.5], type=pa.float32())}),
)
rows = next(
Permutation.identity(nullable_float)
.with_format("torch_row")
.iter(3, skip_last_batch=False)
)
assert rows[0].dtype == torch.float32
assert rows[0].tolist() == [0.5]
assert torch.isnan(rows[1]).all()
assert rows[2].tolist() == [2.5]
nullable_mixed = mem_db.create_table(
"nullable_mixed",
pa.table(
{
"id": pa.array([1, None, 3], type=pa.int64()),
"score": pa.array([0.5, 1.5, 2.5], type=pa.float32()),
}
),
)
rows = next(
Permutation.identity(nullable_mixed)
.with_format("torch_row")
.iter(3, skip_last_batch=False)
)
assert rows[0].dtype == torch.float64
assert rows[0].tolist() == [1.0, 0.5]
assert torch.isnan(rows[1][0])
assert rows[1][1].item() == 1.5
assert rows[2].tolist() == [3.0, 2.5]
def test_permutation_torch_formats_fixed_shape_tensor_permutation(mem_db):
physical_values = np.arange(2 * 2 * 3 * 4, dtype=np.float32).reshape(2, 2, 3, 4)
tensor_array = _fixed_shape_tensor_array(
physical_values, shape=(2, 3, 4), permutation=[0, 2, 1]
)
table = mem_db.create_table(
"tensor_permutation",
pa.table({"id": range(2), "tensor": tensor_array}),
)
permutation = Permutation.identity(table)
expected = np.transpose(physical_values, (0, 1, 3, 2))
batch = next(permutation.with_format("torch_dict").iter(2, skip_last_batch=False))
assert batch["tensor"].shape == (2, 2, 4, 3)
assert torch.equal(batch["tensor"], torch.from_numpy(expected.copy()))
tensor_only = permutation.select_columns(["tensor"])
rows = next(tensor_only.with_format("torch_row").iter(2, skip_last_batch=False))
assert rows[0].shape == (1, 2, 4, 3)
assert torch.equal(rows[0][0], torch.from_numpy(expected[0].copy()))
dataloader = torch.utils.data.DataLoader(
tensor_only.with_format("torch"), batch_size=2, shuffle=False
)
default_collated = next(iter(dataloader))
assert default_collated["tensor"].shape == (2, 2, 4, 3)
def test_permutation_torch_formats_bfloat16(mem_db):
values = [1.0, -1.5, 2.5, 0.0]
scalar_values = _bf16_array(values)
vector_values = pa.FixedSizeListArray.from_arrays(
_bf16_array([value for value in values for _ in range(2)]), 2
)
table = mem_db.create_table(
"bfloat16",
pa.table(
{
"id": range(4),
"scalar": scalar_values,
"vector": vector_values,
}
),
)
permutation = Permutation.identity(table)
batch = next(permutation.with_format("torch_dict").iter(2, skip_last_batch=False))
assert batch["scalar"].dtype == torch.bfloat16
assert batch["vector"].dtype == torch.bfloat16
assert torch.equal(batch["scalar"], torch.tensor(values[:2], dtype=torch.bfloat16))
assert torch.equal(
batch["vector"],
torch.tensor([[value, value] for value in values[:2]], dtype=torch.bfloat16),
)
arrow_batch = next(permutation.with_format("arrow").iter(2, skip_last_batch=False))
arrow_tensors = batch_to_tensor_columns(arrow_batch)
scalar_array = arrow_batch.column("scalar")
assert arrow_tensors["scalar"].data_ptr() == (
scalar_array.buffers()[1].address + scalar_array.offset * 2
)
sliced = arrow_batch.slice(1, 1)
sliced_tensors = batch_to_tensor_columns(sliced)
assert torch.equal(
sliced_tensors["scalar"],
torch.tensor([values[1]], dtype=torch.bfloat16),
)
assert torch.equal(
sliced_tensors["vector"],
torch.tensor([[values[1], values[1]]], dtype=torch.bfloat16),
)
skipped = next(
permutation.with_skip(1)
.with_format("torch_dict")
.iter(2, skip_last_batch=False)
)
assert torch.equal(
skipped["scalar"], torch.tensor(values[1:3], dtype=torch.bfloat16)
)
empty = permutation.with_format("torch_dict").take_offsets([])
assert empty["scalar"].shape == (0,)
assert empty["scalar"].dtype == torch.bfloat16
assert empty["vector"].shape == (0, 2)
assert empty["vector"].dtype == torch.bfloat16
unmarked = mem_db.create_table(
"unmarked_bfloat16",
pa.table(
{
"vector": pa.FixedSizeListArray.from_arrays(
pa.array(_bf16_storage(values), type=pa.binary(2)), 2
)
}
),
)
with pytest.raises(ValueError, match="not marked.*lance.bfloat16"):
next(
Permutation.identity(unmarked)
.with_format("torch_dict")
.iter(2, skip_last_batch=False)
)
def test_torch_formats_reject_nulls(mem_db):
parent_nulls = mem_db.create_table(
"parent_nulls",
pa.table(
{
"id": range(3),
"values": pa.array(
[[1.0, 2.0], None, [5.0, 6.0]],
type=pa.list_(pa.float32(), 2),
),
}
),
)
with pytest.raises(ValueError, match="contains 1 null"):
next(
Permutation.identity(parent_nulls)
.with_format("torch_dict")
.iter(2, skip_last_batch=False)
)
leaf_nulls = mem_db.create_table(
"leaf_nulls",
pa.table(
{
"id": range(2),
"values": pa.FixedSizeListArray.from_arrays(
pa.array([1.0, None, 5.0, 6.0], type=pa.float32()), 2
),
}
),
)
with pytest.raises(ValueError, match="contains 1 null"):
next(
Permutation.identity(leaf_nulls)
.with_format("torch_dict")
.iter(2, skip_last_batch=False)
)
leaf_only = Permutation.identity(leaf_nulls).select_columns(["values"])
with pytest.raises(ValueError, match="contains 1 null"):
next(leaf_only.with_format("torch_row").iter(2, skip_last_batch=False))
+27
View File
@@ -407,6 +407,33 @@ def test_value_to_sql_nan_and_infinity(tmp_path):
assert rows[4]["f64"] == 4.0 and rows[4]["f32"] == 4.0
def test_value_to_sql_enum_members(tmp_path):
# str() of an int- or float-valued Enum member is its name, which SQL reads
# as a field access, and a plain Enum member raised NotImplementedError.
import enum
class Priority(int, enum.Enum):
LOW = 1
HIGH = 2
class Weight(float, enum.Enum):
HALF = 0.5
class Color(enum.Enum):
RED = "red"
assert value_to_sql(Priority.HIGH) == "2"
assert value_to_sql(Weight.HALF) == "0.5"
assert value_to_sql(Color.RED) == "'red'"
db = lancedb.connect(tmp_path)
table = db.create_table(
"test", pa.table({"id": [1], "p": [1], "w": [1.0], "c": ["blue"]})
)
table.update(values={"p": Priority.HIGH, "w": Weight.HALF, "c": Color.RED})
assert table.to_arrow().to_pylist() == [{"id": 1, "p": 2, "w": 0.5, "c": "red"}]
def test_append_vector_columns():
registry = EmbeddingFunctionRegistry.get_instance()
registry.register("test")(MockTextEmbeddingFunction)
+1 -1
View File
@@ -120,7 +120,7 @@ def test_wal_hybrid_fuses_on_the_key_and_drops_it_again():
with_row_ids=True,
)
results = builder._finish_hybrid_results(
combined, blob_mode="lazy", blob_sources={}
combined, blob_mode="lazy", blob_sources={}, schema=None
)
assert "_rowid" not in results.column_names, "the surrogate is internal"
+40 -13
View File
@@ -5,7 +5,7 @@ use std::sync::Arc;
use std::time::Duration;
use crate::error::PythonErrorExt;
use crate::runtime::future_into_py;
use crate::runtime::{block_on_interruptible, future_into_py};
use arrow::{
array::RecordBatch,
datatypes::SchemaRef,
@@ -99,22 +99,49 @@ where
Q: ExecutableQuery + Send + 'static,
{
future_into_py(py, async move {
let mut options = QueryExecutionOptions::default();
// `None` means the caller wants one eager result, not the core's
// default batch size. An explicit value is still honored.
options.max_batch_length = max_batch_length.unwrap_or(0);
options.timeout = timeout;
let stream = query.execute_with_options(options).await.infer_error()?;
let schema = stream.schema();
let batches = stream.try_collect::<Vec<_>>().await.infer_error()?;
let reader: Box<dyn ArrowRecordBatchReader + Send> = Box::new(RecordBatchIterator::new(
batches.into_iter().map(Ok),
schema,
));
let reader = collect_to_reader(query, max_batch_length, timeout).await?;
Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind()))
})
}
/// Synchronous counterpart of [`execute_to_reader`].
///
/// The returned reader owns the collected batches; the caller converts it to
/// Python after reattaching to the interpreter. The wait releases the GIL and
/// keeps Python signal handlers on the calling thread.
pub fn execute_to_reader_sync<Q>(
query: Q,
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> PyResult<Box<dyn ArrowRecordBatchReader + Send>>
where
Q: ExecutableQuery + Send + 'static,
{
block_on_interruptible(collect_to_reader(query, max_batch_length, timeout))
}
async fn collect_to_reader<Q>(
query: Q,
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> PyResult<Box<dyn ArrowRecordBatchReader + Send>>
where
Q: ExecutableQuery + Send + 'static,
{
let mut options = QueryExecutionOptions::default();
// `None` means the caller wants one eager result, not the core's
// default batch size. An explicit value is still honored.
options.max_batch_length = max_batch_length.unwrap_or(0);
options.timeout = timeout;
let stream = query.execute_with_options(options).await.infer_error()?;
let schema = stream.schema();
let batches = stream.try_collect::<Vec<_>>().await.infer_error()?;
Ok(Box::new(RecordBatchIterator::new(
batches.into_iter().map(Ok),
schema,
)))
}
#[cfg(test)]
mod tests {
use super::*;
+152 -4
View File
@@ -20,6 +20,7 @@ use arrow::{
pyarrow::{FromPyArrow, PyArrowType, ToPyArrow},
};
use lancedb::{
BasePath,
connection::Connection as LanceConnection,
connection::NamespaceClientPushdownOperation,
database::namespace::LanceNamespaceDatabase,
@@ -30,9 +31,9 @@ use lancedb::{
};
use pyo3::{
Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python,
exceptions::{PyRuntimeError, PyValueError},
exceptions::{PyRuntimeError, PyTypeError, PyValueError},
pyclass, pyfunction, pymethods,
types::{PyAnyMethods, PyDict, PyDictMethods, PyList},
types::{PyAnyMethods, PyBool, PyDict, PyDictMethods, PyList},
};
fn materialized_view_builder(
@@ -56,6 +57,139 @@ fn materialized_view_builder(
}
}
/// Parse `initial_bases` into Lance base paths.
///
/// Accepts LanceDB's lightweight `BasePath`, a mapping with the same keys, or
/// a duck-typed `lance.DatasetBasePath`. `None` maps to no bases. Object
/// attributes follow `DatasetBasePath`: a reported `id` of `0` means
/// automatic assignment, while a mapping that sets `id=0` explicitly is
/// rejected because `0` is reserved for unregistered blob URIs. Explicit
/// non-zero ids must be unique.
fn parse_initial_bases(initial_bases: Option<Bound<'_, PyAny>>) -> PyResult<Option<Vec<BasePath>>> {
let Some(value) = initial_bases else {
return Ok(None);
};
if value.is_none() {
return Ok(None);
}
let mut bases = Vec::new();
let mut explicit_ids: HashSet<u32> = HashSet::new();
for (index, item) in value.try_iter()?.enumerate() {
let item = item?;
let base = parse_base_path(&item, index)?;
if base.id != 0 && !explicit_ids.insert(base.id) {
return Err(PyValueError::new_err(format!(
"initial_bases[{index}] reuses base id {}; explicit ids must be unique",
base.id
)));
}
bases.push(base);
}
Ok(Some(bases))
}
fn parse_base_path(item: &Bound<'_, PyAny>, index: usize) -> PyResult<BasePath> {
let (path, name, is_dataset_root, id) = if let Ok(dict) = item.cast::<PyDict>() {
let path = required_string(dict.get_item("path")?, index, "path")?;
let name = optional_string(dict.get_item("name")?, index, "name")?;
let is_dataset_root =
optional_bool(dict.get_item("is_dataset_root")?, index, "is_dataset_root")?;
let id = match dict.get_item("id")? {
None => 0,
Some(value) if value.is_none() => 0,
Some(value) => {
let id = base_id(&value, index)?;
if id == 0 {
return Err(PyValueError::new_err(format!(
"initial_bases[{index}] sets id=0, which is reserved for unregistered \
blob URIs; pass id=None to let Lance assign an ID"
)));
}
id
}
};
(path, name, is_dataset_root, id)
} else {
let path = item.getattr("path").map_err(|_| {
PyTypeError::new_err(format!(
"initial_bases[{index}] must be a BasePath, dict, or DatasetBasePath"
))
})?;
let path = required_string(Some(path), index, "path")?;
let name = item.getattr("name").ok().filter(|value| !value.is_none());
let name = optional_string(name, index, "name")?;
let is_dataset_root = match item.getattr("is_dataset_root") {
Ok(value) if !value.is_none() => value.extract::<bool>().map_err(|_| {
PyTypeError::new_err(format!(
"initial_bases[{index}].is_dataset_root must be a bool"
))
})?,
_ => false,
};
let id = match item.getattr("id") {
Ok(value) if !value.is_none() => base_id(&value, index)?,
_ => 0,
};
(path, name, is_dataset_root, id)
};
if path.is_empty() {
return Err(PyValueError::new_err(format!(
"initial_bases[{index}].path must not be empty"
)));
}
Ok(BasePath::new(id, path, name, is_dataset_root))
}
fn required_string(value: Option<Bound<'_, PyAny>>, index: usize, field: &str) -> PyResult<String> {
let Some(value) = value else {
return Err(PyValueError::new_err(format!(
"initial_bases[{index}] is missing '{field}'"
)));
};
value.extract::<String>().map_err(|_| {
PyTypeError::new_err(format!("initial_bases[{index}].{field} must be a string"))
})
}
fn optional_string(
value: Option<Bound<'_, PyAny>>,
index: usize,
field: &str,
) -> PyResult<Option<String>> {
match value {
None => Ok(None),
Some(value) if value.is_none() => Ok(None),
Some(value) => value.extract::<String>().map(Some).map_err(|_| {
PyTypeError::new_err(format!("initial_bases[{index}].{field} must be a string"))
}),
}
}
fn optional_bool(value: Option<Bound<'_, PyAny>>, index: usize, field: &str) -> PyResult<bool> {
match value {
None => Ok(false),
Some(value) if value.is_none() => Ok(false),
Some(value) => value.extract::<bool>().map_err(|_| {
PyTypeError::new_err(format!("initial_bases[{index}].{field} must be a bool"))
}),
}
}
fn base_id(value: &Bound<'_, PyAny>, index: usize) -> PyResult<u32> {
if value.is_instance_of::<PyBool>() {
return Err(PyTypeError::new_err(format!(
"initial_bases[{index}].id must be a positive integer, not a bool"
)));
}
value.extract::<u32>().map_err(|_| {
PyValueError::new_err(format!(
"initial_bases[{index}].id must be a positive integer that fits in a u32"
))
})
}
#[pyclass]
pub struct Connection {
inner: Option<LanceConnection>,
@@ -311,7 +445,7 @@ impl Connection {
}
#[allow(clippy::too_many_arguments)]
#[pyo3(signature = (name, mode, data, namespace_path=None, storage_options=None, location=None, namespace_client=None))]
#[pyo3(signature = (name, mode, data, namespace_path=None, storage_options=None, location=None, namespace_client=None, initial_bases=None, allow_external_blob_outside_bases=false))]
pub fn create_table<'a>(
self_: PyRef<'a, Self>,
name: String,
@@ -321,11 +455,14 @@ impl Connection {
storage_options: Option<HashMap<String, String>>,
location: Option<String>,
namespace_client: Option<Py<PyAny>>,
initial_bases: Option<Bound<'_, PyAny>>,
allow_external_blob_outside_bases: bool,
) -> PyResult<Bound<'a, PyAny>> {
let inner = self_.get_inner()?.clone();
let py = self_.py();
let mode = Self::parse_create_mode_str(mode)?;
let initial_bases = parse_initial_bases(initial_bases)?;
let batches: Box<dyn arrow::array::RecordBatchReader + Send> =
Box::new(ArrowArrayStreamReader::from_pyarrow_bound(&data)?);
@@ -333,6 +470,12 @@ impl Connection {
let ns_path = namespace_path.clone().unwrap_or_default();
let mut builder = inner.create_table(name.clone(), batches).mode(mode);
if let Some(bases) = initial_bases {
builder = builder.initial_bases(bases);
}
if allow_external_blob_outside_bases {
builder = builder.allow_external_blob_outside_bases(true);
}
builder = builder.namespace(ns_path.clone());
if let Some(storage_options) = storage_options {
builder = builder.storage_options(storage_options);
@@ -359,7 +502,7 @@ impl Connection {
}
#[allow(clippy::too_many_arguments)]
#[pyo3(signature = (name, mode, schema, namespace_path=None, storage_options=None, location=None, namespace_client=None))]
#[pyo3(signature = (name, mode, schema, namespace_path=None, storage_options=None, location=None, namespace_client=None, initial_bases=None))]
pub fn create_empty_table<'a>(
self_: PyRef<'a, Self>,
name: String,
@@ -369,11 +512,13 @@ impl Connection {
storage_options: Option<HashMap<String, String>>,
location: Option<String>,
namespace_client: Option<Py<PyAny>>,
initial_bases: Option<Bound<'_, PyAny>>,
) -> PyResult<Bound<'a, PyAny>> {
let inner = self_.get_inner()?.clone();
let py = self_.py();
let mode = Self::parse_create_mode_str(mode)?;
let initial_bases = parse_initial_bases(initial_bases)?;
let schema = Schema::from_pyarrow_bound(&schema)?;
@@ -382,6 +527,9 @@ impl Connection {
.create_empty_table(name.clone(), Arc::new(schema))
.mode(mode);
if let Some(bases) = initial_bases {
builder = builder.initial_bases(bases);
}
builder = builder.namespace(ns_path.clone());
if let Some(storage_options) = storage_options {
builder = builder.storage_options(storage_options);
+57
View File
@@ -33,6 +33,7 @@ use lancedb::query::{HasQuery, QueryBase};
use lancedb::table::AnyQuery;
use pyo3::Bound;
use pyo3::IntoPyObject;
use pyo3::Py;
use pyo3::PyAny;
use pyo3::PyRef;
use pyo3::PyResult;
@@ -65,6 +66,20 @@ fn analyze_plan_options(distributed_metrics: Option<&str>) -> PyResult<QueryExec
Ok(options)
}
fn execute_to_reader_sync<Q>(
py: Python<'_>,
query: Q,
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> PyResult<Py<PyAny>>
where
Q: ExecutableQuery + Send + 'static,
{
let reader =
py.detach(move || crate::arrow::execute_to_reader_sync(query, max_batch_length, timeout))?;
Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind()))
}
impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB<FtsQuery> {
type Error = PyErr;
@@ -357,6 +372,7 @@ pub struct PyQueryRequest {
pub offset: Option<usize>,
pub take_offsets: Option<Vec<u64>>,
pub take_row_ids: Option<Vec<u64>>,
pub preserve_order: Option<bool>,
pub filter: Option<PyQueryFilter>,
pub full_text_search: Option<PyLanceDB<FtsQuery>>,
pub select: PySelect,
@@ -390,6 +406,7 @@ impl From<AnyQuery> for PyQueryRequest {
offset: query_request.offset,
take_offsets: query_request.take_offsets,
take_row_ids: query_request.take_row_ids,
preserve_order: query_request.preserve_order.then_some(true),
filter: query_request.filter.map(PyQueryFilter),
full_text_search: query_request
.full_text_search
@@ -423,6 +440,7 @@ impl From<AnyQuery> for PyQueryRequest {
offset: vector_query.base.offset,
take_offsets: vector_query.base.take_offsets,
take_row_ids: vector_query.base.take_row_ids,
preserve_order: vector_query.base.preserve_order.then_some(true),
filter: vector_query.base.filter.map(PyQueryFilter),
full_text_search: None,
select_source_columns: PySelect::source_columns(&vector_query.base.select),
@@ -710,6 +728,15 @@ impl Query {
crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout)
}
#[pyo3(signature = (max_batch_length=None, timeout=None))]
pub fn execute_to_reader_sync(
self_: PyRef<'_, Self>,
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> PyResult<Py<PyAny>> {
execute_to_reader_sync(self_.py(), self_.inner.clone(), max_batch_length, timeout)
}
pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move {
@@ -765,6 +792,10 @@ impl TakeQuery {
self.inner = self.inner.clone().with_row_id();
}
pub fn preserve_order(&mut self) {
self.inner = self.inner.clone().preserve_order();
}
pub fn use_rte(&mut self, enable: bool) {
self.inner = self.inner.clone().use_rte(enable);
}
@@ -959,6 +990,23 @@ impl FTSQuery {
)
}
#[pyo3(signature = (max_batch_length=None, timeout=None))]
pub fn execute_to_reader_sync(
self_: PyRef<'_, Self>,
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> PyResult<Py<PyAny>> {
execute_to_reader_sync(
self_.py(),
self_
.inner
.clone()
.full_text_search(self_.fts_query.clone()),
max_batch_length,
timeout,
)
}
pub fn count_rows(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let mut inner = self_
.inner
@@ -1212,6 +1260,15 @@ impl VectorQuery {
crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout)
}
#[pyo3(signature = (max_batch_length=None, timeout=None))]
pub fn execute_to_reader_sync(
self_: PyRef<'_, Self>,
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> PyResult<Py<PyAny>> {
execute_to_reader_sync(self_.py(), self_.inner.clone(), max_batch_length, timeout)
}
pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move {
+199 -1
View File
@@ -93,15 +93,19 @@
//! `Arc` clone from becoming the final owner that drops it.
use std::future::Future;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::mpsc::{self, RecvTimeoutError};
use std::time::{Duration, Instant};
use arc_swap::ArcSwapOption;
use pyo3::{Bound, PyAny, PyResult, Python, conversion::IntoPyObject};
use futures::FutureExt;
use pyo3::{Bound, PyAny, PyResult, Python, conversion::IntoPyObject, exceptions::PyRuntimeError};
use pyo3_async_runtimes::{
TaskLocals,
err::RustPanic,
generic::{ContextExt, JoinError, Runtime},
};
use tokio::{runtime, task};
@@ -282,6 +286,111 @@ pub fn block_on<F: std::future::Future>(fut: F) -> F::Output {
get_runtime().block_on(fut)
}
/// How often an interruptible wait returns to the Python caller for signal checks.
const SIGNAL_CHECK_INTERVAL: Duration = Duration::from_millis(25);
/// Block on `fut` while keeping the Python caller responsive to signals.
///
/// The query task lives on the shared runtime and carries an [`OutstandingGuard`].
/// The caller waits on the result channel without holding the GIL and periodically
/// reacquires it to run CPython's signal handlers on the same thread. A signal
/// exception aborts the task and drops the result receiver.
///
/// A synchronous callback already running on a multi-threaded Tokio worker uses
/// [`tokio::task::block_in_place`] so the core can be handed off while the callback
/// waits. Current-thread runtimes and contexts that reject blocking are returned as
/// Python errors instead of falling back to the Python event loop.
pub fn block_on_interruptible<F, T>(fut: F) -> PyResult<T>
where
F: Future<Output = PyResult<T>> + Send + 'static,
T: Send + 'static,
{
block_on_interruptible_with(fut, || Python::attach(|py| py.check_signals()))
}
fn block_on_interruptible_with<F, T, C>(fut: F, check: C) -> PyResult<T>
where
F: Future<Output = PyResult<T>> + Send + 'static,
T: Send + 'static,
C: FnMut() -> PyResult<()>,
{
match runtime::Handle::try_current() {
Ok(handle) => match handle.runtime_flavor() {
runtime::RuntimeFlavor::MultiThread => {
let result = catch_unwind(AssertUnwindSafe(|| {
task::block_in_place(|| block_on_interruptible_inner(fut, check))
}));
match result {
Ok(result) => result,
Err(payload) => Err(PyRuntimeError::new_err(format!(
"synchronous query cannot block in this Tokio context: {}",
panic_message(payload.as_ref())
))),
}
}
_ => Err(PyRuntimeError::new_err(
"synchronous query execution cannot block on a current-thread Tokio runtime; use the async API",
)),
},
Err(_) => block_on_interruptible_inner(fut, check),
}
}
fn block_on_interruptible_inner<F, T, C>(fut: F, mut check: C) -> PyResult<T>
where
F: Future<Output = PyResult<T>> + Send + 'static,
T: Send + 'static,
C: FnMut() -> PyResult<()>,
{
let guard = OutstandingGuard::new();
let (tx, rx) = mpsc::sync_channel(1);
let task = async move {
let _guard = guard;
let result = AssertUnwindSafe(fut).catch_unwind().await;
// Dropping a completed result is enough when the caller has already
// returned on an interrupt; the task's guard is dropped with it.
let _ = tx.send(result);
};
let handle = get_runtime().spawn(task);
loop {
match rx.recv_timeout(SIGNAL_CHECK_INTERVAL) {
Ok(Ok(result)) => {
check()?;
return result;
}
Ok(Err(payload)) => {
check()?;
return Err(RustPanic::new_err(format!(
"rust future panicked: {}",
panic_message(payload.as_ref())
)));
}
Err(RecvTimeoutError::Timeout) => {
if let Err(error) = check() {
handle.abort();
return Err(error);
}
}
Err(RecvTimeoutError::Disconnected) => {
return Err(PyRuntimeError::new_err(
"query task stopped before producing a result",
));
}
}
}
}
fn panic_message(payload: &(dyn std::any::Any + Send)) -> &str {
if let Some(message) = payload.downcast_ref::<&str>() {
message
} else if let Some(message) = payload.downcast_ref::<String>() {
message.as_str()
} else {
"unknown error"
}
}
/// Run a detached task, including when the caller is already on a runtime worker.
/// Keep it visible to [`shutdown`] until it finishes.
pub fn spawn_background<F>(fut: F)
@@ -571,6 +680,95 @@ mod tests {
shutdown(Duration::from_secs(5));
}
#[test]
fn test_block_on_interruptible_aborts_and_drops_future() {
use std::sync::mpsc;
Python::initialize();
let _lock = lock_runtime_state_for_test();
let (started_tx, started_rx) = mpsc::channel();
let (dropped_tx, dropped_rx) = mpsc::channel();
struct DropNotify(Option<mpsc::Sender<()>>);
impl Drop for DropNotify {
fn drop(&mut self) {
if let Some(tx) = self.0.take() {
let _ = tx.send(());
}
}
}
let fut = async move {
started_tx.send(()).unwrap();
let _notify = DropNotify(Some(dropped_tx));
std::future::pending::<()>().await;
#[allow(unreachable_code)]
Ok::<(), pyo3::PyErr>(())
};
let result = block_on_interruptible_with(fut, || {
Err(pyo3::exceptions::PyRuntimeError::new_err("interrupted"))
});
assert!(result.is_err());
started_rx
.recv_timeout(Duration::from_secs(2))
.expect("query task never started");
dropped_rx
.recv_timeout(Duration::from_secs(2))
.expect("interrupted query future was not dropped");
shutdown(Duration::from_secs(5));
}
#[test]
fn test_block_on_interruptible_maps_panic() {
Python::initialize();
let result = block_on_interruptible(async {
panic!("boom");
#[allow(unreachable_code)]
Ok::<(), pyo3::PyErr>(())
});
assert!(
result
.expect_err("panic must become a Python exception")
.to_string()
.contains("rust future panicked: boom")
);
}
#[test]
fn test_block_on_interruptible_rejects_current_thread_runtime() {
Python::initialize();
let runtime = runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("current-thread runtime");
let error = runtime
.block_on(async { block_on_interruptible(async { Ok::<_, pyo3::PyErr>(1) }) })
.expect_err("current-thread runtime must be rejected");
assert!(error.to_string().contains("current-thread"));
}
#[cfg(target_os = "linux")]
#[test]
fn test_block_on_interruptible_from_single_worker_runtime() {
Python::initialize();
let _lock = lock_runtime_state_for_test();
let _worker_threads = TestWorkerThreads::new(1);
shutdown(Duration::from_secs(5));
let (done_tx, done_rx) = mpsc::channel();
drop(get_runtime().spawn(async move {
let result = block_on_interruptible(async { Ok::<_, pyo3::PyErr>(42) });
let _ = done_tx.send(result.map_err(|error| error.to_string()));
}));
let result = done_rx
.recv_timeout(Duration::from_secs(10))
.expect("single-worker runtime made no progress");
assert_eq!(result.expect("single-worker query failed"), 42);
shutdown(Duration::from_secs(5));
}
// Adapted from the concurrent reproducer that found the original bug:
// many threads hammering the runtime while shutdown races them, not
// just the sequential rebuild path above. Before every reader held its
+24 -2
View File
@@ -9,7 +9,7 @@ use std::{
},
};
use crate::runtime::{block_on, future_into_py, spawn_background};
use crate::runtime::{block_on, block_on_interruptible, future_into_py, spawn_background};
use crate::{
connection::Connection,
error::PythonErrorExt,
@@ -1619,6 +1619,14 @@ impl Table {
})
}
pub fn schema_sync(self_: PyRef<'_, Self>) -> PyResult<Py<PyAny>> {
let inner = self_.inner_ref()?.clone();
let schema = self_.py().detach(move || {
block_on_interruptible(async move { inner.schema().await.infer_error() })
})?;
Python::attach(|py| schema.to_pyarrow(py).map(|obj| obj.unbind()))
}
#[pyo3(signature = (data, mode, progress=None, write_parallelism=None, allow_external_blob_outside_bases=false, retries=None))]
pub fn add<'a>(
self_: PyRef<'a, Self>,
@@ -2240,15 +2248,29 @@ impl Table {
}
/// Open lazy blob handles for `row_ids` from blob v2 column `column`.
#[pyo3(signature = (column, row_ids, buffer_size=None))]
#[pyo3(signature = (column, row_ids, buffer_size=None, *, version=None, snapshot_identity=None))]
pub fn fetch_blob_files(
self_: PyRef<'_, Self>,
column: String,
row_ids: Vec<u64>,
buffer_size: Option<usize>,
version: Option<u64>,
snapshot_identity: Option<String>,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
let inner = match (version, snapshot_identity) {
(None, None) => inner,
(Some(version), Some(identity)) => inner
.query_snapshot_with_identity(version, &identity)
.await
.infer_error()?,
_ => {
return Err(PyValueError::new_err(
"deferred blob reads require both query version and snapshot identity",
));
}
};
let handles = inner
.fetch_blob_files(column.as_str(), &row_ids)
.await