Merge branch 'main' of https://github.com/lancedb/lancedb into merge-insert-source-stats

# Conflicts:
#	rust/lancedb/src/table/computed_columns.rs
#	rust/lancedb/src/table/refresh.rs
This commit is contained in:
Will Jones
2026-10-29 21:28:02 +00:00
529 changed files with 53347 additions and 6953 deletions
+12
View File
@@ -48,6 +48,18 @@ Build the package
make develop
```
Local SQL computed columns and materialized-view creation/refresh are experimental
and disabled in published packages. To opt in when building from this directory:
```shell
uv run --extra tests --extra dev maturin develop --features experimental-functions --extras tests,dev
uv run --no-sync pytest python/tests -m experimental_functions
```
Rebuild without `--features experimental-functions` to test the default package.
The tests detect the compiled feature; remote operations, metadata protections,
and ordinary eager `add_columns` transforms remain available in both builds.
Format:
```shell
+7 -5
View File
@@ -1,6 +1,6 @@
[package]
name = "lancedb-python"
version = "0.41.0-beta.9"
version = "0.41.0-beta.17"
publish = false
edition.workspace = true
description = "Python bindings for LanceDB"
@@ -8,7 +8,7 @@ license.workspace = true
repository.workspace = true
keywords.workspace = true
categories.workspace = true
rust-version = "1.94.0"
rust-version = "1.95.0"
[lib]
name = "_lancedb"
@@ -22,6 +22,7 @@ bytes.workspace = true
lancedb.workspace = true
datafusion-common.workspace = true
lance-core.workspace = true
lance-arrow.workspace = true
lance-namespace.workspace = true
lance-namespace-impls.workspace = true
lance-io.workspace = true
@@ -29,9 +30,9 @@ env_logger.workspace = true
log.workspace = true
# Maturin enables extension-module mode for Python builds. Keeping it out of
# Cargo features lets Rust unit tests link against libpython.
pyo3 = { version = "0.28", features = ["abi3-py310", "chrono", "uuid"] }
pyo3 = { version = "0.29", features = ["abi3-py310", "chrono", "uuid"] }
chrono.workspace = true
pyo3-async-runtimes = { version = "0.28", features = [
pyo3-async-runtimes = { version = "0.29", features = [
"attributes",
"tokio-runtime",
] }
@@ -45,9 +46,10 @@ uuid.workspace = true
libc = "0.2"
[build-dependencies]
pyo3-build-config = { version = "0.28", features = ["abi3-py310"] }
pyo3-build-config = "0.29"
[features]
default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/cos", "lancedb/goosefs", "lancedb/metrics-otel"]
fp16kernels = ["lancedb/fp16kernels"]
remote = ["lancedb/remote"]
experimental-functions = ["lancedb/experimental-functions"]
+76
View File
@@ -40,6 +40,33 @@ Stable releases are created about every 2 weeks. For the latest features and bug
pip install --pre --extra-index-url https://pypi.fury.io/lancedb/ lancedb
```
If you also need the optional `lance` Python API, install the `pylance` extra
and include the Lance preview index:
```bash
pip install --pre \
--extra-index-url https://pypi.fury.io/lancedb/ \
--extra-index-url https://pypi.fury.io/lance-format/ \
"lancedb[pylance]"
```
With uv, also select the best matching version across the indexes:
```bash
uv pip install --prerelease allow \
--index https://pypi.fury.io/lancedb/ \
--index https://pypi.fury.io/lance-format/ \
--index-strategy unsafe-best-match \
"lancedb[pylance]"
```
The LanceDB preview index contains old `pylance` releases; current Lance previews
are published to the `lance-format` index. By default, uv only considers versions
from the first index containing a package, which can select an old `pylance` or
backtrack to an older LanceDB release. `unsafe-best-match` searches all configured
indexes, like pip; use it only with indexes you trust. Install the extra rather
than an unconstrained `pylance` so LanceDB's minimum supported version is enforced.
### Threading in CPU-limited containers
LanceDB uses separate pools for compute work and storage I/O. On a container with
@@ -74,3 +101,52 @@ print(results)
### Development
See [CONTRIBUTING.md](./CONTRIBUTING.md) for information on how to contribute to LanceDB.
### Opening SQL blob descriptors
A SQL `blob_descriptor(video)` result keeps the Blob V2 storage metadata and a
`source` struct containing its table URI, version, commit timestamp, branch,
column and row identity. This example uses a remote SQL connection whose SQL
service produces those source-bearing descriptors. Open the reference on the
source table to read incrementally:
```python
rows = db.execute_query("""
SELECT f.timestamp, blob_descriptor(v.video) AS video
FROM videos v JOIN frames f ON v.id = f.video_id
""").read_all()
videos = db.open_table("videos")
for row in rows.to_pylist():
if row["video"] is not None:
with videos.open_blob_file(row["video"]) as video:
frame = extract_frame(video, row["timestamp"])
```
`open_blob_file` accepts the dictionary or an Arrow struct scalar directly. It
keeps the query's version and branch without changing the table handle's checkout.
Payload bytes load on reads. An external blob with an unspecified size may need a
metadata-only HEAD request to open.
`videos.open_blob_files(rows["video"])` returns an iterator over the same handles,
preserving order, duplicates and nulls (`None`). It accepts Arrow arrays/chunked
arrays or another iterable and opens each handle as iteration advances. Close each
non-null handle after use. Async tables offer `await videos.open_blob_file(...)`
and `async for video in videos.open_blob_files(...)`.
```python
for video in videos.open_blob_files(rows["video"]):
if video is not None:
with video:
header = video.read(4096)
```
To extract a frame while retaining each row's timestamp, iterate over the
handles and rows together:
```python
for row, video in zip(rows.to_pylist(), videos.open_blob_files(rows["video"])):
if video is not None:
with video:
frame = extract_frame(video, row["timestamp"])
```
+3 -2
View File
@@ -45,7 +45,8 @@ repository = "https://github.com/lancedb/lancedb"
[project.optional-dependencies]
pylance = [
"pylance>=5.0.0b5",
# Keep the minimum in the bundled Lance major and compatible with tests below.
"pylance>=15.0.0b3",
]
# A library only needs the OpenTelemetry API; the application supplies and
# configures the SDK (the actual exporter/reader). See
@@ -63,7 +64,7 @@ tests = [
"polars>=0.19, <=1.32.3",
"pyarrow<25",
"pyarrow-stubs>=16.0",
"pylance==14.0.0b12",
"pylance==15.0.0b6",
"requests>=2.31.0",
"datafusion>=54,<55",
"opentelemetry-sdk>=1.30.0",
+44 -25
View File
@@ -2,14 +2,12 @@
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import importlib.metadata
import os
from concurrent.futures import ThreadPoolExecutor
from datetime import timedelta
from typing import Dict, Optional, Union, Any, List, Iterable, TYPE_CHECKING
__version__ = importlib.metadata.version("lancedb")
from ._lancedb import __version__ as __version__
from ._lancedb import connect as lancedb_connect
from ._lancedb import FtsToken
from ._lancedb import FunctionErrorFragment as FunctionErrorFragment
@@ -24,6 +22,7 @@ from .remote import ClientConfig
from .remote.db import RemoteDBConnection
from .expr import Expr, col, lit, func
from .schema import blob, vector
from ._blob_reader import BlobReader as BlobReader
from .job import AsyncJob, Job
from .sql import AsyncQuery as AsyncSqlQuery
from .sql import Query as SqlQuery
@@ -48,7 +47,7 @@ from .materialized_view import (
MaterializedViewDefinition,
)
from .view import ViewDescription as ViewDescription
from .table import AsyncTable, Table
from .table import AsyncTable, CompactionOptions, Table
from .types import BaseTokenizerType
from ._lancedb import Session
from .namespace import (
@@ -138,18 +137,18 @@ def connect(
The uri of the database. When ``namespace_client_impl`` is provided you may
omit ``uri`` and connect through a namespace client instead.
api_key: str, optional
If presented, connect to LanceDB cloud.
If presented, connect to LanceDB Enterprise or LanceDB Cloud (legacy).
Otherwise, connect to a database on file system or cloud storage.
Can be set via environment variable `LANCEDB_API_KEY`.
OAuth configuration is currently supported only by ``connect_async``;
synchronous LanceDB Cloud connections require an API key.
synchronous ``db://`` connections require an API key.
region: str, default "us-east-1"
The region to use for LanceDB Cloud.
The region to use for LanceDB Cloud (legacy).
host_override: str, optional
The override url for LanceDB Cloud.
The URL of the LanceDB Enterprise deployment to connect to.
sql_host_override: str, optional
The remote SQL service endpoint override. The client connects lazily when SQL
is first executed and retains that connection.
The LanceDB Enterprise SQL service endpoint override. The client
connects lazily when SQL is first executed and retains that connection.
read_consistency_interval: timedelta, default None
The interval at which to check for updates to the table from other
processes. If None, then consistency is not checked. For performance
@@ -165,18 +164,19 @@ def connect(
often each read pays the cost of checking for updates against object
storage, raising per-read latency and cost.
client_config: ClientConfig or dict, optional
Configuration options for the LanceDB Cloud HTTP client. If a dict, then
Configuration options for the HTTP client used by ``db://`` connections.
If a dict, then
the keys are the attributes of the ClientConfig class. If None, then the
default configuration is used.
storage_options: dict, optional
Additional options for the storage backend. See available options at
<https://docs.lancedb.com/storage/>
manifest_enabled : bool, default False
When true for local/native connections, use directory namespace
When true for LanceDB Embedded connections, use directory namespace
manifests as the source of truth for table metadata. Existing
directory-listed root tables are migrated into the manifest on access.
session: Session, optional
(For LanceDB OSS only)
(For LanceDB Embedded only)
A session to use for this connection. Sessions allow you to configure
cache sizes for index and metadata caches, which can significantly
impact memory use and performance. They can also be re-used across
@@ -232,7 +232,7 @@ def connect(
In-memory databases are not persisted. Tables are dropped when the last
connection or table handle referencing them is closed.
Connect to LanceDB cloud:
Connect to LanceDB Enterprise or LanceDB Cloud (legacy):
>>> db = lancedb.connect("db://my_database", api_key="ldb_...",
... client_config={"retry_config": {"retries": 5}})
@@ -280,10 +280,27 @@ def connect(
"uri is required when not connecting through a namespace client"
)
if isinstance(uri, str) and uri.startswith("db://"):
# Preserve the deprecated remote timeout options, but validate all other
# unknown keywords just as the local connection does.
unknown_kwargs = {
key: value
for key, value in kwargs.items()
if key not in ("connection_timeout", "read_timeout")
}
if unknown_kwargs:
raise ValueError(f"Unknown keyword arguments: {unknown_kwargs}")
if session is not None:
raise NotImplementedError(
"session is not supported for LanceDB Distributed connections"
)
if manifest_enabled:
raise NotImplementedError(
"manifest_enabled is not supported for LanceDB Distributed connections"
)
if api_key is None:
api_key = os.environ.get("LANCEDB_API_KEY")
if api_key is None:
raise ValueError(f"api_key is required to connect to LanceDB cloud: {uri}")
raise ValueError(f"api_key is required to connect to {uri}")
if isinstance(request_thread_pool, int):
request_thread_pool = ThreadPoolExecutor(request_thread_pool)
return RemoteDBConnection(
@@ -466,16 +483,16 @@ async def connect_async(
uri: str or Path
The uri of the database.
api_key: str, optional
If present, connect to LanceDB cloud.
If present, connect to LanceDB Enterprise or LanceDB Cloud (legacy).
Otherwise, connect to a database on file system or cloud storage.
Can be set via environment variable `LANCEDB_API_KEY`.
region: str, default "us-east-1"
The region to use for LanceDB Cloud.
The region to use for LanceDB Cloud (legacy).
host_override: str, optional
The override url for LanceDB Cloud.
The URL of the LanceDB Enterprise deployment to connect to.
sql_host_override: str, optional
The remote SQL service endpoint override. The client connects lazily when SQL
is first executed and retains that connection.
The LanceDB Enterprise SQL service endpoint override. The client
connects lazily when SQL is first executed and retains that connection.
read_consistency_interval: timedelta, default None
The interval at which to check for updates to the table from other
processes. If None, then consistency is not checked. For performance
@@ -491,27 +508,28 @@ async def connect_async(
often each read pays the cost of checking for updates against object
storage, raising per-read latency and cost.
client_config: ClientConfig or dict, optional
Configuration options for the LanceDB Cloud HTTP client. If a dict, then
Configuration options for the HTTP client used by ``db://`` connections.
If a dict, then
the keys are the attributes of the ClientConfig class. If None, then the
default configuration is used.
storage_options: dict, optional
Additional options for the storage backend. See available options at
<https://docs.lancedb.com/storage/>
session: Session, optional
(For LanceDB OSS only)
(For LanceDB Embedded only)
A session to use for this connection. Sessions allow you to configure
cache sizes for index and metadata caches, which can significantly
impact memory use and performance. They can also be re-used across
multiple connections to share the same cache state.
manifest_enabled : bool, default False
When true for local/native connections, use directory namespace
When true for LanceDB Embedded connections, use directory namespace
manifests as the source of truth for table metadata. Existing
directory-listed root tables are migrated into the manifest on access.
namespace_client_properties : dict, optional
Additional directory namespace client properties to use with
``manifest_enabled=True``.
oauth_config : OAuthConfig, optional
OAuth configuration for LanceDB Cloud/Enterprise. This is supported by
OAuth configuration for LanceDB Enterprise. This is supported by
``connect_async`` only; synchronous ``connect`` uses API key
authentication for ``db://`` URIs.
@@ -537,7 +555,7 @@ async def connect_async(
... )
... # For tests and temporary data, use an in-memory database
... db = await lancedb.connect_async("memory://")
... # Connect to LanceDB cloud
... # Connect to LanceDB Enterprise or LanceDB Cloud (legacy)
... db = await lancedb.connect_async("db://my_database", api_key="ldb_...",
... client_config={
... "retry_config": {"retries": 5}})
@@ -594,6 +612,7 @@ __all__ = [
"AsyncSqlQuery",
"AsyncLanceNamespaceDBConnection",
"AsyncTable",
"CompactionOptions",
"FtsToken",
"col",
"Expr",
+25 -3
View File
@@ -7,7 +7,7 @@ from __future__ import annotations
import io
import operator
from collections.abc import Awaitable, Callable, Iterable
from collections.abc import Awaitable, Callable, Iterable, Mapping
from typing import TYPE_CHECKING, Optional, Union
import pyarrow as pa
@@ -31,6 +31,18 @@ FetchBlobsSync = Callable[[str, list[int]], pa.Array | pa.ChunkedArray]
FetchBlobsAsync = Callable[[str, list[int]], Awaitable[pa.Array | pa.ChunkedArray]]
def _normalize_blob_descriptor(value):
if isinstance(value, pa.Scalar):
value = value.as_py()
if value is None:
return None
if not isinstance(value, Mapping):
raise TypeError(
"blob descriptor must be a mapping, an Arrow struct scalar, or None"
)
return dict(value)
class BlobFile(io.RawIOBase):
"""Seekable lazy handle from :meth:`~lancedb.table.Table.fetch_blob_files`.
@@ -268,7 +280,11 @@ async def replace_v2_blob_columns_with_bytes(
row_ids = _hit_row_ids(tbl, present)
for output_name, source_name in present.items():
tbl = _set_blob_column(
tbl, output_name, await fetch_blobs(source_name, row_ids)
tbl,
output_name,
await fetch_blobs(source_name, row_ids)
if row_ids
else pa.array([], type=pa.large_binary()),
)
return tbl
@@ -283,7 +299,13 @@ def replace_v2_blob_columns_with_bytes_sync(
return tbl
row_ids = _hit_row_ids(tbl, present)
for output_name, source_name in present.items():
tbl = _set_blob_column(tbl, output_name, fetch_blobs(source_name, row_ids))
tbl = _set_blob_column(
tbl,
output_name,
fetch_blobs(source_name, row_ids)
if row_ids
else pa.array([], type=pa.large_binary()),
)
return tbl
+123
View File
@@ -0,0 +1,123 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Seekable binary input for Functions that consume Blob V2 values lazily."""
import io
import operator
import urllib.request
from collections.abc import Callable
from http import HTTPStatus
_READ_CHUNK_BYTES = 1024 * 1024
_READ_TIMEOUT_SECONDS = 300
class BlobReader(io.RawIOBase):
"""Read a blob incrementally inside a Function.
Annotating a Function input with ``BlobReader`` requests a lazy, seekable
reader. Annotating it with ``bytes`` requests materialized bytes instead.
``read_range`` does not change the sequential cursor. Readers are scoped
to the invocation and must not be retained for a later call.
A packaged Function's source imports the worker's ``lance_blob.BlobReader``
in place of this class.
For local calls, construct a reader from a range-reading callable and the
blob's size. The callable accepts an offset and length and returns bytes.
"""
def __init__(self, read_range: Callable[[int, int], bytes], size: int):
super().__init__()
self._read_range = read_range
self._size = operator.index(size)
if self._size < 0:
raise ValueError("blob size must be nonnegative")
self._position = 0
@classmethod
def _from_uri(cls, uri: str, size: int):
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
def read_range(offset, length):
request = urllib.request.Request(
uri, headers={"Range": f"bytes={offset}-{offset + length - 1}"}
)
with opener.open(request, timeout=_READ_TIMEOUT_SECONDS) as response:
if response.status != HTTPStatus.PARTIAL_CONTENT:
raise OSError(
"blob range service did not return a partial response"
)
data = response.read(length + 1)
if len(data) != length:
raise OSError(
"blob range service returned an invalid payload length"
)
return data
return cls(read_range, size)
def readable(self) -> bool:
return not self.closed
def seekable(self) -> bool:
return not self.closed
def size(self) -> int:
"""Return the blob size without reading its payload."""
self._checkClosed()
return self._size
def tell(self) -> int:
self._checkClosed()
return self._position
def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
self._checkClosed()
offset = operator.index(offset)
if whence == io.SEEK_SET:
position = offset
elif whence == io.SEEK_CUR:
position = self._position + offset
elif whence == io.SEEK_END:
position = self._size + offset
else:
raise ValueError(f"invalid whence: {whence}")
if position < 0:
raise ValueError("negative seek position")
self._position = position
return position
def read_range(self, offset: int, length: int) -> bytes:
"""Read a byte range without changing the cursor; truncate at EOF."""
self._checkClosed()
offset, length = operator.index(offset), operator.index(length)
if offset < 0 or length < 0:
raise ValueError("offset and length must be nonnegative")
remaining = min(length, max(0, self._size - offset))
chunks = []
while remaining:
count = min(remaining, _READ_CHUNK_BYTES)
chunk = self._read_range(offset, count)
if len(chunk) != count:
raise OSError("blob range reader returned an invalid payload length")
chunks.append(chunk)
offset += count
remaining -= count
return b"".join(chunks)
def read(self, size: int = -1) -> bytes:
self._checkClosed()
size = -1 if size is None else operator.index(size)
if size < 0:
size = max(0, self._size - self._position)
data = self.read_range(self._position, size)
self._position += len(data)
return data
def readinto(self, buffer) -> int:
view = memoryview(buffer).cast("B")
data = self.read(len(view))
view[: len(data)] = data
return len(data)
+45 -17
View File
@@ -19,19 +19,20 @@ from .index import (
FTS,
)
from lance_namespace import (
ListNamespacesResponse,
CreateNamespaceResponse,
DropNamespaceResponse,
DescribeNamespaceResponse,
ListTablesResponse,
)
from .remote import ClientConfig
from .types import BaseTokenizerType
_experimental_functions_enabled: bool
IvfHnswPq: type[HnswPq] = HnswPq
IvfHnswSq: type[HnswSq] = HnswSq
IvfHnswFlat: type[HnswFlat] = HnswFlat
AnalyzePlanDistributedMetrics = Literal["aggregate", "per_worker", "full"]
__version__: str
class MetricPoint:
name: str
@@ -114,12 +115,12 @@ class Connection(object):
uri: str
async def is_open(self): ...
async def close(self): ...
async def list_namespaces(
def list_namespaces(
self,
namespace_path: Optional[List[str]] = None,
page_token: Optional[str] = None,
limit: Optional[int] = None,
) -> ListNamespacesResponse: ...
) -> NameListing: ...
async def create_namespace(
self,
namespace_path: List[str],
@@ -136,12 +137,14 @@ class Connection(object):
self,
namespace_path: List[str],
) -> DescribeNamespaceResponse: ...
async def list_tables(
async def namespace_exists(self, namespace_id: List[str]) -> bool: ...
async def table_exists(self, table_id: List[str]) -> bool: ...
def list_tables(
self,
namespace_path: Optional[List[str]] = None,
page_token: Optional[str] = None,
limit: Optional[int] = None,
) -> ListTablesResponse: ...
) -> NameListing: ...
async def table_names(
self,
namespace_path: Optional[List[str]],
@@ -270,6 +273,8 @@ class Connection(object):
filter: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> Table: ...
async def create_materialized_view_async(
self,
@@ -279,6 +284,8 @@ class Connection(object):
filter: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> Job: ...
def list_materialized_views(
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
@@ -318,6 +325,8 @@ class Job:
@property
def id(self) -> Optional[str]: ...
@property
def job_type(self) -> Optional[str]: ...
@property
def _state(self) -> Optional[str]: ...
@property
def _description(self) -> Optional[JobDescription]: ...
@@ -501,10 +510,17 @@ class Table:
async def delete(self, filter: Union[str, PyExpr]) -> DeleteResult: ...
async def add_columns(self, columns: list[tuple[str, str]]) -> AddColumnsResult: ...
async def add_computed_columns(
self, columns: list[tuple[str, str]]
self,
columns: list[tuple[str, str]],
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[int] = None,
) -> AddColumnsResult: ...
async def add_function_columns(
self, application_json: str, output_name: Optional[str]
self,
application_json: str,
output_name: Optional[str],
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[int] = None,
) -> AddColumnsResult: ...
async def refresh_column(self, column: str) -> RefreshColumnResult: ...
async def refresh_column_async(self, column: str) -> Job: ...
@@ -515,10 +531,10 @@ class Table:
limit: Optional[int] = None,
) -> FunctionErrors: ...
async def refresh_materialized_view(
self, source_version: Optional[int] = None
self, source_version: Optional[int] = None, *, full: bool = False
) -> RefreshMaterializedViewResult: ...
async def refresh_materialized_view_async(
self, source_version: Optional[int] = None
self, source_version: Optional[int] = None, *, full: bool = False
) -> Job: ...
async def materialized_view_definition(self) -> str: ...
async def add_columns_with_schema(self, schema: pa.Schema) -> AddColumnsResult: ...
@@ -533,6 +549,7 @@ class Table:
*,
cleanup_since_ms: Optional[int] = None,
delete_unverified: Optional[bool] = None,
compaction_options: Optional[Dict[str, Any]] = None,
) -> OptimizeStats: ...
async def uri(self) -> str: ...
async def initial_storage_options(self) -> Optional[Dict[str, str]]: ...
@@ -569,6 +586,7 @@ class Table:
async def fetch_blob_files(
self, column: str, row_ids: list[int]
) -> list[Optional[BlobFile]]: ...
async def open_blob_file(self, descriptor: str) -> BlobFile: ...
def vector_search(self) -> VectorQuery: ...
class Tags:
@@ -850,9 +868,9 @@ class RTEWriteSpec:
@staticmethod
def unsharded() -> "RTEWriteSpec": ...
def with_maintained_indexes(self, indexes: Optional[List[str]]) -> "RTEWriteSpec":
"""Set which indexes the RTE keeps up to date. None resolves every
index on the table at install, failing if one cannot be maintained;
a list is verbatim, empty means none."""
"""Set which indexes the RTE keeps up to date. None is every index on
the table, now and later, skipping any it cannot maintain; a list is
verbatim, empty means none."""
...
def with_writer_config_defaults(self, defaults: Dict[str, str]) -> "RTEWriteSpec":
"""Return a copy of this spec recording the given default
@@ -906,9 +924,9 @@ class FunctionErrors:
class RefreshMaterializedViewResult:
@staticmethod
def from_json(value: str) -> RefreshMaterializedViewResult: ...
mode: str
rows_written: int
source_version: int
mode: Optional[str]
rows_written: Optional[int]
source_version: Optional[int]
version: int
class AlterColumnsResult:
@@ -940,6 +958,15 @@ class AsyncPermutationBuilder:
counts: Optional[List[int]] = None,
fixed: Optional[int] = None,
) -> "AsyncPermutationBuilder": ...
def bootstrap_sample(
self,
num_samples: int,
*,
ratios: Optional[List[float]] = None,
counts: Optional[List[int]] = None,
fixed: Optional[int] = None,
seed: Optional[int] = None,
) -> "AsyncPermutationBuilder": ...
def split_calculated(self, calculation: str) -> "AsyncPermutationBuilder": ...
def shuffle(
self, seed: Optional[int], clump_size: Optional[int]
@@ -965,7 +992,7 @@ class Catalog:
) -> Connection: ...
async def connect_database(self, name: str) -> Connection: ...
async def drop_database(
self, name: str, *, ignore_missing: bool = False
self, name: str, *, ignore_missing: bool = False, cascade: bool = False
) -> None: ...
def list_databases(
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
@@ -990,6 +1017,7 @@ async def connect_catalog(
class NameListing:
def num_page_results(self) -> int: ...
def page_token(self) -> Optional[str]: ...
async def next_page(self) -> Optional[dict[str, Any]]: ...
def __aiter__(self) -> NameListing: ...
async def __anext__(self) -> str: ...
+12 -1
View File
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
from functools import singledispatch
from typing import List, Optional, Tuple, Union
from typing import AsyncIterator, List, Optional, Tuple, Union
from lancedb.pydantic import LanceModel, model_to_dict
import pyarrow as pa
@@ -30,6 +30,7 @@ class AsyncRecordBatchReader:
The schema of the batches produced by the stream.
Accessing the schema does not consume any data from the stream
"""
self._inner: AsyncIterator[pa.RecordBatch]
if isinstance(inner, pa.Table):
self._inner = self._async_iter_from_table(inner, max_batch_length)
self.schema: pa.Schema = inner.schema
@@ -39,6 +40,16 @@ class AsyncRecordBatchReader:
else:
raise TypeError("inner must be a RecordBatchStream or a Table")
@classmethod
def _from_batches(
cls, schema: pa.Schema, batches: AsyncIterator[pa.RecordBatch]
) -> "AsyncRecordBatchReader":
"""Wrap a transformed stream without consuming its first batch."""
reader = cls.__new__(cls)
reader.schema = schema
reader._inner = batches
return reader
async def read_all(self) -> List[pa.RecordBatch]:
"""
Read all the record batches from the stream
+20 -6
View File
@@ -130,9 +130,15 @@ class AsyncCatalog:
self._inner.list_databases(page_token=page_token, page_limit=page_limit)
)
async def drop_database(self, name: str, *, ignore_missing: bool = False) -> None:
"""Drop an empty database. A nonempty database is an error."""
await self._inner.drop_database(name, ignore_missing=ignore_missing)
async def drop_database(
self, name: str, *, ignore_missing: bool = False, cascade: bool = False
) -> None:
"""Drop a database. A nonempty database is an error unless ``cascade`` is set,
which drops everything in it first; the name stays taken until the server
finishes cleaning up their storage."""
await self._inner.drop_database(
name, ignore_missing=ignore_missing, cascade=cascade
)
class Catalog:
@@ -207,9 +213,17 @@ class Catalog:
self._inner.list_databases(page_token=page_token, page_limit=page_limit)
)
def drop_database(self, name: str, *, ignore_missing: bool = False) -> None:
"""Drop an empty database. A nonempty database is an error."""
LOOP.run(self._inner.drop_database(name, ignore_missing=ignore_missing))
def drop_database(
self, name: str, *, ignore_missing: bool = False, cascade: bool = False
) -> None:
"""Drop a database. A nonempty database is an error unless ``cascade`` is set,
which drops everything in it first; the name stays taken until the server
finishes cleaning up their storage."""
LOOP.run(
self._inner.drop_database(
name, ignore_missing=ignore_missing, cascade=cascade
)
)
async def connect_catalog_async(
+267 -109
View File
@@ -5,6 +5,7 @@
from __future__ import annotations
from abc import abstractmethod
import asyncio
from datetime import timedelta
from pathlib import Path
import sys
@@ -31,18 +32,24 @@ if sys.version_info >= (3, 12):
else:
from overrides import EnforceOverrides, override # type: ignore
from lancedb.listing import AsyncListing, Listing
from lancedb.listing import (
AsyncListing,
AsyncNamespaceListing,
AsyncTableListing,
Listing,
NamespaceListing,
TableListing,
validate_page_limit,
)
from lancedb.embeddings.registry import EmbeddingFunctionRegistry
from lancedb.common import data_to_reader, sanitize_uri, validate_schema
from lancedb.background_loop import LOOP
from lance_namespace import (
LanceNamespace,
ListNamespacesResponse,
CreateNamespaceResponse,
DropNamespaceResponse,
DescribeNamespaceResponse,
ListTablesResponse,
connect as namespace_connect,
)
from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError
@@ -170,7 +177,7 @@ class DBConnection(EnforceOverrides):
namespace_path: Optional[List[str]] = None,
page_token: Optional[str] = None,
limit: Optional[int] = None,
) -> ListNamespacesResponse:
) -> NamespaceListing:
"""List immediate child namespace names in the given namespace.
Parameters
@@ -186,12 +193,12 @@ class DBConnection(EnforceOverrides):
Returns
-------
ListNamespacesResponse
NamespaceListing
Response containing namespace names and optional page_token for pagination.
"""
if namespace_path is None:
namespace_path = []
return ListNamespacesResponse(namespaces=[], page_token=None)
return NamespaceListing(AsyncNamespaceListing(None, empty=True))
def create_namespace(
self,
@@ -316,8 +323,8 @@ class DBConnection(EnforceOverrides):
namespace_path: Optional[List[str]] = None,
page_token: Optional[str] = None,
limit: Optional[int] = None,
) -> ListTablesResponse:
"""List a page of tables in this database.
) -> TableListing:
"""List tables in this database, one page at a time.
Parameters
----------
@@ -333,7 +340,7 @@ class DBConnection(EnforceOverrides):
Returns
-------
ListTablesResponse
TableListing
Response containing table names and optional page_token for pagination.
"""
raise NotImplementedError(
@@ -409,6 +416,10 @@ class DBConnection(EnforceOverrides):
- pyarrow.Schema
- [LanceModel][lancedb.pydantic.LanceModel]
Plain binary values are cast into blob columns declared with
[blob][lancedb.schema.blob]. To construct Arrow record batches
explicitly, use [blob_array][lancedb.schema.blob_array].
mode: str; default "create"
The mode to use when creating the table.
Can be "create", "overwrite", or "exist_ok".
@@ -421,10 +432,13 @@ class DBConnection(EnforceOverrides):
it will not add the provided data but will validate against any
schema that's specified.
on_bad_vectors: str, default "error"
What to do if any of the vectors are not the same size or contains NaNs.
One of "error", "drop", "fill".
How to handle vectors with incorrect sizes, NaNs, or null elements.
One of "error", "drop", "fill", "null".
fill_value: float
The value to use when filling vectors. Only used if on_bad_vectors="fill".
NaN or null elements and missing trailing elements are replaced with this
value. Valid elements are preserved, and vectors longer than the expected
dimension are truncated.
storage_options: dict, optional
Additional options for the storage backend. Options already set on the
connection will be inherited by the table, but can be overridden here.
@@ -541,7 +555,9 @@ class DBConnection(EnforceOverrides):
LanceTable(name='table4', ...)
"""
raise NotImplementedError
raise NotImplementedError(
"create_table is not supported for this connection type"
)
def __getitem__(self, name: str) -> LanceTable:
return self.open_table(name)
@@ -596,7 +612,9 @@ class DBConnection(EnforceOverrides):
-------
A LanceTable object representing the table.
"""
raise NotImplementedError
raise NotImplementedError(
"open_table is not supported for this connection type"
)
def create_materialized_view(
self,
@@ -607,9 +625,15 @@ class DBConnection(EnforceOverrides):
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> MaterializedView:
"""Define a materialized view named ``name`` over the table ``source``.
LanceDB Embedded creation and refresh require a source build with the
``experimental-functions`` Cargo feature. Published packages leave it
disabled; LanceDB Distributed operations remain available.
The view is populated before creation returns. Pass
``with_no_data=True`` to create only its definition and empty backing
table. The view is a normal table: it can be queried, indexed and
@@ -631,6 +655,13 @@ class DBConnection(EnforceOverrides):
Cap the view at this many rows, in materialization order.
with_no_data: bool, default False
Skip the initial refresh and leave the backing table empty.
auto_refresh_enabled: bool, optional
Enable or disable automatic refresh in LanceDB Distributed.
When omitted, the server determines whether automatic refresh is enabled.
LanceDB Embedded does not support automatic refresh.
auto_refresh_interval_seconds: float, optional
Positive, finite refresh interval in seconds in LanceDB Distributed.
When omitted, the server determines when to refresh.
Returns
-------
@@ -649,13 +680,17 @@ class DBConnection(EnforceOverrides):
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> Job[None]:
"""Submit materialized-view creation and return its job.
The job may already be complete for a local database. On LanceDB
Cloud and Enterprise, its ``id`` is the server job identifier from
the ``202 Accepted`` create response. Wait for the job before opening
or querying the view.
The job may already be complete in LanceDB Embedded. In LanceDB
Distributed, creation
submits CREATE MATERIALIZED VIEW through the SQL server. Its job has
``job_type == "query"`` and ``id`` identifies the connection-scoped
query. Registry event history is unavailable.
Wait for the job before opening or querying the view.
"""
raise NotImplementedError(
"materialized views are not supported on this connection type"
@@ -691,9 +726,9 @@ class DBConnection(EnforceOverrides):
) -> None:
"""Drop a materialized view.
The view may become unavailable before physical cleanup finishes. Use
:meth:`drop_materialized_view_async` to retain and wait for the cleanup
job.
In LanceDB Distributed, drops wait for the SQL command to remove the
catalog binding.
Physical cleanup continues in the background.
"""
raise NotImplementedError(
"materialized views are not supported on this connection type"
@@ -702,11 +737,12 @@ class DBConnection(EnforceOverrides):
def drop_materialized_view_async(
self, name: str, namespace_path: Optional[List[str]] = None
) -> Job[None]:
"""Start dropping a materialized view and return its cleanup job.
"""Start dropping a materialized view and return its job.
The job may already be complete for a local database. On LanceDB Cloud
and Enterprise, its ``id`` is the server job identifier from the
``202 Accepted`` drop response.
The job may already be complete in LanceDB Embedded. In LanceDB
Distributed, jobs have
type ``query`` and use the SQL query ID as ``id``. Waiting confirms
catalog removal; physical cleanup continues in the background.
"""
raise NotImplementedError(
"materialized views are not supported on this connection type"
@@ -725,13 +761,17 @@ class DBConnection(EnforceOverrides):
"""
if namespace_path is None:
namespace_path = []
raise NotImplementedError
raise NotImplementedError(
"drop_table is not supported for this connection type"
)
def drop_table_async(
self, name: str, namespace_path: Optional[List[str]] = None
) -> Job:
"""Start dropping a table and return its cleanup job."""
raise NotImplementedError
raise NotImplementedError(
"drop_table_async is not supported for this connection type"
)
def rename_table(
self,
@@ -759,19 +799,26 @@ class DBConnection(EnforceOverrides):
cur_namespace_path = []
if new_namespace_path is None:
new_namespace_path = []
raise NotImplementedError
raise NotImplementedError(
"rename_table is not supported for this connection type"
)
def drop_database(self):
"""
Drop database
This is the same thing as dropping all the tables
"""
raise NotImplementedError
raise NotImplementedError(
"drop_database is not supported for this connection type"
)
def drop_all_tables(self, namespace_path: Optional[List[str]] = None):
"""
Drop all tables from the database
LanceDB Distributed does not currently support this operation. Use
``list_tables()`` and ``drop_table()`` to drop tables individually.
Parameters
----------
namespace_path: List[str], optional
@@ -780,12 +827,32 @@ class DBConnection(EnforceOverrides):
"""
if namespace_path is None:
namespace_path = []
raise NotImplementedError
raise NotImplementedError(
"drop_all_tables is not supported for this connection type"
)
@property
def uri(self) -> str:
"""The URI of this database."""
return self._uri
def _all_table_names(self) -> Generator[str, None, None]:
page_token = None
while True:
response = self.list_tables(page_token=page_token)
yield from response.tables
page_token = response.page_token
if not page_token:
return
def __len__(self) -> int:
"""Return the number of tables in the root namespace across all pages."""
return sum(1 for _ in self._all_table_names())
def __contains__(self, name: str) -> bool:
"""Return whether the root namespace contains the named table."""
return name in self._all_table_names()
def namespace_client(self) -> LanceNamespace:
"""Get the equivalent namespace client for this connection.
@@ -794,7 +861,7 @@ class DBConnection(EnforceOverrides):
For namespace connections, this returns the backing namespace client.
For enterprise (remote) connections, this returns a RestNamespace
For LanceDB Enterprise connections, this returns a RestNamespace
with the same URI and authentication headers.
Returns
@@ -830,7 +897,7 @@ class DBConnection(EnforceOverrides):
The server builds the OCI image and registers the completed artifact.
This is the blocking counterpart of :meth:`create_function_async`.
Local connections raise ``NotImplementedError``.
LanceDB Embedded connections raise ``NotImplementedError``.
Parameters
----------
@@ -874,7 +941,7 @@ class DBConnection(EnforceOverrides):
The server-side job builds the OCI image, then registers the completed
artifact. Waiting on the job returns the immutable Function version.
Local connections raise ``NotImplementedError``.
LanceDB Embedded connections raise ``NotImplementedError``.
"""
raise NotImplementedError(
"Function catalog operations are not supported for this connection type"
@@ -902,7 +969,7 @@ class DBConnection(EnforceOverrides):
"""List every published immutable Function version in a namespace.
Functions in child namespaces are not included. Results are ordered by
Function name then version. Local connections raise
Function name then version. LanceDB Embedded connections raise
``NotImplementedError``.
Examples
@@ -952,7 +1019,7 @@ class DBConnection(EnforceOverrides):
The name is unbound before this returns; the object's content may still
be being deleted. Call :meth:`Job.wait` to wait for that to finish. When
the server deletes inline, or when nothing was bound, the returned job
is already finished and has no id. Local connections raise
is already finished and has no id. LanceDB Embedded connections raise
NotImplementedError.
"""
raise NotImplementedError(
@@ -981,7 +1048,7 @@ class DBConnection(EnforceOverrides):
Fails if it does not exist. Every Function bound to the Secret uses the
new value from its next job, and no new Function version is created --
which is how a rotation reaches columns pinned to a version registered
before it. Local connections raise ``NotImplementedError``.
before it. LanceDB Embedded connections raise ``NotImplementedError``.
"""
raise NotImplementedError(
"Secret operations are not supported for this connection type"
@@ -997,7 +1064,8 @@ class DBConnection(EnforceOverrides):
"""The names of every Secret in this database.
Names only. No method returns a stored credential, by construction
rather than by policy. Local connections raise ``NotImplementedError``.
rather than by policy. LanceDB Embedded connections raise
``NotImplementedError``.
Returns a lazy iterator. ``page_limit`` limits each request, not the total;
``page_token`` resumes from a saved token. Requests and errors occur during
@@ -1015,7 +1083,7 @@ class DBConnection(EnforceOverrides):
Functions bound to it fail at their next job, naming the Secret; that
is the revocation path. The name becomes free to reuse, and a new
Secret under it is picked up by everything still bound to that name.
Local connections raise ``NotImplementedError``.
LanceDB Embedded connections raise ``NotImplementedError``.
"""
raise NotImplementedError(
"Secret operations are not supported for this connection type"
@@ -1043,7 +1111,7 @@ class DBConnection(EnforceOverrides):
its readers see its sources as they are at read time.
There is no replace: a name already taken is an error, and changing a
view is a drop followed by a create. Local connections raise
view is a drop followed by a create. LanceDB Embedded connections raise
``NotImplementedError``.
>>> import lancedb
@@ -1065,7 +1133,7 @@ class DBConnection(EnforceOverrides):
schema that query resolved to.
The schema is the one recorded at creation; a source altered since then
shows up when the view is read. Local connections raise
shows up when the view is read. LanceDB Embedded connections raise
``NotImplementedError``.
"""
raise NotImplementedError(
@@ -1079,7 +1147,7 @@ class DBConnection(EnforceOverrides):
The tables it reads are untouched: a view holds no rows of its own. Use
:meth:`drop_view_async` to get the cleanup job instead of waiting on it.
Local connections raise ``NotImplementedError``.
LanceDB Embedded connections raise ``NotImplementedError``.
"""
raise NotImplementedError(
"View operations are not supported for this connection type"
@@ -1218,18 +1286,19 @@ class DBConnection(EnforceOverrides):
parameters=[np.array([0.1, 0.2, 0.3], dtype=np.float32), 10],
)
Parameters are supported in queries, not in DDL or DML. A
parameterized query runs on the call that returns its rows:
cancelling it, or dropping its handle before reading, stops it on the
server. Its status follows that stream as well: ``describe()``
reports ``running`` until the reader has received every row, so open
``reader()`` directly rather than waiting for ``finished``.
Parameters are supported in queries, not in DDL or DML. With or
without parameters, the server chooses whether to stream rows on the
initial call or return a polling continuation. The reader follows
either path transparently. Dropping an unread handle or its reader
stops a directly streamed query; deferred execution requires explicit
cancellation. Open ``reader()`` directly: a streamed query needs its
reader to make progress and reports ``running`` until the stream ends.
Local connections do not support SQL.
LanceDB Embedded connections do not support SQL.
"""
raise NotImplementedError("SQL is not supported for this connection type")
def describe_query(self, query_id: UUID) -> QueryDescription:
def describe_query(self, query_id: Union[UUID, str]) -> QueryDescription:
"""Describe a submitted SQL query by its connection-scoped id."""
raise NotImplementedError("SQL is not supported for this connection type")
@@ -1288,6 +1357,10 @@ class LanceDBConnection(DBConnection):
self.storage_options = storage_options
self._manifest_enabled = manifest_enabled
self._namespace_client_properties = namespace_client_properties
# The native connection does not expose the Python Session wrapper.
# Keep the object supplied by the caller so this property stays
# synchronous for debugger inspection.
self._session = session
if _inner is not None:
self._conn = _inner
# Native-derived wrappers resolve this in their async reconstruction
@@ -1354,7 +1427,12 @@ class LanceDBConnection(DBConnection):
@property
def session(self) -> Optional[Session]:
return self._conn.session
"""Return the session supplied when this connection was opened.
None when the caller did not pass a session, including connections
reconstructed with :meth:`from_inner`.
"""
return self._session
@property
def uri(self) -> str:
@@ -1415,7 +1493,7 @@ class LanceDBConnection(DBConnection):
namespace_path: Optional[List[str]] = None,
page_token: Optional[str] = None,
limit: Optional[int] = None,
) -> ListNamespacesResponse:
) -> NamespaceListing:
"""List immediate child namespace names in the given namespace.
Parameters
@@ -1431,16 +1509,14 @@ class LanceDBConnection(DBConnection):
Returns
-------
ListNamespacesResponse
NamespaceListing
Response containing namespace names and optional page_token for pagination.
"""
if namespace_path is None:
namespace_path = []
return LOOP.run(
return NamespaceListing(
self._conn.list_namespaces(
namespace_path=namespace_path,
page_token=page_token,
limit=limit,
namespace_path=namespace_path, page_token=page_token, limit=limit
)
)
@@ -1491,8 +1567,8 @@ class LanceDBConnection(DBConnection):
namespace_path: Optional[List[str]] = None,
page_token: Optional[str] = None,
limit: Optional[int] = None,
) -> ListTablesResponse:
"""List a page of tables in this database.
) -> TableListing:
"""List tables in this database, one page at a time.
Parameters
----------
@@ -1508,12 +1584,12 @@ class LanceDBConnection(DBConnection):
Returns
-------
ListTablesResponse
TableListing
Response containing table names and optional page_token for pagination.
"""
if namespace_path is None:
namespace_path = []
return LOOP.run(
return TableListing(
self._conn.list_tables(
namespace_path=namespace_path, page_token=page_token, limit=limit
)
@@ -1562,21 +1638,6 @@ class LanceDBConnection(DBConnection):
)
)
def _all_table_names(self) -> Generator[str, None, None]:
page_token = None
while True:
response = self.list_tables(page_token=page_token)
yield from response.tables
page_token = response.page_token
if not page_token:
return
def __len__(self) -> int:
return sum(1 for _ in self._all_table_names())
def __contains__(self, name: str) -> bool:
return name in self._all_table_names()
@override
def create_table(
self,
@@ -1706,8 +1767,14 @@ class LanceDBConnection(DBConnection):
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> MaterializedView:
"""Define a materialized view named ``name`` over the table ``source``.
LanceDB Embedded creation and refresh require a source build with the
``experimental-functions`` Cargo feature. Published packages leave it
disabled; LanceDB Distributed operations remain available.
See
[DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view].
@@ -1717,13 +1784,13 @@ class LanceDBConnection(DBConnection):
>>> db = lancedb.connect("./.lancedb")
>>> data = [{"name": "ada", "age": 36}, {"name": "kid", "age": 7}]
>>> table = db.create_table("people", data)
>>> view = db.create_materialized_view(
>>> view = db.create_materialized_view( # doctest: +SKIP
... "adults",
... "people",
... select=["name", ("shout", "upper(name)")],
... where="age >= 18",
... )
>>> view.table.count_rows()
>>> view.table.count_rows() # doctest: +SKIP
1
"""
LOOP.run(
@@ -1734,6 +1801,8 @@ class LanceDBConnection(DBConnection):
where=where,
limit=limit,
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
)
)
return MaterializedView(self.open_table(name))
@@ -1748,6 +1817,8 @@ class LanceDBConnection(DBConnection):
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> Job[None]:
job = LOOP.run(
self._conn.create_materialized_view_async(
@@ -1757,6 +1828,8 @@ class LanceDBConnection(DBConnection):
where=where,
limit=limit,
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
)
)
return Job(job)
@@ -2196,12 +2269,12 @@ class AsyncConnection(object):
To obtain a connection you can use the [connect_async][lancedb.connect_async]
function.
This could be a native connection (using lance) or a remote connection (e.g. for
connecting to LanceDb Cloud)
This could be a LanceDB Embedded connection (using lance) or a LanceDB Distributed
connection (e.g. for connecting to LanceDB Enterprise)
Local connections do not currently hold any open resources but they may do so in the
future (for example, for shared cache or connections to catalog services) Remote
connections represent an open connection to the remote server. The
Embedded connections do not currently hold any open resources but they may do so in
the future (for example, for shared cache or connections to catalog services)
Distributed connections represent an open connection to the server. The
[close][lancedb.db.AsyncConnection.close] method can be used to release any
underlying resources eagerly. The connection can also be used as a context manager.
@@ -2257,12 +2330,12 @@ class AsyncConnection(object):
else:
return None
async def list_namespaces(
def list_namespaces(
self,
namespace_path: Optional[List[str]] = None,
page_token: Optional[str] = None,
limit: Optional[int] = None,
) -> ListNamespacesResponse:
) -> AsyncNamespaceListing:
"""List immediate child namespace names in the given namespace.
Parameters
@@ -2277,15 +2350,18 @@ class AsyncConnection(object):
Returns
-------
ListNamespacesResponse
AsyncNamespaceListing
Response containing namespace names and optional pagination token
"""
if namespace_path is None:
namespace_path = []
result = await self._inner.list_namespaces(
validate_page_limit(limit)
inner = self._inner.list_namespaces(
namespace_path=namespace_path, page_token=page_token, limit=limit
)
return ListNamespacesResponse(**result)
if limit == 0:
return AsyncNamespaceListing(None, empty=True)
return AsyncNamespaceListing(inner, page_token)
async def create_namespace(
self,
@@ -2364,13 +2440,56 @@ class AsyncConnection(object):
result = await self._inner.describe_namespace(namespace_path)
return DescribeNamespaceResponse(**result)
async def list_tables(
async def namespace_exists(self, namespace_id: List[str]) -> bool:
"""Check if a namespace exists.
Parameters
----------
namespace_id: List[str]
The namespace identifier to check. An empty list represents root.
Returns
-------
bool
True if the namespace exists, False if it is not found.
Other errors, including permission errors, are propagated.
Examples
--------
>>> async def check_namespace(conn):
... return await conn.namespace_exists(["analytics"])
"""
return await self._inner.namespace_exists(namespace_id)
async def table_exists(self, table_id: List[str]) -> bool:
"""Check if a table exists.
Parameters
----------
table_id: List[str]
The full identifier, including namespace segments and table name.
Must contain at least the table name.
Returns
-------
bool
True if the table exists, False if it is not found.
Other errors, including permission errors, are propagated.
Examples
--------
>>> async def check_table(conn):
... return await conn.table_exists(["analytics", "events"])
"""
return await self._inner.table_exists(table_id)
def list_tables(
self,
namespace_path: Optional[List[str]] = None,
page_token: Optional[str] = None,
limit: Optional[int] = None,
) -> ListTablesResponse:
"""List a page of tables in this database.
) -> AsyncTableListing:
"""List tables in this database, one page at a time.
Parameters
----------
@@ -2386,15 +2505,18 @@ class AsyncConnection(object):
Returns
-------
ListTablesResponse
AsyncTableListing
Response containing table names and optional page_token for pagination.
"""
if namespace_path is None:
namespace_path = []
result = await self._inner.list_tables(
validate_page_limit(limit)
inner = self._inner.list_tables(
namespace_path=namespace_path, page_token=page_token, limit=limit
)
return ListTablesResponse(**result)
if limit == 0:
return AsyncTableListing(None, empty=True)
return AsyncTableListing(inner, page_token)
async def table_names(
self,
@@ -2480,6 +2602,10 @@ class AsyncConnection(object):
- pyarrow.Schema
- [LanceModel][lancedb.pydantic.LanceModel]
Plain binary values are cast into blob columns declared with
[blob][lancedb.schema.blob]. To construct Arrow record batches
explicitly, use [blob_array][lancedb.schema.blob_array].
mode: Literal["create", "overwrite", "exist_ok"]; default "create"
The mode to use when creating the table.
Can be "create", "overwrite", or "exist_ok".
@@ -2492,10 +2618,13 @@ class AsyncConnection(object):
it will not add the provided data but will validate against any
schema that's specified.
on_bad_vectors: str, default "error"
What to do if any of the vectors are not the same size or contains NaNs.
One of "error", "drop", "fill".
How to handle vectors with incorrect sizes, NaNs, or null elements.
One of "error", "drop", "fill", "null".
fill_value: float
The value to use when filling vectors. Only used if on_bad_vectors="fill".
NaN or null elements and missing trailing elements are replaced with this
value. Valid elements are preserved, and vectors longer than the expected
dimension are truncated.
storage_options: dict, optional
Additional options for the storage backend. Options already set on the
connection will be inherited by the table, but can be overridden here.
@@ -2633,8 +2762,16 @@ class AsyncConnection(object):
if fill_value is None:
fill_value = 0.0
data, schema = sanitize_create_table(
data, schema, metadata, on_bad_vectors, fill_value
# Input preparation may advance a user-provided iterator. Keep that work
# off the background event loop so an iterator can use the synchronous
# LanceDB API without blocking the loop that API needs to make progress.
data, schema = await asyncio.to_thread(
sanitize_create_table,
data,
schema,
metadata,
on_bad_vectors,
fill_value,
)
validate_schema(schema)
@@ -2767,8 +2904,14 @@ class AsyncConnection(object):
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> AsyncMaterializedView:
"""Define a materialized view named ``name`` over the table ``source``.
LanceDB Embedded creation and refresh require a source build with the
``experimental-functions`` Cargo feature. Published packages leave it
disabled; LanceDB Distributed operations remain available.
See
[DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view].
"""
@@ -2782,6 +2925,8 @@ class AsyncConnection(object):
filter=where,
limit=limit,
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
**native_options,
)
return AsyncMaterializedView(AsyncTable(inner))
@@ -2795,10 +2940,14 @@ class AsyncConnection(object):
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> AsyncJob[None]:
"""Submit materialized-view creation and return its job.
Wait for the returned job before opening or querying the view.
Wait for the returned job before opening or querying the view. In LanceDB
Distributed, creation uses SQL; ``job_type`` is ``"query"`` and ``id``
identifies that query on this connection.
"""
source, native_options = await self._materialized_view_source(
source, select, where, limit
@@ -2810,6 +2959,8 @@ class AsyncConnection(object):
filter=where,
limit=limit,
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
**native_options,
)
return AsyncJob(inner)
@@ -2849,9 +3000,9 @@ class AsyncConnection(object):
) -> None:
"""Drop a materialized view.
The view may become unavailable before physical cleanup finishes. Use
:meth:`drop_materialized_view_async` to retain and wait for the cleanup
job.
In LanceDB Distributed, drops wait for the SQL command to remove the
catalog binding.
Physical cleanup continues in the background.
"""
if namespace_path is None:
namespace_path = []
@@ -2863,10 +3014,11 @@ class AsyncConnection(object):
*,
namespace_path: Optional[List[str]] = None,
) -> AsyncJob[None]:
"""Start dropping a materialized view and return its cleanup job.
"""Start dropping a materialized view and return its job.
Await :meth:`AsyncJob.wait` before assuming physical cleanup has
finished.
In LanceDB Distributed, the job has type ``query`` and its ID identifies
the SQL query. Await :meth:`AsyncJob.wait` for catalog removal; physical
cleanup continues in the background.
"""
if namespace_path is None:
namespace_path = []
@@ -3039,7 +3191,7 @@ class AsyncConnection(object):
[EnvVarSecret][lancedb.secrets.EnvVarSecret], each naming a Secret and
the environment variable its value arrives in. ``namespace_path`` is
the namespace the Function is registered in; None or an empty list is
the root. Local connections raise ``NotImplementedError``.
the root. LanceDB Embedded connections raise ``NotImplementedError``.
"""
if not isinstance(definition, UdfDefinition):
raise TypeError("create_function_async requires a @udf definition")
@@ -3071,7 +3223,7 @@ class AsyncConnection(object):
"""List every published immutable Function version in a namespace.
Functions in child namespaces are not included. Results are ordered by
Function name then version. Local connections raise
Function name then version. LanceDB Embedded connections raise
``NotImplementedError``.
Returns a lazy iterator. ``page_limit`` limits each request, not the total;
@@ -3326,7 +3478,7 @@ class AsyncConnection(object):
references. The namespace defaults to ``["public"]``. ``parameters``
binds values to ``$1`` / ``$name`` placeholders; see
[DBConnection.execute_query_async][lancedb.db.DBConnection.execute_query_async].
Local connections raise ``NotImplementedError``.
LanceDB Embedded connections raise ``NotImplementedError``.
"""
return AsyncSqlQuery(
await self._inner.execute_query_async(
@@ -3336,8 +3488,14 @@ class AsyncConnection(object):
)
)
async def describe_query(self, query_id: UUID) -> QueryDescription:
"""Describe a submitted SQL query by its connection-scoped id."""
async def describe_query(self, query_id: Union[UUID, str]) -> QueryDescription:
"""Describe a submitted SQL query by its UUID or string ID.
For a handle with ``job_type == "query"``, pass its ``id`` on the
connection that submitted it. Registry job IDs are not query IDs.
"""
if isinstance(query_id, str):
query_id = UUID(query_id)
return await self._inner.describe_query(query_id)
async def namespace_client(self) -> LanceNamespace:
@@ -3348,7 +3506,7 @@ class AsyncConnection(object):
For namespace connections, this returns the backing namespace client.
For enterprise (remote) connections, this returns a RestNamespace
For LanceDB Enterprise connections, this returns a RestNamespace
with the same URI and authentication headers.
Returns
@@ -16,6 +16,7 @@ from .instructor import InstructorEmbeddingFunction
from .ollama import OllamaEmbeddings
from .open_clip import OpenClipEmbeddings
from .openai import OpenAIEmbeddings
from .nvidia import NvidiaEmbeddings
from .registry import EmbeddingFunctionRegistry, get_registry, register
from .sentence_transformers import SentenceTransformerEmbeddings
from .gte import GteEmbeddings
@@ -40,6 +41,7 @@ __all__ = [
"register",
"SentenceTransformerEmbeddings",
"OpenAIEmbeddings",
"NvidiaEmbeddings",
"OpenClipEmbeddings",
"BedRockText",
"CohereEmbeddingFunction",
+11 -5
View File
@@ -38,9 +38,11 @@ class EmbeddingFunction(BaseModel, ABC):
3. ndims() which returns the number of dimensions of the vector column
"""
max_retries: int = (
7 # Setting 0 disables retires. Maybe this should not be enabled by default,
)
# Maximum number of retries for transient errors (rate limits, 5xx responses,
# connection errors, ...), with exponential backoff capped at 60 seconds between
# attempts. Permanent errors (HTTP 4xx other than 408/409/429) are never retried.
# Setting 0 disables retries.
max_retries: int = 7
_ndims: int = PrivateAttr()
_original_args: dict = PrivateAttr()
@@ -239,7 +241,9 @@ class EmbeddingFunction(BaseModel, ABC):
Creates a pydantic Field that can automatically annotate
the source column for this embedding function
"""
return Field(json_schema_extra={"source_column_for": self}, **kwargs)
json_schema_extra = dict(kwargs.pop("json_schema_extra", None) or {})
json_schema_extra["source_column_for"] = self
return Field(json_schema_extra=json_schema_extra, **kwargs)
def VectorField(self, **kwargs):
"""
@@ -250,7 +254,9 @@ class EmbeddingFunction(BaseModel, ABC):
static type checkers. LanceDB will infer the fixed vector dimension from
this embedding function.
"""
return Field(json_schema_extra={"vector_column_for": self}, **kwargs)
json_schema_extra = dict(kwargs.pop("json_schema_extra", None) or {})
json_schema_extra["vector_column_for"] = self
return Field(json_schema_extra=json_schema_extra, **kwargs)
def __eq__(self, __value: object) -> bool:
if not hasattr(__value, "__dict__"):
+10 -6
View File
@@ -22,16 +22,20 @@ class CohereEmbeddingFunction(TextEmbeddingFunction):
Parameters
----------
name : str, default "embed-multilingual-v2.0"
name : str, default "embed-multilingual-v3.0"
The name of the model to use. List of acceptable models:
* embed-english-v3.0
* embed-multilingual-v3.0
* embed-english-light-v3.0
* embed-multilingual-light-v3.0
* embed-english-v2.0
* embed-english-light-v2.0
* embed-multilingual-v2.0
The v2.0 models (embed-english-v2.0, embed-english-light-v2.0 and
embed-multilingual-v2.0) were retired by Cohere on April 4, 2026.
The previous default produced 768-dimensional vectors, while the new
default produces 1024-dimensional vectors. Existing tables containing
vectors from a v2.0 model must be re-embedded with an active model into
a table whose vector column has the matching dimension.
source_input_type : str, default "search_document"
The input type for the source column in the database
@@ -65,7 +69,7 @@ class CohereEmbeddingFunction(TextEmbeddingFunction):
cohere = EmbeddingFunctionRegistry
.get_instance()
.get("cohere")
.create(name="embed-multilingual-v2.0")
.create(name="embed-multilingual-v3.0")
class TextModel(LanceModel):
text: str = cohere.SourceField()
@@ -81,7 +85,7 @@ class CohereEmbeddingFunction(TextEmbeddingFunction):
"""
name: str = "embed-multilingual-v2.0"
name: str = "embed-multilingual-v3.0"
source_input_type: str = "search_document"
query_input_type: str = "search_query"
client: ClassVar = None
+13 -13
View File
@@ -5,9 +5,10 @@
import os
import io
import base64
from functools import cached_property
from urllib.parse import urlparse
from pathlib import Path
from typing import TYPE_CHECKING, ClassVar, List, Union, Optional, Any, Dict
from typing import TYPE_CHECKING, List, Union, Optional, Any, Dict
import numpy as np
import pyarrow as pa
@@ -51,7 +52,6 @@ class JinaEmbeddings(EmbeddingFunction):
name: str = "jina-clip-v1"
api_key: Optional[str] = None
_session: ClassVar = None
def ndims(self):
# TODO: fix hardcoding
@@ -206,8 +206,7 @@ class JinaEmbeddings(EmbeddingFunction):
texts: list[str] or np.ndarray (of str)
The texts to embed
"""
self._init_client()
resp = JinaEmbeddings._session.post( # type: ignore
resp = self._session.post(
API_URL, json={"input": input, "model": self.name}
).json()
if "data" not in resp:
@@ -220,14 +219,15 @@ class JinaEmbeddings(EmbeddingFunction):
return [result["embedding"] for result in sorted_embeddings]
def _init_client(self):
@cached_property
def _session(self):
import requests
if JinaEmbeddings._session is None:
if self.api_key is None and os.environ.get("JINA_API_KEY") is None:
api_key_not_found_help("jina")
api_key = self.api_key or os.environ.get("JINA_API_KEY")
JinaEmbeddings._session = requests.Session()
JinaEmbeddings._session.headers.update(
{"Authorization": f"Bearer {api_key}", "Accept-Encoding": "identity"}
)
if self.api_key is None and os.environ.get("JINA_API_KEY") is None:
api_key_not_found_help("jina")
api_key = self.api_key or os.environ.get("JINA_API_KEY")
session = requests.Session()
session.headers.update(
{"Authorization": f"Bearer {api_key}", "Accept-Encoding": "identity"}
)
return session
+194
View File
@@ -0,0 +1,194 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import math
import os
from functools import cached_property
from typing import List, Literal, Optional
from pydantic import Field, model_validator
from ..util import attempt_import_or_raise
from .base import TextEmbeddingFunction
from .registry import register
from .utils import TEXT, MissingApiKeyError, retry_with_exponential_backoff
NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1"
# Hosted model ID -> (default dimensions, minimum dimensions)
MODEL_DIMENSIONS = {
"nvidia/nemotron-3.5-embed-1b": (2048, 128),
"nvidia/nemotron-3.5-embed-8b": (4096, 1),
}
@register("nvidia")
class NvidiaEmbeddings(TextEmbeddingFunction):
"""Text embeddings using NVIDIA Nemotron 3.5 Embed 1B or 8B.
Uses the optional ``openai`` package for NVIDIA-hosted and self-hosted NIM
``/v1/embeddings`` endpoints. Documents use ``input_type="passage"`` and
queries use ``input_type="query"``. Null and empty strings get a null
embedding. Image inputs are not supported.
Parameters
----------
name : str
Hosted model ID, or the served model ID from a NIM ``/v1/models`` response.
dim : int, optional
Requested output dimensions. Defaults to 2048 for the hosted 1B model
and 4096 for the hosted 8B model. Required for other served model IDs;
use a dimension supported by your deployment.
base_url : str
API base URL including ``/v1``. Defaults to NVIDIA's hosted API.
api_key : str, optional
Registry variable reference, such as ``$var:nvidia-key``. Otherwise the
hosted API uses ``NVIDIA_API_KEY``. Custom endpoints only receive an
explicit ``api_key`` and can run without authentication.
batch_size : int
Maximum inputs per request (default 32). Reduce for deployment limits.
truncate : str
``END`` (default) truncates overlong text; ``NONE`` rejects it.
max_retries : int
Inherited LanceDB retry limit, applied to each request. The OpenAI
client's own retries are disabled.
Examples
--------
Set ``NVIDIA_API_KEY`` before using the hosted API:
>>> from lancedb.embeddings import get_registry
>>> from lancedb.pydantic import LanceModel, Vector
>>> func = get_registry().get("nvidia").create()
>>> class Document(LanceModel):
... text: str = func.SourceField()
... vector: Vector(func.ndims()) = func.VectorField()
Embedding runs client-side for both local and remote tables. For a custom
endpoint restored from table metadata in a new process, first call
[allow_endpoint][lancedb.embeddings.EmbeddingFunctionRegistry.allow_endpoint].
"""
name: str = "nvidia/nemotron-3.5-embed-1b"
dim: Optional[int] = Field(default=None, gt=0)
base_url: str = NVIDIA_BASE_URL
api_key: Optional[str] = Field(default=None, repr=False)
batch_size: int = Field(default=32, gt=0)
truncate: Literal["END", "NONE"] = "END"
@model_validator(mode="after")
def _validate_dimensions(self):
dimensions = MODEL_DIMENSIONS.get(self.name)
if dimensions is None and self.dim is None:
raise ValueError("Set dim explicitly for self-hosted NIM model IDs")
if dimensions is not None and self.dim is not None:
native_dim, minimum = dimensions
if not minimum <= self.dim <= native_dim:
raise ValueError(
f"{self.name} supports dimensions from {minimum} to {native_dim}"
)
return self
@staticmethod
def sensitive_keys():
return ["api_key"]
def endpoints(self) -> List[str]:
return [] if self.base_url.rstrip("/") == NVIDIA_BASE_URL else [self.base_url]
def ndims(self) -> int:
return self.dim if self.dim is not None else MODEL_DIMENSIONS[self.name][0]
def compute_query_embeddings(
self, query: str, *args, **kwargs
) -> List[Optional[List[float]]]:
return self._embed(query, input_type="query")
def generate_embeddings(self, texts: TEXT) -> List[Optional[List[float]]]:
return self._embed(texts, input_type="passage")
# Retry each request rather than the whole call, so a transient failure does
# not resend batches that already succeeded, and invalid inputs or responses
# fail at once instead of being retried.
def compute_query_embeddings_with_retry(
self, query: str, *args, **kwargs
) -> List[Optional[List[float]]]:
return self._embed(query, input_type="query", max_retries=self.max_retries)
def compute_source_embeddings_with_retry(
self, texts: TEXT, *args, **kwargs
) -> List[Optional[List[float]]]:
return self._embed(texts, input_type="passage", max_retries=self.max_retries)
def _embed(
self,
texts: TEXT,
*,
input_type: Literal["passage", "query"],
max_retries: int = 0,
) -> List[Optional[List[float]]]:
texts = list(self.sanitize_input(texts))
if any(text is not None and not isinstance(text, str) for text in texts):
raise ValueError("NVIDIA embeddings support text strings only")
request = self._request
if max_retries > 0:
request = retry_with_exponential_backoff(request, max_retries=max_retries)
embeddings = [None] * len(texts)
valid = [index for index, text in enumerate(texts) if text]
for start in range(0, len(valid), self.batch_size):
rows = valid[start : start + self.batch_size]
data = request([texts[row] for row in rows], input_type)
if not isinstance(data, list) or len(data) != len(rows):
raise ValueError("NVIDIA returned an unexpected number of embeddings")
indices = [getattr(item, "index", None) for item in data]
if any(type(index) is not int for index in indices) or sorted(
indices
) != list(range(len(rows))):
raise ValueError("NVIDIA returned invalid embedding indices")
for row, item in zip(rows, sorted(data, key=lambda item: item.index)):
vector = getattr(item, "embedding", None)
if (
not isinstance(vector, list)
or len(vector) != self.ndims()
or any(
type(value) not in (int, float) or not math.isfinite(value)
for value in vector
)
):
raise ValueError(
"NVIDIA returned an invalid embedding: expected "
f"{self.ndims()} finite numeric values"
)
embeddings[row] = vector
return embeddings
def _request(self, batch: List[str], input_type: str):
response = self._client.embeddings.create(
model=self.name,
input=batch,
encoding_format="float",
# The typed dimensions parameter is unavailable in openai 1.6.1.
extra_body={
"dimensions": self.ndims(),
"input_type": input_type,
"modality": "text",
"truncate": self.truncate,
},
)
return getattr(response, "data", None)
@cached_property
def _client(self):
openai = attempt_import_or_raise("openai")
hosted = not self.endpoints()
# Never send the hosted API key from the environment to a custom endpoint
api_key = self.api_key or (os.environ.get("NVIDIA_API_KEY") if hosted else None)
if not api_key and hosted:
raise MissingApiKeyError(
"Set NVIDIA_API_KEY or provide api_key via a registry variable"
)
return openai.OpenAI(
base_url=self.base_url,
api_key=api_key or "not-required",
max_retries=0,
)
@@ -70,6 +70,8 @@ class OllamaEmbeddings(TextEmbeddingFunction):
The texts to embed
"""
# TODO retry, rate limit, token limit
if isinstance(texts, np.ndarray):
texts = texts.tolist()
embeddings = self._compute_embedding(texts)
return list(embeddings)
@@ -49,6 +49,9 @@ class OpenClipEmbeddings(EmbeddingFunction):
self.name, pretrained=self.pretrained
)
model.to(self.device)
# open_clip returns the model in training mode, which keeps dropout,
# stochastic depth and batch norm in their training behaviour.
model.eval()
self._model, self._preprocess = model, preprocess
self._tokenizer = open_clip.get_tokenizer(self.name)
self._ndims = None
+18 -7
View File
@@ -101,24 +101,35 @@ class OpenAIEmbeddings(TextEmbeddingFunction):
valid_indices.append(idx)
# TODO retry, rate limit, token limit
try:
def embed_batch(texts_batch, indices_batch):
kwargs = {
"input": valid_texts,
"input": texts_batch,
"model": self.name,
}
if self.name != "text-embedding-ada-002":
kwargs["dimensions"] = self.dim
rs = self._openai_client.embeddings.create(**kwargs)
valid_embeddings = {
idx: v.embedding for v, idx in zip(rs.data, valid_indices)
}
return {idx: v.embedding for v, idx in zip(rs.data, indices_batch)}
def embed_one_or_log(idx, text):
# Retry a single rejected input
try:
return embed_batch([text], [idx])
except openai.BadRequestError:
logging.exception("Bad request for input at index %d: %r", idx, text)
return {}
try:
valid_embeddings = embed_batch(valid_texts, valid_indices)
except openai.AuthenticationError:
logging.error("Authentication failed: Invalid API key provided")
raise
except openai.BadRequestError:
logging.exception("Bad request: %s", texts)
return [None] * len(texts)
# Retry each input individually
valid_embeddings = {}
for idx, text in zip(valid_indices, valid_texts):
valid_embeddings.update(embed_one_or_log(idx, text))
except Exception:
logging.exception("OpenAI embeddings error")
raise
+26 -3
View File
@@ -69,11 +69,15 @@ class EmbeddingFunctionRegistry:
def decorator(cls):
if not issubclass(cls, EmbeddingFunction):
raise TypeError("Must be a subclass of EmbeddingFunction")
if cls.__name__ in self._functions:
raise KeyError(f"{cls.__name__} was already registered")
key = alias or cls.__name__
if key in self._functions and (
not alias or self._functions[key] is not cls
):
raise KeyError(f"{key} was already registered")
self._functions[key] = cls
cls.__embedding_function_registry_alias__ = alias
# Store the name the class is registered under, so the table
# metadata written for it can be looked up again when reading.
cls.__embedding_function_registry_alias__ = key
return cls
return decorator
@@ -97,6 +101,25 @@ class EmbeddingFunctionRegistry:
"""
return self._functions[name]
def list_functions(self) -> list[str]:
"""List the names of registered embedding functions.
Returns
-------
list[str]
Registered aliases, or class names for functions registered without
an alias, in registration order. Each name can be passed to
:meth:`get`. The returned list is a copy; changing it does not
change the registry.
Examples
--------
>>> registry = get_registry()
>>> "openai" in registry.list_functions()
True
"""
return list(self._functions)
def parse_functions(
self, metadata: Optional[Dict[bytes, bytes]]
) -> Dict[str, "EmbeddingFunctionConfig"]:
+97 -17
View File
@@ -241,15 +241,30 @@ def retry_with_exponential_backoff(
exponential_base: float = 2,
jitter: bool = True,
max_retries: int = 7,
max_delay: float = 60,
):
"""Retry a function with exponential backoff.
Only errors that may succeed when repeated are retried. Errors that carry an
HTTP status code are retried when the status is 408, 409, 429 or >= 500; any
other 4xx status (for example 400, 401, 403, 404 or 422) is a permanent failure
that is raised immediately. Errors without a recognisable status code (for
example connection errors, timeouts, or exceptions raised by a custom embedding
function) are retried.
The delay before the n-th retry is ``initial_delay * exponential_base ** n``,
never more than ``max_delay``. With ``jitter`` enabled, a random amount of up to
half of that delay is removed ("equal jitter"), so the actual wait is always in
the range ``[delay / 2, delay]``.
Args:
func (function): The function to be retried.
initial_delay (float): Initial delay in seconds (default is 1).
exponential_base (float): The base for exponential backoff (default is 2).
jitter (bool): Whether to add jitter to the delay (default is True).
max_retries (int): Maximum number of retries (default is 7).
max_delay (float): Maximum delay between two attempts, in seconds
(default is 60).
Returns:
function: The decorated function.
@@ -265,13 +280,12 @@ def retry_with_exponential_backoff(
try:
return func(*args, **kwargs)
# Currently retrying on all exceptions as there is no way to know the
# format of the error msgs used by different APIs. We'll log the error
# and say that it is assumed that if this portion errors out, it's due
# to rate limit but the user should check the error message to be sure.
# Errors are retried unless they are known to be permanent (see
# `_is_non_retryable_error`). Custom embedding functions can raise
# arbitrary exceptions, so unknown errors are assumed to be transient.
except Exception as e: # noqa: PERF203
# Don't retry on authentication errors (e.g., OpenAI 401)
# These are permanent failures that won't be fixed by retrying
# Don't retry permanent failures (e.g., OpenAI 401 or 404). They
# won't be fixed by retrying and would only delay the real error.
if _is_non_retryable_error(e):
raise
@@ -280,24 +294,72 @@ def retry_with_exponential_backoff(
if num_retries > max_retries:
raise Exception(
f"Maximum number of retries ({max_retries}) exceeded.", e
)
) from e
delay *= exponential_base * (1 + jitter * random.random())
delay = min(delay * exponential_base, max_delay)
sleep_for = delay
if jitter:
sleep_for = delay / 2 + random.random() * delay / 2
logging.warning(
"Error occurred: %s \n Retrying in %s seconds (retry %s of %s) \n",
e,
delay,
sleep_for,
num_retries,
max_retries,
)
time.sleep(delay)
time.sleep(sleep_for)
return wrapper
# HTTP statuses in the 4xx range that are worth retrying: request timeout,
# conflict (the OpenAI SDK treats it as transient) and rate limiting.
_RETRYABLE_CLIENT_STATUSES = (408, 409, 429)
# AWS error codes that are reported with a 4xx status but are transient.
_RETRYABLE_AWS_ERROR_CODES = (
"Throttl",
"TooManyRequests",
"RequestLimitExceeded",
"ProvisionedThroughputExceeded",
"ModelNotReady",
"ModelTimeout",
)
def _get_http_status(error: Exception):
"""Best-effort extraction of an HTTP status code from an exception.
Provider SDKs expose it in different ways: ``status_code`` (openai, cohere),
``http_status`` (voyageai), ``response.status_code`` (requests, httpx),
``code`` (google-api-core, urllib) or ``response["ResponseMetadata"]``
(botocore). Returns None if no status can be found.
"""
candidates = [
getattr(error, "status_code", None),
getattr(error, "http_status", None),
]
response = getattr(error, "response", None)
if isinstance(response, dict):
candidates.append(response.get("ResponseMetadata", {}).get("HTTPStatusCode"))
else:
candidates.append(getattr(response, "status_code", None))
candidates.append(getattr(error, "code", None))
for status in candidates:
if isinstance(status, int) and not isinstance(status, bool):
if 100 <= status <= 599:
return status
return None
def _is_non_retryable_error(error: Exception) -> bool:
"""Check if an error should not be retried.
An error is non-retryable if it is an authentication error or if it carries an
HTTP client-error status (4xx) other than 408, 409 and 429. Errors without a
recognisable status are treated as retryable.
Args:
error: The exception to check
@@ -314,13 +376,25 @@ def _is_non_retryable_error(error: Exception) -> bool:
if error_type == "AuthenticationError":
return True
# Check for other common non-retryable HTTP status codes
# 401 Unauthorized, 403 Forbidden
if hasattr(error, "status_code"):
if error.status_code in (401, 403):
return True
# A missing API key or a missing optional dependency fails the same way on
# every attempt
if isinstance(error, (MissingApiKeyError, ImportError)):
return True
return False
status = _get_http_status(error)
if status is None or not 400 <= status < 500:
return False
if status in _RETRYABLE_CLIENT_STATUSES:
return False
# AWS reports throttling with a 400 status; the error code tells them apart.
response = getattr(error, "response", None)
if isinstance(response, dict):
aws_code = str(response.get("Error", {}).get("Code", ""))
if aws_code.startswith(_RETRYABLE_AWS_ERROR_CODES):
return False
return True
def url_retrieve(url: str):
@@ -337,9 +411,15 @@ def url_retrieve(url: str):
raise ConnectionError("could not download {} due to {}".format(url, err))
class MissingApiKeyError(ValueError):
"""Raised when an embedding provider's API key is not set."""
def api_key_not_found_help(provider):
logging.error("Could not find API key for %s", provider)
raise ValueError(f"Please set the {provider.upper()}_API_KEY environment variable.")
raise MissingApiKeyError(
f"Please set the {provider.upper()}_API_KEY environment variable."
)
def is_flash_attn_2_available():
+5 -3
View File
@@ -75,7 +75,7 @@ def transform_input(input_data: Union[str, bytes, Path]):
content = {"type": "text", "text": input_data}
elif isinstance(input_data, PIL_Image.Image):
buffered = BytesIO()
input_data.save(buffered, format="JPEG")
input_data.convert("RGB").save(buffered, format="JPEG")
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
content = {
"type": "image_base64",
@@ -84,7 +84,7 @@ def transform_input(input_data: Union[str, bytes, Path]):
elif isinstance(input_data, bytes):
img = PIL_Image.open(BytesIO(input_data))
buffered = BytesIO()
img.save(buffered, format="JPEG")
img.convert("RGB").save(buffered, format="JPEG")
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
content = {
"type": "image_base64",
@@ -103,7 +103,7 @@ def transform_input(input_data: Union[str, bytes, Path]):
else:
img = PIL_Image.open(input_data)
buffered = BytesIO()
img.save(buffered, format="JPEG")
img.convert("RGB").save(buffered, format="JPEG")
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
content = {
"type": "image_base64",
@@ -145,6 +145,8 @@ def sanitize_text_input(inputs: TEXT) -> List[str]:
"""
if isinstance(inputs, str):
inputs = [inputs]
elif isinstance(inputs, (list, np.ndarray)):
inputs = list(inputs)
elif isinstance(inputs, pa.Array):
inputs = inputs.to_pylist()
elif isinstance(inputs, pa.ChunkedArray):
+20
View File
@@ -79,6 +79,13 @@ class Expr:
>>> from lancedb.expr import col, lit
>>> filt = (col("age") > lit(18)) & (col("name").lower() == lit("alice"))
>>> proj = {"double": col("x") * lit(2)}
Notes
-----
An ``Expr`` has no Python truth value: ``bool(expr)`` raises ``TypeError``.
Combine expressions with ``&``, ``|`` and ``~`` (wrapping each comparison in
parentheses) instead of ``and``, ``or`` and ``not``, and write a range as
``(col("x") > 1) & (col("x") < 5)`` rather than ``1 < col("x") < 5``.
"""
# Make Expr unhashable so that == returns an Expr rather than being used
@@ -89,6 +96,19 @@ class Expr:
self._inner = inner
self._column_path = column_path
def __bool__(self) -> bool:
# An Expr describes a predicate that the query engine evaluates per row,
# so it has no Python truth value. Without this, ``and`` / ``or`` /
# ``not`` and chained comparisons (``1 < col("x") < 5``) would silently
# keep a single operand and drop the rest of the filter.
raise TypeError(
"The truth value of an Expr is ambiguous. Combine expressions with "
"'&' (and), '|' (or) and '~' (not), and wrap each comparison in "
"parentheses, e.g. (col('x') > 1) & (col('x') < 5). Do not use "
"'and', 'or', 'not', 'in' or chained comparisons such as "
"1 < col('x') < 5; use Expr.isin() for membership."
)
# ── comparisons ──────────────────────────────────────────────────────────
def __eq__(self, other: ExprLike) -> "Expr": # type: ignore[override]
+205 -59
View File
@@ -4,7 +4,7 @@
"""Canonical Function values exchanged with LanceDB Enterprise services.
These immutable models contain client/wire state only. Catalog persistence,
environment bake, secret resolution, and execution are owned by Sophon.
environment bake, secret resolution, and execution are owned by LanceDB Enterprise.
``RefreshColumnResult`` is also the backend-neutral result of a local
expression-backed refresh job.
"""
@@ -33,6 +33,7 @@ from typing import (
Annotated,
Any,
Callable,
Literal,
Optional,
Union,
get_args,
@@ -52,7 +53,9 @@ from pydantic import (
model_validator,
)
from .schema import blob as _blob_field
from .schema import is_blob_v2_field as _is_blob_v2_field
from ._blob_reader import BlobReader
from .secrets import EnvVarSecret
_Int32 = conint(strict=True, ge=-(2**31), le=2**31 - 1)
@@ -213,6 +216,7 @@ class FunctionParameter(_RemoteValue):
name: str
arrow_type: str
nullable: bool
blob_access: Optional[Literal["bytes", "reader"]] = None
class FunctionResultField(_OpenRemoteValue):
@@ -271,7 +275,7 @@ class FunctionSignature(_RemoteValue):
class PythonEnvironmentSpec(_RemoteValue):
"""One Sophon-managed Python environment source."""
"""One LanceDB Enterprise-managed Python environment source."""
kind: str
packages: tuple[str, ...] = ()
@@ -279,6 +283,7 @@ class PythonEnvironmentSpec(_RemoteValue):
path: Optional[str] = None
modules: tuple[str, ...] = ()
image: Optional[str] = None
system_packages: tuple[str, ...] = ()
class PythonRuntimeSpec(_RemoteValue):
@@ -362,6 +367,12 @@ class FunctionVersion(_RemoteValue):
[SecretReference][lancedb.functions.SecretReference] carries a Secret's;
they are what [get_function][lancedb.db.DBConnection.get_function] takes.
An empty ``namespace_path`` is the root namespace.
``source_digest`` identifies the registered source artifact, independently
of the built ``image``. Compare it with
``udf_def.registration_request.artifact.digest`` to check whether a local
[UdfDefinition][lancedb.functions.UdfDefinition] has the same source.
It is ``None`` when the server does not provide a source digest.
"""
name: str
@@ -370,6 +381,7 @@ class FunctionVersion(_RemoteValue):
location: str
version: _ObjectVersion
image: FunctionImage
source_digest: Optional[str] = None
signature: FunctionSignature
secret_bindings: tuple[SecretBinding, ...] = ()
created_at_millis: int
@@ -649,8 +661,8 @@ class FunctionBinding(_RemoteValue):
class RefreshColumnResult(_RemoteValue):
"""Terminal result of an expression-backed or Function-backed refresh Job.
Local jobs produce this value in process. LanceDB Cloud and Enterprise
decode the same value from the durable server-job terminal payload.
LanceDB Embedded jobs produce this value in process. LanceDB Distributed
decodes the same value from the durable server-job terminal payload.
"""
rows_assigned: _UInt64
@@ -670,7 +682,7 @@ class RefreshColumnResult(_RemoteValue):
return self.published_version
_FUNCTION_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_.-]*$")
_FUNCTION_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
_FUNCTION_BLOB_V2_TYPE = "blob_v2"
_ARROW_EXTENSION_NAME_KEY = "ARROW:extension:name"
@@ -989,6 +1001,11 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]:
if isinstance(annotation, pa.DataType):
return annotation, nullable
if annotation is pa.Array or annotation is pa.RecordBatch:
raise TypeError(
f"cannot infer Arrow types from Function annotation {annotation!r}; "
"provide input_schema and output_schema together for batch callables"
)
if annotation is bool:
return pa.bool_(), nullable
if annotation is int:
@@ -1093,8 +1110,43 @@ def _infer_signature(
parameters = _callable_parameters(function)
if method:
parameters = parameters[1:]
if (input_schema is None) != (output_schema is None):
raise ValueError("input_schema and output_schema must be provided together")
try:
annotations = get_type_hints(function, include_extras=True)
except Exception as error:
raise TypeError(f"failed to resolve Function annotations: {error}") from error
def input_parameter(field):
annotation = annotations.get(field.name)
if get_origin(annotation) in (Union, types.UnionType):
choices = [
value for value in get_args(annotation) if value is not type(None)
]
if len(choices) == 1:
annotation = choices[0]
arrow_type = _canonical_arrow_field(field)
if annotation is BlobReader:
if arrow_type != _FUNCTION_BLOB_V2_TYPE:
raise TypeError(
f"BlobReader input '{field.name}' requires a Blob V2 field"
)
access = "reader"
elif annotation is bytes:
if arrow_type != _FUNCTION_BLOB_V2_TYPE and not (
pa.types.is_binary(field.type) or pa.types.is_large_binary(field.type)
):
raise TypeError(
f"bytes input '{field.name}' requires binary or Blob V2"
)
access = "bytes"
else:
access = "bytes" if arrow_type == _FUNCTION_BLOB_V2_TYPE else None
return FunctionParameter(
name=field.name,
arrow_type=arrow_type,
nullable=field.nullable,
blob_access=access,
)
if input_schema is not None:
if not isinstance(input_schema, pa.Schema):
@@ -1110,45 +1162,46 @@ def _infer_signature(
"input_schema fields must exactly match callable parameters in order: "
f"expected {expected!r}, got {actual!r}"
)
inputs = tuple(
FunctionParameter(
name=field.name,
arrow_type=_canonical_arrow_field(field),
nullable=field.nullable,
)
for field in input_schema
)
return FunctionSignature(inputs=inputs, output=_function_output(output_schema))
inputs = tuple(input_parameter(field) for field in input_schema)
else:
inputs = None
missing = []
if inputs is None:
missing += [p.name for p in parameters if p.name not in annotations]
if output_schema is None and "return" not in annotations:
missing.append("return")
if missing:
raise TypeError(f"missing Function annotations: {missing!r}")
if output_schema is not None:
output = _function_output(output_schema)
else:
output_type, output_nullable = _annotation_type(annotations["return"])
if output_nullable:
raise ValueError("Function output must be non-nullable")
output = _function_output(pa.field("result", output_type, nullable=False))
if inputs is not None:
return FunctionSignature(inputs=inputs, output=output)
try:
annotations = get_type_hints(function, include_extras=True)
except Exception as error:
raise TypeError(f"failed to resolve Function annotations: {error}") from error
missing = [
parameter.name for parameter in parameters if parameter.name not in annotations
]
if missing or "return" not in annotations:
names = missing + ([] if "return" in annotations else ["return"])
raise TypeError(f"missing Function annotations: {names!r}")
inputs = []
for parameter in parameters:
data_type, nullable = _annotation_type(annotations[parameter.name])
inputs.append(
FunctionParameter(
name=parameter.name,
arrow_type=_canonical_arrow_field(
pa.field(parameter.name, data_type, nullable=nullable)
),
nullable=nullable,
annotation = annotations[parameter.name]
base = annotation
nullable = False
if get_origin(base) in (Union, types.UnionType):
choices = [value for value in get_args(base) if value is not type(None)]
if len(choices) == 1:
base, nullable = choices[0], True
if base is BlobReader:
inputs.append(
input_parameter(_blob_field(parameter.name, nullable=nullable))
)
continue
data_type, nullable = _annotation_type(annotation)
inputs.append(
input_parameter(pa.field(parameter.name, data_type, nullable=nullable))
)
output_type, output_nullable = _annotation_type(annotations["return"])
if output_nullable:
raise ValueError("Function output must be non-nullable")
return FunctionSignature(
inputs=tuple(inputs),
output=_function_output(pa.field("result", output_type, nullable=False)),
)
return FunctionSignature(inputs=tuple(inputs), output=output)
def _is_udf_decorator(node: ast.expr) -> bool:
@@ -1239,7 +1292,7 @@ _PYTHON_CALLABLE_ARTIFACT = "python_callable"
_PYTHON_BUNDLE_ARTIFACT = "python_bundle"
# Modules the Function image places beside user code.
_RESERVED_SOURCE_MODULES = frozenset(
{"user_function", "lance_source", "lance_callable"}
{"user_function", "lance_source", "lance_callable", "lance_blob"}
)
# The service accepts bundle paths made of these components only.
_SOURCE_PATH_COMPONENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
@@ -1426,8 +1479,8 @@ class _SourcePackager:
self._packaged: set[int] = set()
self._names: dict[str, Any] = {}
def package(self, target: Any) -> str:
entry = self._definition(target, entry=True)
def package(self, target: Any, signature: FunctionSignature) -> str:
entry = self._definition(target, entry=True, signature=signature)
parts = [_SOURCE_HEADER]
if self._imports:
parts.extend(["", *(self._imports[name] for name in sorted(self._imports))])
@@ -1436,12 +1489,20 @@ class _SourcePackager:
parts.extend(["", entry, ""])
return "\n".join(parts)
def _definition(self, target: Any, *, entry: bool) -> str:
def _definition(
self, target: Any, *, entry: bool, signature: Optional[FunctionSignature] = None
) -> str:
definition = _definition_node(target, entry=entry)
if not inspect.isclass(target) and inspect.getclosurevars(target).nonlocals:
raise ValueError(
"@udf cannot package functions that capture closure values"
)
namespace = _definition_namespace(target)
reader_name = (
self._blob_annotations(definition, signature, namespace)
if signature is not None
else None
)
source = ast.unparse(definition)
references = _module_references(f"{_SOURCE_HEADER}\n\n{source}\n")
dynamic = _namespace_acquisition(definition, references)
@@ -1449,9 +1510,10 @@ class _SourcePackager:
raise ValueError(
f"@udf cannot package dynamic namespace access: {dynamic!r}"
)
namespace = _definition_namespace(target)
self._packaged.add(id(target))
self._claim(target.__name__, ("definition", id(target)))
if reader_name is not None:
self._bind(reader_name, BlobReader)
unresolved = []
for name in sorted(references):
if name == target.__name__:
@@ -1472,6 +1534,44 @@ class _SourcePackager:
)
return source
def _blob_annotations(
self,
definition: Union[ast.FunctionDef, ast.ClassDef],
signature: FunctionSignature,
namespace: Mapping[str, Any],
) -> Optional[str]:
"""Bind reader inputs to the worker type, including postponed aliases."""
readers = {
parameter.name: parameter
for parameter in signature.inputs
if parameter.blob_access == "reader"
}
if not readers:
return None
call = definition
if isinstance(definition, ast.ClassDef):
call = next(
(
member
for member in definition.body
if isinstance(member, ast.FunctionDef) and member.name == "__call__"
),
None,
)
if call is None:
return None
# Avoid shadowing globals used by the body or other packaged definitions.
name = "_lance_blob_reader"
while name in namespace or name in self._names or name == definition.name:
name += "_"
for argument in (*call.args.args, *call.args.kwonlyargs):
if argument.arg in readers:
annotation = name
if readers[argument.arg].nullable:
annotation += " | None"
argument.annotation = ast.parse(annotation, mode="eval").body
return name
def _claim(self, name: str, meaning: Any) -> None:
claimed = self._names.setdefault(name, meaning)
if claimed != meaning:
@@ -1499,6 +1599,8 @@ class _SourcePackager:
"""One module-level line that rebinds `name` to `value` in the artifact:
an import for modules and importable classes/functions, a literal
otherwise."""
if value is BlobReader:
return f"from lance_blob import BlobReader as {name}"
if isinstance(value, types.ModuleType):
if value.__name__.split(".")[0] in _NAMESPACE_MODULES:
raise ValueError(
@@ -1753,6 +1855,7 @@ class UdfDefinition:
gpu: bool = False,
conda: tuple[str, ...] = (),
conda_channels: tuple[str, ...] = (),
apt: tuple[str, ...] = (),
code: tuple[types.ModuleType, ...] = (),
):
is_class = inspect.isclass(function)
@@ -1768,14 +1871,23 @@ class UdfDefinition:
if conda_channels and not conda:
raise ValueError("conda_channels requires conda packages")
packages = tuple(sorted(set(conda if conda else pip)))
if any(not package or package != package.strip() for package in packages):
system_packages = tuple(sorted(set(apt)))
if any(
not package or package != package.strip()
for package in packages + system_packages
):
raise ValueError("package requirements must be non-empty and trimmed")
if conda:
environment_spec = PythonEnvironmentSpec(
kind="conda", packages=packages, channels=tuple(conda_channels)
kind="conda",
packages=packages,
channels=tuple(conda_channels),
system_packages=system_packages,
)
else:
environment_spec = PythonEnvironmentSpec(kind="pip", packages=packages)
environment_spec = PythonEnvironmentSpec(
kind="pip", packages=packages, system_packages=system_packages
)
environment = dict(env)
if any(
not isinstance(key, str) or not isinstance(value, str)
@@ -1807,7 +1919,7 @@ class UdfDefinition:
code_files, code_modules = _code_files(code)
entry_source = _SourcePackager(
code_modules, frozenset(_requirement_name(package) for package in packages)
).package(function)
).package(function, signature)
if code_files:
kind = _PYTHON_BUNDLE_ARTIFACT
source = json.dumps(
@@ -1944,6 +2056,7 @@ def udf(
gpu: bool = False,
conda: tuple[str, ...] | list[str] = (),
conda_channels: tuple[str, ...] | list[str] = (),
apt: tuple[str, ...] | list[str] = (),
code: Sequence[types.ModuleType] = (),
) -> Callable[[Callable[..., Any]], UdfDefinition]: ...
@@ -1960,20 +2073,33 @@ def udf(
gpu: bool = False,
conda: tuple[str, ...] | list[str] = (),
conda_channels: tuple[str, ...] | list[str] = (),
apt: tuple[str, ...] | list[str] = (),
code: Sequence[types.ModuleType] = (),
):
"""Prepare a Python function or class for remote Function registration.
Input and output signatures are inferred from supported annotations. For
Arrow types annotations cannot express precisely, pass ``input_schema``
and ``output_schema`` together. Scalar outputs must be non-nullable. Every
named-struct field may be nullable; Enterprise preserves the struct's
validity when the result is expanded into sibling columns.
Input and output signatures are inferred from supported annotations. A
parameter annotated ``T`` is non-nullable and binds only a non-nullable
column; annotate ``Optional[T]`` to bind a nullable one, and it receives
``None`` for a null value. PyArrow fields are nullable unless declared
otherwise, so most columns need ``Optional``. For Arrow types annotations
cannot express precisely, pass ``input_schema``, ``output_schema``, or
both; the one omitted is inferred. Scalar outputs must be non-nullable.
Every named-struct field may be nullable; Enterprise preserves the
struct's validity when the result is expanded into sibling columns.
**Large values.** A ``bytes`` parameter receives the whole value, which
is held in memory with its row and counts against the server's per-row
input limit. To pass large binary values, such as video, store them in a
Blob V2 column and annotate the parameter ``BlobReader``, which streams.
**Functions and classes.** A decorated function is called once per row,
or once per batch when its parameters are annotated ``pyarrow.Array`` or
it takes one ``pyarrow.RecordBatch``. A decorated class is the same
callable with state: each remote instance calls ``__init__`` once, calls
it takes one ``pyarrow.RecordBatch``. These batch annotations require both
``input_schema`` and ``output_schema`` explicitly: the annotations do not
specify Arrow element types or fields. This also applies to a class's
``__call__`` method. A decorated class is the same callable with state:
each remote instance calls ``__init__`` once, calls
``__call__`` for every row or batch of every input it processes, and calls
``close()``, if defined, once when it retires. Load models, open clients,
and build rate limiters in ``__init__``; every batch of the instance then
@@ -2021,18 +2147,28 @@ def udf(
The synchronous callable, or the class whose instances are called.
name : str, optional
The remote Function name. Defaults to the callable name.
Must start with an ASCII letter or underscore and contain only ASCII
letters, digits, and underscores.
input_schema : pyarrow.Schema, optional
Explicit input fields in the exact order of the callable parameters.
Must be provided together with ``output_schema``.
Required for batch annotations. When omitted, inputs are inferred from
the parameter annotations.
output_schema : pyarrow.DataType, pyarrow.Field, or pyarrow.Schema, optional
Explicit scalar or named-struct output. Scalar outputs must be
non-nullable. Must be provided together with ``input_schema``.
non-nullable. Required for batch annotations. When omitted, the output
is inferred from the return annotation.
pip : sequence of str, optional
Pip requirements for the remote environment.
conda : sequence of str, optional
Conda packages for the remote environment, instead of ``pip``.
conda_channels : sequence of str, optional
Conda channels in priority order; requires ``conda``.
apt : sequence of str, optional
Debian packages (``"name"`` or ``"name=version"``) added to the remote
image before the Python environment, for shared libraries pip and
conda cannot provide, such as FFmpeg's for ``torchcodec``. Packages
are unpacked without running their maintainer scripts. Works with
``pip`` or ``conda``; requires image execution.
env : mapping of str to str, optional
Environment variables included in the Function definition. Not for
credentials -- these are ordinary configuration, stored with the
@@ -2064,6 +2200,15 @@ def udf(
... return value * 2
>>> score(1.5)
3.0
>>> import pyarrow as pa
>>> @udf(
... input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]),
... output_schema=pa.int64(),
... )
... def batch_identity(value: pa.Array) -> pa.Array:
... return value
>>> batch_identity(pa.array([1, 2, 3])).to_pylist()
[1, 2, 3]
>>> @udf(pip=["cupy-cuda12x"], gpu=True)
... def gpu_score(value: int) -> int:
... return value * 2
@@ -2093,6 +2238,7 @@ def udf(
gpu=gpu,
conda=tuple(conda),
conda_channels=tuple(conda_channels),
apt=tuple(apt),
code=tuple(code),
)
+11 -7
View File
@@ -145,9 +145,9 @@ class FTS:
Lance tokenizer can panic on malformed triples; see
https://github.com/lance-format/lance/issues/8812.
Remote tables use the same ``FTS()`` configuration and require a server
that supports JSON FTS. Wait for ``table.wait_for_index(["doc_idx"])``
before searching a newly created remote index with its default name.
LanceDB Distributed uses the same ``FTS()`` configuration and requires a
server that supports JSON FTS. Wait for ``table.wait_for_index(["doc_idx"])``
before searching a newly created index there with its default name.
Examples
--------
@@ -210,12 +210,12 @@ class FTS:
memory_limit : int, optional
The total memory limit in MiB for the local FTS build stage. The limit
is divided evenly among indexing workers. This build-only setting is
not persisted with the index and does not apply to remote tables.
not persisted with the index and does not apply to LanceDB Distributed.
num_workers : int, optional
The number of workers for a local FTS build. By default Lance uses
roughly half of the available CPU cores. The effective value is
limited by the available compute capacity. This build-only setting is
not persisted with the index and does not apply to remote tables.
not persisted with the index and does not apply to LanceDB Distributed.
document_granularity : DocumentGranularity, default ROW
``ROW`` treats the selected text in one table row as one document.
``LIST_ELEMENT`` treats each element of the deepest list on the indexed
@@ -882,8 +882,12 @@ class IvfRq:
num_partitions: int, default sqrt(num_rows)
Number of IVF partitions to create.
num_bits: int, default 1
num_bits: int, optional
Number of bits to encode each dimension in the RabitQ codebook.
If None, uses Lance's default (currently 5), matching Rust and Node.
Set to 1 to retain the previous Python default and maximum compression.
Five-bit vector codes use roughly five times the storage of one-bit codes,
in addition to other index overhead.
max_iterations: int, default 50
Max iterations to train kmeans when computing IVF partitions.
@@ -897,7 +901,7 @@ class IvfRq:
distance_type: Literal["l2", "cosine", "dot"] = "l2"
num_partitions: Optional[int] = None
num_bits: int = 1
num_bits: Optional[int] = None
max_iterations: int = 50
sample_rate: int = 256
target_partition_size: Optional[int] = None
+23 -1
View File
@@ -52,6 +52,9 @@ class PyarrowScannerAdapter(pa.dataset.Scanner):
raise NotImplementedError("memory_pool not supported")
def count_rows(self):
if isinstance(self.filter, pa.compute.Expression):
# stream the batches so memory does not grow with the matching rows
return sum(batch.num_rows for batch in self.to_reader())
return self.table.count_rows(self.filter)
def from_batches(self, **kwargs):
@@ -83,6 +86,8 @@ class PyarrowScannerAdapter(pa.dataset.Scanner):
return self.to_reader().read_all()
def to_reader(self, *, limit: Optional[int] = None):
if isinstance(self.filter, pa.compute.Expression):
return self._to_reader_with_expression(limit=limit)
query = self.table.search()
# Disable the builtin limit
if limit is None:
@@ -98,13 +103,30 @@ class PyarrowScannerAdapter(pa.dataset.Scanner):
query = query.where(self.filter, prefilter=True)
return query.to_batches(batch_size=self.batch_size)
def _to_reader_with_expression(self, *, limit: Optional[int] = None):
# LanceDB filters are SQL strings, but engines such as DuckDB push down
# pyarrow compute expressions. Scan the table and apply the filter and
# projection with pyarrow, since the filter may reference columns that
# are not part of the projection.
if limit is not None and limit <= 0:
raise ValueError("limit must be positive")
query = self.table.search().limit(self.table.count_rows())
scanner = pa.dataset.Scanner.from_batches(
query.to_batches(batch_size=self.batch_size),
columns=self.columns,
filter=self.filter,
)
if limit is None:
return scanner.to_reader()
return scanner.head(limit).to_reader()
class PyarrowDatasetAdapter(pa.dataset.Dataset):
def __init__(self, table: Table):
self.table = table
def count_rows(self, filter: Optional[Filter] = None):
return self.table.count_rows(filter)
return self.scanner(filter=filter).count_rows()
def get_fragments(self, filter: Optional[Filter] = None):
raise NotImplementedError
+17 -13
View File
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Handles to operations a server may run asynchronously."""
"""Handles to asynchronous registry jobs, SQL queries, and local operations."""
import asyncio
import json
@@ -44,12 +44,12 @@ class AsyncJob(Generic[T]):
@property
def id(self) -> Optional[str]:
"""Identifies the operation on the server that is running it.
"""The operation's opaque ID, interpreted according to :attr:`job_type`.
Returned for correlating with server logs or the jobs API. Operations
that run in this process have no server id and return `None`. The value
is opaque: parsing it or storing it to resume the job later is not
supported.
Registry jobs expose a registry job ID; SQL-backed jobs expose a
connection-scoped query ID as a string. Local operations return ``None``.
Query IDs cannot be used with registry job APIs or to resume after a
client restart.
"""
return self._inner.id if self._inner is not None else None
@@ -94,9 +94,11 @@ class AsyncJob(Generic[T]):
"""Ask the backend for this job's current state, and for a server-side
job its full record, then cache it for the properties below.
The properties are all `None` until this runs, because submitting an
operation returns only a job id. `status` fetches the whole record too;
`wait` records only the terminal state it establishes.
Registry details are `None` until this runs, because submitting an
operation does not fetch its full registry record. Query-backed jobs
expose only lifecycle state through this method. For registry jobs,
`status` fetches the whole record too; `wait` records only the terminal
state it establishes.
"""
if self._inner is None:
return
@@ -114,11 +116,13 @@ class AsyncJob(Generic[T]):
@property
def job_type(self) -> Optional[str]:
"""The job's type, as the server names it.
"""The job's kind of work, without contacting the backend.
`None` for an in-process job, which has no server-side record.
SQL-backed handles report ``"query"`` immediately. Registry handles
report the server's job type after :meth:`refresh` or :meth:`status`.
In-process handles return ``None``.
"""
return self._field("job_type")
return self._inner.job_type if self._inner is not None else None
@property
def creation_ms(self) -> Optional[int]:
@@ -294,7 +298,7 @@ class Job(Generic[T]):
@property
def job_type(self) -> Optional[str]:
"""The job's type. See :attr:`AsyncJob.job_type`."""
return self._field("job_type")
return self._inner.job_type if self._inner is not None else None
@property
def creation_ms(self) -> Optional[int]:
+171
View File
@@ -5,6 +5,7 @@
from __future__ import annotations
import asyncio
from typing import Any, AsyncIterator, Callable, Generic, Iterator, Optional, TypeVar
from .background_loop import LOOP
@@ -83,3 +84,173 @@ class Listing(Iterator[T], Generic[T]):
for initial, cached, final-page, and error behavior.
"""
return self._inner.page_token()
def validate_page_limit(limit: Optional[int]) -> None:
"""Validate the legacy limit argument before passing it to the bindings."""
if limit is not None and (
not isinstance(limit, int) or limit < 0 or limit > 2**31 - 1
):
raise ValueError("limit must be between 0 and 2147483647")
class _AsyncPagedNameListing(AsyncIterator[str]):
"""An async listing with an inspectable copy of its current backend page."""
def __init__(
self, inner: Any, page_token: Optional[str] = None, *, empty: bool = False
):
self._inner = inner
self._token = page_token
self._page: Optional[list[str]] = [] if empty else None
self._position = 0
self._done = empty
self._failure: Optional[BaseException] = None
self._lock = asyncio.Lock()
@property
def page_token(self) -> Optional[str]:
"""The continuation token for the next backend request."""
return self._token
def num_page_results(self) -> int:
"""Count the remaining names in the current page."""
return 0 if self._page is None else len(self._page) - self._position
def _page_copy(self) -> list[str]:
if self._page is None:
raise RuntimeError("Await or iterate the listing before reading its page")
return self._page.copy()
async def _fetch_page(self) -> None:
try:
page = await self._inner.next_page()
except asyncio.CancelledError:
raise
except BaseException as exc:
self._failure = exc
self._done = True
raise
if page is None:
self._page = []
self._token = None
self._done = True
else:
self._page = page["items"]
self._token = page["page_token"]
self._done = self._token is None
self._position = 0
async def _load_initial(self):
async with self._lock:
if self._failure is not None:
raise self._failure
if self._page is None:
await self._fetch_page()
return self
def __await__(self):
return self._load_initial().__await__()
def __aiter__(self):
return self
async def __anext__(self) -> str:
async with self._lock:
if self._failure is not None:
raise StopAsyncIteration
if self._page is None:
await self._fetch_page()
assert self._page is not None
while self._position >= len(self._page):
if self._done:
raise StopAsyncIteration
await self._fetch_page()
assert self._page is not None
item = self._page[self._position]
self._position += 1
return item
class AsyncTableListing(_AsyncPagedNameListing):
"""Awaitable table iterator; awaiting loads one page.
For example::
page = await db.list_tables(limit=20)
print(page.tables, page.page_token)
async for name in db.list_tables(limit=20):
print(name)
"""
@property
def tables(self) -> list[str]:
"""A copy of every table name in the most recently fetched page."""
return self._page_copy()
class AsyncNamespaceListing(_AsyncPagedNameListing):
"""Awaitable namespace iterator; awaiting loads one page.
For example::
page = await db.list_namespaces(limit=20)
print(page.namespaces, page.page_token)
"""
@property
def namespaces(self) -> list[str]:
"""A copy of every name in the most recently fetched page."""
return self._page_copy()
class _PagedNameListing(Iterator[str]):
def __init__(self, inner: _AsyncPagedNameListing):
self._inner = inner
LOOP.run(inner._load_initial())
def __iter__(self):
return self
def __next__(self) -> str:
try:
return LOOP.run(self._inner.__anext__())
except StopAsyncIteration:
raise StopIteration from None
@property
def page_token(self) -> Optional[str]:
return self._inner.page_token
def num_page_results(self) -> int:
return self._inner.num_page_results()
class TableListing(_PagedNameListing):
"""Table iterator retaining the current page as a list.
For example::
page = db.list_tables(limit=20)
print(page.tables, page.page_token)
for name in db.list_tables(limit=20):
print(name)
"""
@property
def tables(self) -> list[str]:
return self._inner.tables
class NamespaceListing(_PagedNameListing):
"""Namespace iterator retaining the current page as a list.
For example::
page = db.list_namespaces(limit=20)
print(page.namespaces, page.page_token)
"""
@property
def namespaces(self) -> list[str]:
return self._inner.namespaces
+31 -14
View File
@@ -2,7 +2,13 @@
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Materialized views: tables defined by a query over a source table and
maintained by refresh. See ``DBConnection.create_materialized_view``."""
maintained by refresh. See ``DBConnection.create_materialized_view``.
LanceDB Embedded creation and refresh require the ``experimental-functions``
Cargo feature in a source build. Published packages disable it. Opening, reading,
listing and dropping existing views and LanceDB Distributed operations remain
available.
"""
from __future__ import annotations
@@ -179,31 +185,38 @@ class AsyncMaterializedView:
return _definition_from_json(raw)
async def refresh(
self, *, source_version: Optional[int] = None
self, *, full: bool = False, source_version: Optional[int] = None
) -> "RefreshMaterializedViewResult":
"""Recompute the view from its source.
Every refresh rebuilds the complete view. For local views,
``source_version`` refreshes to that source version instead of the
latest; remote SQL refreshes do not support source-version pinning.
In LanceDB Distributed, ``full=True`` forces a rebuild; otherwise the
server chooses the refresh mode. LanceDB Embedded views always rebuild,
and ``source_version`` selects a source version instead of the latest.
LanceDB Distributed SQL refreshes do not support source-version pinning.
LanceDB Distributed results leave ``mode``, ``rows_written``, and
``source_version`` as ``None`` because the SQL job adapter does not expose
these metrics.
"""
return await self._table._inner.refresh_materialized_view(
source_version=source_version
source_version=source_version, full=full
)
async def refresh_async(
self, *, source_version: Optional[int] = None
self, *, full: bool = False, source_version: Optional[int] = None
) -> "AsyncJob[RefreshMaterializedViewResult]":
"""Submit a refresh and return its job without waiting.
The job may already be complete for a local view. Remote refreshes are
submitted through the SQL service.
The job may already be complete in LanceDB Embedded. In LanceDB
Distributed, refreshes are submitted through the SQL service. Options and
result metrics follow
[refresh][lancedb.materialized_view.AsyncMaterializedView.refresh].
"""
from ._lancedb import RefreshMaterializedViewResult
return _typed_job(
await self._table._inner.refresh_materialized_view_async(
source_version=source_version
source_version=source_version, full=full
),
RefreshMaterializedViewResult.from_json,
)
@@ -235,18 +248,22 @@ class MaterializedView:
return LOOP.run(self._async.definition())
def refresh(
self, *, source_version: Optional[int] = None
self, *, full: bool = False, source_version: Optional[int] = None
) -> "RefreshMaterializedViewResult":
"""Recompute the view from its source. See
[AsyncMaterializedView.refresh][lancedb.materialized_view.AsyncMaterializedView.refresh]."""
return LOOP.run(self._async.refresh(source_version=source_version))
return LOOP.run(self._async.refresh(full=full, source_version=source_version))
def refresh_async(
self, *, source_version: Optional[int] = None
self, *, full: bool = False, source_version: Optional[int] = None
) -> "Job[RefreshMaterializedViewResult]":
"""Submit a refresh and return its job without waiting.
See
[AsyncMaterializedView.refresh_async][lancedb.materialized_view.AsyncMaterializedView.refresh_async].
"""
return Job(LOOP.run(self._async.refresh_async(source_version=source_version)))
return Job(
LOOP.run(
self._async.refresh_async(full=full, source_version=source_version)
)
)
+72 -19
View File
@@ -11,6 +11,7 @@ through a namespace abstraction.
from __future__ import annotations
import sys
import warnings
from typing import Any, Dict, Iterable, List, Optional, Union
from uuid import UUID
@@ -51,7 +52,14 @@ from lancedb.background_loop import LOOP
from lancedb.arrow import AsyncRecordBatchReader
from lancedb.db import AsyncConnection, DBConnection
from lancedb.job import AsyncJob, Job
from lancedb.listing import AsyncListing, Listing
from lancedb.listing import (
AsyncListing,
AsyncNamespaceListing,
AsyncTableListing,
Listing,
NamespaceListing,
TableListing,
)
from lancedb.sql import AsyncQuery as AsyncSqlQuery
from lancedb.sql import QueryDescription, QueryParameters
from lance_namespace import (
@@ -60,8 +68,6 @@ from lance_namespace import (
CreateNamespaceResponse,
DescribeNamespaceResponse,
DropNamespaceResponse,
ListNamespacesResponse,
ListTablesResponse,
NamespaceExistsRequest,
TableExistsRequest,
)
@@ -82,6 +88,31 @@ from ._lancedb import Session
_MAX_QUERY_K = 2**31 - 1
def _create_table_storage_options(
storage_options: Optional[Dict[str, str]],
data_storage_version: Optional[str],
enable_v2_manifest_paths: Optional[bool],
) -> Optional[Dict[str, str]]:
if data_storage_version is None and enable_v2_manifest_paths is None:
return storage_options
options = dict(storage_options or {})
for name, value in (
("data_storage_version", data_storage_version),
("enable_v2_manifest_paths", enable_v2_manifest_paths),
):
if value is not None:
warnings.warn(
f"setting {name} directly on create_table is deprecated. "
"Use storage_options instead.",
DeprecationWarning,
stacklevel=3,
)
options[f"new_table_{name}"] = (
str(value).lower() if isinstance(value, bool) else value
)
return options
def _query_to_namespace_request(
table_id: List[str],
query: "Query",
@@ -587,6 +618,9 @@ class LanceNamespaceDBConnection(DBConnection):
if mode.lower() not in ["create", "overwrite"]:
raise ValueError("mode must be either 'create' or 'overwrite'")
validate_table_name(name)
storage_options = _create_table_storage_options(
storage_options, data_storage_version, enable_v2_manifest_paths
)
async_table = LOOP.run(
self._inner.create_table(
name,
@@ -665,6 +699,8 @@ class LanceNamespaceDBConnection(DBConnection):
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> "MaterializedView":
"""Define a materialized view over a table in the root namespace.
See
@@ -680,6 +716,8 @@ class LanceNamespaceDBConnection(DBConnection):
where=where,
limit=limit,
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
)
).name
)
@@ -695,6 +733,8 @@ class LanceNamespaceDBConnection(DBConnection):
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> Job[None]:
job = LOOP.run(
self._inner.create_materialized_view_async(
@@ -704,6 +744,8 @@ class LanceNamespaceDBConnection(DBConnection):
where=where,
limit=limit,
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
)
)
return Job(job)
@@ -817,7 +859,7 @@ class LanceNamespaceDBConnection(DBConnection):
namespace_path: Optional[List[str]] = None,
page_token: Optional[str] = None,
limit: Optional[int] = None,
) -> ListNamespacesResponse:
) -> NamespaceListing:
"""
List child namespaces under the given namespace.
@@ -834,12 +876,12 @@ class LanceNamespaceDBConnection(DBConnection):
Returns
-------
ListNamespacesResponse
NamespaceListing
Response containing namespace names and optional page_token for pagination.
"""
if namespace_path is None:
namespace_path = []
return LOOP.run(
return NamespaceListing(
self._inner.list_namespaces(
namespace_path=namespace_path, page_token=page_token, limit=limit
)
@@ -986,7 +1028,7 @@ class LanceNamespaceDBConnection(DBConnection):
namespace_path: Optional[List[str]] = None,
page_token: Optional[str] = None,
limit: Optional[int] = None,
) -> ListTablesResponse:
) -> TableListing:
"""
List all tables in this database with pagination support.
@@ -1003,12 +1045,12 @@ class LanceNamespaceDBConnection(DBConnection):
Returns
-------
ListTablesResponse
TableListing
Response containing table names and optional page_token for pagination.
"""
if namespace_path is None:
namespace_path = []
return LOOP.run(
return TableListing(
self._inner.list_tables(
namespace_path=namespace_path, page_token=page_token, limit=limit
)
@@ -1222,6 +1264,9 @@ class AsyncLanceNamespaceDBConnection:
if mode.lower() not in ["create", "overwrite"]:
raise ValueError("mode must be either 'create' or 'overwrite'")
validate_table_name(name)
storage_options = _create_table_storage_options(
storage_options, data_storage_version, enable_v2_manifest_paths
)
table = await self._inner.create_table(
name,
data,
@@ -1288,6 +1333,8 @@ class AsyncLanceNamespaceDBConnection:
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> "AsyncMaterializedView":
"""Define a materialized view over a table in the root namespace."""
view = await self._inner.create_materialized_view(
@@ -1297,6 +1344,8 @@ class AsyncLanceNamespaceDBConnection:
where=where,
limit=limit,
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
)
# Reopen through the namespace so the view's table carries the
# namespace client and pushdown configuration a bare inner table lacks.
@@ -1311,6 +1360,8 @@ class AsyncLanceNamespaceDBConnection:
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> AsyncJob[None]:
"""Submit materialized-view creation and return its job."""
return await self._inner.create_materialized_view_async(
@@ -1320,6 +1371,8 @@ class AsyncLanceNamespaceDBConnection:
where=where,
limit=limit,
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
)
async def open_materialized_view(self, name: str) -> "AsyncMaterializedView":
@@ -1411,12 +1464,12 @@ class AsyncLanceNamespaceDBConnection:
namespace_path = []
await self._inner.drop_all_tables(namespace_path=namespace_path)
async def list_namespaces(
def list_namespaces(
self,
namespace_path: Optional[List[str]] = None,
page_token: Optional[str] = None,
limit: Optional[int] = None,
) -> ListNamespacesResponse:
) -> AsyncNamespaceListing:
"""
List child namespaces under the given namespace.
@@ -1433,12 +1486,12 @@ class AsyncLanceNamespaceDBConnection:
Returns
-------
ListNamespacesResponse
NamespaceListing
Response containing namespace names and optional page_token for pagination.
"""
if namespace_path is None:
namespace_path = []
return await self._inner.list_namespaces(
return self._inner.list_namespaces(
namespace_path=namespace_path, page_token=page_token, limit=limit
)
@@ -1568,12 +1621,12 @@ class AsyncLanceNamespaceDBConnection:
except TableNotFoundError:
return False
async def list_tables(
def list_tables(
self,
namespace_path: Optional[List[str]] = None,
page_token: Optional[str] = None,
limit: Optional[int] = None,
) -> ListTablesResponse:
) -> AsyncTableListing:
"""
List all tables in this database with pagination support.
@@ -1590,12 +1643,12 @@ class AsyncLanceNamespaceDBConnection:
Returns
-------
ListTablesResponse
TableListing
Response containing table names and optional page_token for pagination.
"""
if namespace_path is None:
namespace_path = []
return await self._inner.list_tables(
return self._inner.list_tables(
namespace_path=namespace_path, page_token=page_token, limit=limit
)
@@ -1622,7 +1675,7 @@ class AsyncLanceNamespaceDBConnection:
) -> AsyncSqlQuery:
"""Start executing SQL when supported by the underlying connection.
Namespace-backed local connections do not support SQL.
Namespace-backed LanceDB Embedded connections do not support SQL.
"""
return await self._inner.execute_query_async(
query,
@@ -1630,7 +1683,7 @@ class AsyncLanceNamespaceDBConnection:
parameters=parameters,
)
async def describe_query(self, query_id: UUID) -> QueryDescription:
async def describe_query(self, query_id: Union[UUID, str]) -> QueryDescription:
"""Describe a submitted SQL query when supported."""
return await self._inner.describe_query(query_id)
+52 -6
View File
@@ -169,6 +169,50 @@ class PermutationBuilder:
)
return self
def bootstrap_sample(
self,
num_samples: int,
*,
ratios: Optional[list[float]] = None,
counts: Optional[list[int]] = None,
fixed: Optional[int] = None,
seed: Optional[int] = None,
split_names: Optional[list[str]] = None,
) -> "PermutationBuilder":
"""
Sample rows uniformly **with replacement**, independently per split.
Unlike the other split strategies, the number of output rows is
``num_samples``, not the number of (optionally filtered) input rows: the
same row can appear zero, one, or many times, and ``num_samples`` may be
larger or smaller than the input row count. Useful for bootstrap
resampling, oversampling rare classes, or any training workload that
wants a fixed-size stream of random draws rather than a single
deterministic pass over every row. Combine with :meth:`filter` to
restrict the eligible population.
One of ratios, counts, or fixed must be provided, with the same meaning
as in :meth:`split_random`, except they divide ``num_samples`` across
splits rather than the input row count: if fixed is 4, each split gets
``num_samples // 4`` samples.
Each split draws its own sample using a seed derived independently from
``(seed, split_index)``, so a split's content does not change if the samples are
later redistributed across a different number of splits.
The optional split_names can be provided to name the splits. If not provided,
the splits can only be referenced by their index.
"""
self._async.bootstrap_sample(
num_samples,
ratios=ratios,
counts=counts,
fixed=fixed,
seed=seed,
split_names=split_names,
)
return self
def split_calculated(
self, calculation: str, split_names: Optional[list[str]] = None
) -> "PermutationBuilder":
@@ -504,7 +548,7 @@ class Permutation:
picklable classes implementing ``__call__``. Lambdas and closures over
local variables don't pickle with the default protocol.
A factory is optional for normal local and remote LanceDB connections:
A factory is optional for normal LanceDB Embedded and Distributed connections:
if not set, ``__getstate__`` captures the table's own picklable reopen
state. Use a factory when that default state is not enough, for example
when credentials should be loaded from the worker environment instead
@@ -543,7 +587,7 @@ class Permutation:
{"root": "/data/lance_db"},
)
LanceDB Cloud, reading credentials from env vars at worker startup
LanceDB Enterprise, reading credentials from env vars at worker startup
so secrets aren't pickled into the dataset::
import os, lancedb
@@ -597,7 +641,7 @@ class Permutation:
if split is not None:
if permutation_table is None:
raise ValueError(
"Cannot create a permutation on split `{split}`"
f"Cannot create a permutation on split `{split}`"
" because no permutation table is provided"
)
if isinstance(split, str):
@@ -865,9 +909,11 @@ class Permutation:
f"Cannot rename column `{old_name}` to `{new_name}` because a column "
"with that name already exists"
)
new_selection = self.selection.copy()
new_selection[new_name] = new_selection[old_name]
del new_selection[old_name]
# Rebuild the mapping so the renamed column keeps its position
new_selection = {
(new_name if name == old_name else name): value
for name, value in self.selection.items()
}
return self._with_selection(new_selection)
def rename_columns(self, column_map: dict[str, str]) -> "Permutation":
+53 -4
View File
@@ -127,7 +127,11 @@ def Vector(
core_schema.list_schema(
min_length=dim,
max_length=dim,
items_schema=core_schema.float_schema(),
items_schema=(
core_schema.int_schema()
if pa.types.is_integer(value_type)
else core_schema.float_schema()
),
),
)
@@ -208,7 +212,11 @@ def MultiVector(
items_schema=core_schema.list_schema(
min_length=dim,
max_length=dim,
items_schema=core_schema.float_schema(),
items_schema=(
core_schema.int_schema()
if pa.types.is_integer(value_type)
else core_schema.float_schema()
),
),
),
)
@@ -251,6 +259,15 @@ def _py_type_to_arrow_type(py_type: Type[Any], field: FieldInfo) -> pa.DataType:
f"{py_type}. Specify the element type, e.g. List[int] instead "
"of a bare List."
)
# An Arrow list has a single element type, so a tuple such as
# Tuple[int, str] cannot be stored as one. Tuple[int, ...] is homogeneous.
element_types = {arg for arg in args if arg is not Ellipsis}
if len(element_types) > 1:
raise TypeError(
"Converting Pydantic type to Arrow Type: unsupported type "
f"{py_type}. All tuple elements must have the same type; use a "
"nested LanceModel for a fixed set of fields with different types."
)
child = args[0]
return _pydantic_list_child_to_arrow(child, field)
raise TypeError(
@@ -260,7 +277,9 @@ def _py_type_to_arrow_type(py_type: Type[Any], field: FieldInfo) -> pa.DataType:
def _pydantic_model_to_fields(model: pydantic.BaseModel) -> List[pa.Field]:
return [
_pydantic_to_field(name, field) for name, field in model.model_fields.items()
_pydantic_to_field(name, field)
for name, field in model.model_fields.items()
if field.exclude is not True
]
@@ -409,6 +428,15 @@ def pydantic_to_schema(model: Type[pydantic.BaseModel]) -> pa.Schema:
pyarrow.Schema
The Arrow Schema
Raises
------
TypeError
If a field has a type with no Arrow equivalent. A ``Tuple`` field becomes
an Arrow list, so all its elements must have the same type, as in
``Tuple[int, int]`` or ``Tuple[float, ...]``; for a fixed set of fields
with different types, such as ``Tuple[int, str]``, use a nested
``LanceModel`` (an Arrow struct) instead.
Examples
--------
@@ -493,6 +521,9 @@ class LanceModel(pydantic.BaseModel):
vec_and_function = []
for name, field_info in cls.safe_get_fields().items():
if field_info.exclude is True:
continue
func = get_extras(field_info, "vector_column_for")
if func is not None:
vec_and_function.append([name, func])
@@ -500,6 +531,8 @@ class LanceModel(pydantic.BaseModel):
configs = []
for vec, func in vec_and_function:
for source, field_info in cls.safe_get_fields().items():
if field_info.exclude is True:
continue
src_func = get_extras(field_info, "source_column_for")
if src_func is func:
# note we can't use == here since the function is a pydantic
@@ -524,4 +557,20 @@ def get_extras(field_info: FieldInfo, key: str) -> Any:
def model_to_dict(model: pydantic.BaseModel) -> dict[str, Any]:
"""Convert a Pydantic model to a dictionary."""
return model.model_dump()
return _enum_members_to_values(model.model_dump())
def _enum_members_to_values(value: Any) -> Any:
# model_dump() keeps Enum members, and Arrow cannot convert a member of a
# plain Enum (one without a str or int mixin). Write its value instead,
# which is what the Arrow type of the field is derived from.
if isinstance(value, Enum):
return value.value
if isinstance(value, dict):
return {k: _enum_members_to_values(v) for k, v in value.items()}
if isinstance(value, (list, tuple)) and value:
# Skip lists of plain scalars, such as vectors, without walking them.
if isinstance(value[0], (int, float, str, bytes)):
return value
return [_enum_members_to_values(v) for v in value]
return value
+272 -65
View File
@@ -82,6 +82,7 @@ if TYPE_CHECKING:
T = TypeVar("T", bound="LanceModel")
AnalyzePlanDistributedMetrics = Literal["aggregate", "per_worker", "full"]
_SYNC_VECTOR_QUERY_TYPES = (list, tuple, np.ndarray, pa.Array, pa.ChunkedArray)
# Number of rows a hybrid query returns when no limit was set on it. This
# mirrors the default the Rust query builder applies to its sub-queries.
@@ -103,11 +104,13 @@ class _LanceScanner(Protocol):
def _unsupported_blob_pandas_error(reason: str) -> RuntimeError:
reason = reason.rstrip(".")
reason = reason[0].upper() + reason[1:]
return RuntimeError(
"blob columns require Lance native scanner conversion for query "
f"to_pandas(), but {reason}. Use a plain scan query, pass "
"blob_mode='bytes' or blob_mode='descriptions', or remove blob columns "
"from the projection."
"Blob columns require Lance native scanner conversion for this query's "
f"to_pandas(). {reason}. For supported blob v2 queries, pass "
"blob_mode='bytes' or blob_mode='descriptions'. Otherwise, install "
"pylance for scanner conversion or remove blob columns from the projection."
)
@@ -122,7 +125,7 @@ def _supports_local_blob_fetch(
def _blob_bytes_without_snapshot_error() -> NotImplementedError:
return NotImplementedError(
"blob_mode='bytes' cannot safely materialize blob columns without a "
"stable table snapshot. Remote tables and namespace QueryTable pushdown "
"stable table snapshot. LanceDB Distributed and namespace QueryTable pushdown "
"run the query on a server, so the blob fetch could read another table "
"version. Use blob_mode='descriptions'."
)
@@ -442,6 +445,7 @@ class FullTextQueryType(str, Enum):
MATCH_PHRASE = "match_phrase"
BOOST = "boost"
MULTI_MATCH = "multi_match"
COMBINED_FIELDS = "combined_fields"
BOOLEAN = "boolean"
@@ -590,8 +594,8 @@ class PhraseQuery(FullTextQuery):
----------
query : str
The query string to match against.
column : str
The name of the column to match against.
column : str, optional
The column to match against. None leaves column selection to query planning.
slop : int, default 0
The maximum number of intervening positions permitted in the phrase.
document_granularity : DocumentGranularity, optional
@@ -601,7 +605,7 @@ class PhraseQuery(FullTextQuery):
"""
query: str
column: str
column: Optional[str] = None
slop: int = pydantic.Field(0, kw_only=True)
document_granularity: Optional[DocumentGranularity] = pydantic.Field(
None, kw_only=True
@@ -666,6 +670,42 @@ class MultiMatchQuery(FullTextQuery):
return FullTextQueryType.MULTI_MATCH
@pydantic.dataclasses.dataclass
class CombinedFieldsQuery(FullTextQuery):
"""
Combined-fields (BM25F) query for full-text search.
Unlike `MultiMatchQuery`, which scores each column on its own and keeps
the best one, this query treats the columns as a single virtual field, so
term statistics are blended across them. A query term can then match in
any of the columns, e.g. a first name in one column and a last name in
another.
Parameters
----------
query : str
The query string to match against.
columns : list[str]
The columns combined into the virtual field. Every column must have the
same tokenizer configuration, and at least one must have an FTS index.
boosts : list[float], optional
The weight of each column, aligned with `columns`. Each weight must be
at least 1. If not provided, every column has a weight of 1.
operator : FullTextOperator, default OR
The operator to use for combining the query terms.
If `AND`, every term must appear in at least one of the columns.
If `OR`, at least one term must match.
"""
query: str
columns: list[str]
boosts: Optional[list[float]] = pydantic.Field(None, kw_only=True)
operator: FullTextOperator = pydantic.Field(FullTextOperator.OR, kw_only=True)
def query_type(self) -> FullTextQueryType:
return FullTextQueryType.COMBINED_FIELDS
@pydantic.dataclasses.dataclass
class BooleanQuery(FullTextQuery):
"""
@@ -909,6 +949,8 @@ class Query(pydantic.BaseModel):
query.filter = req.filter
query.full_text_query = req.full_text_search
query.columns = req.select
# Keep the unset value for this opt-in flag, as in the sync builders.
query.fast_search = req.fast_search or None
query.with_row_id = req.with_row_id
# use_rte is a genuine tri-state (None / True / False); preserve it as-is
# so a round-tripped query keeps an explicit False.
@@ -1024,10 +1066,12 @@ class LanceQueryBuilder(ABC):
fast_search=fast_search,
)
if isinstance(query, list):
if isinstance(query, (list, tuple)):
query = np.array(query, dtype=np.float32)
elif isinstance(query, np.ndarray):
query = query.astype(np.float32)
elif isinstance(query, (pa.Array, pa.ChunkedArray)):
query = np.array(query.to_pylist(), dtype=np.float32)
else:
raise TypeError(f"Unsupported query type: {type(query)}")
@@ -1049,7 +1093,7 @@ class LanceQueryBuilder(ABC):
query = cls._query_to_vector(table, query, vector_column_name)
return query, query_type
elif query_type == "auto":
if isinstance(query, (list, np.ndarray)):
if isinstance(query, _SYNC_VECTOR_QUERY_TYPES):
return query, "vector"
else:
conf = table.embedding_functions.get(vector_column_name)
@@ -1065,7 +1109,7 @@ class LanceQueryBuilder(ABC):
@classmethod
def _query_to_vector(cls, table, query, vector_column_name):
if isinstance(query, (list, np.ndarray)):
if isinstance(query, _SYNC_VECTOR_QUERY_TYPES):
return query
conf = table.embedding_functions.get(vector_column_name)
if conf is not None:
@@ -1134,12 +1178,14 @@ class LanceQueryBuilder(ABC):
The maximum time to wait for the query to complete.
If None, wait indefinitely.
blob_mode: str, default "lazy"
Controls how blob columns are returned. Eligible local plain scans
use Lance's scanner, which returns lazy blob handles in ``"lazy"``
mode and also supports legacy blob columns. Other local blob v2
Controls how blob columns are returned. Local blob v2 queries support
``"bytes"`` and ``"descriptions"`` without pylance. Eligible local
plain scans use pylance's scanner for lazy blob handles in ``"lazy"``
mode and for legacy blob columns. Other local blob v2
queries return descriptors in ``"lazy"`` and ``"descriptions"``
modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`.
Remote blob queries support only ``"descriptions"`` until a stable
LanceDB Distributed blob queries support only ``"descriptions"`` until a
stable
table snapshot can bind the query and blob fetches.
**kwargs
Forwarded to pyarrow.Table.to_pandas after query execution and
@@ -1214,15 +1260,16 @@ class LanceQueryBuilder(ABC):
batch_size: Optional[int] = None,
*,
timeout: Optional[timedelta] = None,
blob_mode: BlobMode = "lazy",
) -> pa.RecordBatchReader:
"""
Execute the query and return the results as a pyarrow
[RecordBatchReader](https://arrow.apache.org/docs/python/generated/pyarrow.RecordBatchReader.html)
For v2 blob projections, ``to_batches`` keeps the auto ``_rowid``
column visible so batch consumers can call ``fetch_blobs``. Use
``to_arrow``, ``to_list``, or ``to_pandas`` if you want LanceDB to hide
auto row ids in the final collected result.
For v2 blob projections, the default ``blob_mode="lazy"`` keeps the
auto ``_rowid`` column visible so batch consumers can call
``fetch_blobs``. The ``"bytes"`` and ``"descriptions"`` modes hide
automatic row ids.
Parameters
----------
@@ -1231,6 +1278,16 @@ class LanceQueryBuilder(ABC):
timeout: Optional[timedelta]
The maximum time to wait for the query to complete.
If None, wait indefinitely.
blob_mode: str, default "lazy"
``"lazy"`` keeps blob descriptors and auto row ids for manual fetches.
``"descriptions"`` omits auto row ids. ``"bytes"`` fetches blob v2
payloads one batch at a time, without requiring pylance. Bytes mode
has the same restrictions as :meth:`to_arrow`.
Examples
--------
Stream blob payloads with ``query.to_batches(blob_mode="bytes")`` and
convert each batch separately with ``batch.to_pandas()``.
"""
raise NotImplementedError
@@ -1494,6 +1551,28 @@ class LanceQueryBuilder(ABC):
finalized = finalized.drop_columns(["_rowid"])
return finalized
def _batches_in_mode(
self,
reader: pa.RecordBatchReader,
blob_mode: BlobMode,
blob_sources: dict[str, str],
) -> 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
)
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())
def with_row_address(self, with_row_address: bool = True) -> Self:
"""Set whether to return row addresses.
@@ -1558,9 +1637,10 @@ class LanceQueryBuilder(ABC):
ProjectionExec: expr=[vector@0 as vector, _distance@2 as _distance]
GlobalLimitExec: skip=0, fetch=10
FilterExec: _distance@2 IS NOT NULL
SortExec: TopK(fetch=10), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false]
SortExec: TopK(fetch=1), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false]
KNNVectorDistance: metric=l2
LanceRead: uri=..., projection=[vector], ...
LanceRead: uri=..., projection=[vector], num_fragments=..., ...
<BLANKLINE>
Parameters
----------
@@ -1616,8 +1696,8 @@ class LanceQueryBuilder(ABC):
GlobalLimitExec: elapsed=..., skip=0, fetch=10,
metrics=[output_rows=..., elapsed_compute=..., output_bytes=...]
FilterExec: elapsed=..., _distance@2 IS NOT NULL, metrics=[...]
SortExec: elapsed=..., TopK(fetch=10), expr=[...],
preserve_partitioning=[...],
SortExec: elapsed=..., TopK(fetch=1), expr=[...],
preserve_partitioning=[...], filter=[...],
metrics=[output_rows=..., elapsed_compute=...,
output_bytes=..., row_replacements=...]
KNNVectorDistance: elapsed=..., metric=l2,
@@ -1630,6 +1710,7 @@ class LanceQueryBuilder(ABC):
metrics=[output_rows=..., elapsed_compute=..., output_bytes=...,
fragments_scanned=..., ranges_scanned=1, rows_scanned=1,
bytes_read=..., iops=..., requests=..., task_wait_time=...]
<BLANKLINE>
Parameters
----------
@@ -1648,12 +1729,12 @@ class LanceQueryBuilder(ABC):
self.to_query_object(), distributed_metrics=distributed_metrics
)
def vector(self, vector: Union[np.ndarray, list]) -> Self:
def vector(self, vector: Union[VEC, Tuple]) -> Self:
"""Set the vector to search for.
Parameters
----------
vector: np.ndarray or list
vector: list, tuple, np.ndarray, pa.Array, or pa.ChunkedArray
The vector to search for.
Returns
@@ -1710,7 +1791,18 @@ class LanceQueryBuilder(ABC):
get_uri_scheme(self._table._dataset_path) == "memory"
):
return None
dataset = self._table.to_lance()
# Blob v2 payloads and descriptions use LanceDB's native fetch path.
# Only lazy handles, legacy blobs, and scanner-only options need pylance.
if (
blob_mode != "lazy"
and not _query_needs_lance_scanner(self)
and blob_v2_projection_sources(self._table.schema, query.columns)
):
return None
try:
dataset = self._table.to_lance()
except ImportError as err:
raise _unsupported_blob_pandas_error(str(err)) from err
blob_auto_row_id = self._blob_auto_row_id_enabled()
blob_sources = (
blob_v2_projection_sources(self._table.schema, query.columns)
@@ -2069,6 +2161,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
batch_size: Optional[int] = None,
*,
timeout: Optional[timedelta] = None,
blob_mode: BlobMode = "lazy",
) -> pa.RecordBatchReader:
"""
Execute the query and return the result as a RecordBatchReader object.
@@ -2080,11 +2173,15 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
timeout: timedelta, default None
The maximum time to wait for the query to complete.
If None, wait indefinitely.
blob_mode: str, default "lazy"
Controls blob conversion as described in
:meth:`LanceQueryBuilder.to_batches`.
Returns
-------
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]
@@ -2101,7 +2198,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
result_set.schema, result_set.to_batches()
)
return result_set
return self._batches_in_mode(result_set, blob_mode, blob_sources)
def where(
self, where: Union[str, Expr], prefilter: bool = None
@@ -2316,7 +2413,12 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
)
def to_batches(
self, /, batch_size: Optional[int] = None, timeout: Optional[timedelta] = None
self,
/,
batch_size: Optional[int] = None,
timeout: Optional[timedelta] = None,
*,
blob_mode: BlobMode = "lazy",
):
raise NotImplementedError("to_batches on an FTS query")
@@ -2372,10 +2474,19 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder):
return self._table._output_schema(query)
def to_batches(
self, /, batch_size: Optional[int] = None, timeout: Optional[timedelta] = None
self,
/,
batch_size: Optional[int] = None,
timeout: Optional[timedelta] = None,
*,
blob_mode: BlobMode = "lazy",
) -> pa.RecordBatchReader:
blob_sources = self._validated_blob_sources(blob_mode)
query = self._query_for_scan()
return self._table._execute_query(query, batch_size=batch_size, timeout=timeout)
reader = self._table._execute_query(
query, batch_size=batch_size, timeout=timeout
)
return self._batches_in_mode(reader, blob_mode, blob_sources)
def rerank(self, reranker: Reranker) -> LanceEmptyQueryBuilder:
"""Rerank the results using the specified reranker.
@@ -2438,12 +2549,20 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
if query is not None and (vector is not None or text is not None):
raise ValueError(
"You can either provide a string query in search() method "
"or set `vector()` and `text()` explicitly for hybrid search."
"or set `vector()` and `text()` explicitly for hybrid search. "
"But not both."
)
vector_query = vector if vector is not None else query
if not isinstance(vector_query, (str, list, np.ndarray)):
# Accept the same containers as the vector search path, which
# normalizes them in `LanceQueryBuilder.create`.
if isinstance(vector_query, (list, tuple)):
vector_query = np.array(vector_query, dtype=np.float32)
elif isinstance(vector_query, np.ndarray):
vector_query = vector_query.astype(np.float32)
elif isinstance(vector_query, (pa.Array, pa.ChunkedArray)):
vector_query = np.array(vector_query.to_pylist(), dtype=np.float32)
elif not isinstance(vector_query, str):
raise ValueError("Vector query must be either a string or a vector")
text_query = text or query
@@ -2572,10 +2691,6 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
with_row_ids: bool,
offset: Optional[int] = None,
) -> pa.Table:
if norm == "rank":
vector_results = LanceHybridQueryBuilder._rank(vector_results, "_distance")
fts_results = LanceHybridQueryBuilder._rank(fts_results, "_score")
# If both result sets are empty (e.g. after hard filtering),
# return early to avoid errors in reranking or score restoration.
if vector_results.num_rows == 0 and fts_results.num_rows == 0:
@@ -2602,15 +2717,23 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
original_score_row_ids = None
# normalize the scores to be between 0 and 1, 0 being most relevant
# We check whether the results (vector and FTS) are empty, because when
# they are, they often are missing the _rowid column, which causes an error
# they are, they often are missing the _rowid column, which causes an error.
# The original values are captured before any rank conversion so that
# they can be restored after reranking.
if vector_results.num_rows > 0:
distance_i = vector_results.column_names.index("_distance")
original_distances = vector_results.column(distance_i)
original_distance_row_ids = vector_results.column("_rowid")
if norm == "rank":
vector_results = LanceHybridQueryBuilder._rank(
vector_results, "_distance"
)
vector_results = vector_results.set_column(
distance_i,
vector_results.field(distance_i),
LanceHybridQueryBuilder._normalize_scores(original_distances),
LanceHybridQueryBuilder._normalize_scores(
vector_results.column(distance_i)
),
)
# In fts higher scores represent relevance. Not inverting them here as
@@ -2619,10 +2742,12 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
score_i = fts_results.column_names.index("_score")
original_scores = fts_results.column(score_i)
original_score_row_ids = fts_results.column("_rowid")
if norm == "rank":
fts_results = LanceHybridQueryBuilder._rank(fts_results, "_score")
fts_results = fts_results.set_column(
score_i,
fts_results.field(score_i),
LanceHybridQueryBuilder._normalize_scores(original_scores),
LanceHybridQueryBuilder._normalize_scores(fts_results.column(score_i)),
)
results = reranker.rerank_hybrid(fts_query, vector_results, fts_results)
@@ -2655,7 +2780,12 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
return results
def to_batches(
self, /, batch_size: Optional[int] = None, timeout: Optional[timedelta] = None
self,
/,
batch_size: Optional[int] = None,
timeout: Optional[timedelta] = None,
*,
blob_mode: BlobMode = "lazy",
):
raise NotImplementedError("to_batches not yet supported on a hybrid query")
@@ -2910,7 +3040,19 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
self._refine_factor = refine_factor
return self
def vector(self, vector: Union[np.ndarray, list]) -> LanceHybridQueryBuilder:
def vector(self, vector: Union[VEC, Tuple]) -> LanceHybridQueryBuilder:
"""Set the vector to search for.
Parameters
----------
vector: list, tuple, np.ndarray, pa.Array, or pa.ChunkedArray
The vector to search for.
Returns
-------
LanceHybridQueryBuilder
The LanceHybridQueryBuilder object.
"""
self._vector = vector
return self
@@ -2950,9 +3092,10 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
ProjectionExec: expr=[vector@0 as vector, _distance@2 as _distance]
GlobalLimitExec: skip=0, fetch=10
FilterExec: _distance@2 IS NOT NULL
SortExec: TopK(fetch=10), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false]
SortExec: TopK(fetch=1), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false]
KNNVectorDistance: metric=l2
LanceRead: uri=..., projection=[vector], ...
LanceRead: uri=..., projection=[vector], num_fragments=..., ...
<BLANKLINE>
Parameters
----------
@@ -3050,7 +3193,10 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
if columns:
self._vector_query.select(columns)
self._fts_query.select(columns)
if self._where:
# An Expr has no truth value (it raises on bool()), so test for it
# explicitly instead of relying on truthiness; an empty SQL string is
# still skipped.
if isinstance(self._where, Expr) or self._where:
self._vector_query.where(self._where, not self._postfilter)
self._fts_query.where(self._where, not self._postfilter)
# WAL-PK-FUSION: without the fallback, `if self._with_row_id:`.
@@ -3242,6 +3388,7 @@ class AsyncQueryBase(object):
*,
max_batch_length: Optional[int] = None,
timeout: Optional[timedelta] = None,
blob_mode: BlobMode = "lazy",
) -> AsyncRecordBatchReader:
"""
Execute the query and return the results as an Apache Arrow RecordBatchReader.
@@ -3258,7 +3405,47 @@ class AsyncQueryBase(object):
The maximum time to wait for the query to complete.
If not specified, no timeout is applied. If the query does not
complete within the specified time, an error will be raised.
blob_mode: str, default "lazy"
``"lazy"`` keeps blob descriptors and auto row ids for manual fetches.
``"descriptions"`` omits auto row ids. ``"bytes"`` fetches blob v2
payloads one batch at a time, without requiring pylance. Bytes mode
has the same restrictions as :meth:`to_arrow`.
Examples
--------
Use ``async for batch in await query.to_batches(blob_mode="bytes")``
to stream blob payloads and convert each batch with ``batch.to_pandas()``.
"""
blob_sources = await self._validated_blob_sources(blob_mode)
reader = await self._execute_batches(
max_batch_length=max_batch_length, timeout=timeout
)
if blob_mode == "lazy":
return reader
async def convert(tbl: pa.Table) -> pa.Table:
tbl = self._finalize_blob_query_table(tbl)
tbl = await self._apply_arrow_blob_mode(tbl, blob_mode, blob_sources)
if not self._user_requested_row_id() and "_rowid" in tbl.column_names:
tbl = tbl.drop_columns(["_rowid"])
return tbl
schema = (await convert(pa.Table.from_batches([], schema=reader.schema))).schema
async def batches():
async for batch in reader:
tbl = await convert(pa.Table.from_batches([batch]))
for converted in tbl.to_batches():
yield converted
return AsyncRecordBatchReader._from_batches(schema, batches())
async def _execute_batches(
self,
*,
max_batch_length: Optional[int] = None,
timeout: Optional[timedelta] = None,
) -> AsyncRecordBatchReader:
await self._maybe_add_blob_row_id()
return AsyncRecordBatchReader(
await self._inner.execute(
@@ -3334,7 +3521,7 @@ class AsyncQueryBase(object):
``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
``"bytes"`` returns payload bytes and raises for legacy blob columns
and blobs inside lists.
Remote tables and namespace query pushdown refuse ``"bytes"``.
LanceDB Distributed and namespace query pushdown refuse ``"bytes"``.
"""
blob_sources = await self._validated_blob_sources(blob_mode)
batch_iter = await self.to_batches(timeout=timeout)
@@ -3407,12 +3594,14 @@ class AsyncQueryBase(object):
If not specified, no timeout is applied. If the query does not
complete within the specified time, an error will be raised.
blob_mode: str, default "lazy"
Controls how blob columns are returned. Eligible local plain scans
use Lance's scanner, which returns lazy blob handles in ``"lazy"``
mode and also supports legacy blob columns. Other local blob v2
Controls how blob columns are returned. Local blob v2 queries support
``"bytes"`` and ``"descriptions"`` without pylance. Eligible local
plain scans use pylance's scanner for lazy blob handles in ``"lazy"``
mode and for legacy blob columns. Other local blob v2
queries return descriptors in ``"lazy"`` and ``"descriptions"``
modes, or payloads in ``"bytes"`` mode, through :meth:`to_arrow`.
Remote blob queries support only ``"descriptions"`` until a stable
LanceDB Distributed blob queries support only ``"descriptions"`` until a
stable
table snapshot can bind the query and blob fetches.
**kwargs
Forwarded to pyarrow.Table.to_pandas after query execution and
@@ -3499,7 +3688,16 @@ class AsyncQueryBase(object):
get_uri_scheme(await self._table.uri()) == "memory"
):
return None
dataset = await self._table.to_lance()
if (
blob_mode != "lazy"
and not _query_needs_lance_scanner(self)
and blob_v2_projection_sources(schema, query.columns)
):
return None
try:
dataset = await self._table.to_lance()
except ImportError as err:
raise _unsupported_blob_pandas_error(str(err)) from err
scanner = dataset.scanner(
**_scanner_kwargs_for_query(
query,
@@ -3592,9 +3790,10 @@ class AsyncQueryBase(object):
ProjectionExec: expr=[vector@0 as vector, _distance@2 as _distance]
GlobalLimitExec: skip=0, fetch=10
FilterExec: _distance@2 IS NOT NULL
SortExec: TopK(fetch=10), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false]
SortExec: TopK(fetch=1), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false]
KNNVectorDistance: metric=l2
LanceRead: uri=..., projection=[vector], ...
LanceRead: uri=..., projection=[vector], num_fragments=..., ...
<BLANKLINE>
<BLANKLINE>
Parameters
@@ -3998,13 +4197,13 @@ class AsyncFTSQuery(AsyncStandardQuery):
self._table,
)
async def to_batches(
async def _execute_batches(
self,
*,
max_batch_length: Optional[int] = None,
timeout: Optional[timedelta] = None,
) -> AsyncRecordBatchReader:
reader = await super().to_batches(timeout=timeout)
reader = await super()._execute_batches(timeout=timeout)
results = pa.Table.from_batches(await reader.read_all(), reader.schema)
if self._reranker:
results = self._reranker.rerank_fts(self.get_query(), results)
@@ -4049,9 +4248,10 @@ class AsyncVectorQueryBase:
your actual data to find the smallest possible value that will still give
you the desired recall.
LanceDB retains this as `nprobes` through local and remote request
construction. Lance sets both probe bounds to this value. Explicit minimum
or maximum settings can override their respective bounds.
LanceDB retains this as `nprobes` through LanceDB Embedded and LanceDB
Distributed request construction. Lance sets both probe bounds to this
value. Explicit minimum or maximum settings can override their respective
bounds.
"""
self._inner.nprobes(nprobes)
return self
@@ -4289,13 +4489,13 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
self._inner.nearest_to_text({"query": query}), self._table
)
async def to_batches(
async def _execute_batches(
self,
*,
max_batch_length: Optional[int] = None,
timeout: Optional[timedelta] = None,
) -> AsyncRecordBatchReader:
reader = await super().to_batches(timeout=timeout)
reader = await super()._execute_batches(timeout=timeout)
results = pa.Table.from_batches(await reader.read_all(), reader.schema)
if self._reranker:
results = self._reranker.rerank_vector(self._query_string, results)
@@ -4418,7 +4618,7 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
return fts_query, vec_query, limit, offset
async def to_batches(
async def _execute_batches(
self,
*,
max_batch_length: Optional[int] = None,
@@ -4512,9 +4712,9 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
LanceRead: uri=..., projection=[text], source=stream(_rowid)
GlobalLimitExec: skip=0, fetch=10
FilterExec: _distance@2 IS NOT NULL
SortExec: TopK(fetch=10), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false]
SortExec: TopK(fetch=1), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false]
KNNVectorDistance: metric=l2
LanceRead: uri=..., projection=[vector], ...
LanceRead: uri=..., projection=[vector], num_fragments=..., ...
ProjectionExec: expr=[vector@2 as vector, text@3 as text, _score@1 as _score, _rowid@0 as _rowid]
LanceRead: uri=..., projection=[vector, text], source=stream(_rowid)
GlobalLimitExec: skip=0, fetch=10
@@ -4688,6 +4888,7 @@ class BaseQueryBuilder(object):
*,
max_batch_length: Optional[int] = None,
timeout: Optional[timedelta] = None,
blob_mode: BlobMode = "lazy",
) -> pa.RecordBatchReader:
"""
Execute the query and return the results as an Apache Arrow RecordBatchReader.
@@ -4704,9 +4905,14 @@ class BaseQueryBuilder(object):
The maximum time to wait for the query to complete.
If not specified, no timeout is applied. If the query does not
complete within the specified time, an error will be raised.
blob_mode: str, default "lazy"
Controls blob conversion as described in
:meth:`AsyncQueryBase.to_batches`.
"""
async_reader = LOOP.run(
self._inner.to_batches(max_batch_length=max_batch_length, timeout=timeout)
self._inner.to_batches(
max_batch_length=max_batch_length, timeout=timeout, blob_mode=blob_mode
)
)
def iter_sync():
@@ -4868,9 +5074,10 @@ class BaseQueryBuilder(object):
ProjectionExec: expr=[vector@0 as vector, _distance@2 as _distance]
GlobalLimitExec: skip=0, fetch=10
FilterExec: _distance@2 IS NOT NULL
SortExec: TopK(fetch=10), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false]
SortExec: TopK(fetch=1), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false]
KNNVectorDistance: metric=l2
LanceRead: uri=..., projection=[vector], ...
LanceRead: uri=..., projection=[vector], num_fragments=..., ...
<BLANKLINE>
<BLANKLINE>
Parameters
+7 -4
View File
@@ -52,7 +52,10 @@ class TimeoutConfig:
`LANCE_CLIENT_CONNECT_TIMEOUT`, as an integer number of seconds.
read_timeout: Optional[timedelta]
The timeout for reading data from the server. Default is 300 seconds
(5 minutes). This can also be set via the environment variable
(5 minutes). This also applies while waiting for response headers during
an upload. Increase it for large or slowly produced inputs to
`create_table`, even if data is still being uploaded. This can also be
set via the environment variable
`LANCE_CLIENT_READ_TIMEOUT`, as an integer number of seconds.
pool_idle_timeout: Optional[timedelta]
The timeout for keeping idle connections in the connection pool. Default
@@ -121,7 +124,7 @@ class RetryConfig:
`LANCE_CLIENT_RETRY_BACKOFF_JITTER`.
statuses: Optional[List[int]
The HTTP status codes for which to retry the request. Default is
[429, 500, 502, 503].
[409, 429, 500, 502, 503, 504].
You can also set this via the environment variable
`LANCE_CLIENT_RETRY_STATUSES`. Use a comma-separated list of integers.
@@ -160,7 +163,7 @@ class TlsConfig:
@dataclass
class ClientConfig:
"""Configuration for the LanceDB Cloud HTTP client.
"""Configuration for the HTTP client used to connect to LanceDB Enterprise.
Attributes
----------
@@ -187,7 +190,7 @@ class ClientConfig:
Provider for dynamic headers to be added to each request.
user_id: Optional[str]
User identifier for tracking purposes. This is sent as the
`x-lancedb-user-id` header in requests to LanceDB Cloud/Enterprise.
`x-lancedb-user-id` header in requests to LanceDB Enterprise.
This can also be set via the `LANCEDB_USER_ID` environment variable.
Alternatively, set `LANCEDB_USER_ID_ENV_KEY` to specify another
+113 -29
View File
@@ -7,7 +7,6 @@ from __future__ import annotations
from dataclasses import replace
from datetime import timedelta
import json
import logging
from concurrent.futures import ThreadPoolExecutor
import sys
from typing import (
@@ -36,7 +35,7 @@ from lancedb.remote import ClientConfig, RetryConfig, TimeoutConfig, TlsConfig
import pyarrow as pa
from ..common import DATA
from lancedb.listing import Listing
from lancedb.listing import Listing, NamespaceListing, TableListing
from ..db import DBConnection, LOOP
from ..functions import FunctionVersion, UdfDefinition
from ..job import AsyncJob, Job
@@ -47,15 +46,13 @@ from ..secrets import EnvVarSecret, SecretInfo
from ..view import ViewDescription
if TYPE_CHECKING:
from .._lancedb import JobInfo
from .._lancedb import JobInfo, Session
from ..embeddings import EmbeddingFunctionConfig
from lance_namespace import (
LanceNamespace,
CreateNamespaceResponse,
DescribeNamespaceResponse,
DropNamespaceResponse,
ListNamespacesResponse,
ListTablesResponse,
)
from ..pydantic import LanceModel
from ..table import Table
@@ -104,7 +101,7 @@ def _tls_config_to_dict(config: Optional[TlsConfig]) -> Optional[dict[str, Any]]
def _client_config_to_dict(config: ClientConfig) -> dict[str, Any]:
if config.header_provider is not None:
raise ValueError(
"Cannot serialize a remote connection with a header_provider. "
"Cannot serialize a LanceDB Distributed connection with a header_provider. "
"Use static api_key/extra_headers or provide a worker-side "
"connection factory instead."
)
@@ -122,7 +119,7 @@ def _client_config_to_dict(config: ClientConfig) -> dict[str, Any]:
class RemoteDBConnection(DBConnection):
"""A connection to a remote LanceDB database."""
"""A connection to a LanceDB Enterprise database."""
def __init__(
self,
@@ -138,7 +135,7 @@ class RemoteDBConnection(DBConnection):
read_consistency_interval: Optional[timedelta] = None,
sql_host_override: Optional[str] = None,
):
"""Connect to a remote LanceDB database."""
"""Connect to a LanceDB Enterprise database."""
if isinstance(client_config, dict):
client_config = ClientConfig(**client_config)
elif client_config is None:
@@ -242,6 +239,26 @@ class RemoteDBConnection(DBConnection):
def __repr__(self) -> str:
return f"RemoteConnect(name={self.db_name})"
@property
@override
def uri(self) -> str:
return self._conn.uri
@property
def session(self) -> Optional["Session"]:
"""LanceDB Distributed connections do not expose a local cache session."""
raise NotImplementedError(
"session is not supported by LanceDB Distributed connections"
)
@property
def read_consistency_interval(self) -> Optional[timedelta]:
"""LanceDB Distributed connections do not expose a read consistency interval."""
raise NotImplementedError(
"read_consistency_interval is not supported by LanceDB Distributed "
"connections"
)
@override
def serialize(self) -> str:
if getattr(self, "_catalog_oauth", False):
@@ -268,7 +285,7 @@ class RemoteDBConnection(DBConnection):
namespace_path: Optional[List[str]] = None,
page_token: Optional[str] = None,
limit: Optional[int] = None,
) -> ListNamespacesResponse:
) -> NamespaceListing:
"""List immediate child namespace names in the given namespace.
Parameters
@@ -284,12 +301,12 @@ class RemoteDBConnection(DBConnection):
Returns
-------
ListNamespacesResponse
NamespaceListing
Response containing namespace names and optional page_token for pagination.
"""
if namespace_path is None:
namespace_path = []
return LOOP.run(
return NamespaceListing(
self._conn.list_namespaces(
namespace_path=namespace_path, page_token=page_token, limit=limit
)
@@ -373,13 +390,43 @@ class RemoteDBConnection(DBConnection):
"""
return LOOP.run(self._conn.describe_namespace(namespace_path=namespace_path))
@override
def namespace_exists(self, namespace_id: List[str]) -> bool:
"""Check if a namespace exists.
``namespace_id`` contains the namespace segments; an empty list represents
root. Returns False only if the namespace is not found. Other errors,
including permission errors, are propagated.
Examples
--------
>>> def check_namespace(conn):
... return conn.namespace_exists(["analytics"])
"""
return LOOP.run(self._conn.namespace_exists(namespace_id))
@override
def table_exists(self, table_id: List[str]) -> bool:
"""Check if a table exists.
``table_id`` contains the namespace segments followed by the table name.
Returns False only if the table is not found. Other errors, including
permission errors, are propagated.
Examples
--------
>>> def check_table(conn):
... return conn.table_exists(["analytics", "events"])
"""
return LOOP.run(self._conn.table_exists(table_id))
@override
def list_tables(
self,
namespace_path: Optional[List[str]] = None,
page_token: Optional[str] = None,
limit: Optional[int] = None,
) -> ListTablesResponse:
) -> TableListing:
"""List a page of tables in this database.
Parameters
@@ -396,12 +443,12 @@ class RemoteDBConnection(DBConnection):
Returns
-------
ListTablesResponse
TableListing
Response containing table names and optional page_token for pagination.
"""
if namespace_path is None:
namespace_path = []
return LOOP.run(
return TableListing(
self._conn.list_tables(
namespace_path=namespace_path, page_token=page_token, limit=limit
)
@@ -487,18 +534,14 @@ class RemoteDBConnection(DBConnection):
if namespace_path is None:
namespace_path = []
if storage_options is not None:
logging.info(
"storage_options is ignored for remote tables"
" (storage is managed; set storage_options on connect() instead)"
table = LOOP.run(
self._conn.open_table(
name,
namespace_path=namespace_path,
storage_options=storage_options,
index_cache_size=index_cache_size,
)
if index_cache_size is not None:
logging.info(
"index_cache_size is ignored for remote tables"
" (there is no local cache to configure)"
)
table = LOOP.run(self._conn.open_table(name, namespace_path=namespace_path))
)
tbl = RemoteTable(
table,
self.db_name,
@@ -571,13 +614,16 @@ class RemoteDBConnection(DBConnection):
name: str,
data: DATA = None,
schema: Optional[Union[pa.Schema, LanceModel]] = None,
on_bad_vectors: str = "error",
fill_value: float = 0.0,
mode: Optional[str] = None,
exist_ok: bool = False,
on_bad_vectors: str = "error",
fill_value: float = 0.0,
embedding_functions: Optional[List[EmbeddingFunctionConfig]] = None,
*,
namespace_path: Optional[List[str]] = None,
storage_options: Optional[Dict[str, str]] = None,
data_storage_version: Optional[str] = None,
enable_v2_manifest_paths: Optional[bool] = None,
) -> Table:
"""Create a [Table][lancedb.table.Table] in the database.
@@ -617,6 +663,12 @@ class RemoteDBConnection(DBConnection):
embedding_functions: list of EmbeddingFunctionConfig, optional
The embedding functions to store in the table schema and use to
generate vectors when creating the table or adding data.
storage_options: dict, optional
Not supported in LanceDB Distributed. Raises NotImplementedError.
data_storage_version: str, optional
Not supported in LanceDB Distributed. Raises NotImplementedError.
enable_v2_manifest_paths: bool, optional
Not supported in LanceDB Distributed. Raises NotImplementedError.
Returns
-------
@@ -683,6 +735,15 @@ class RemoteDBConnection(DBConnection):
LanceTable(table4)
"""
for option, value in (
("data_storage_version", data_storage_version),
("enable_v2_manifest_paths", enable_v2_manifest_paths),
):
if value is not None:
raise NotImplementedError(
f"{option} is not supported for table creation in "
"LanceDB Distributed"
)
if exist_ok:
if mode == "create":
mode = "exist_ok"
@@ -704,6 +765,7 @@ class RemoteDBConnection(DBConnection):
on_bad_vectors=on_bad_vectors,
fill_value=fill_value,
embedding_functions=embedding_functions,
storage_options=storage_options,
)
)
return RemoteTable(
@@ -723,6 +785,8 @@ class RemoteDBConnection(DBConnection):
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> MaterializedView:
from .table import RemoteTable
@@ -734,6 +798,8 @@ class RemoteDBConnection(DBConnection):
where=where,
limit=limit,
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
)
)
return MaterializedView(
@@ -755,6 +821,8 @@ class RemoteDBConnection(DBConnection):
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> Job[None]:
job = LOOP.run(
self._conn.create_materialized_view_async(
@@ -764,6 +832,8 @@ class RemoteDBConnection(DBConnection):
where=where,
limit=limit,
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
)
)
return Job(job)
@@ -835,6 +905,20 @@ class RemoteDBConnection(DBConnection):
job = LOOP.run(self._conn.drop_table_async(name, namespace_path=namespace_path))
return Job(job if isinstance(job, AsyncJob) else AsyncJob(job))
@override
def drop_all_tables(self, namespace_path: Optional[List[str]] = None):
"""Drop all tables from the database.
The remote API does not currently support this operation. Use
``list_tables()`` and ``drop_table()`` to drop tables individually.
"""
LOOP.run(self._conn.drop_all_tables(namespace_path=namespace_path))
@override
def drop_database(self):
"""Deprecated alias for ``drop_all_tables()``."""
LOOP.run(self._conn.drop_database())
@override
def rename_table(
self,
@@ -1095,7 +1179,7 @@ class RemoteDBConnection(DBConnection):
default_namespace_path: Optional[List[str]] = None,
parameters: Optional[QueryParameters] = None,
) -> SqlQuery:
"""Start executing SQL through this remote connection.
"""Start executing SQL through this LanceDB Distributed connection.
Unqualified tables use this connection's database and the
``["public"]`` namespace by default. Fully qualified table names may
@@ -1114,7 +1198,7 @@ class RemoteDBConnection(DBConnection):
)
@override
def describe_query(self, query_id: UUID) -> QueryDescription:
def describe_query(self, query_id: Union[UUID, str]) -> QueryDescription:
"""Describe a submitted SQL query by its connection-scoped id."""
return LOOP.run(
self._conn.describe_query(
+2 -2
View File
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Header providers for LanceDB remote connections.
"""Header providers for LanceDB Enterprise connections.
This module provides a flexible header management framework for LanceDB remote
connections, allowing users to implement custom header strategies for
@@ -141,7 +141,7 @@ class OAuthProvider(HeaderProvider):
# Set expiration if provided
expires_in = token_data.get("expires_in")
if expires_in:
if expires_in is not None:
self._token_expires_at = time.time() + expires_in
else:
# Token doesn't expire or expiration unknown
+288 -168
View File
@@ -4,9 +4,10 @@
from datetime import timedelta
import deprecation
import logging
from functools import cached_property
from functools import cached_property, wraps
import os
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
@@ -41,19 +42,12 @@ from lancedb.index import (
FTS,
BTree,
Bitmap,
HnswFlat,
HnswPq,
HnswSq,
IvfFlat,
IvfPq,
IvfRq,
IvfSq,
LabelList,
)
from lancedb.job import Job
from lancedb.functions import FunctionApplication, RefreshColumnResult
from lancedb.remote.db import LOOP
from lancedb.table import IndexConfigType, KNOWN_METRICS
from lancedb.table import IndexConfigType, _maybe_add_fts_error_note
import pyarrow as pa
from lancedb.common import DATA, VEC, VECTOR_COLUMN_NAME
@@ -68,20 +62,46 @@ from ..query import (
FullTextQuery,
LanceQueryBuilder,
LanceTakeQueryBuilder,
LanceVectorQueryBuilder,
)
from ..table import (
AsyncTable,
BlobMode,
Branches,
CompactionOptions,
IndexStatistics,
Query,
Table,
Tags,
)
from ..types import BaseTokenizerType
from ..types import BaseTokenizerType, ScalarIndexType
from ..util import infer_vector_column_name
if TYPE_CHECKING:
import lance
import polars as pl
def _deprecated_keyword(old_name: str, new_name: str):
"""Keep old remote-only keyword names without changing the Table signature."""
def decorate(method):
@wraps(method)
def wrapped(self, *args, **kwargs):
if old_name in kwargs:
if new_name in kwargs:
raise TypeError(f"Cannot specify both {old_name} and {new_name}")
warnings.warn(
f"{old_name} is deprecated; use {new_name} instead",
DeprecationWarning,
stacklevel=2,
)
kwargs[new_name] = kwargs.pop(old_name)
return method(self, *args, **kwargs)
return wrapped
return decorate
class RemoteTable(Table):
def __init__(
@@ -106,8 +126,8 @@ class RemoteTable(Table):
def _serialized_connection_state(self) -> str:
if self._connection_state is None:
raise RuntimeError(
"Cannot reopen this remote table because it does not carry "
"serialized connection state"
"Cannot reopen this LanceDB Distributed table because it does not "
"carry serialized connection state"
)
if callable(self._connection_state):
self._connection_state = self._connection_state()
@@ -173,6 +193,18 @@ class RemoteTable(Table):
"""The name of the table"""
return self._name
@property
def namespace(self) -> List[str]:
return self._namespace_path
@deprecation.deprecated(
deprecated_in="0.33.1",
current_version=__version__,
details="Use update_field_metadata() instead.",
)
def replace_field_metadata(self, field_name: str, new_metadata: Dict[str, str]):
LOOP.run(self._table.replace_field_metadata(field_name, new_metadata))
def __repr__(self) -> str:
return f"RemoteTable({self.db_name}.{self.name})"
@@ -241,14 +273,34 @@ class RemoteTable(Table):
return LOOP.run(self._table.list_versions())
def to_arrow(self, *, blob_mode: BlobMode = "lazy") -> pa.Table:
"""to_arrow() is not supported for remote tables."""
"""to_arrow() is not supported in LanceDB Distributed."""
validate_blob_mode(blob_mode)
raise NotImplementedError("to_arrow() is not supported for remote tables.")
raise NotImplementedError(
"to_arrow() is not supported in LanceDB Distributed. "
"Use table.search().to_arrow() instead."
)
def to_pandas(self, blob_mode: BlobMode = "lazy", **kwargs):
"""to_pandas() is not supported for remote tables."""
"""to_pandas() is not supported in LanceDB Distributed."""
validate_blob_mode(blob_mode)
raise NotImplementedError("to_pandas() is not supported for remote tables.")
raise NotImplementedError(
"to_pandas() is not supported in LanceDB Distributed. "
"Use table.search().to_pandas() instead."
)
def to_lance(self, **kwargs) -> "lance.LanceDataset":
"""Direct Lance dataset access is not supported in LanceDB Distributed.
Use ``table.search().to_arrow()`` to read query results through the server.
"""
return LOOP.run(self._table.to_lance(**kwargs))
def to_polars(self, batch_size=None) -> "pl.LazyFrame":
"""Use ``table.search().to_polars()`` to read query results."""
raise NotImplementedError(
"to_polars() is not supported in LanceDB Distributed. "
"Use table.search().to_polars() instead."
)
def checkout(self, version: Union[int, str]):
result = LOOP.run(self._table.checkout(version))
@@ -279,16 +331,21 @@ class RemoteTable(Table):
"""Tokenize a query using the tokenizer configured on an FTS index.
Model-backed tokenizers such as ``jieba/*`` and ``lindera/*`` are
rebuilt in the client process from index metadata, so the same tokenizer
model files must exist locally.
rebuilt in the client process from index metadata. In LanceDB Distributed,
this means the same tokenizer model files must also exist locally
(under ``LANCE_LANGUAGE_MODEL_HOME``) and must match the files the
server uses. A mismatch cannot be detected: the returned tokens may
differ from what the server's index produces. If the model files are
missing, an error naming the tokenizer is raised.
"""
return LOOP.run(
self._table.tokenize(query, column=column, index_name=index_name)
)
def index_stats(self, index_uuid: str) -> Optional[IndexStatistics]:
@_deprecated_keyword("index_uuid", "index_name")
def index_stats(self, index_name: str) -> Optional[IndexStatistics]:
"""List all the stats of a specified index"""
return LOOP.run(self._table.index_stats(index_uuid))
return LOOP.run(self._table.index_stats(index_name))
@deprecation.deprecated(
deprecated_in="0.25.0",
@@ -298,43 +355,38 @@ class RemoteTable(Table):
def create_scalar_index(
self,
column: str,
index_type: Literal["BTREE", "BITMAP", "LABEL_LIST", "scalar"] = "scalar",
*,
replace: bool = False,
replace: bool = True,
index_type: ScalarIndexType = "BTREE",
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
):
"""Creates a scalar index.
"""Create a scalar index on a column.
.. deprecated:: 0.25.0
Use :meth:`create_index` with a BTree, Bitmap, or LabelList config instead.
Example: ``table.create_index("column", config=BTree())``
Parameters
----------
column : str
The column to be indexed. Must be a boolean, integer, float,
or string column.
index_type : str
The index type of the scalar index. Must be "scalar" (BTREE),
"BTREE", "BITMAP", or "LABEL_LIST",
replace : bool
If True, replace the existing index with the new one.
"""
if index_type == "scalar" or index_type == "BTREE":
if index_type == "scalar":
warnings.warn(
'index_type="scalar" is deprecated; use "BTREE" instead',
DeprecationWarning,
stacklevel=2,
)
index_type = "BTREE"
if index_type == "BTREE":
config = BTree()
elif index_type == "BITMAP":
config = Bitmap()
elif index_type == "LABEL_LIST":
config = LabelList()
else:
raise ValueError(f"Unknown index type: {index_type}")
LOOP.run(
raise ValueError(f"Unknown index type {index_type}")
return LOOP.run(
self._table.create_index(
column,
config=config,
replace=replace,
config=config,
wait_timeout=wait_timeout,
name=name,
)
@@ -345,12 +397,16 @@ class RemoteTable(Table):
current_version=__version__,
details="Use create_index() with config=FTS() instead.",
)
@_deprecated_keyword("column", "field_names")
def create_fts_index(
self,
column: str,
field_names: Union[str, List[str]],
*,
ordering_field_names: Optional[Union[str, List[str]]] = None,
replace: bool = False,
wait_timeout: Optional[timedelta] = None,
writer_heap_size: Optional[int] = 1024 * 1024 * 1024,
use_tantivy: bool = False,
tokenizer_name: Optional[str] = None,
with_position: bool = False,
# tokenizer configs:
base_tokenizer: BaseTokenizerType = "simple",
@@ -366,6 +422,7 @@ class RemoteTable(Table):
prefix_only: bool = False,
block_size: int = 128,
document_granularity: DocumentGranularity = DocumentGranularity.ROW,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
):
"""Create a full-text search index on a column.
@@ -374,31 +431,70 @@ class RemoteTable(Table):
Use :meth:`create_index` with an FTS config instead.
Example: ``table.create_index("text_column", config=FTS())``
"""
if use_tantivy:
raise ValueError(
"Tantivy-based FTS has been removed. "
"Remove use_tantivy and recreate the index with native FTS."
)
if ordering_field_names is not None:
raise ValueError(
"ordering_field_names was only supported by the removed "
"Tantivy-based FTS implementation."
)
if writer_heap_size != 1024 * 1024 * 1024:
raise ValueError(
"writer_heap_size was only supported by the removed "
"Tantivy-based FTS implementation."
)
if not isinstance(field_names, str):
raise ValueError(
"Native FTS indexes can only be created on a single field "
"at a time. To search over multiple text fields, create a "
"separate FTS index for each field."
)
if tokenizer_name is None:
tokenizer_configs = {
"base_tokenizer": base_tokenizer,
"language": language,
"with_position": with_position,
"max_token_length": max_token_length,
"lower_case": lower_case,
"stem": stem,
"remove_stop_words": remove_stop_words,
"custom_stop_words": custom_stop_words,
"ascii_folding": ascii_folding,
"ngram_min_length": ngram_min_length,
"ngram_max_length": ngram_max_length,
"prefix_only": prefix_only,
}
else:
tokenizer_configs = self.infer_tokenizer_configs(tokenizer_name)
tokenizer_configs["custom_stop_words"] = custom_stop_words
config = FTS(
with_position=with_position,
base_tokenizer=base_tokenizer,
language=language,
max_token_length=max_token_length,
lower_case=lower_case,
stem=stem,
remove_stop_words=remove_stop_words,
custom_stop_words=custom_stop_words,
ascii_folding=ascii_folding,
ngram_min_length=ngram_min_length,
ngram_max_length=ngram_max_length,
prefix_only=prefix_only,
block_size=block_size,
document_granularity=document_granularity,
**tokenizer_configs,
)
LOOP.run(
self._table.create_index(
column,
config=config,
replace=replace,
wait_timeout=wait_timeout,
name=name,
try:
LOOP.run(
self._table.create_index(
field_names,
replace=replace,
config=config,
name=name,
wait_timeout=wait_timeout,
)
)
)
except (ValueError, RuntimeError) as e:
_maybe_add_fts_error_note(
e,
base_tokenizer=config.base_tokenizer,
language=config.language,
)
raise e
# New unified API overload
@overload
@@ -408,6 +504,7 @@ class RemoteTable(Table):
/,
*,
config: IndexConfigType,
replace: bool = ...,
wait_timeout: Optional[timedelta] = ...,
name: Optional[str] = ...,
train: bool = ...,
@@ -418,38 +515,56 @@ class RemoteTable(Table):
def create_index(
self,
metric: Literal["l2", "cosine", "dot", "hamming"] = ...,
vector_column_name: str = ...,
index_cache_size: Optional[int] = ...,
num_partitions: Optional[int] = ...,
num_sub_vectors: Optional[int] = ...,
replace: Optional[bool] = ...,
vector_column_name: str = ...,
replace: bool = ...,
accelerator: Optional[str] = ...,
index_type: Literal[
"VECTOR", "IVF_FLAT", "IVF_SQ", "IVF_PQ", "IVF_HNSW_SQ", "IVF_HNSW_PQ"
] = ...,
wait_timeout: Optional[timedelta] = ...,
*,
index_cache_size: Optional[int] = ...,
num_bits: int = ...,
index_type: Literal[
"IVF_FLAT", "IVF_SQ", "IVF_PQ", "IVF_RQ", "IVF_HNSW_SQ", "IVF_HNSW_PQ"
] = ...,
max_iterations: int = ...,
sample_rate: int = ...,
m: int = ...,
ef_construction: int = ...,
*,
wait_timeout: Optional[timedelta] = ...,
name: Optional[str] = ...,
train: bool = ...,
target_partition_size: Optional[int] = ...,
) -> None: ...
def create_index(
self,
metric: str = "l2",
vector_column_name: str = VECTOR_COLUMN_NAME,
index_cache_size: Optional[int] = None,
num_partitions: Optional[int] = None,
num_sub_vectors: Optional[int] = None,
replace: Optional[bool] = None,
vector_column_name: str = VECTOR_COLUMN_NAME,
replace: bool = True,
accelerator: Optional[str] = None,
index_type="vector",
wait_timeout: Optional[timedelta] = None,
*,
index_cache_size: Optional[int] = None,
num_bits: int = 8,
index_type: Literal[
"IVF_FLAT",
"IVF_SQ",
"IVF_PQ",
"IVF_RQ",
"IVF_HNSW_SQ",
"IVF_HNSW_PQ",
"IVF_HNSW_FLAT",
] = "IVF_PQ",
max_iterations: int = 50,
sample_rate: int = 256,
m: int = 20,
ef_construction: int = 300,
*,
config: Optional[IndexConfigType] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
train: bool = True,
target_partition_size: Optional[int] = None,
):
"""Create an index on a column.
@@ -460,6 +575,24 @@ class RemoteTable(Table):
argument plus separate ``vector_column_name`` / ``num_partitions`` /
etc. parameters, and emits a ``DeprecationWarning``.
Parameters
----------
metric : str
For new API: the column name to index.
For legacy API: the distance metric ("l2", "cosine", "dot", "hamming").
config : IndexConfigType, optional
The index configuration object. If provided, uses the new unified API.
Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq,
BTree, Bitmap, LabelList, Fm, FTS.
replace : bool, default True
Whether to replace an existing index on this column.
wait_timeout : timedelta, optional
Timeout to wait for async indexing to complete.
name : str, optional
Custom name for the index.
train : bool, default True
Whether to train the index with existing data.
Examples
--------
New API (recommended):
@@ -485,7 +618,6 @@ class RemoteTable(Table):
vector_column_name,
accelerator,
index_cache_size,
replace,
)
if is_legacy:
@@ -501,53 +633,36 @@ class RemoteTable(Table):
stacklevel=2,
)
# Legacy API: first arg is the distance metric
column = vector_column_name
if accelerator is not None:
logging.warning(
"GPU accelerator is not supported for remote tables "
"GPU accelerator is not supported in LanceDB Distributed "
"and will be ignored."
)
idx_type = index_type.upper()
if idx_type == "VECTOR" or idx_type == "IVF_PQ":
config = IvfPq(
distance_type=metric,
num_partitions=num_partitions,
num_sub_vectors=num_sub_vectors,
num_bits=num_bits,
)
elif idx_type == "IVF_RQ":
config = IvfRq(
distance_type=metric,
num_partitions=num_partitions,
num_bits=num_bits,
)
elif idx_type == "IVF_SQ":
config = IvfSq(distance_type=metric, num_partitions=num_partitions)
elif idx_type == "IVF_HNSW_PQ":
config = HnswPq(
distance_type=metric,
num_partitions=num_partitions,
num_sub_vectors=num_sub_vectors,
num_bits=num_bits,
)
elif idx_type == "IVF_HNSW_SQ":
config = HnswSq(distance_type=metric, num_partitions=num_partitions)
elif idx_type == "IVF_HNSW_FLAT":
config = HnswFlat(distance_type=metric, num_partitions=num_partitions)
elif idx_type == "IVF_FLAT":
config = IvfFlat(distance_type=metric, num_partitions=num_partitions)
else:
raise ValueError(
f"Unknown vector index type: {idx_type}. Valid options are"
" 'IVF_FLAT', 'IVF_PQ', 'IVF_RQ', 'IVF_SQ',"
" 'IVF_HNSW_PQ', 'IVF_HNSW_SQ', 'IVF_HNSW_FLAT'"
)
# Build config from legacy parameters
config = self._build_vector_config_from_legacy_params(
metric=metric,
index_type="IVF_PQ"
if index_type.upper() == "VECTOR"
else index_type.upper(),
num_partitions=num_partitions,
num_sub_vectors=num_sub_vectors,
num_bits=num_bits,
max_iterations=max_iterations,
sample_rate=sample_rate,
m=m,
ef_construction=ef_construction,
target_partition_size=target_partition_size,
accelerator=None,
)
else:
column = metric
LOOP.run(
return LOOP.run(
self._table.create_index(
column,
replace=replace,
@@ -586,37 +701,6 @@ class RemoteTable(Table):
)
)
def _is_legacy_create_index_call(
self,
first_arg: str,
config: Optional[IndexConfigType],
num_partitions: Optional[int],
num_sub_vectors: Optional[int],
vector_column_name: str,
accelerator: Optional[str],
index_cache_size: Optional[int],
replace: Optional[bool],
) -> bool:
"""Detect if this is a legacy create_index call."""
if config is not None:
return False
if any(
x is not None
for x in (
num_partitions,
num_sub_vectors,
accelerator,
index_cache_size,
replace,
)
):
return True
if vector_column_name != VECTOR_COLUMN_NAME:
return True
if first_arg.lower() in KNOWN_METRICS:
return True
return False
def add(
self,
data: DATA,
@@ -629,7 +713,7 @@ class RemoteTable(Table):
) -> AddResult:
"""Add more data to the [Table][lancedb.table.Table].
It has the same API signature as the OSS version.
It has the same API signature as the LanceDB Embedded version.
Parameters
----------
@@ -659,7 +743,7 @@ class RemoteTable(Table):
capped at the number of CPU cores. Lower this if bulk ingestion is
using too much memory.
allow_external_blob_outside_bases: bool, default False
Not supported for remote tables. Setting this raises.
Not supported in LanceDB Distributed. Setting this raises.
Returns
-------
@@ -688,9 +772,10 @@ class RemoteTable(Table):
query: Union[VEC, str] = None,
vector_column_name: Optional[str] = None,
query_type="auto",
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
fast_search: Optional[bool] = None,
) -> LanceVectorQueryBuilder:
) -> LanceQueryBuilder:
"""Create a search query to find the nearest neighbors
of the given query vector. We currently support
[vector search](https://lancedb.com/docs/search/vector-search/)
@@ -781,6 +866,7 @@ class RemoteTable(Table):
query,
query_type,
vector_column_name=vector_column_name,
ordering_field_name=ordering_field_name,
fts_columns=fts_columns or [],
fast_search=fast_search,
)
@@ -840,7 +926,8 @@ class RemoteTable(Table):
self._table._do_merge(merge, new_data, on_bad_vectors, fill_value)
)
def delete(self, predicate: str) -> DeleteResult:
@_deprecated_keyword("predicate", "where")
def delete(self, where: Union[str, Expr]) -> DeleteResult:
"""Delete rows from the table.
This can be used to delete a single row, many rows, all rows, or
@@ -848,7 +935,7 @@ class RemoteTable(Table):
Parameters
----------
predicate: str
where: Union[str, Expr]
The SQL where clause to use when deleting rows.
- For example, 'x = 2' or 'x IN (1, 2, 3)'.
@@ -892,7 +979,7 @@ class RemoteTable(Table):
x vector _distance # doctest: +SKIP
0 2 [3.0, 4.0] 85.0 # doctest: +SKIP
"""
return LOOP.run(self._table.delete(predicate))
return LOOP.run(self._table.delete(where))
def update(
self,
@@ -954,22 +1041,27 @@ class RemoteTable(Table):
self._table.update(where=where, updates=values, updates_sql=values_sql)
)
def cleanup_old_versions(self, *_):
def cleanup_old_versions(
self,
older_than: Optional[timedelta] = None,
*,
delete_unverified: bool = False,
):
"""
cleanup_old_versions() is a no-op for remote tables.
cleanup_old_versions() is a no-op in LanceDB Distributed.
"""
warnings.warn(
"cleanup_old_versions() is a no-op for remote tables.",
"cleanup_old_versions() is a no-op in LanceDB Distributed.",
stacklevel=2,
)
pass
def compact_files(self, *_):
def compact_files(self, *args, **kwargs):
"""
compact_files() is a no-op for remote tables.
compact_files() is a no-op in LanceDB Distributed.
"""
warnings.warn(
"compact_files() is a no-op for remote tables.",
"compact_files() is a no-op in LanceDB Distributed.",
stacklevel=2,
)
pass
@@ -979,12 +1071,15 @@ class RemoteTable(Table):
*,
cleanup_older_than: Optional[timedelta] = None,
delete_unverified: bool = False,
retrain: bool = False,
compaction_options: Optional[CompactionOptions] = None,
):
"""optimize() is not supported for remote tables."""
"""optimize() is not supported in LanceDB Distributed."""
return LOOP.run(
self._table.optimize(
cleanup_older_than=cleanup_older_than,
delete_unverified=delete_unverified,
retrain=retrain,
)
)
@@ -1001,8 +1096,17 @@ class RemoteTable(Table):
| None = None,
*,
computed: Dict[str, str] | None = None,
auto_refresh_enabled: bool | None = None,
auto_refresh_interval_seconds: int | None = None,
) -> AddColumnsResult:
return LOOP.run(self._table.add_columns(transforms, computed=computed))
return LOOP.run(
self._table.add_columns(
transforms,
computed=computed,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
)
)
def refresh_column(self, column: str):
return LOOP.run(self._table.refresh_column(column))
@@ -1080,11 +1184,12 @@ class RemoteTable(Table):
)
def close_rte_writers(self) -> None:
"""No-op for remote tables (no local shard writers)."""
"""No-op in LanceDB Distributed (no local shard writers)."""
return LOOP.run(self._table.close_rte_writers())
def drop_index(self, index_name: str):
return LOOP.run(self._table.drop_index(index_name))
@_deprecated_keyword("index_name", "name")
def drop_index(self, name: str) -> None:
return LOOP.run(self._table.drop_index(name))
def prewarm_index(self, name: str) -> None:
"""Prewarm an index in the table.
@@ -1108,7 +1213,7 @@ class RemoteTable(Table):
This is a hint to the database that the given columns will be accessed
in the future and the database should prefetch the data if possible.
Currently only supported on remote tables.
Currently only supported in LanceDB Distributed.
This call initiates prewarming and returns once the request is accepted.
It is idempotent and safe to call from multiple clients concurrently.
@@ -1137,15 +1242,25 @@ class RemoteTable(Table):
def uri(self) -> str:
"""The table URI (storage location).
For remote tables, this fetches the location from the server via describe.
In LanceDB Distributed, this fetches the location from the server via describe.
"""
return LOOP.run(self._table.uri())
def take_offsets(self, offsets: list[int]) -> LanceTakeQueryBuilder:
return LanceTakeQueryBuilder(self._table.take_offsets(offsets))
def take_offsets(
self, offsets: list[int], *, with_row_id: bool = False
) -> LanceTakeQueryBuilder:
builder = LanceTakeQueryBuilder(self._table.take_offsets(offsets))
if with_row_id:
builder.with_row_id()
return builder
def take_row_ids(self, row_ids: list[int]) -> LanceTakeQueryBuilder:
return LanceTakeQueryBuilder(self._table.take_row_ids(row_ids))
def take_row_ids(
self, row_ids: list[int], *, with_row_id: bool = False
) -> LanceTakeQueryBuilder:
builder = LanceTakeQueryBuilder(self._table.take_row_ids(row_ids))
if with_row_id:
builder.with_row_id()
return builder
def uses_v2_manifest_paths(self) -> bool:
return LOOP.run(self._table.uses_v2_manifest_paths())
@@ -1173,6 +1288,11 @@ class RemoteTable(Table):
) -> "list[Optional[BlobFile]]":
return LOOP.run(self._table.fetch_blob_files(column, row_ids))
def open_blob_file(
self, descriptor: Union[dict, pa.StructScalar, None]
) -> Optional[BlobFile]:
return LOOP.run(self._table.open_blob_file(descriptor))
def head(self, n=5) -> pa.Table:
"""
Return the first `n` rows of the table.
+4 -1
View File
@@ -241,6 +241,7 @@ class Reranker(ABC):
This op is slower than just keeping relevance score but can be useful
for debugging.
"""
combined_schema = pa.unify_schemas([vector_results.schema, fts_results.schema])
# add nulls to fts results for _distance
if "_distance" not in fts_results.column_names:
fts_results = fts_results.append_column(
@@ -265,7 +266,9 @@ class Reranker(ABC):
else:
vector_results_dict[key] = value
combined = pa.Table.from_pylist(list(vector_results_dict.values()))
combined = pa.Table.from_pylist(
list(vector_results_dict.values()), schema=combined_schema
)
return combined
def _keep_relevance_score(self, combined_results: pa.Table):
+1 -1
View File
@@ -62,7 +62,7 @@ class CohereReranker(Reranker):
"COHERE_API_KEY not set. Either set it in your environment or \
pass it as `api_key` argument to the CohereReranker."
)
return cohere.Client(os.environ.get("COHERE_API_KEY") or self.api_key)
return cohere.Client(self.api_key or os.environ.get("COHERE_API_KEY"))
def _rerank(self, result_set: pa.Table, query: str):
result_set = self._handle_empty_results(result_set)
+6 -1
View File
@@ -97,7 +97,12 @@ class MRRReranker(Reranker):
weighted_mrr = self.weight_vector * vector_rr + self.weight_fts * fts_rr
final_mrr_scores[result_id] = weighted_mrr
combined_results = self.merge_results(vector_results, fts_results)
# With return_score="all", a row found by both searches must keep its
# `_distance` and its `_score`.
if self.score == "all":
combined_results = self._merge_and_keep_scores(vector_results, fts_results)
else:
combined_results = self.merge_results(vector_results, fts_results)
combined_row_ids = combined_results["_rowid"].to_pylist()
relevance_scores = [final_mrr_scores[row_id] for row_id in combined_row_ids]
combined_results = combined_results.append_column(
+15 -13
View File
@@ -21,7 +21,7 @@ class OpenaiReranker(Reranker):
Parameters
----------
model_name : str, default "gpt-4-turbo-preview"
model_name : str, default "gpt-5.6-sol"
The name of the cross encoder model to use.
column : str, default "text"
The name of the column to use as input to the cross encoder model.
@@ -33,7 +33,7 @@ class OpenaiReranker(Reranker):
def __init__(
self,
model_name: str = "gpt-4-turbo-preview",
model_name: str = "gpt-5.6-sol",
column: str = "text",
return_score="relevance",
api_key: Optional[str] = None,
@@ -54,7 +54,6 @@ class OpenaiReranker(Reranker):
response = self._client.chat.completions.create(
model=self.model_name,
response_format={"type": "json_object"},
temperature=0,
messages=[
{
"role": "system",
@@ -70,15 +69,18 @@ class OpenaiReranker(Reranker):
],
)
results = json.loads(response.choices[0].message.content)["documents"]
docs, scores = list(
zip(*[(result["content"], result["relevance_score"]) for result in results])
) # tuples
# replace the self.column column with the docs
result_set = result_set.drop(self.column)
result_set = result_set.append_column(
self.column, pa.array(docs, type=pa.string())
)
# add the scores
# The model returns the documents in its own order, so match each score
# back to its row by content.
scores_by_content = {
result["content"]: result["relevance_score"] for result in results
}
missing = sum(doc not in scores_by_content for doc in docs)
if missing:
raise ValueError(
f"The model returned no relevance_score for {missing} of "
f"{len(docs)} documents"
)
scores = [scores_by_content[doc] for doc in docs]
result_set = result_set.append_column(
"_relevance_score", pa.array(scores, type=pa.float32())
)
@@ -129,4 +131,4 @@ class OpenaiReranker(Reranker):
"OPENAI_API_KEY not set. Either set it in your environment or \
pass it as `api_key` argument to the CohereReranker."
)
return openai.OpenAI(api_key=os.environ.get("OPENAI_API_KEY") or self.api_key)
return openai.OpenAI(api_key=self.api_key or os.environ.get("OPENAI_API_KEY"))
+6 -2
View File
@@ -54,8 +54,12 @@ class RRFReranker(Reranker):
for i, result_id in enumerate(ids, 1):
rrf_score_map[result_id] += 1 / (i + self.K)
# Sort the results based on RRF score
combined_results = self.merge_results(vector_results, fts_results)
# Sort the results based on RRF score. With return_score="all", a row found
# by both searches must keep its `_distance` and its `_score`.
if self.score == "all":
combined_results = self._merge_and_keep_scores(vector_results, fts_results)
else:
combined_results = self.merge_results(vector_results, fts_results)
combined_row_ids = combined_results["_rowid"].to_pylist()
relevance_scores = [rrf_score_map[row_id] for row_id in combined_row_ids]
combined_results = combined_results.append_column(
+2 -2
View File
@@ -32,7 +32,7 @@ class VoyageAIReranker(Reranker):
return_score : str, default "relevance"
options are "relevance" or "all". Only "relevance" is supported for now.
api_key : str, default None
The API key to use. If None, will use the OPENAI_API_KEY environment variable.
The API key to use. If None, will use the VOYAGE_API_KEY environment variable.
truncation : Optional[bool], default None
"""
@@ -64,7 +64,7 @@ class VoyageAIReranker(Reranker):
pass it as `api_key` argument to the VoyageAIReranker."
)
return voyageai.Client(
api_key=os.environ.get("VOYAGE_API_KEY") or self.api_key,
api_key=self.api_key or os.environ.get("VOYAGE_API_KEY"),
)
def _rerank(self, result_set: pa.Table, query: str):
+18 -2
View File
@@ -276,6 +276,14 @@ def _from_iterable(data: Iterator) -> Scannable:
_registered_modules: set[str] = set()
def _hf_batches(data):
if data._indices is None:
yield from data.data.to_batches()
else:
for table in data.with_format("arrow").iter(batch_size=1000):
yield from table.to_batches()
def _register_optional_converters():
"""Register converters for optional dependencies that are already imported."""
@@ -323,7 +331,15 @@ def _register_optional_converters():
def _from_hf_dataset(data: HFDataset) -> Scannable:
table = data.data.table # Access underlying Arrow table
return Scannable(
schema=table.schema, num_rows=len(data), reader=table.to_reader
schema=table.schema,
num_rows=len(data),
reader=(
table.to_reader
if data._indices is None
else lambda: pa.RecordBatchReader.from_batches(
table.schema, _hf_batches(data)
)
),
)
@to_scannable.register(HFDatasetDict)
@@ -335,7 +351,7 @@ def _register_optional_converters():
def gen():
for split_name, dataset in data.items():
for batch in dataset.data.to_batches():
for batch in _hf_batches(dataset):
split_arr = pa.array(
[split_name] * len(batch), type=pa.string()
)
+126 -28
View File
@@ -4,8 +4,9 @@
"""Schema helpers for Lance blob columns."""
import ctypes
import importlib
from typing import TYPE_CHECKING, Optional
from typing import TYPE_CHECKING, Iterable, Optional
import pyarrow as pa
import pyarrow.ipc
@@ -16,6 +17,7 @@ if TYPE_CHECKING:
_BLOB_EXTENSION_NAME = "lance.blob.v2"
_BLOB_V1_KEY = "lance-encoding:blob"
_ARROW_EXT_NAME_KEY = "ARROW:extension:name"
_MAX_RUST_USIZE = ctypes.c_size_t(-1).value
_BLOB_V2_STORAGE_TYPE = pa.struct(
[
pa.field("data", pa.large_binary(), nullable=True),
@@ -30,8 +32,8 @@ _resolved_blob_type = None
class _FallbackBlobType(pa.ExtensionType):
"""lance.blob.v2 extension type used when pylance is not installed."""
def __init__(self) -> None:
pa.ExtensionType.__init__(self, _BLOB_V2_STORAGE_TYPE, _BLOB_EXTENSION_NAME)
def __init__(self, storage_type: pa.DataType = _BLOB_V2_STORAGE_TYPE) -> None:
pa.ExtensionType.__init__(self, storage_type, _BLOB_EXTENSION_NAME)
def __arrow_ext_serialize__(self) -> bytes:
return b""
@@ -40,7 +42,7 @@ class _FallbackBlobType(pa.ExtensionType):
def __arrow_ext_deserialize__(
cls, storage_type: pa.DataType, serialized: bytes
) -> "_FallbackBlobType":
return cls()
return cls(storage_type)
def __reduce__(self):
return type(self).__arrow_ext_deserialize__, (
@@ -181,6 +183,24 @@ def _resolve_blob_type():
return _resolved_blob_type
def _restore_blob_extensions(schema: pa.Schema) -> pa.Schema:
"""Restore blob fields read before their extension type was registered."""
unrestored = _collect_blob_paths(
schema,
lambda field: (
not isinstance(field.type, pa.ExtensionType)
and _metadata_marks_blob_v2(field.metadata or {})
),
)
if not unrestored:
return schema
_resolve_blob_type()
# Arrow's deserializer uses the registered class and preserves nested fields,
# storage layouts, nullability, and unrelated metadata. Only the schema is read.
return pa.ipc.read_schema(schema.serialize())
def blob(
name: str,
nullable: bool = True,
@@ -209,32 +229,110 @@ def blob(
Maximum size in bytes of a single packed blob sidecar file before
a new one is started. Must be positive.
The thresholds are forwarded to ``lance.blob_field``, which validates
them and stores them as field metadata, so pylance is required whenever
any threshold is set. When all thresholds are omitted the behavior is
unchanged.
Notes
-----
Thresholds are validated and stored as Arrow field metadata, with the
same format as ``lance.blob_field``. They do not require pylance.
The extension's storage is a struct with nullable fields ``data``
(large_binary), ``uri`` (string), ``position`` (uint64), and ``size``
(uint64). Each non-null blob must set exactly one of ``data`` and ``uri``:
- Inline bytes use ``data``, leaving all other fields null. ``b""`` is a
valid empty blob; use a null struct for a null blob.
- External blobs use ``uri``, leaving ``data`` null. Set both ``position``
and ``size`` to select a byte range, or leave both null for the whole
object. A range's ``size`` must be greater than zero.
Use [blob_array][lancedb.schema.blob_array] to build inline blob arrays
for Arrow record batches. For external descriptors, build the struct
array with ``field.type.storage_type`` and wrap it with
``pa.ExtensionArray.from_storage(field.type, storage)``.
``create_table(..., schema=...)`` casts plain binary values into blob
columns declared by this field, and ``table.add(...)`` does the same
using the table's schema. PyArrow's ``RecordBatch.from_pylist`` does not
perform this conversion; construct blob arrays explicitly instead.
"""
if (
inline_size_threshold is None
and dedicated_size_threshold is None
and pack_file_size_threshold is None
metadata = {}
for threshold, value, allow_zero, key in (
(
"inline_size_threshold",
inline_size_threshold,
True,
"lance-encoding:blob-inline-size-threshold",
),
(
"dedicated_size_threshold",
dedicated_size_threshold,
False,
"lance-encoding:blob-dedicated-size-threshold",
),
(
"pack_file_size_threshold",
pack_file_size_threshold,
False,
"lance-encoding:blob-pack-file-size-threshold",
),
):
blob_type = _resolve_blob_type()
return pa.field(name, blob_type(), nullable=nullable)
try:
lance = importlib.import_module("lance")
except ModuleNotFoundError as err:
raise ValueError(
"Setting blob tier thresholds requires pylance to be installed"
) from err
_resolve_blob_type()
return lance.blob_field(
name,
nullable=nullable,
inline_size_threshold=inline_size_threshold,
dedicated_size_threshold=dedicated_size_threshold,
pack_file_size_threshold=pack_file_size_threshold,
)
if value is None:
continue
if isinstance(value, bool) or not isinstance(value, int):
raise TypeError(f"{threshold} must be an int, got {type(value).__name__}")
if value < 0 or (value == 0 and not allow_zero):
bound = "non-negative" if allow_zero else "positive"
raise ValueError(f"{threshold} must be {bound}")
if value > _MAX_RUST_USIZE:
raise OverflowError(f"{threshold} must fit in a Rust usize")
metadata[key] = str(value)
blob_type = _resolve_blob_type()
field = pa.field(name, blob_type(), nullable=nullable)
return field.with_metadata(metadata) if metadata else field
def blob_array(payloads: Iterable[Optional[bytes]]) -> pa.ExtensionArray:
"""Build a Lance blob v2 extension array from inline bytes.
Uses the same extension type as [blob][lancedb.schema.blob], with or
without pylance installed.
Parameters
----------
payloads:
An iterable of ``bytes`` or ``None``. ``None`` creates a null blob;
``b""`` creates a valid empty blob.
Returns
-------
pa.ExtensionArray
Inline blob values ready to use in Arrow tables or record batches.
Raises
------
TypeError
If a payload is neither ``bytes`` nor ``None``.
Examples
--------
>>> import pyarrow as pa
>>> from lancedb.schema import blob, blob_array
>>> schema = pa.schema([blob("video")])
>>> videos = blob_array([b"abc", None, b""])
>>> batch = pa.RecordBatch.from_arrays([videos], schema=schema)
>>> batch.num_rows
3
"""
blob_type = _resolve_blob_type()()
descriptors = []
for payload in payloads:
if payload is not None and not isinstance(payload, bytes):
raise TypeError(
f"payloads must contain bytes or None, got {type(payload).__name__}"
)
descriptors.append(None if payload is None else {"data": payload})
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:
+1 -1
View File
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Handles to SQL queries running on a remote database."""
"""Handles to SQL queries running on a LanceDB Distributed database."""
from typing import Any, Mapping, Optional, Sequence, Union
from uuid import UUID
+157 -3
View File
@@ -19,6 +19,7 @@ above.
"""
import ctypes
import hashlib
import heapq
import logging
import os
@@ -39,6 +40,7 @@ from torch.utils.data import DataLoader, IterableDataset, get_worker_info
from .permutation import (
Permutation,
PermutationBuilder,
Transforms,
permutation_builder,
_drop_base_version,
@@ -244,6 +246,20 @@ class StreamingDataset(IterableDataset):
default) rows are shuffled using ``shuffle_seed`` and ``epoch``.
When ``False`` rows are divided into splits sequentially in storage
order, which can be useful for deterministic debugging or evaluation.
Ignored when ``split_strategy`` is provided.
split_strategy:
Escape hatch for any ``PermutationBuilder`` split strategy this class
doesn't otherwise expose a dedicated parameter for -- ``split_hash``,
``split_calculated``, ``bootstrap_sample`` (uniform sampling with
replacement), or any strategy added later. A callable that receives a
fresh ``PermutationBuilder`` for ``table`` and returns a configured one;
it is called and ``.execute()``'d directly, taking over permutation
construction entirely. When provided, ``shuffle``, ``shuffle_seed``,
``epoch``, and ``shuffle_clump_size`` are ignored -- the callable is
solely responsible for how rows are split and ordered. For example,
``split_strategy=lambda b: b.bootstrap_sample(10_000, fixed=num_splits,
seed=42)`` draws 10,000 samples with replacement, divided evenly across
``num_splits`` splits.
shuffle_seed:
Base seed for the random permutation. Combined with ``epoch`` so
each epoch produces a different ordering. Pass ``None`` to generate
@@ -379,6 +395,16 @@ class StreamingDataset(IterableDataset):
capping peak memory when the consumer (e.g. a GPU training step) is
slower than the transform stage. Must be greater than zero.
``None`` (the default) imposes no limit.
connection_factory:
Optional picklable function that takes the table name and returns an
open LanceDB table. When set, pickling the dataset (as DataLoader
workers do under the ``spawn`` and ``forkserver`` start methods)
replaces the table's reopen state with its name, and each worker calls
the factory with that name to reopen the table. The factory itself is
pickled too, so credentials stay out of the pickle only if the factory
loads them in the worker, for example from the environment, instead of
capturing them. ``None`` (the default) pickles the table's own reopen
state instead.
worker_info_override:
If set, used in place of ``torch.utils.data.get_worker_info()`` to
determine the DataLoader worker assignment. Intended for unit tests
@@ -393,6 +419,9 @@ class StreamingDataset(IterableDataset):
*,
num_splits: Optional[int] = None,
shuffle: bool = True,
split_strategy: Optional[
Callable[[PermutationBuilder], PermutationBuilder]
] = None,
shuffle_seed: Optional[int] = 0,
epoch: int = 0,
rank: int = 0,
@@ -583,13 +612,70 @@ class StreamingDataset(IterableDataset):
builder = permutation_builder(table)
if filter is not None:
builder = builder.filter(filter)
if shuffle:
if split_strategy is not None:
# Escape hatch: lets any PermutationBuilder split strategy drive this
# dataset (split_hash, split_calculated, bootstrap_sample, or any future
# strategy) without StreamingDataset needing a bespoke parameter for each
# one. shuffle/shuffle_seed/epoch/shuffle_clump_size are ignored in this
# path -- the caller's split_strategy is solely responsible for ordering.
self._perm_table = split_strategy(builder).execute()
# _rank_splits below assumes split ids are exactly 0..num_splits-1 with no
# gaps (every other path guarantees this by always building with
# fixed=num_splits) -- a split_strategy callable has no such guarantee, and
# a mismatch would otherwise silently drop rows (ids >= num_splits) or leave
# some ranks reading an empty split (missing ids < num_splits).
split_value_counts = (
self._perm_table.to_arrow().column("split_id").value_counts()
)
counts_by_split = dict(
zip(
split_value_counts.field("values").to_pylist(),
split_value_counts.field("counts").to_pylist(),
)
)
expected_splits = set(range(num_splits))
if set(counts_by_split) != expected_splits:
raise ValueError(
f"split_strategy produced split ids {sorted(counts_by_split)}, "
f"but num_splits={num_splits} requires exactly "
f"{{0, ..., {num_splits - 1}}}. Pass num_splits matching the "
"strategy's own split count (e.g. `fixed=num_splits` on "
"bootstrap_sample/split_random/etc.)."
)
# The round-robin iteration below (and in _iter_owned) assumes every
# split has the same row count -- it stops as soon as any one owned
# split is exhausted (see its own comment: "all splits exhaust
# simultaneously"). Every other path guarantees this by always building
# with fixed=num_splits; a split_strategy using ratios/counts/split_hash
# weights has no such guarantee, and unequal sizes would otherwise
# silently drop rows from the larger splits -- or, with world_size > 1
# where each rank owns different splits, end ranks after different row
# counts and desync or hang a distributed run's end-of-epoch collectives.
if len(set(counts_by_split.values())) > 1:
raise ValueError(
f"split_strategy produced unequal split sizes "
f"{counts_by_split} (split id -> row count). Every split must "
"have the same row count. Use `fixed=num_splits` rather than "
"`ratios`/`counts`/weighted `split_hash`, which can produce "
"unequal sizes, or split unevenly-sized groups into separate "
"StreamingDatasets instead."
)
elif shuffle:
perm_seed = shuffle_seed + epoch * _EPOCH_PRIME
self._perm_table = builder.split_random(
fixed=num_splits, seed=perm_seed, clump_size=shuffle_clump_size
).execute()
else:
self._perm_table = builder.split_sequential(fixed=num_splits).execute()
# Only the split_strategy path needs a permutation fingerprint in the
# checkpoint (see `_checkpoint_snapshot`): split_random/split_sequential are
# already fully pinned by shuffle_seed/num_splits, and a fingerprint over raw
# row ids would spuriously reject an otherwise-valid resume after those row
# ids get renumbered by compaction (row ids are not stable by default).
self._uses_split_strategy = split_strategy is not None
# Lazily computed and cached by `_perm_fingerprint` -- `_perm_table` never
# changes after construction, so this is correct to compute once.
self._perm_fingerprint_cache: Optional[str] = None
if self._blocks_per_epoch == "auto":
self._blocks_per_epoch = self._estimate_blocks_per_epoch()
@@ -1406,11 +1492,51 @@ class StreamingDataset(IterableDataset):
)
return state
@property
def _perm_fingerprint(self) -> str:
"""Cheap identity check for the built permutation, computed once and cached
(``_perm_table`` never changes after construction).
Only meaningful -- and only recorded in a checkpoint -- for the
``split_strategy`` path (see ``_checkpoint_snapshot``): ``num_splits``/
``shuffle_seed`` alone cannot detect a `load_state_dict` resuming saved
per-split progress against a *different* permutation than the one that
produced it, since a ``split_strategy`` callable ignores ``shuffle_seed``
entirely -- e.g. a ``bootstrap_sample`` with no seed (or any changed
callable) can rebuild a completely different permutation on the next run
while ``shuffle_seed`` keeps its same default value and the existing check
passes anyway. ``split_random``/``split_sequential`` are already fully
pinned by ``shuffle_seed``/``num_splits`` and must *not* additionally be
fingerprinted: this hashes physical row ids, which are not stable across
compaction by default, so checking it on those paths would reject an
otherwise-valid resume after the table gets compacted between save and
load even though the seeded permutation itself is unchanged.
"""
if self._perm_fingerprint_cache is None:
arrow_tbl = self._perm_table.to_arrow()
hasher = hashlib.sha256()
hasher.update(str(arrow_tbl.num_rows).encode())
for name in ("row_id", "split_id"):
column = arrow_tbl.column(name).combine_chunks()
hasher.update(column.to_numpy(zero_copy_only=False).tobytes())
self._perm_fingerprint_cache = hasher.hexdigest()
return self._perm_fingerprint_cache
def _checkpoint_snapshot(self) -> dict:
# Only recorded for split_strategy: split_random/split_sequential are
# already fully pinned by shuffle_seed/num_splits below, and row ids are not
# stable across compaction by default, so fingerprinting them unconditionally
# would reject an otherwise-valid resume after the table got compacted.
perm_fingerprint = (
{"perm_fingerprint": self._perm_fingerprint}
if (self._uses_split_strategy)
else {}
)
if self._pack_sequences is not None:
return {
"shuffle_seed": self._shuffle_seed,
"num_splits": self._num_splits,
**perm_fingerprint,
"epoch": self._epoch,
"pack_sequences": self._pack_sequences,
"eos_id": self._eos_id,
@@ -1431,6 +1557,7 @@ class StreamingDataset(IterableDataset):
return {
"shuffle_seed": self._shuffle_seed,
"num_splits": self._num_splits,
**perm_fingerprint,
"epoch": self._epoch,
"samples_consumed_per_split": samples,
"positions_consumed_per_split": positions,
@@ -1560,8 +1687,16 @@ class StreamingDataset(IterableDataset):
Raises ``ValueError`` if ``num_splits`` or ``shuffle_seed`` differ
from the checkpoint, since a different split structure or shuffle order
makes mid-epoch resumption meaningless. Packed checkpoints
pin ``pack_sequences``, ``eos_id``, ``pad_id``,
makes mid-epoch resumption meaningless. Also raises if the checkpoint
was built with ``split_strategy`` and records a permutation fingerprint
that does not match the current dataset's permutation -- this catches a
changed or non-deterministically-reseeded ``split_strategy`` that
``num_splits``/``shuffle_seed`` alone cannot detect, since ``shuffle_seed``
is unused on that path. Checkpoints from ``split_random``/
``split_sequential`` never carry this fingerprint (row ids are not stable
across compaction, so it would reject an otherwise-valid resume), and
continue to rely on ``shuffle_seed``/``num_splits`` alone as before.
Packed checkpoints pin ``pack_sequences``, ``eos_id``, ``pad_id``,
``blocks_per_epoch``, and ``epoch``.
"""
if state["num_splits"] != self._num_splits:
@@ -1574,6 +1709,19 @@ class StreamingDataset(IterableDataset):
f"shuffle_seed mismatch: checkpoint has {state['shuffle_seed']}, "
f"current dataset has {self._shuffle_seed}"
)
checkpoint_fingerprint = state.get("perm_fingerprint")
if (
checkpoint_fingerprint is not None
and checkpoint_fingerprint != self._perm_fingerprint
):
raise ValueError(
"permutation mismatch: this checkpoint was saved against a "
"different permutation (e.g. a split_strategy that resamples "
"differently between runs, such as bootstrap_sample with no "
"seed, or a changed callable) than the current dataset built. "
"Resuming would apply saved per-split positions to the wrong "
"rows."
)
self._consumer_checkpoint_requires_uniform = False
if "pack_buffers" in state or self._pack_sequences is not None:
@@ -1675,6 +1823,10 @@ class StreamingDataset(IterableDataset):
first = states[0]
packed = "pack_buffers" in first
config_keys = ["shuffle_seed", "num_splits", "epoch"]
if "perm_fingerprint" in first:
# Absent only in checkpoints saved before this key existed; skip rather
# than KeyError so old checkpoints keep merging.
config_keys.append("perm_fingerprint")
if packed:
config_keys.extend(
["pack_sequences", "eos_id", "pad_id", "blocks_per_epoch"]
@@ -1684,6 +1836,8 @@ class StreamingDataset(IterableDataset):
if ("pack_buffers" in state) != packed:
raise ValueError("cannot merge packed and unpacked state dicts")
for key in config_keys:
if key not in state:
continue
if state[key] != first[key]:
raise ValueError(
f"{key} mismatch across state dicts: "
File diff suppressed because it is too large Load Diff
+81 -10
View File
@@ -9,7 +9,7 @@ import math
import os
import pathlib
import warnings
from datetime import date, datetime
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from functools import singledispatch
from typing import Tuple, Union, Optional, Any, List
@@ -34,20 +34,20 @@ def safe_import_adlfs():
adlfs = safe_import_adlfs()
def get_uri_scheme(uri: str) -> str:
def get_uri_scheme(uri: Union[str, pathlib.Path]) -> str:
"""
Get the scheme of a URI. If the URI does not have a scheme, assume it is a file URI.
Parameters
----------
uri : str
uri : str or pathlib.Path
The URI to parse.
Returns
-------
str: The scheme of the URI.
"""
parsed = urlparse(uri)
parsed = urlparse(str(uri))
scheme = parsed.scheme
if not scheme:
scheme = "file"
@@ -61,25 +61,26 @@ def get_uri_scheme(uri: str) -> str:
return scheme
def get_uri_location(uri: str) -> str:
def get_uri_location(uri: Union[str, pathlib.Path]) -> str:
"""
Get the location of a URI. If the parameter is not a url, assumes it is just a path
Parameters
----------
uri : str
uri : str or pathlib.Path
The URI to parse.
Returns
-------
str: Location part of the URL, without scheme
"""
parsed = urlparse(uri)
uri_str = str(uri)
parsed = urlparse(uri_str)
if len(parsed.scheme) == 1:
# Windows drive names are parsed as the scheme
# e.g. "c:\path" -> ParseResult(scheme="c", netloc="", path="/path", ...)
# So we add special handling here for schemes that are a single character
return uri
return uri_str
if not parsed.netloc:
return parsed.path
@@ -309,7 +310,16 @@ def _query_vector_dim(query: Optional[Any]) -> Optional[int]:
if query.ndim == 0:
return None
return query.shape[-1]
if isinstance(query, list) and query:
if isinstance(query, (pa.Array, pa.ChunkedArray)):
if len(query) == 0:
return None
if pa.types.is_fixed_size_list(query.type):
return query.type.list_size
if pa.types.is_list(query.type) or pa.types.is_large_list(query.type):
first = query[0].as_py()
return len(first) if first is not None else None
return len(query)
if isinstance(query, (list, tuple)) and query:
first = query[0]
if isinstance(first, (list, tuple, np.ndarray)):
return len(first)
@@ -415,8 +425,31 @@ def _(value: date):
return f"'{value.isoformat()}'"
@value_to_sql.register(time)
def _(value: time):
if value.utcoffset() is not None:
raise ValueError(
"time values with a timezone cannot be converted to SQL, "
"because Arrow time columns do not store one"
)
# A plain string literal can be assigned to a time column but not compared with one.
return f"arrow_cast('{value.isoformat()}', 'Time64(Microsecond)')"
@value_to_sql.register(timedelta)
def _(value: timedelta):
# Lance does not accept INTERVAL literals, so cast the exact count of the
# smallest unit. pandas.Timedelta, a timedelta subclass, keeps nanoseconds.
nanoseconds = getattr(value, "value", None)
if isinstance(nanoseconds, int):
return f"arrow_cast({nanoseconds}, 'Duration(Nanosecond)')"
microseconds = value // timedelta(microseconds=1)
return f"arrow_cast({microseconds}, 'Duration(Microsecond)')"
@value_to_sql.register(list)
def _(value: list):
@value_to_sql.register(tuple)
def _(value: Union[list, tuple]):
return "[" + ", ".join(map(value_to_sql, value)) + "]"
@@ -441,6 +474,35 @@ def _(value: pa.Scalar):
return value_to_sql(value.as_py())
_ARROW_TIME_UNITS = {
"s": "Second",
"ms": "Millisecond",
"us": "Microsecond",
"ns": "Nanosecond",
}
@value_to_sql.register(pa.DurationScalar)
@value_to_sql.register(pa.Time64Scalar)
def _(value: Union[pa.DurationScalar, pa.Time64Scalar]):
# Cast the raw count in the scalar's own unit: as_py() would round a
# nanosecond value to the microseconds of a Python timedelta or time.
if not value.is_valid:
return value_to_sql(None)
kind = "Duration" if pa.types.is_duration(value.type) else "Time64"
unit = _ARROW_TIME_UNITS[value.type.unit]
return f"arrow_cast({value.value}, '{kind}({unit})')"
@value_to_sql.register(pa.MapScalar)
def _(value: pa.MapScalar):
if not value.is_valid:
return value_to_sql(None)
keys = value_to_sql(list(value.values.field(0)))
values = value_to_sql(list(value.values.field(1)))
return f"map({keys}, {values})"
@value_to_sql.register(np.ndarray)
def _(value: np.ndarray):
return value_to_sql(value.tolist())
@@ -461,6 +523,15 @@ def _(value: np.floating):
return value_to_sql(float(value))
@value_to_sql.register(np.datetime64)
def _(value: np.datetime64):
if np.isnat(value):
return value_to_sql(None)
if np.datetime_data(value.dtype)[0] in ("ps", "fs", "as"):
raise ValueError("SQL timestamps cannot preserve sub-nanosecond precision")
return value_to_sql(str(np.datetime_as_string(value, unit="ns", timezone="UTC")))
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
+15
View File
@@ -9,6 +9,21 @@ import pytest
import pytest_asyncio
def pytest_configure(config):
config.addinivalue_line(
"markers", "experimental_functions: requires the experimental-functions build"
)
def pytest_collection_modifyitems(items):
if lancedb._lancedb._experimental_functions_enabled:
return
skip = pytest.mark.skip(reason="requires the experimental-functions Cargo feature")
for item in items:
if item.get_closest_marker("experimental_functions"):
item.add_marker(skip)
def pandas_string_type():
"""Return the PyArrow string type that pandas uses for string columns.
+2 -14
View File
@@ -91,19 +91,13 @@ def test_quickstart(tmp_path):
}
)
# --8<-- [end:alter_columns_vector]
# Change it back since we can get a panic with fp16
tbl.alter_columns(
{
"path": "vector",
"data_type": pa.list_(pa.float32(), list_size=2),
}
)
# --8<-- [start:drop_columns]
tbl.drop_columns(["dbl_price"])
# --8<-- [end:drop_columns]
# --8<-- [start:create_index]
tbl.create_index(num_sub_vectors=1)
# --8<-- [end:create_index]
tbl.search([100, 100]).limit(2).to_pandas()
# --8<-- [start:delete_rows]
tbl.delete("item = 'fizz'")
# --8<-- [end:delete_rows]
@@ -185,13 +179,6 @@ async def test_quickstart_async(tmp_path):
}
)
# --8<-- [end:alter_columns_async_vector]
# Change it back since we can get a panic with fp16
await tbl.alter_columns(
{
"path": "vector",
"data_type": pa.list_(pa.float32(), list_size=2),
}
)
# --8<-- [start:drop_columns_async]
await tbl.drop_columns(["dbl_price"])
# --8<-- [end:drop_columns_async]
@@ -200,6 +187,7 @@ async def test_quickstart_async(tmp_path):
# --8<-- [start:create_index_async]
await tbl.create_index("vector")
# --8<-- [end:create_index_async]
await tbl.vector_search([100, 100]).limit(2).to_pandas()
# --8<-- [start:delete_rows_async]
await tbl.delete("item = 'fizz'")
# --8<-- [end:delete_rows_async]
+427 -15
View File
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import ctypes
import io
import subprocess
import sys
@@ -14,6 +15,7 @@ import pytest
from lance.blob import Blob, BlobType as LanceBlobType
import lancedb
from lancedb import schema as schema_module
from lancedb._blob import (
_set_blob_column,
blob_v2_projection_sources,
@@ -139,6 +141,41 @@ def test_blob_without_thresholds_has_no_threshold_metadata():
assert not any(b"threshold" in key for key in metadata)
@pytest.mark.parametrize("nullable", [False, True])
@pytest.mark.parametrize(
"thresholds",
[
{},
{"inline_size_threshold": 0},
{"inline_size_threshold": 8192},
{"dedicated_size_threshold": 1 << 20},
{"pack_file_size_threshold": 1 << 26},
{
"inline_size_threshold": 8192,
"dedicated_size_threshold": 1 << 20,
"pack_file_size_threshold": 1 << 26,
},
{
"inline_size_threshold": ctypes.c_size_t(-1).value,
"dedicated_size_threshold": ctypes.c_size_t(-1).value,
"pack_file_size_threshold": ctypes.c_size_t(-1).value,
},
],
)
def test_blob_thresholds_match_pylance(monkeypatch, nullable, thresholds):
expected = lance.blob_field("payload", nullable=nullable, **thresholds)
actual = lancedb.blob("payload", nullable=nullable, **thresholds)
assert type(actual.type) is LanceBlobType
assert actual.equals(expected, check_metadata=True)
# Both extension classes must encode the same Arrow field on the wire.
monkeypatch.setattr(
schema_module, "_resolve_blob_type", lambda: schema_module._FallbackBlobType
)
fallback = lancedb.blob("payload", nullable=nullable, **thresholds)
assert pa.schema([fallback]).serialize() == pa.schema([expected]).serialize()
def test_blob_thresholds_are_validated():
with pytest.raises(ValueError, match="inline_size_threshold must be non-negative"):
lancedb.blob("payload", inline_size_threshold=-1)
@@ -194,6 +231,78 @@ def test_blob_type_works_without_pylance():
assert result.returncode == 0, result.stderr
@pytest.mark.parametrize("use_async", [False, True])
@pytest.mark.parametrize("with_pylance", [False, True])
def test_local_schema_restores_blob_extensions(tmp_path, use_async, with_pylance):
db = lancedb.connect(tmp_path)
db.create_table(
"images",
schema=pa.schema(
[
pa.field("id", pa.int64()),
lancedb.blob("image", nullable=False, inline_size_threshold=8192),
],
metadata={"schema-key": "schema-value"},
),
)
# Reopening must restore the type before blob() or pylance registers it in
# the reader process, including when pylance is not installed.
script = textwrap.dedent(
"""\
import asyncio
import importlib.abc
import sys
import pyarrow as pa
if sys.argv[3] == "False":
class NoLance(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, NoLance())
import lancedb
assert "lance.blob" not in sys.modules
async def read_schema():
db = await lancedb.connect_async(sys.argv[1])
table = await db.open_table("images")
return await table.schema()
if sys.argv[2] == "True":
schema = asyncio.run(read_schema())
else:
schema = lancedb.connect(sys.argv[1]).open_table("images").schema
image = schema.field("image")
assert isinstance(image.type, pa.ExtensionType), image
assert image.type == lancedb.blob("x").type
assert type(image.type) is lancedb.BlobType
assert not image.nullable
assert image.metadata == {
b"lance-encoding:blob-inline-size-threshold": b"8192"
}
assert schema.field("id") == pa.field("id", pa.int64())
assert schema.metadata == {b"schema-key": b"schema-value"}
"""
)
result = subprocess.run(
[
sys.executable,
"-c",
script,
str(tmp_path),
str(use_async),
str(with_pylance),
],
capture_output=True,
text=True,
timeout=30,
)
assert result.returncode == 0, result.stderr
def test_blob_resolves_pylance_type_without_eager_import():
script = textwrap.dedent(
"""\
@@ -806,8 +915,7 @@ def test_to_pandas_does_not_drop_fragment_selection_on_fallback():
table.search().with_row_address(True).to_pandas(blob_mode="descriptions")
@pytest.mark.parametrize("blob_mode", ["lazy", "descriptions", "bytes"])
def test_to_pandas_reports_lance_dataset_failures(tmp_path, blob_mode):
def test_to_pandas_reports_lance_dataset_failures(tmp_path):
table = lancedb.connect(tmp_path).create_table(
"dataset_failure",
schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]),
@@ -819,7 +927,59 @@ def test_to_pandas_reports_lance_dataset_failures(tmp_path, blob_mode):
table.to_lance = reject_credentials
with pytest.raises(PermissionError, match="storage credentials rejected"):
table.search().to_pandas(blob_mode=blob_mode)
table.search().to_pandas(blob_mode="lazy")
@pytest.mark.parametrize("blob_mode", ["lazy", "descriptions", "bytes"])
@pytest.mark.parametrize("with_row_id", [None, True, False])
def test_to_batches_blob_modes(tmp_path, monkeypatch, blob_mode, with_row_id):
table = _nested_blob_table(lancedb.connect(tmp_path), "batch_blob_modes")
query = table.search().select({"renamed": "info"})
if with_row_id is not None:
query.with_row_id(with_row_id)
fetched = []
fetch_blobs = table.fetch_blobs
def fetch(column, row_ids):
fetched.append(row_ids)
return fetch_blobs(column, row_ids)
monkeypatch.setattr(table, "fetch_blobs", fetch)
reader = query.to_batches(batch_size=1, blob_mode=blob_mode)
assert fetched == []
first = reader.read_next_batch()
assert first.schema == reader.schema
assert len(fetched) == (1 if blob_mode == "bytes" else 0)
batches = [first, *reader]
assert all(batch.schema == reader.schema for batch in batches)
assert all(batch.num_rows == 1 for batch in batches)
assert len(fetched) == (3 if blob_mode == "bytes" else 0)
if blob_mode == "bytes":
assert [row["renamed"] for batch in batches for row in batch.to_pylist()] == [
{"name": "first", "blob": b"hello"},
{"name": "second", "blob": None},
None,
]
if blob_mode != "lazy":
assert ("_rowid" in reader.schema.names) == (with_row_id is True)
assert "_lance_row_id" not in str(reader.schema)
else:
assert "_rowid" in reader.schema.names
@pytest.mark.parametrize("blob_mode", ["descriptions", "bytes"])
def test_empty_to_batches_blob_schema(blob_mode):
table = _blob_table("empty_blob_batches", [{"id": 1, "image": b"one"}])
query = table.search().where("id < 0")
reader = query.to_batches(blob_mode=blob_mode)
assert reader.schema == query.to_arrow(blob_mode=blob_mode).schema
assert reader.read_all().num_rows == 0
def test_to_batches_validates_blob_mode():
table = _blob_table("invalid_batch_blob_mode", [{"id": 1, "image": b"one"}])
with pytest.raises(ValueError, match="blob_mode must be one of"):
table.search().to_batches(blob_mode="handles")
def test_to_pandas_keeps_to_arrow_overrides_without_blob_mode():
@@ -857,6 +1017,12 @@ def test_take_queries_honor_blob_mode():
]
description = table.take_row_ids([0]).to_list(blob_mode="descriptions")[0]["image"]
assert "_lance_row_id" not in description
batches = table.take_row_ids([0]).to_batches(blob_mode="bytes")
assert batches.read_all().to_pylist() == [{"id": 1, "image": b"one"}]
batches = table.take_row_ids([0]).to_batches(blob_mode="descriptions")
assert "_rowid" not in batches.schema.names
assert "_lance_row_id" not in str(batches.schema)
assert batches.read_all().num_rows == 1
def test_bytes_mode_follows_swapped_blob_aliases():
@@ -902,6 +1068,8 @@ def test_bytes_mode_refused_under_namespace_query_pushdown(tmp_path):
table.search().to_list(blob_mode="bytes")
with pytest.raises(NotImplementedError, match="stable table snapshot"):
table.take_row_ids([0]).to_list(blob_mode="bytes")
with pytest.raises(NotImplementedError, match="stable table snapshot"):
table.search().to_batches(blob_mode="bytes")
descriptor = table.to_arrow(blob_mode="descriptions")["image"].to_pylist()[0]
assert "_lance_row_id" not in descriptor
@@ -923,6 +1091,8 @@ async def test_async_bytes_mode_refused_under_namespace_query_pushdown(tmp_path)
await table.to_arrow(blob_mode="bytes")
with pytest.raises(NotImplementedError, match="stable table snapshot"):
await table.query().to_list(blob_mode="bytes")
with pytest.raises(NotImplementedError, match="stable table snapshot"):
await table.query().to_batches(blob_mode="bytes")
def test_fetch_blobs_round_trip():
@@ -1197,12 +1367,13 @@ def test_merge_insert_bytes_after_reopen_without_touching_blob_type(tmp_path):
script = textwrap.dedent(
f"""\
import lancedb
import pyarrow as pa
db = lancedb.connect({str(tmp_path)!r})
table = db.open_table("images")
image_type = table.schema.field("image").type
if type(image_type).__name__ != "StructType":
raise SystemExit(f"expected StructType, got {{type(image_type)}}")
if not isinstance(image_type, pa.ExtensionType):
raise SystemExit(f"expected ExtensionType, got {{type(image_type)}}")
result = (
table.merge_insert("id")
.when_matched_update_all()
@@ -1241,12 +1412,13 @@ def test_merge_insert_bytes_after_reopen_without_pylance(tmp_path):
script = _HIDE_LANCE_BLOB + textwrap.dedent(
f"""\
import lancedb
import pyarrow as pa
db = lancedb.connect({str(tmp_path)!r})
table = db.open_table("images")
image_type = table.schema.field("image").type
if type(image_type).__name__ != "StructType":
raise SystemExit(f"expected StructType, got {{type(image_type)}}")
if not isinstance(image_type, pa.ExtensionType):
raise SystemExit(f"expected ExtensionType, got {{type(image_type)}}")
result = (
table.merge_insert("id")
.when_matched_update_all()
@@ -1276,7 +1448,7 @@ def test_merge_insert_bytes_after_reopen_without_pylance(tmp_path):
assert result.returncode == 0, result.stderr
def test_merge_insert_blob_array_into_reopened_unregistered_table(tmp_path):
def test_merge_insert_blob_array_into_reopened_table(tmp_path):
db = lancedb.connect(tmp_path)
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
table = db.create_table("images", schema=schema)
@@ -1290,10 +1462,8 @@ def test_merge_insert_blob_array_into_reopened_unregistered_table(tmp_path):
db = lancedb.connect({str(tmp_path)!r})
table = db.open_table("images")
image_type = table.schema.field("image").type
if type(image_type).__name__ != "StructType":
raise SystemExit(
f"expected StructType before lance import, got {{type(image_type)}}"
)
if not isinstance(image_type, pa.ExtensionType):
raise SystemExit(f"expected ExtensionType, got {{type(image_type)}}")
import lance
@@ -1866,10 +2036,74 @@ def test_legacy_v1_query_omits_auto_row_id():
assert "_rowid" not in hits.column_names
def test_fetch_blobs_rejects_legacy_v1_column():
def test_fetch_legacy_v1_blobs():
table = _legacy_v1_table("legacy_fetch")
with pytest.raises(ValueError, match="legacy blob column.*blob v2"):
table.fetch_blobs("legacy", [0])
table.add(
[
{"id": 2, "legacy": None},
{"id": 3, "legacy": b""},
{"id": 4, "legacy": b"another fragment"},
]
)
hits = table.search().select(["id", "legacy"]).with_row_id(True).to_arrow()
assert pa.types.is_struct(hits["legacy"].type)
by_id = dict(zip(hits["id"].to_pylist(), hits["_rowid"].to_pylist()))
row_ids = [by_id[i] for i in [4, 2, 1, 3, 4]]
expected = [b"another fragment", None, b"old", b"", b"another fragment"]
assert table.fetch_blobs("legacy", row_ids).to_pylist() == expected
assert table.blob_columns() == ["legacy"]
assert table.fetch_blobs("legacy", hits).to_pylist() == [
b"old",
None,
b"",
b"another fragment",
]
assert table.fetch_blobs("legacy", []).to_pylist() == []
assert table.fetch_blob_files("legacy", []) == []
handles = table.fetch_blob_files("legacy", row_ids)
assert len(handles) == len(expected)
for handle, payload in zip(handles, expected):
if payload is None:
assert handle is None
else:
with handle:
assert handle.size() == len(payload)
assert handle.read(2) == payload[:2]
assert handle.seek(0) == 0
assert handle.read() == payload
assert table.fetch_blob_ranges(
"legacy", [(by_id[4], 8, 8), (by_id[2], 0, 1), (by_id[3], 0, 0)]
).to_pylist() == [b"fragment", None, b""]
table.delete("id = 2")
for fetch in [table.fetch_blobs, table.fetch_blob_files]:
with pytest.raises(ValueError, match="row ids but some do not exist"):
fetch("legacy", [by_id[1], by_id[2]])
@pytest.mark.asyncio
async def test_async_fetch_legacy_v1_blobs(tmp_path):
table = _legacy_v1_table("legacy_async_source")
# Open a dataset written by Lance independently of the LanceDB connection.
lance.write_dataset(
pa.Table.from_pylist(
[{"id": 1, "legacy": b"old"}, {"id": 2, "legacy": None}],
schema=table.schema,
),
tmp_path / "legacy.lance",
data_storage_version="2.0",
)
db = await lancedb.connect_async(tmp_path)
table = await db.open_table("legacy")
assert await table.blob_columns() == ["legacy"]
hits = await table.query().with_row_id().to_arrow()
assert (await table.fetch_blobs("legacy", hits)).to_pylist() == [b"old", None]
handles = await table.fetch_blob_files("legacy", hits)
assert handles[0].read() == b"old"
handles[0].close()
assert handles[1] is None
@pytest.mark.asyncio
@@ -1975,6 +2209,10 @@ def test_blob_mode_for_every_query_shape(shape, blob_mode, with_row_id):
assert all("_lance_row_id" not in image for image in images.values())
df = query.to_pandas(blob_mode=blob_mode)
assert dict(zip(df["id"], df["image"])) == images
if shape in ("scan", "vector"):
reader = query.to_batches(batch_size=1, blob_mode=blob_mode)
assert reader.schema == hits.schema
assert reader.read_all().equals(hits)
@pytest.mark.asyncio
@@ -2001,6 +2239,48 @@ async def test_async_blob_bytes_for_every_query_shape(shape):
assert dict(zip(df["id"], df["image"])) == {1: b"alpha", 2: b"beta"}
@pytest.mark.asyncio
@pytest.mark.parametrize("shape", ["scan", "vector", "fts", "hybrid"])
@pytest.mark.parametrize("blob_mode", ["lazy", "descriptions", "bytes"])
async def test_async_to_batches_blob_modes(shape, blob_mode, monkeypatch):
db = await lancedb.connect_async("memory:///")
table = await _hybrid_blob_table_async(db)
query = table.query()
if shape in ("vector", "hybrid"):
query = query.nearest_to([1.0, 0.0])
if shape in ("fts", "hybrid"):
query = query.nearest_to_text("hello")
if shape == "scan":
query = query.where("id < 3")
query = query.select({"id": "id", "payload": "image"}).limit(2)
fetched = []
fetch_blobs = table.fetch_blobs
async def fetch(column, row_ids):
fetched.append(row_ids)
return await fetch_blobs(column, row_ids)
monkeypatch.setattr(table, "fetch_blobs", fetch)
reader = await query.to_batches(max_batch_length=1, blob_mode=blob_mode)
assert fetched == []
first = await reader.__anext__()
assert len(fetched) == (1 if blob_mode == "bytes" else 0)
batches = [first, *[batch async for batch in reader]]
assert all(batch.num_rows == 1 for batch in batches)
assert all(batch.schema == reader.schema for batch in batches)
if blob_mode == "bytes":
assert len(fetched) == 2
assert {
row["id"]: row["payload"] for b in batches for row in b.to_pylist()
} == {
1: b"alpha",
2: b"beta",
}
if blob_mode != "lazy":
assert "_rowid" not in reader.schema.names
assert "_lance_row_id" not in str(reader.schema)
class _KeepAllScoresReranker(Reranker):
"""Rebuilds the merged table like model rerankers with return_score="all"."""
@@ -2659,3 +2939,135 @@ def test_create_table_with_python_blob_dict_and_object():
b"from-dict",
b"from-blob",
]
def _openable_descriptors(table, *, by_address):
hits = (
table.search()
.select(["id", "image", "_rowaddr"])
.with_row_id(True)
.limit(100)
.to_arrow(blob_mode="descriptions")
)
version = table.version
committed_at = next(
item["timestamp"]
for item in table.list_versions()
if item["version"] == version
)
descriptors = {}
for row in hits.to_pylist():
descriptor = row["image"]
if descriptor is not None and descriptor.get("kind") is not None:
descriptor = dict(descriptor)
descriptor["source"] = {
"uri": table.to_lance().uri,
"version": version,
"committed_at_micros": round(committed_at.timestamp() * 1_000_000),
"branch": None,
"column": "image",
"row_reference": row["_rowaddr" if by_address else "_rowid"],
"row_is_address": by_address,
}
else:
descriptor = None
descriptors[row["id"]] = descriptor
return descriptors
@pytest.mark.parametrize("by_address", [False, True])
def test_open_blob_files_preserve_snapshot_order_nulls_and_empty_values(
tmp_path, by_address
):
db = lancedb.connect(str(tmp_path))
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
table = db.create_table("videos", schema=schema)
table.add(
[
{"id": 1, "image": b"alpha"},
{"id": 2, "image": None},
{"id": 3, "image": b"beta"},
{"id": 4, "image": b""},
]
)
descriptors = _openable_descriptors(table, by_address=by_address)
table.add([{"id": 1, "image": b"replacement"}], mode="overwrite")
latest_version = table.version
values = pa.array(
[descriptors[3], descriptors[2], descriptors[1], descriptors[3], descriptors[4]]
)
files = table.open_blob_files(
pa.chunked_array([values.slice(0, 2), values.slice(2)])
)
assert iter(files) is files
actual = []
for file in files:
if file is None:
actual.append(None)
else:
with file:
actual.append(file.read())
assert file.closed
assert actual == [b"beta", None, b"alpha", b"beta", b""]
with table.open_blob_file(descriptors[1]) as file:
file.seek(2)
assert file.read_range(0, 2) == b"al"
assert file.tell() == 2
assert file.read(2) == b"ph"
assert table.version == latest_version
assert table.open_blob_file(pa.scalar(None, type=values.type)) is None
other = db.create_table("other", schema=schema)
with pytest.raises(ValueError, match="different table"):
other.open_blob_file(descriptors[1])
stale = dict(descriptors[1], source=dict(descriptors[1]["source"]))
stale["source"]["committed_at_micros"] += 1
with pytest.raises(ValueError, match="snapshot has been replaced"):
table.open_blob_file(stale)
raw = {key: value for key, value in descriptors[1].items() if key != "source"}
with pytest.raises(ValueError, match="source"):
table.open_blob_file(raw)
with pytest.raises(TypeError, match="descriptor"):
table.open_blob_file("not a descriptor")
def test_open_blob_files_does_not_open_ahead(monkeypatch):
table = _blob_table("lazy_descriptor_iteration", [{"id": 1, "image": b"x"}])
opened = []
def open_file(descriptor):
opened.append(descriptor)
return descriptor
monkeypatch.setattr(table, "open_blob_file", open_file)
files = table.open_blob_files(iter([1, None, 2]))
assert opened == []
assert next(files) == 1
assert opened == [1]
assert list(files) == [None, 2]
assert opened == [1, None, 2]
@pytest.mark.asyncio
async def test_open_blob_files_async_iterates_snapshot_handles(tmp_path):
db = lancedb.connect(str(tmp_path))
table = db.create_table(
"videos",
schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]),
)
table.add([{"id": 1, "image": b"alpha"}, {"id": 2, "image": None}])
descriptors = _openable_descriptors(table, by_address=True)
async_db = await lancedb.connect_async(str(tmp_path))
videos = await async_db.open_table("videos")
file = await videos.open_blob_file(pa.scalar(descriptors[1]))
with file:
assert file.read(2) == b"al"
actual = []
async for file in videos.open_blob_files(
[descriptors[2], descriptors[1], descriptors[1]]
):
if file is None:
actual.append(None)
else:
with file:
actual.append(await file.aread())
assert actual == [None, b"alpha", b"alpha"]
+85
View File
@@ -0,0 +1,85 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import subprocess
import sys
import textwrap
import pytest
@pytest.mark.parametrize("with_pylance", [False, True])
def test_blob_array(with_pylance):
# Use fresh processes so each extension class can own Arrow's registry.
script = textwrap.dedent(
"""\
import importlib.abc
import sys
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.schema import blob, blob_array
if sys.argv[1] == "True":
from lance.blob import BlobType
else:
from lancedb.schema import _FallbackBlobType as BlobType
schema = pa.schema([blob("video")])
payloads = [b"abc", None, b"", b"\\x00\\xff"]
for values in ([], [None, None], payloads):
for source in (values, iter(values)):
array = blob_array(source)
assert isinstance(array, pa.ExtensionArray)
assert type(array.type) is BlobType
assert array.type == schema.field("video").type
assert array.null_count == values.count(None)
assert array.storage.to_pylist() == [
None if value is None else {
"data": value, "uri": None, "position": None, "size": None
}
for value in values
]
batch = pa.RecordBatch.from_arrays([array], schema=schema)
with pa.BufferOutputStream() as sink:
with pa.ipc.new_stream(sink, schema) as writer:
writer.write_batch(batch)
restored = pa.ipc.open_stream(sink.getvalue()).read_next_batch()
assert restored.equals(batch)
for invalid in ("file:///video", {"data": b"abc"}, 123):
try:
blob_array([invalid])
except TypeError as error:
assert "bytes or None" in str(error)
else:
raise AssertionError(f"accepted unsupported payload: {invalid!r}")
# Batch iterators are the ingestion path that needs explicit arrays.
batches = [
pa.RecordBatch.from_arrays([blob_array([value])], schema=schema)
for value in payloads
]
table = lancedb.connect("memory:///").create_table(
"videos", data=iter(batches[:2]), schema=schema
)
table.add(iter(batches[2:]))
row_ids = table.search().with_row_id(True).to_arrow()["_rowid"]
assert table.fetch_blobs("video", row_ids).to_pylist() == payloads
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
@@ -0,0 +1,94 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import subprocess
import sys
import textwrap
import pytest
@pytest.mark.parametrize("api", ["sync", "async"])
@pytest.mark.parametrize("result", ["pandas", "batches", "lazy_error"])
def test_blob_query_without_pylance(tmp_path, api, result):
script = """\
import importlib.abc
import sys
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())
""" + textwrap.dedent(
"""\
import asyncio
import lancedb
import pyarrow as pa
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
rows = [{"id": 1, "video": b"one"}, {"id": 2, "video": None},
{"id": 3, "video": b"three"}]
def check(data):
assert data == [{"filename": 2, "payload": None},
{"filename": 3, "payload": b"three"}], data
async def main():
if sys.argv[2] == "async":
db = await lancedb.connect_async(sys.argv[1])
table = await db.create_table("videos", schema=schema)
await table.add(rows)
query = table.query()
else:
db = lancedb.connect(sys.argv[1])
table = db.create_table("videos", schema=schema)
table.add(rows)
query = table.search()
query = query.select({"filename": "id", "payload": "video"}).offset(1)
if sys.argv[3] == "pandas":
frame = query.to_pandas(blob_mode="bytes", split_blocks=True)
if sys.argv[2] == "async":
frame = await frame
check(frame.to_dict("records"))
frame = table.to_pandas(blob_mode="bytes")
if sys.argv[2] == "async":
frame = await frame
assert frame.to_dict("records") == rows
elif sys.argv[3] == "batches":
if sys.argv[2] == "async":
reader = await query.to_batches(
max_batch_length=1, blob_mode="bytes")
batches = [batch async for batch in reader]
else:
reader = query.to_batches(batch_size=1, blob_mode="bytes")
batches = list(reader)
assert reader.schema.field("payload").type == pa.large_binary()
assert all(batch.num_rows <= 1 for batch in batches)
assert all(batch.schema == reader.schema for batch in batches)
check([row for batch in batches for row in batch.to_pylist()])
else:
try:
frame = query.to_pandas()
if sys.argv[2] == "async":
await frame
except RuntimeError as error:
message = str(error)
assert "pip install pylance" in message, message
assert ".." not in message, message
assert "Use a plain scan query" not in message, message
assert "but The" not in message, message
else:
raise AssertionError("lazy handles should require pylance")
assert "lance" not in sys.modules
asyncio.run(main())
"""
)
completed = subprocess.run(
[sys.executable, "-c", script, str(tmp_path), api, result],
capture_output=True,
text=True,
)
assert completed.returncode == 0, completed.stderr
+59
View File
@@ -0,0 +1,59 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import io
import pytest
from lancedb import BlobReader
def test_reader_is_lazy_and_seekable():
requests = []
size = 64 * 1024 * 1024
def read_range(offset, length):
requests.append((offset, length))
return bytes((index % 251 for index in range(offset, offset + length)))
with BlobReader(read_range, size) as reader:
assert requests == []
assert reader.size() == size
reader.seek(-4, io.SEEK_END)
assert reader.read(10) == bytes(index % 251 for index in range(size - 4, size))
assert reader.read(1) == b""
assert requests == [(size - 4, 4)]
assert reader.read_range(1, 3) == b"\x01\x02\x03"
assert reader.tell() == size
reader.seek(2)
target = bytearray(3)
assert reader.readinto(target) == 3
assert target == b"\x02\x03\x04"
reader.seek(-1, io.SEEK_CUR)
assert reader.tell() == 4
with pytest.raises(ValueError, match="closed"):
reader.read(1)
def test_reader_supports_buffered_io_and_bounds_range_requests():
requests = []
payload = b"x" * (3 * 1024 * 1024 + 7)
def read_range(offset, length):
requests.append((offset, length))
return payload[offset : offset + length]
with io.BufferedReader(BlobReader(read_range, len(payload))) as reader:
assert reader.read() == payload
assert requests
assert all(length <= 1024 * 1024 for _, length in requests)
def test_reader_rejects_invalid_ranges_and_short_reads():
reader = BlobReader(lambda offset, length: b"", 10)
with pytest.raises(ValueError):
reader.seek(-1)
with pytest.raises(ValueError):
reader.read_range(-1, 1)
with pytest.raises(OSError, match="payload length"):
reader.read(1)
+4 -5
View File
@@ -3,13 +3,13 @@
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
from threading import Thread
import pytest
import lancedb
from lancedb.db import AsyncConnection, DBConnection
from lancedb.remote.errors import HttpError
from utils import start_server_thread
@pytest.fixture
@@ -38,8 +38,7 @@ def catalog_server():
do_POST = handle_request
with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
thread = Thread(target=server.serve_forever, daemon=True)
thread.start()
thread = start_server_thread(server, daemon=True)
try:
yield f"http://127.0.0.1:{server.server_port}", requests, responses
finally:
@@ -86,12 +85,12 @@ def test_catalog_sync_scope_and_serialization(catalog_server):
connection.execute_query_async("SELECT 1")
assert restored.table_names() == []
assert list(catalog.list_databases()) == ["team/search"]
catalog.drop_database("team/search", ignore_missing=True)
catalog.drop_database("team/search", ignore_missing=True, cascade=True)
assert requests[0][0] == "/v1/namespace/team%2Fsearch/create"
assert requests[0][2] == {"mode": "ExistOk"}
assert requests[1][0] == "/v1/namespace/team%2Fsearch/describe"
assert requests[4][0] == "/v1/namespace/$/list"
assert requests[5][2] == {"mode": "Skip", "behavior": "Restrict"}
assert requests[5][2] == {"mode": "Skip", "behavior": "Cascade"}
for i, (_, headers, _) in enumerate(requests):
headers = {key.lower(): value for key, value in headers.items()}
assert headers.get("x-lancedb-database") == (
@@ -0,0 +1,32 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import pytest
from lancedb.db import AsyncConnection
@pytest.mark.asyncio
@pytest.mark.parametrize("operation", ["count_rows", "query", "head"])
async def test_closed_table_queries_raise_runtime_error(
mem_db_async: AsyncConnection, operation
):
table = await mem_db_async.create_table("closed_query", data=[{"id": 0}])
assert (await table.query().to_arrow()).to_pylist() == [{"id": 0}]
table.close()
table.close()
assert not table.is_open()
with pytest.raises(RuntimeError, match="Table closed_query is closed"):
if operation == "query":
table.query()
else:
await getattr(table, operation)()
@pytest.mark.asyncio
async def test_open_table_queries(mem_db_async: AsyncConnection):
table = await mem_db_async.create_table("open_query", data=[{"id": 0}])
assert await table.count_rows() == 1
assert (await table.query().to_arrow()).to_pylist() == [{"id": 0}]
assert (await table.head()).to_pylist() == [{"id": 0}]
table.close()
+21
View File
@@ -86,6 +86,7 @@ def test_sync_debugger_inspection_does_not_use_background_loop(tmp_path, monkeyp
assert members["uri"] == str(tmp_path)
assert members["read_consistency_interval"] is None
assert members["session"] is None
assert repr(db) == f"LanceDBConnection(uri={str(tmp_path)!r})"
assert repr(table) == f"LanceTable(name='test', _conn={db!r})"
@@ -105,6 +106,8 @@ def test_read_consistency_interval_does_not_use_background_loop(tmp_path, monkey
assert db.read_consistency_interval == consistency_interval
assert db_from_inner.read_consistency_interval == consistency_interval
assert db.session is None
assert db_from_inner.session is None
def test_ingest_pd(tmp_path):
@@ -1146,6 +1149,24 @@ def test_local_namespace_operations(tmp_path):
assert db.list_namespaces().namespaces == []
@pytest.mark.asyncio
async def test_local_async_namespace_exists(tmp_path):
db = await lancedb.connect_async(tmp_path)
await db.create_namespace(["existing"])
await db.create_namespace(["existing", "nested"])
assert await db.namespace_exists([]) is True
assert await db.namespace_exists(["existing"]) is True
assert await db.namespace_exists(["existing", "nested"]) is True
assert await db.namespace_exists(["missing"]) is False
assert await db.namespace_exists(["existing", "missing"]) is False
assert await db.namespace_exists(["missing", "nested"]) is False
await db.drop_namespace(["existing", "nested"])
assert await db.namespace_exists(["existing", "nested"]) is False
assert await db.namespace_exists(["existing"]) is True
def test_local_sync_namespace_uses_rust_without_python_client(tmp_path, monkeypatch):
"""Sync local namespace operations should avoid the Python namespace client."""
db = lancedb.connect(tmp_path)
+16
View File
@@ -22,3 +22,19 @@ def test_basic_query(tmp_path):
results = duck_conn.sql("SELECT SUM(y) FROM adapter").fetchall()
assert results[0][0] == 26
def test_query_with_filter(tmp_path):
data = pa.table({"x": [1, 2, 3, 4], "y": [5, 6, 7, 8]})
conn = lancedb.connect(tmp_path)
tbl = conn.create_table("test", data)
adapter = PyarrowDatasetAdapter(tbl) # noqa: F841
duck_conn = duckdb.connect()
results = duck_conn.sql("SELECT SUM(y) FROM adapter WHERE x > 2").fetchall()
assert results[0][0] == 15
results = duck_conn.sql("SELECT y FROM adapter WHERE x > 2 ORDER BY y").fetchall()
assert results == [(7,), (8,)]
@@ -3297,3 +3297,230 @@ def test_streaming_dataset_over_remote_table():
assert len(server.scans) == 1, "the permutation is built with one row-id scan"
assert server.takes, "rows must be fetched with row-id takes"
assert_server_safe_row_id_requests(server)
# ---------------------------------------------------------------------------
# split_strategy escape hatch
# ---------------------------------------------------------------------------
def test_split_strategy_bootstrap_sample(lance_table):
"""split_strategy lets StreamingDataset use bootstrap_sample directly, producing
more rows than the base table has (sampling with replacement)."""
num_samples = 4 * NUM_ROWS
ds = StreamingDataset(
lance_table,
split_strategy=lambda b: b.bootstrap_sample(
num_samples, fixed=NUM_SPLITS, seed=SHUFFLE_SEED
),
num_splits=NUM_SPLITS,
)
ids = [row["id"] for row in ds]
assert len(ids) == num_samples
# 4x oversampling a small table must produce at least one repeat.
assert len(set(ids)) < len(ids)
assert set(ids).issubset(set(range(NUM_ROWS)))
def test_split_strategy_matches_direct_permutation_builder_use(lance_table):
"""StreamingDataset(split_strategy=...), read single-process (no DataLoader
workers, so this one process owns every split and round-robins across all of
them), must yield exactly what calling the same strategy directly on a
PermutationBuilder would read, interleaved one row per split per cycle.
Reads each split via __getitems__ (explicit indices), not plain iteration:
Permutation's sequential __iter__ returns empty for a permutation with repeated
row_ids (confirmed directly -- len() is correct, __getitems__ returns the right
rows, but `for row in perm` yields nothing). That's a pre-existing limitation of
Permutation's iterator, unrelated to Bootstrap sampling's correctness: it doesn't
affect StreamingDataset or this benchmark, since both only ever read via
explicit-index batched fetches (take_offsets/__getitems__), never the plain
iterator -- flagged separately, not fixed here (out of scope for this change).
"""
from lancedb.permutation import Permutation, permutation_builder
def strategy(builder):
return builder.bootstrap_sample(2 * NUM_ROWS, fixed=NUM_SPLITS, seed=1)
direct_perm_tbl = strategy(permutation_builder(lance_table)).execute()
expected_by_split = []
for split in range(NUM_SPLITS):
perm = Permutation.from_tables(lance_table, direct_perm_tbl, split=split)
rows = perm.__getitems__(list(range(len(perm))))
expected_by_split.append([row["id"] for row in rows])
samples_per_split = len(expected_by_split[0])
expected = [
expected_by_split[split][cycle]
for cycle in range(samples_per_split)
for split in range(NUM_SPLITS)
]
ds = StreamingDataset(lance_table, split_strategy=strategy, num_splits=NUM_SPLITS)
actual = [row["id"] for row in ds]
assert actual == expected
def test_split_strategy_is_reproducible_across_instances(lance_table):
def strategy(builder):
return builder.bootstrap_sample(3 * NUM_ROWS, fixed=NUM_SPLITS, seed=99)
ds1 = StreamingDataset(lance_table, split_strategy=strategy, num_splits=NUM_SPLITS)
ds2 = StreamingDataset(lance_table, split_strategy=strategy, num_splits=NUM_SPLITS)
assert [row["id"] for row in ds1] == [row["id"] for row in ds2]
def test_split_strategy_num_splits_mismatch_raises(lance_table):
"""StreamingDataset(split_strategy=...) must reject a strategy whose split
count doesn't match num_splits. `_rank_splits` assumes split ids are exactly
0..num_splits-1 with no gaps; a mismatch would otherwise silently drop rows
(split ids >= num_splits) or leave some ranks reading an empty split (missing
ids < num_splits)."""
with pytest.raises(ValueError, match="num_splits"):
StreamingDataset(
lance_table,
split_strategy=lambda b: b.bootstrap_sample(
2 * NUM_ROWS, fixed=NUM_SPLITS, seed=SHUFFLE_SEED
),
num_splits=NUM_SPLITS + 1, # the strategy above always builds NUM_SPLITS
)
def test_split_strategy_unequal_split_sizes_raises(lance_table):
"""StreamingDataset(split_strategy=...) must reject a strategy whose splits
all exist (ids 0..num_splits-1) but aren't the same size. The round-robin
iteration (see _iter_owned) assumes every owned split has the same row count
and stops as soon as any one is exhausted -- `ratios`/`counts` (unlike
`fixed`) can produce unequal split sizes, which would otherwise silently
drop rows from the larger splits."""
with pytest.raises(ValueError, match="unequal split sizes"):
StreamingDataset(
lance_table,
split_strategy=lambda b: b.bootstrap_sample(
100, ratios=[0.7, 0.3], seed=SHUFFLE_SEED
),
num_splits=2,
)
def test_split_strategy_permutation_mismatch_on_resume_raises(lance_table):
"""load_state_dict must reject resuming against a different permutation than
the one that produced the checkpoint. num_splits/shuffle_seed alone can't catch
this for split_strategy, since that path ignores shuffle_seed entirely: a
bootstrap_sample reseeded differently resamples completely differently while
shuffle_seed keeps whatever value the caller passed either way, so the
pre-existing checks would pass despite the mismatch."""
def strategy(seed):
return lambda b: b.bootstrap_sample(2 * NUM_ROWS, fixed=NUM_SPLITS, seed=seed)
ds1 = StreamingDataset(
lance_table,
split_strategy=strategy(1),
num_splits=NUM_SPLITS,
shuffle_seed=SHUFFLE_SEED,
)
it = iter(ds1)
for _ in range(NUM_SPLITS): # one full cycle: every split advances uniformly
next(it)
checkpoint = ds1.state_dict()
ds2 = StreamingDataset(
lance_table,
split_strategy=strategy(2), # different seed -> a different permutation
num_splits=NUM_SPLITS,
shuffle_seed=SHUFFLE_SEED, # unchanged -- irrelevant on this path
)
with pytest.raises(ValueError, match="permutation mismatch"):
ds2.load_state_dict(checkpoint)
def test_split_strategy_resume_with_matching_permutation_succeeds(lance_table):
"""The common case: resuming against the same split_strategy (same seed) must
work exactly like the non-split_strategy checkpoint/resume path, continuing
from exactly the same position with no gaps or repeats."""
def strategy(b):
return b.bootstrap_sample(2 * NUM_ROWS, fixed=NUM_SPLITS, seed=7)
ds1 = StreamingDataset(
lance_table,
split_strategy=strategy,
num_splits=NUM_SPLITS,
shuffle_seed=SHUFFLE_SEED,
)
it = iter(ds1)
for _ in range(NUM_SPLITS):
next(it)
checkpoint = ds1.state_dict()
remaining_original = [row["id"] for row in it]
ds2 = StreamingDataset(
lance_table,
split_strategy=strategy,
num_splits=NUM_SPLITS,
shuffle_seed=SHUFFLE_SEED,
)
ds2.load_state_dict(checkpoint) # must not raise
remaining_resumed = [row["id"] for row in ds2]
assert remaining_original == remaining_resumed
def test_default_checkpoint_omits_perm_fingerprint(lance_table):
"""split_random/split_sequential checkpoints must not carry a
perm_fingerprint -- see test_default_checkpoint_resumes_after_compaction for
why checking one on this path would be wrong, not just unnecessary."""
ds = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED)
assert "perm_fingerprint" not in ds.state_dict()
def test_split_strategy_checkpoint_includes_perm_fingerprint(lance_table):
ds = StreamingDataset(
lance_table,
split_strategy=lambda b: b.bootstrap_sample(
2 * NUM_ROWS, fixed=NUM_SPLITS, seed=SHUFFLE_SEED
),
num_splits=NUM_SPLITS,
)
assert "perm_fingerprint" in ds.state_dict()
def test_default_checkpoint_resumes_after_compaction(lance_table):
"""split_random/split_sequential checkpoints must resume normally even after
the table is compacted between save and load. Lance row ids are not stable
across compaction by default (confirmed empirically: a 2-fragment table's
row ids differ before and after `optimize()`), so fingerprinting raw row ids
on this path -- instead of relying on shuffle_seed/num_splits alone, as it
does -- would reject this resume even though the seeded permutation itself
is unchanged."""
lance_table.add(pa.table({"id": [NUM_ROWS]})) # a second fragment to compact
ds = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED)
it = iter(ds)
for _ in range(NUM_SPLITS):
next(it)
checkpoint = ds.state_dict()
assert "perm_fingerprint" not in checkpoint
before_compaction = set(
lance_table.to_lance()
.to_table(columns=[], with_row_id=True)["_rowid"]
.to_pylist()
)
lance_table.optimize()
after_compaction = set(
lance_table.to_lance()
.to_table(columns=[], with_row_id=True)["_rowid"]
.to_pylist()
)
assert before_compaction != after_compaction, (
"test setup didn't actually renumber row ids -- fix the fixture, not "
"the assertion below"
)
ds_resumed = StreamingDataset(
lance_table, num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED
)
ds_resumed.load_state_dict(checkpoint) # must not raise
@@ -0,0 +1,84 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import copy
import lancedb
import pytest
from lancedb.embeddings.base import TextEmbeddingFunction
from lancedb.embeddings.registry import get_registry
from lancedb.pydantic import LanceModel, Vector
class LocalEmbedding(TextEmbeddingFunction):
def ndims(self):
return 2
def generate_embeddings(self, texts):
return [[1.0, 0.0] if text == "alpha" else [0.0, 1.0] for text in texts]
@pytest.mark.parametrize(
"method,tag",
[("SourceField", "source_column_for"), ("VectorField", "vector_column_for")],
)
@pytest.mark.parametrize("extra", [None, {}, {"x-purpose": "retrieval"}])
def test_embedding_field_preserves_extra_metadata(method, tag, extra):
function = LocalEmbedding.create(max_retries=0)
original = copy.deepcopy(extra)
field = getattr(function, method)(json_schema_extra=extra)
assert extra == original
assert field.json_schema_extra[tag] is function
for key, value in (extra or {}).items():
assert field.json_schema_extra[key] == value
@pytest.mark.parametrize(
"method,tag",
[("SourceField", "source_column_for"), ("VectorField", "vector_column_for")],
)
def test_extra_metadata_cannot_replace_embedding_identity(method, tag):
function = LocalEmbedding.create(max_retries=0)
supplied = {tag: "caller value", "x-purpose": "retrieval"}
field = getattr(function, method)(json_schema_extra=supplied)
assert supplied[tag] == "caller value"
assert field.json_schema_extra[tag] is function
assert field.json_schema_extra["x-purpose"] == "retrieval"
@pytest.mark.parametrize("method", ["SourceField", "VectorField"])
def test_embedding_field_preserves_other_field_arguments(method):
function = LocalEmbedding.create(max_retries=0)
field = getattr(function, method)(title="Custom title", description="Custom field")
assert field.title == "Custom title"
assert field.description == "Custom field"
def test_extra_metadata_preserves_schema_and_local_embedding(tmp_path, monkeypatch):
registry = get_registry()
monkeypatch.setattr(registry, "_functions", registry._functions.copy())
registry.register("test-embedding-field-extra")(LocalEmbedding)
function = LocalEmbedding.create(max_retries=0)
class Row(LanceModel):
text: str = function.SourceField(json_schema_extra={"x-purpose": "source"})
vector: Vector(2) = function.VectorField(
json_schema_extra={"x-purpose": "embedding"}
)
json_schema = Row.model_json_schema()
assert json_schema["properties"]["text"]["x-purpose"] == "source"
assert json_schema["properties"]["vector"]["x-purpose"] == "embedding"
configs = Row.parse_embedding_functions()
assert len(configs) == 1
assert configs[0].function is function
assert configs[0].source_column == "text"
assert configs[0].vector_column == "vector"
db = lancedb.connect(tmp_path)
table = db.create_table(
"rows", schema=Row, data=[{"text": "alpha"}, {"text": "beta"}]
)
assert table.search("alpha").limit(1).to_list()[0]["text"] == "alpha"
reopened = lancedb.connect(tmp_path).open_table("rows")
assert isinstance(reopened.embedding_functions["vector"].function, LocalEmbedding)
assert reopened.search("alpha").limit(1).to_list()[0]["text"] == "alpha"
@@ -0,0 +1,88 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import lancedb
import pytest
from lancedb.embeddings.base import TextEmbeddingFunction
from lancedb.embeddings.registry import EmbeddingFunctionRegistry, get_registry
from lancedb.pydantic import LanceModel, Vector
class FirstEmbedding(TextEmbeddingFunction):
def ndims(self):
return 2
def generate_embeddings(self, texts):
return [[1.0, 0.0] if text == "alpha" else [0.0, 1.0] for text in texts]
class SecondEmbedding(FirstEmbedding):
def generate_embeddings(self, texts):
return [[0.0, 1.0] if text == "alpha" else [1.0, 0.0] for text in texts]
@pytest.mark.parametrize(
"first_alias,second_alias,second_class",
[
("shared", "shared", SecondEmbedding),
(None, "FirstEmbedding", SecondEmbedding),
("SecondEmbedding", None, SecondEmbedding),
(None, None, FirstEmbedding),
("", "", FirstEmbedding),
],
)
def test_duplicate_registration_preserves_original(
first_alias, second_alias, second_class
):
registry = EmbeddingFunctionRegistry()
registry.register(first_alias)(FirstEmbedding)
key = first_alias or "FirstEmbedding"
original_alias = FirstEmbedding.__embedding_function_registry_alias__
second_attributes = dict(second_class.__dict__)
with pytest.raises(KeyError, match=f"{key} was already registered"):
registry.register(second_alias)(second_class)
assert registry.get(key) is FirstEmbedding
assert FirstEmbedding.__embedding_function_registry_alias__ == original_alias
assert dict(second_class.__dict__) == second_attributes
def test_class_name_does_not_collide_with_distinct_alias():
registry = EmbeddingFunctionRegistry()
registry.register()(FirstEmbedding)
same_name = type("FirstEmbedding", (SecondEmbedding,), {})
registry.register("separate")(same_name)
assert registry.get("FirstEmbedding") is FirstEmbedding
assert registry.get("separate") is same_name
def test_same_class_explicit_alias_registration_is_idempotent():
registry = EmbeddingFunctionRegistry()
assert registry.register("shared")(FirstEmbedding) is FirstEmbedding
attributes = dict(FirstEmbedding.__dict__)
assert registry.register("shared")(FirstEmbedding) is FirstEmbedding
assert registry.get("shared") is FirstEmbedding
assert dict(FirstEmbedding.__dict__) == attributes
def test_alias_collision_does_not_change_persisted_table(tmp_path, monkeypatch):
registry = get_registry()
monkeypatch.setattr(registry, "_functions", registry._functions.copy())
alias = "test-alias-collision-persisted-table"
registry.register(alias)(FirstEmbedding)
function = FirstEmbedding.create(max_retries=0)
class Row(LanceModel):
text: str = function.SourceField()
vector: Vector(2) = function.VectorField()
db = lancedb.connect(tmp_path)
table = db.create_table(
"rows", schema=Row, data=[{"text": "alpha"}, {"text": "beta"}]
)
assert table.search("alpha").limit(1).to_list()[0]["text"] == "alpha"
assert registry.register(alias)(FirstEmbedding) is FirstEmbedding
with pytest.raises(KeyError, match=f"{alias} was already registered"):
registry.register(alias)(SecondEmbedding)
reopened = lancedb.connect(tmp_path).open_table("rows")
assert isinstance(reopened.embedding_functions["vector"].function, FirstEmbedding)
assert reopened.search("alpha").limit(1).to_list()[0]["text"] == "alpha"
@@ -0,0 +1,55 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
from lancedb.embeddings import EmbeddingFunctionRegistry, TextEmbeddingFunction
class ExampleEmbedding(TextEmbeddingFunction):
def ndims(self):
return 2
def generate_embeddings(self, texts):
return [[1.0, 0.0] for _ in texts]
class OtherEmbedding(ExampleEmbedding):
pass
def test_list_functions_empty_registry():
registry = EmbeddingFunctionRegistry()
assert registry.list_functions() == []
def test_list_functions_names_and_registration_order():
registry = EmbeddingFunctionRegistry()
registry.register("custom-embedding")(ExampleEmbedding)
registry.register()(OtherEmbedding)
assert registry.list_functions() == ["custom-embedding", "OtherEmbedding"]
assert [registry.get(name) for name in registry.list_functions()] == [
ExampleEmbedding,
OtherEmbedding,
]
def test_list_functions_returns_independent_snapshot():
registry = EmbeddingFunctionRegistry()
registry.register("first")(ExampleEmbedding)
names = registry.list_functions()
names.append("not-registered")
assert registry.list_functions() == ["first"]
registry.register("second")(OtherEmbedding)
assert names == ["first", "not-registered"]
assert registry.list_functions() == ["first", "second"]
def test_list_functions_after_reset():
registry = EmbeddingFunctionRegistry()
registry.register("custom-embedding")(ExampleEmbedding)
names = registry.list_functions()
registry.reset()
assert registry.list_functions() == []
assert names == ["custom-embedding"]
+462
View File
@@ -23,6 +23,12 @@ from lancedb.embeddings.utils import retry
from lancedb.pydantic import LanceModel, Vector
@pytest.fixture(autouse=True)
def isolated_embedding_registry(monkeypatch):
registry = get_registry()
monkeypatch.setattr(registry, "_functions", registry._functions.copy())
def mock_embed_func(input_data):
return [np.random.randn(128).tolist() for _ in range(len(input_data))]
@@ -64,6 +70,37 @@ def test_embedding_function(tmp_path):
assert np.allclose(actual, expected)
def test_embedding_function_registered_without_alias(tmp_path):
registry = EmbeddingFunctionRegistry.get_instance()
@registry.register()
class NoAliasEmbeddingFunction(TextEmbeddingFunction):
def ndims(self):
return 2
def generate_embeddings(self, texts):
return [np.array([1.0, 2.0]) for _ in texts]
assert registry.get("NoAliasEmbeddingFunction") is NoAliasEmbeddingFunction
func = NoAliasEmbeddingFunction.create()
class Schema(LanceModel):
text: str = func.SourceField()
vector: Vector(2) = func.VectorField()
db = lancedb.connect(tmp_path)
db.create_table("test", schema=Schema)
# The class name is written to the table metadata, so the function can be
# resolved again when the table is reopened.
table = lancedb.connect(tmp_path).open_table("test")
table.add([{"text": "hello"}])
conf = table.embedding_functions["vector"]
assert isinstance(conf.function, NoAliasEmbeddingFunction)
assert table.to_arrow()["vector"].to_pylist() == [[1.0, 2.0]]
def test_instructor_ndims_uses_instruction():
instructor = get_registry().get("instructor").create()
model = MagicMock()
@@ -596,6 +633,363 @@ def test_openai_no_retry_on_401(mock_sleep):
assert mock_sleep.call_count == 0
class _HttpStatusError(Exception):
"""Stand-in for provider SDK errors (openai, cohere, ...) with a status code."""
def __init__(self, status_code, message="error"):
super().__init__(message)
self.status_code = status_code
class _ResponseStatusError(Exception):
"""Stand-in for requests/httpx errors, which expose `response.status_code`."""
def __init__(self, status_code):
super().__init__(f"HTTP {status_code}")
self.response = MagicMock(status_code=status_code)
def _run_with_retry(side_effect, **kwargs):
"""Run a function through the retry helper with a mocked `time.sleep`.
Returns (mock_func, sleeps, error).
"""
from lancedb.embeddings.utils import retry_with_exponential_backoff
mock_func = MagicMock(side_effect=side_effect)
sleeps = []
error = None
with patch("time.sleep", side_effect=sleeps.append):
try:
retry_with_exponential_backoff(mock_func, **kwargs)()
except Exception as e:
error = e
return mock_func, sleeps, error
@pytest.mark.parametrize("status", [400, 401, 403, 404, 405, 410, 413, 422])
@pytest.mark.parametrize("make_error", [_HttpStatusError, _ResponseStatusError])
def test_retry_does_not_retry_permanent_http_errors(status, make_error):
err = make_error(status)
mock_func, sleeps, error = _run_with_retry(err, max_retries=7)
assert error is err
assert mock_func.call_count == 1
assert sleeps == []
@pytest.mark.parametrize("status", [408, 409, 429, 500, 502, 503, 504])
@pytest.mark.parametrize("make_error", [_HttpStatusError, _ResponseStatusError])
def test_retry_retries_transient_http_errors(status, make_error):
mock_func, sleeps, error = _run_with_retry(
[make_error(status), make_error(status), "result"], max_retries=7
)
assert error is None
assert mock_func.call_count == 3
assert len(sleeps) == 2
@pytest.mark.parametrize(
"exc",
[
ConnectionError("connection reset"),
TimeoutError("timed out"),
OSError("network is unreachable"),
ValueError("custom embedding function failure"),
RuntimeError("boom"),
Exception("plain exception"),
],
)
def test_retry_retries_errors_without_http_status(exc):
mock_func, sleeps, error = _run_with_retry([exc, exc, "result"], max_retries=7)
assert error is None
assert mock_func.call_count == 3
assert len(sleeps) == 2
def test_retry_error_status_attributes_of_other_types_are_ignored():
# `code` is a string for openai errors ("model_not_found"), and arbitrary
# exceptions may carry unrelated numeric attributes. Neither is an HTTP status.
class WeirdError(Exception):
code = "model_not_found"
status_code = None
class ExitCodeError(Exception):
code = 2
for exc in (WeirdError("a"), ExitCodeError("b")):
mock_func, sleeps, error = _run_with_retry(exc, max_retries=2)
assert mock_func.call_count == 3
assert len(sleeps) == 2
def test_retry_botocore_style_errors():
# botocore ClientError exposes `response["ResponseMetadata"]["HTTPStatusCode"]`.
# Bedrock reports throttling with a 400, which must stay retryable.
class ClientError(Exception):
def __init__(self, status, code):
super().__init__(code)
self.response = {
"ResponseMetadata": {"HTTPStatusCode": status},
"Error": {"Code": code},
}
throttled = ClientError(400, "ThrottlingException")
mock_func, sleeps, error = _run_with_retry([throttled, "result"], max_retries=3)
assert error is None
assert mock_func.call_count == 2
invalid = ClientError(400, "ValidationException")
mock_func, sleeps, error = _run_with_retry(invalid, max_retries=3)
assert error is invalid
assert mock_func.call_count == 1
assert sleeps == []
def test_retry_authentication_error_by_name_not_retried():
class AuthenticationError(Exception):
pass
mock_func, sleeps, error = _run_with_retry(AuthenticationError("bad key"))
assert isinstance(error, AuthenticationError)
assert mock_func.call_count == 1
assert sleeps == []
def test_retry_gives_up_after_max_retries_with_original_error_attached():
original = _HttpStatusError(503, "overloaded")
mock_func, sleeps, error = _run_with_retry(original, max_retries=3)
assert mock_func.call_count == 4
assert len(sleeps) == 3
assert "Maximum number of retries (3) exceeded" in str(error)
assert error.args[1] is original
assert error.__cause__ is original
def test_retry_delay_is_capped_by_max_delay():
# Default settings (7 retries, 60s cap): the old implementation could sleep for
# up to ~47 minutes in a single retry and hours in total.
exc = _HttpStatusError(503)
for seed in range(50):
import random
random.seed(seed)
_, sleeps, _ = _run_with_retry(exc)
assert len(sleeps) == 7
assert max(sleeps) <= 60
assert sum(sleeps) <= 7 * 60
# Custom cap
_, sleeps, _ = _run_with_retry(exc, max_retries=10, max_delay=5)
assert len(sleeps) == 10
assert max(sleeps) <= 5
def test_retry_delay_without_jitter_is_exact_exponential_then_capped():
_, sleeps, _ = _run_with_retry(
_HttpStatusError(500),
initial_delay=1,
exponential_base=2,
jitter=False,
max_retries=8,
max_delay=30,
)
assert sleeps == [2, 4, 8, 16, 30, 30, 30, 30]
def test_retry_jitter_is_bounded():
# Each wait is within [delay / 2, delay], where delay grows by exponential_base
# per retry (no random factor is compounded across retries).
exc = _HttpStatusError(500)
for seed in range(50):
import random
random.seed(seed)
_, sleeps, _ = _run_with_retry(exc, max_retries=8, max_delay=100)
for i, slept in enumerate(sleeps):
delay = min(2 ** (i + 1), 100)
assert delay / 2 <= slept <= delay
# Extremes of the random source map to the ends of the range
with patch("random.random", return_value=0.0):
_, sleeps, _ = _run_with_retry(exc, max_retries=3)
assert sleeps == [1, 2, 4]
with patch("random.random", return_value=1.0):
_, sleeps, _ = _run_with_retry(exc, max_retries=3)
assert sleeps == [2, 4, 8]
def test_retry_large_max_retries_does_not_overflow():
_, sleeps, _ = _run_with_retry(_HttpStatusError(503), max_retries=1500)
assert len(sleeps) == 1500
assert max(sleeps) <= 60
def _register_failing_embedding(name, error):
"""Register an embedding function that always raises `error`.
Returns the class and a list that records every call. The function is
re-created from table metadata, so the call count has to live outside of it.
"""
calls = []
@register(name)
class FailingEmbeddingFunction(TextEmbeddingFunction):
def ndims(self):
return 4
def generate_embeddings(self, texts):
calls.append(len(texts))
raise error
return FailingEmbeddingFunction, calls
@pytest.mark.parametrize("status", [400, 404, 422])
def test_permanent_embedding_error_is_not_retried(tmp_path, status):
"""A permanent provider error (e.g. a misspelled model name) must surface
immediately from both `table.add` and `table.search` instead of being retried
with minutes of backoff."""
error = _HttpStatusError(status, "The model `typo-embed` does not exist")
cls, calls = _register_failing_embedding(f"failing-embedding-{status}", error)
func = cls.create() # default max_retries=7
class Schema(LanceModel):
text: str = func.SourceField()
vector: Vector(func.ndims()) = func.VectorField()
db = lancedb.connect(tmp_path)
table = db.create_table("t", schema=Schema)
with patch("time.sleep") as mock_sleep:
with pytest.raises(Exception, match="The model `typo-embed` does not exist"):
table.add([{"text": "hello"}])
assert len(calls) == 1
with pytest.raises(_HttpStatusError, match="does not exist"):
table.search("hello").limit(1).to_list()
assert len(calls) == 2
mock_sleep.assert_not_called()
def test_transient_embedding_error_is_retried_in_table_add(tmp_path):
cls, calls = _register_failing_embedding(
"failing-embedding-503", _HttpStatusError(503)
)
func = cls.create(max_retries=2)
class Schema(LanceModel):
text: str = func.SourceField()
vector: Vector(func.ndims()) = func.VectorField()
db = lancedb.connect(tmp_path)
table = db.create_table("t", schema=Schema)
with patch("time.sleep") as mock_sleep:
with pytest.raises(Exception, match="Maximum number of retries"):
table.add([{"text": "hello"}])
assert len(calls) == 3
assert mock_sleep.call_count == 2
assert all(call.args[0] <= 60 for call in mock_sleep.call_args_list)
@patch("time.sleep")
@pytest.mark.parametrize(
"error",
[
pytest.param("missing_key", id="missing-api-key"),
pytest.param(ImportError("No module named 'voyageai'"), id="missing-package"),
],
)
def test_no_retry_on_deterministic_errors(mock_sleep, error):
from lancedb.embeddings.utils import (
api_key_not_found_help,
retry_with_exponential_backoff,
)
def func():
if error == "missing_key":
api_key_not_found_help("voyageai")
raise error
mock_func = MagicMock(side_effect=func)
wrapped_func = retry_with_exponential_backoff(mock_func, max_retries=3)
with pytest.raises((ValueError, ImportError)):
wrapped_func()
assert mock_func.call_count == 1
assert mock_sleep.call_count == 0
@patch("time.sleep")
def test_retry_on_wrapped_provider_error(mock_sleep):
"""Providers such as Bedrock wrap throttling in a plain ValueError."""
from lancedb.embeddings.utils import retry_with_exponential_backoff
mock_func = MagicMock(
side_effect=[
ValueError("Error raised by boto3 client: ThrottlingException"),
[0.1],
]
)
wrapped_func = retry_with_exponential_backoff(mock_func, max_retries=3)
assert wrapped_func() == [0.1]
assert mock_func.call_count == 2
assert mock_sleep.call_count == 1
def test_openai_bad_request_partial_batch_recovery():
# Regression test for issue #1677
# Fake exception types, avoids requiring the optional openai/httpx deps
class FakeBadRequestError(Exception):
pass
class FakeAuthenticationError(Exception):
pass
fake_openai_module = MagicMock()
fake_openai_module.BadRequestError = FakeBadRequestError
fake_openai_module.AuthenticationError = FakeAuthenticationError
registry = get_registry()
model = registry.get("openai").create(name="text-embedding-ada-002")
def fake_create(input, model=None, **kwargs):
# Full batch always rejected
if len(input) > 1:
raise FakeBadRequestError("bad request")
if input[0] == "bad text":
raise FakeBadRequestError("bad request")
embedding = MagicMock()
embedding.embedding = [0.1, 0.2, 0.3]
result = MagicMock()
result.data = [embedding]
return result
mock_client = MagicMock()
mock_client.embeddings.create.side_effect = fake_create
with (
patch(
"lancedb.embeddings.openai.attempt_import_or_raise",
return_value=fake_openai_module,
),
patch.object(type(model), "_openai_client", new_callable=lambda: mock_client),
):
embeddings = model.generate_embeddings(["good text", "bad text"])
assert embeddings[0] == [0.1, 0.2, 0.3]
assert embeddings[1] is None
def test_ollama_embeddings_pickle():
"""OllamaEmbeddings must pickle even after the cached client is created."""
registry = get_registry()
@@ -645,6 +1039,39 @@ def test_open_clip_opens_percent_encoded_file_uri(tmp_path):
assert image.size == (4, 4)
def test_open_clip_model_in_eval_mode():
"""
open_clip.create_model_and_transforms returns the model in training mode,
which leaves dropout, stochastic depth and batch norm in their training
behaviour. OpenCLIP must switch the model to eval mode before embedding.
"""
from lancedb.embeddings.open_clip import OpenClipEmbeddings
class FakeModel:
training = True
def to(self, device):
return self
def eval(self):
self.training = False
return self
open_clip = MagicMock()
open_clip.create_model_and_transforms.return_value = (FakeModel(), None, None)
with patch(
"lancedb.embeddings.open_clip.attempt_import_or_raise",
return_value=open_clip,
):
func = OpenClipEmbeddings(name="ViTamin-B", pretrained="datacomp1b")
open_clip.create_model_and_transforms.assert_called_once_with(
"ViTamin-B", pretrained="datacomp1b"
)
assert func._model.training is False
def test_jina_generate_image_input_dict_local_path(tmp_path):
"""
JinaEmbeddings._generate_image_input_dict must accept a local image path
@@ -663,3 +1090,38 @@ def test_jina_generate_image_input_dict_local_path(tmp_path):
image_dict = JinaEmbeddings._generate_image_input_dict(image)
assert "image" in image_dict
assert isinstance(image_dict["image"], str) and len(image_dict["image"]) > 0
def test_jina_embeddings_use_their_own_api_key(monkeypatch):
"""Each JinaEmbeddings instance must send its own API key."""
pytest.importorskip("requests")
monkeypatch.delenv("JINA_API_KEY", raising=False)
registry = get_registry()
registry.set_var("jina_key_a", "key-a")
registry.set_var("jina_key_b", "key-b")
func_a = registry.get("jina").create(api_key="$var:jina_key_a")
func_b = registry.get("jina").create(api_key="$var:jina_key_b")
sent = []
def fake_post(session, url, json=None, **kwargs):
sent.append(session.headers["Authorization"])
response = MagicMock()
response.json.return_value = {"data": [{"index": 0, "embedding": [0.0]}]}
return response
with patch("requests.Session.post", fake_post):
func_a.compute_source_embeddings(["hello"])
func_b.compute_source_embeddings(["hello"])
assert sent == ["Bearer key-a", "Bearer key-b"]
def test_cohere_default_model_is_not_a_retired_v2_model():
# Cohere retired embed-english-v2.0, embed-english-light-v2.0 and
# embed-multilingual-v2.0 on April 4, 2026.
cohere = get_registry().get("cohere").create()
assert cohere.name == "embed-multilingual-v3.0"
assert "v2.0" not in cohere.name
assert cohere.ndims() == 1024
+1 -1
View File
@@ -272,7 +272,7 @@ def test_cohere_embedding_function():
cohere = (
get_registry()
.get("cohere")
.create(name="embed-multilingual-v2.0", max_retries=0)
.create(name="embed-multilingual-v3.0", max_retries=0)
)
class TextModel(LanceModel):
+21
View File
@@ -3,7 +3,28 @@
import pickle
import pytest
from lancedb.db import DBConnection
from lancedb.remote.errors import HttpError, LanceDBClientError, RetryError
from lancedb.table import Table
@pytest.mark.parametrize(
"base, method",
[
(Table, "to_lance"),
(Table, "to_polars"),
(DBConnection, "drop_all_tables"),
(DBConnection, "drop_database"),
],
)
def test_base_unsupported_methods_have_messages(base, method):
with pytest.raises(NotImplementedError) as exc_info:
getattr(base, method)(None)
message = str(exc_info.value)
assert method in message
assert "not supported" in message
def test_pickle_lancedb_client_error():
@@ -0,0 +1,58 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import lancedb
import pytest
pytestmark = pytest.mark.skipif(
lancedb._lancedb._experimental_functions_enabled,
reason="tests the default build without experimental-functions",
)
@pytest.mark.parametrize("namespace", [False, True])
def test_default_build_rejects_local_functions(tmp_path, namespace):
db = (
lancedb.connect_namespace("dir", {"root": str(tmp_path)})
if namespace
else lancedb.connect(tmp_path)
)
table = db.create_table("source", [{"x": 1}, {"x": 2}])
version = table.version
operations = [
lambda: table.add_columns(computed={"doubled": "x * 2"}),
lambda: table.refresh_column("x"),
lambda: table.refresh_column_async("x"),
lambda: db.create_materialized_view("blocked", "source"),
lambda: db.create_materialized_view("blocked", "source", with_no_data=True),
lambda: db.create_materialized_view_async("blocked", "source"),
]
for operation in operations:
with pytest.raises(NotImplementedError, match="experimental-functions"):
operation()
assert table.version == version
assert db.table_names() == ["source"]
table.add_columns({"eager": "x * 2"})
assert table.to_arrow()["eager"].to_pylist() == [2, 4]
@pytest.mark.asyncio
async def test_async_default_build_rejects_local_functions(tmp_path):
db = await lancedb.connect_async(tmp_path)
table = await db.create_table("source", [{"x": 1}, {"x": 2}])
version = await table.version()
operations = [
lambda: table.add_columns(computed={"doubled": "x * 2"}),
lambda: table.refresh_column("x"),
lambda: table.refresh_column_async("x"),
lambda: db.create_materialized_view("blocked", "source"),
lambda: db.create_materialized_view("blocked", "source", with_no_data=True),
lambda: db.create_materialized_view_async("blocked", "source"),
]
for operation in operations:
with pytest.raises(NotImplementedError, match="experimental-functions"):
await operation()
assert await table.version() == version
assert await db.table_names() == ["source"]
await table.add_columns({"eager": "x * 2"})
assert (await table.query().to_arrow())["eager"].to_pylist() == [2, 4]
+242
View File
@@ -11,6 +11,7 @@ import pytest
import lancedb
from lancedb.expr import Expr, col, func, lit
from lancedb.index import FTS
# ── unit tests for Expr construction ─────────────────────────────────────────
@@ -80,6 +81,67 @@ class TestExprConstruction:
e = lit(d)
assert isinstance(e, Expr)
@pytest.mark.parametrize(
"value, decimal_type",
[
("1E-7", pa.decimal128(12, 7)),
("-1.23E-7", pa.decimal128(12, 9)),
("1E+3", pa.decimal128(12, 0)),
("-1.23E+5", pa.decimal128(12, 0)),
("0E-7", pa.decimal128(12, 7)),
("-0E+3", pa.decimal128(12, 0)),
("1E-38", pa.decimal128(38, 38)),
("1E+37", pa.decimal128(38, 0)),
("1.234567890123456789012345678901234567E+37", pa.decimal128(38, 0)),
("0E+128", pa.decimal128(1, 0)),
],
)
def test_lit_decimal_exponent_query(self, tmp_path, value, decimal_type):
expected = Decimal(value)
table = lancedb.connect(tmp_path).create_table(
"decimals",
pa.table(
{
"id": [1, 2],
# Arrow's Python ingestion rejects 0E+128 even though its
# numeric value is representable. Store canonical zero to
# exercise the expression literal independently of ingestion.
"price": pa.array(
[Decimal(0) if expected.is_zero() else expected, None],
type=decimal_type,
),
}
),
)
predicate = col("price") == lit(expected)
result = table.search().where(predicate).to_arrow()
assert result["id"].to_pylist() == [1]
assert result["price"].to_pylist() == [expected]
# Exercise the SQL serializer and parser as well as the typed query path.
sql_result = table.search().where(predicate.to_sql()).to_arrow()
assert sql_result["id"].to_pylist() == [1]
assert sql_result["price"].to_pylist() == [expected]
@pytest.mark.parametrize(
"value",
[
"NaN",
"sNaN",
"Infinity",
"-Infinity",
"1E-39",
"1E+38",
"1E+129",
"1E+1000000000",
"0E+129",
"12345678901234567890123456789012345678E+1",
"9" * 39,
],
)
def test_lit_decimal_unrepresentable_raises(self, value):
with pytest.raises(ValueError):
lit(Decimal(value))
class TestExprOperators:
def test_eq_operator(self):
@@ -322,6 +384,68 @@ class TestExprRepr:
{e: 1}
class TestExprTruthiness:
"""``bool(Expr)`` must raise instead of silently keeping one operand."""
def test_bool_raises(self):
with pytest.raises(TypeError, match="truth value of an Expr is ambiguous"):
bool(col("x") == 1)
def test_bool_error_points_to_operators(self):
with pytest.raises(TypeError, match=r"'&'.*'\|'.*'~'"):
bool(col("x") > 1)
def test_and_raises(self):
with pytest.raises(TypeError, match="ambiguous"):
(col("id") > 7) and (col("g") == 0) # noqa: B015
def test_or_raises(self):
with pytest.raises(TypeError, match="ambiguous"):
(col("id") > 7) or (col("g") == 0) # noqa: B015
def test_not_raises(self):
with pytest.raises(TypeError, match="ambiguous"):
not (col("id") > 7) # noqa: B015
def test_chained_comparison_raises(self):
with pytest.raises(TypeError, match="ambiguous"):
lit(2) < col("id") < lit(5) # noqa: B015
with pytest.raises(TypeError, match="ambiguous"):
2 < col("id") < 5 # noqa: B015
def test_if_raises(self):
with pytest.raises(TypeError, match="ambiguous"):
if col("x"):
pass
def test_membership_in_list_raises(self):
# list membership evaluates ``item == expr`` and calls bool() on the
# result, which used to be silently (and wrongly) True.
with pytest.raises(TypeError, match="ambiguous"):
col("x") in [1, 2, 3] # noqa: B015
def test_any_all_raise(self):
with pytest.raises(TypeError, match="ambiguous"):
any([col("x") > 1])
with pytest.raises(TypeError, match="ambiguous"):
all([col("x") > 1])
def test_operators_still_combine(self):
a, b = col("id") > 7, col("g") == 0
assert (a & b).to_sql() == "((id > 7) AND (g = 0))"
assert (a | b).to_sql() == "((id > 7) OR (g = 0))"
assert (~a).to_sql() == "NOT (id > 7)"
assert ((lit(2) < col("id")) & (col("id") < lit(5))).to_sql() == (
"((2 < id) AND (id < 5))"
)
def test_identity_and_isinstance_checks_do_not_use_truthiness(self):
e = col("x") == 1
assert e is not None
assert isinstance(e, Expr)
assert e is e
class TestExprReflexive:
def test_reflexive_eq(self):
e = 1 == col("x")
@@ -730,3 +854,121 @@ class TestExprDatetimeTimezoneIntegration:
sql = lit(ts).to_sql()
# Must encode 10:00 wall clock, not 10:00+local_offset.
assert "2024-07-01 10:00:00" in sql
# ── where(Expr) must never rely on the truthiness of the filter ──────────────
@pytest.fixture
def search_table(tmp_path):
db = lancedb.connect(str(tmp_path))
data = pa.table(
{
"id": list(range(12)),
"g": [i % 2 for i in range(12)],
"text": ["keep" if i < 9 else "other" for i in range(12)],
"vector": pa.FixedSizeListArray.from_arrays(
pa.array([float(i) for i in range(12) for _ in range(2)], pa.float32()),
2,
),
}
)
table = db.create_table("search", data)
table.create_index("text", config=FTS())
return table
def _ids(rows):
return sorted(r["id"] for r in rows)
class TestExprWhereBuilders:
def test_chained_comparison_is_rejected_before_querying(self, search_table):
# The silent bug: this used to return ids 0..4 (lower bound dropped).
with pytest.raises(TypeError, match="ambiguous"):
search_table.search().where(lit(2) < col("id") < lit(5))
def test_plain_where_expr(self, search_table):
where = (lit(2) < col("id")) & (col("id") < lit(5))
rows = search_table.search().where(where).limit(100).to_list()
assert _ids(rows) == [3, 4]
def test_vector_where_expr(self, search_table):
where = (col("id") > lit(7)) & (col("g") == lit(0))
rows = search_table.search([0.0, 0.0]).where(where).limit(100).to_list()
assert _ids(rows) == [8, 10]
def test_fts_where_expr(self, search_table):
where = (col("id") > lit(3)) | (col("g") == lit(1))
rows = (
search_table.search("keep", query_type="fts")
.where(where)
.limit(100)
.to_list()
)
# "keep" matches ids 0..8; filter keeps id > 3 or odd ids.
assert _ids(rows) == [1, 3, 4, 5, 6, 7, 8]
def test_hybrid_where_expr(self, search_table):
# The hybrid builder used to test ``if self._where:``; that must not
# call bool() on an Expr now that it raises.
where = (col("id") > lit(3)) & (col("g") == lit(0))
rows = (
search_table.search(query_type="hybrid")
.vector([0.0, 0.0])
.text("keep")
.where(where)
.limit(100)
.to_list()
)
# Hybrid search fuses the vector and FTS results, and the filter applies
# to both sides: the vector side alone returns every row passing it.
assert _ids(rows) == [4, 6, 8, 10]
def test_hybrid_where_sql_string_still_works(self, search_table):
rows = (
search_table.search(query_type="hybrid")
.vector([0.0, 0.0])
.text("keep")
.where("id > 3 AND g = 0")
.limit(100)
.to_list()
)
assert _ids(rows) == [4, 6, 8, 10]
def test_hybrid_empty_where_is_ignored(self, search_table):
rows = (
search_table.search(query_type="hybrid")
.vector([0.0, 0.0])
.text("keep")
.where("")
.limit(100)
.to_list()
)
assert _ids(rows) == list(range(12))
def test_repeated_where_expr_combines(self, search_table):
rows = (
search_table.search()
.where(col("id") > lit(2))
.where(col("id") < lit(5))
.limit(100)
.to_list()
)
assert _ids(rows) == [3, 4]
def test_query_model_with_expr_filter(self, search_table):
query = search_table.search().where(col("id") > lit(2)).to_query_object()
assert isinstance(query.filter, Expr)
@pytest.mark.asyncio
async def test_async_where_expr(self, tmp_path):
db = await lancedb.connect_async(str(tmp_path))
table = await db.create_table(
"t", pa.table({"id": list(range(12)), "g": [i % 2 for i in range(12)]})
)
where = (col("id") > lit(7)) & (col("g") == lit(0))
rows = await table.query().where(where).to_list()
assert _ids(rows) == [8, 10]
with pytest.raises(TypeError, match="ambiguous"):
table.query().where(lit(2) < col("id") < lit(5))
@@ -146,6 +146,27 @@ def test_function_version_identity_is_immutable_and_exact():
FunctionVersion(**{**value, "version": invalid})
@pytest.mark.parametrize("source_digest", [None, "sha256:source-artifact"])
def test_function_version_preserves_source_digest(source_digest):
value = job_result("remote_function_job.json")
legacy = FunctionVersion.from_json(json.dumps(value))
assert legacy.source_digest is None
assert "source_digest" not in json.loads(legacy.to_canonical_json())
value["source_digest"] = source_digest
version = FunctionVersion.from_json(json.dumps(value))
assert version.source_digest == source_digest
assert version.image == legacy.image
encoded = version.to_canonical_json()
if source_digest is None:
assert "source_digest" not in json.loads(encoded)
else:
assert json.loads(encoded)["source_digest"] == source_digest
assert FunctionVersion.from_json(encoded) == version
with pytest.raises((TypeError, ValueError)):
version.source_digest = "sha256:changed"
def test_function_version_binds_named_columns_as_one_immutable_application():
version = FunctionVersion.from_json(
json.dumps(job_result("remote_function_job.json"))
@@ -398,8 +419,21 @@ class _FunctionDeclarationInner:
def __init__(self):
self.calls = []
async def add_function_columns(self, application_json, output_name):
self.calls.append((json.loads(application_json), output_name))
async def add_function_columns(
self,
application_json,
output_name,
auto_refresh_enabled,
auto_refresh_interval_seconds,
):
self.calls.append(
(
json.loads(application_json),
output_name,
auto_refresh_enabled,
auto_refresh_interval_seconds,
)
)
return "declared"
@@ -420,14 +454,18 @@ async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomica
)
assert result == "declared"
assert inner.calls[-1][1] == "features"
assert inner.calls[-1][2:] == (None, None)
bare = application._copy(update={"columns": {}}).rename(
columns={"normalized_text": "search_text"}
)
result = await table.add_columns(bare)
result = await table.add_columns(
bare, auto_refresh_enabled=False, auto_refresh_interval_seconds=300
)
assert result == "declared"
assert inner.calls[-1][1] is None
assert inner.calls[-1][0]["columns"] == {"normalized_text": "search_text"}
assert inner.calls[-1][2:] == (False, 300)
@pytest.mark.asyncio
@@ -15,7 +15,6 @@ import os
from pathlib import Path
import subprocess
import sys
import threading
import urllib.parse
from typing import Optional
@@ -23,6 +22,7 @@ import pyarrow as pa
import pytest
import lancedb
from lancedb import BlobReader
from lancedb.functions import (
PythonRuntimeSpec,
SecretBinding,
@@ -33,6 +33,7 @@ from lancedb.functions import (
udf,
)
from lancedb.secrets import EnvVarSecret
from utils import start_server_thread
THRESHOLD = 20
_CACHE = None
@@ -88,6 +89,27 @@ def test_scalar_udf_matches_shared_registration_golden_and_remains_callable():
}
@pytest.mark.parametrize(
"name", ["examples.image_info", "image-info", "image_info.", "image_info-"]
)
def test_udf_rejects_function_names_with_periods_or_hyphens(name):
with pytest.raises(ValueError, match="invalid Function name"):
@udf(name=name)
def image_info(value: int) -> int:
return value
@pytest.mark.parametrize("name", ["image_info", "ImageInfo123", "_image_info", "f"])
def test_udf_accepts_function_names_with_letters_digits_and_underscores(name):
@udf(name=name)
def image_info(value: int) -> int:
return value
assert image_info.registration_request.name == name
assert image_info(1) == 1
def test_secret_bound_udf_matches_its_shared_registration_golden():
assert analyze_caption(" hello ") == "hello"
bound = analyze_caption.bind_secrets(
@@ -273,13 +295,15 @@ class Handler(http.server.BaseHTTPRequestHandler):
self.wfile.write(payload)
server = http.server.ThreadingHTTPServer(("localhost", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(
target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True
).start()
try:
db = lancedb.connect(
"db://dev",
api_key="API_KEY_SENTINEL",
host_override="http://localhost:%d" % server.server_address[1],
host_override="http://127.0.0.1:%d" % server.server_address[1],
client_config={"retry_config": {"retries": 0}},
)
db.create_secret("openai-prod", "SECRET_VALUE_SENTINEL")
@@ -470,6 +494,30 @@ def test_udf_conda_environment():
udf(name="channels", conda_channels=["conda-forge"])(lambda value: value)
def test_udf_apt_system_packages():
@udf(pip=["torchcodec"], apt=["libavutil58", "libavcodec60", "libavutil58"])
def decode(value: float) -> float:
return value
request = json.loads(decode.registration_request.to_canonical_json())
assert request["runtime"]["environment"] == {
"kind": "pip",
"packages": ["torchcodec"],
"system_packages": ["libavcodec60", "libavutil58"],
}
@udf(conda=["numpy"], apt=["libsndfile1"])
def conda_decode(value: float) -> float:
return value
request = json.loads(conda_decode.registration_request.to_canonical_json())
assert request["runtime"]["environment"]["system_packages"] == ["libsndfile1"]
pip_request = json.loads(normalize_score.registration_request.to_canonical_json())
assert "system_packages" not in pip_request["runtime"]["environment"]
with pytest.raises(ValueError, match="trimmed"):
udf(name="padded", apt=[" libsndfile1"])(lambda value: value)
def test_udf_gpu_marker_uses_gpu_runtime():
@udf(pip=["cupy-cuda12x"], gpu=True)
def double_on_gpu(value: int) -> int:
@@ -966,6 +1014,60 @@ def test_blob_fields_use_the_scalar_function_semantic_type():
assert signature.output.arrow_type == "blob_v2"
def test_blob_input_access_is_inferred_from_annotations():
@udf
def read_blob(video: BlobReader, timestamp_s: float) -> bytes:
video.seek(int(timestamp_s))
return video.read(4)
@udf
def read_bytes(video: bytes) -> int:
return len(video)
reader = read_blob.registration_request.signature
assert reader.inputs[0].arrow_type == "blob_v2"
assert reader.inputs[0].blob_access == "reader"
assert reader.inputs[1].blob_access is None
assert reader.output.arrow_type == "binary"
eager = read_bytes.registration_request.signature.inputs[0]
assert eager.arrow_type == "binary"
assert eager.blob_access == "bytes"
encoded = json.loads(read_blob.registration_request.to_canonical_json())
assert encoded["signature"]["inputs"][0]["blob_access"] == "reader"
def test_nullable_blob_reader_and_explicit_blob_bytes():
@udf
def nullable(video: Optional[BlobReader]) -> int:
return 0 if video is None else video.size()
@udf(
input_schema=pa.schema([lancedb.blob("video", nullable=False)]),
output_schema=pa.field("size", pa.int64(), nullable=False),
)
def eager(video: bytes) -> int:
return len(video)
parameter = nullable.registration_request.signature.inputs[0]
assert parameter.nullable is True
assert parameter.blob_access == "reader"
parameter = eager.registration_request.signature.inputs[0]
assert parameter.arrow_type == "blob_v2"
assert parameter.blob_access == "bytes"
def test_blob_reader_rejects_an_incompatible_explicit_schema():
def read(video: BlobReader) -> int:
return video.size()
with pytest.raises(TypeError, match="requires a Blob V2 field"):
udf(
read,
input_schema=pa.schema([pa.field("video", pa.int64(), nullable=False)]),
output_schema=pa.field("size", pa.int64(), nullable=False),
)
def test_whole_named_struct_function_can_include_a_blob_result_field():
@udf(
input_schema=pa.schema([lancedb.blob("image", nullable=False)]),
@@ -1419,7 +1521,7 @@ def test_annotation_and_explicit_schema_validation_fail_closed():
def nullable_output(value: int) -> Optional[int]:
return value
with pytest.raises(ValueError, match="provided together"):
with pytest.raises(TypeError, match=r"missing Function annotations: \['return'\]"):
@udf(input_schema=pa.schema([pa.field("value", pa.int64())]))
def partial_schema(value):
@@ -1575,6 +1677,7 @@ def _mock_remote_function_catalog():
).read_text()
)["image"],
"signature": body["signature"],
"source_digest": body["artifact"]["digest"],
"secret_bindings": body.get("secret_bindings", []),
"created_at_millis": 1787270400000, # 2026-08-21T00:00:00Z
}
@@ -1654,11 +1757,10 @@ def _mock_remote_function_catalog():
response = {"functions": []}
self._write_response(200, response)
with http.server.HTTPServer(("localhost", 0), Handler) as server:
thread = threading.Thread(target=server.serve_forever)
thread.start()
with http.server.HTTPServer(("127.0.0.1", 0), Handler) as server:
thread = start_server_thread(server)
try:
yield f"http://localhost:{server.server_address[1]}", state
yield f"http://127.0.0.1:{server.server_address[1]}", state
finally:
server.shutdown()
thread.join()
@@ -1674,12 +1776,19 @@ def test_remote_registration_job_and_exact_version_reopen_round_trip():
)
registration = db.create_function_async(normalize_score)
assert registration.id == "job-register"
assert registration.job_type is None
assert registration.status() == "finished"
assert registration.job_type == "create_function"
created = registration.wait()
assert registration.job_type == "create_function"
reopened = db.get_function("normalize_score", version=created.version)
assert created == reopened
assert reopened.name == "normalize_score"
assert reopened.version == FUNCTION_VERSION
assert (
reopened.source_digest == normalize_score.registration_request.artifact.digest
)
create_request = state["requests"][0][1]
expected_request = json.loads(
normalize_score.registration_request.to_canonical_json()
@@ -1786,6 +1895,7 @@ def test_blocking_remote_registration_returns_function_version():
assert created.name == "normalize_score"
assert created.version == FUNCTION_VERSION
assert created.source_digest == normalize_score.registration_request.artifact.digest
assert [path for path, _ in state["requests"]] == [
"/v1/function/normalize_score/create",
"/v1/jobs/describe",
@@ -1805,6 +1915,9 @@ def test_remote_list_functions_paginates_and_returns_typed_versions():
functions = list(db.list_functions())
assert functions == [created]
assert functions[0].source_digest == (
normalize_score.registration_request.artifact.digest
)
assert state["requests"] == [
("/v1/namespace/$/function/list", {"include_definition": "true"}),
(
@@ -1829,6 +1942,9 @@ async def test_async_remote_list_functions_returns_typed_versions():
functions = [item async for item in db.list_functions()]
assert functions == [created]
assert functions[0].source_digest == (
normalize_score.registration_request.artifact.digest
)
assert [path for path, _ in state["requests"]] == [
"/v1/namespace/$/function/list",
"/v1/namespace/$/function/list",
@@ -1971,3 +2087,21 @@ def test_a_function_namespace_path_must_be_a_list_of_segments():
list(db.list_functions(namespace_path="analytics"))
assert state["requests"] == []
def test_one_explicit_schema_infers_the_other_from_annotations():
@udf(input_schema=pa.schema([pa.field("value", pa.int64())]))
def explicit_input(value) -> float:
return float(value or 0)
@udf(output_schema=pa.field("result", pa.float32(), nullable=False))
def explicit_output(value: Optional[int]):
return float(value or 0)
for fn in (explicit_input, explicit_output):
signature = fn.registration_request.signature
assert [(p.name, p.arrow_type, p.nullable) for p in signature.inputs] == [
("value", "int64", True)
]
assert explicit_input.registration_request.signature.output.arrow_type == "float64"
assert explicit_output.registration_request.signature.output.arrow_type == "float32"
+171 -1
View File
@@ -26,7 +26,9 @@ from lancedb.db import DBConnection
from lancedb.index import FTS
from lancedb.query import (
BoostQuery,
CombinedFieldsQuery,
DocumentGranularity,
FullTextOperator,
MatchQuery,
MultiMatchQuery,
PhraseQuery,
@@ -384,13 +386,27 @@ def test_custom_stop_words_list(table):
assert [token.text for token in tokens] == ["the", "data"]
empty_tokens = ldb.tokenize("the lance data", stem=False, custom_stop_words=[])
assert [token.text for token in empty_tokens] == ["the", "lance", "data"]
with pytest.raises(TypeError, match=r"custom_stop_words.*int"):
with pytest.raises(TypeError, match=r"'int' object is not an instance of 'str'"):
ldb.tokenize(
"the lance data",
custom_stop_words=["lance", 42],
)
def test_list_indices_with_missing_fts_files(table):
# Regression test for https://github.com/lancedb/lancedb/issues/4250
table.create_fts_index("text")
table.create_scalar_index("id")
fts = next(i for i in table.list_indices() if i.index_type == "FTS")
shutil.rmtree(Path(table.uri) / "_indices" / fts.index_uuid)
indices = {i.name: i for i in table.list_indices()}
assert set(indices) == {"text_idx", "id_idx"}
assert indices["text_idx"].index_type == "FTS"
assert indices["text_idx"].columns == ["text"]
def test_search_fts(table):
table.create_fts_index("text")
results = table.search("puppy").select(["id", "text"]).limit(5).to_list()
@@ -570,6 +586,52 @@ async def test_search_fts_phrase_query_async(async_table):
assert len(phrase_results) > 0
@pytest.mark.asyncio
@pytest.mark.parametrize("columns", [None, ["text"]])
async def test_phrase_query_to_query_object_async(tmp_path, columns):
db = await ldb.connect_async(tmp_path)
table = await db.create_table(
"phrases", pa.table({"text": ["puppy runs fast", "cat sleeps"]})
)
await table.create_index("text", config=FTS(with_position=True))
query = table.query().nearest_to_text('"puppy runs"', columns=columns)
phrase = query.to_query_object().full_text_query.query
expected = (
PhraseQuery("puppy runs", "text") if columns else PhraseQuery("puppy runs")
)
assert phrase == expected
results = await table.query().nearest_to_text(phrase).to_list()
assert [row["text"] for row in results] == ["puppy runs fast"]
@pytest.mark.asyncio
@pytest.mark.parametrize("column", [None, "text"])
async def test_phrase_query_object_roundtrip_async(tmp_path, column):
db = await ldb.connect_async(tmp_path)
table = await db.create_table(
"phrases",
pa.table({"text": ["puppy runs fast", "puppy often runs", "cat sleeps"]}),
)
await table.create_index("text", config=FTS(with_position=True))
phrase = PhraseQuery(
"puppy runs", column, slop=1, document_granularity=DocumentGranularity.ROW
)
query = table.query().nearest_to_text(phrase)
assert query.to_query_object().full_text_query.query == phrase
serialized = json.loads(phrase.to_json())["phrase"]
assert serialized["slop"] == 1
assert serialized["document_granularity"] == "row"
assert serialized.get("column") == column
results = await query.to_list()
assert sorted(row["text"] for row in results) == [
"puppy often runs",
"puppy runs fast",
]
def test_search_fts_specify_column(table):
table.create_fts_index("text")
table.create_fts_index("text2")
@@ -1307,6 +1369,103 @@ def test_match_query_fuzziness_search(tmp_db, options, expected):
assert sorted(row["text"] for row in results) == sorted(expected)
@pytest.mark.parametrize(
"operator,combined_ids,multi_match_ids",
[
# Combined fields treat the columns as one field, so AND also matches
# row 0, where "john" is in the title and "smith" is in the body.
(FullTextOperator.AND, {0, 1}, {1}),
(FullTextOperator.OR, {0, 1, 2}, {0, 1, 2}),
],
)
def test_combined_fields_query(mem_db, operator, combined_ids, multi_match_ids):
table = mem_db.create_table(
"people",
pa.table(
{
"id": [0, 1, 2],
"title": ["john", "john smith", "john"],
"body": ["smith", "foo", "alice"],
}
),
)
table.create_index("title", config=FTS())
table.create_index("body", config=FTS())
def ids(query):
return {row["id"] for row in table.search(query).select(["id"]).to_list()}
combined = CombinedFieldsQuery("john smith", ["title", "body"], operator=operator)
multi_match = MultiMatchQuery("john smith", ["title", "body"], operator=operator)
assert ids(combined) == combined_ids
assert ids(multi_match) == multi_match_ids
def test_combined_fields_query_boosts(mem_db):
table = mem_db.create_table(
"docs", pa.table({"title": ["hello"], "body": ["world"]})
)
table.create_index("title", config=FTS())
table.create_index("body", config=FTS())
results = table.search(
CombinedFieldsQuery("hello", ["title", "body"], boosts=[1.5, 1.0])
).to_list()
assert len(results) == 1
# Each weight must be at least 1, and there must be one per column.
with pytest.raises(ValueError, match="boost"):
table.search(
CombinedFieldsQuery("hello", ["title", "body"], boosts=[0.5, 1.0])
).to_list()
with pytest.raises(ValueError, match="boosts"):
table.search(
CombinedFieldsQuery("hello", ["title", "body"], boosts=[1.0])
).to_list()
@pytest.mark.asyncio
async def test_combined_fields_query_round_trip(mem_db_async):
table = await mem_db_async.create_table(
"docs", pa.table({"title": ["hello"], "body": ["world"]})
)
query = CombinedFieldsQuery(
"hello world",
["title", "body"],
boosts=[2.0, 1.0],
operator=FullTextOperator.AND,
)
query_obj = table.query().nearest_to_text(query).to_query_object()
assert query_obj.full_text_query.query == query
@pytest.mark.asyncio
async def test_combined_fields_query_nested_round_trip(mem_db_async):
table = await mem_db_async.create_table(
"docs", pa.table({"title": ["hello"], "body": ["world"]})
)
query = BooleanQuery(
[
(
Occur.MUST,
CombinedFieldsQuery(
"hello world",
["title", "body"],
boosts=[2.0, 1.0],
operator=FullTextOperator.AND,
),
),
(Occur.MUST_NOT, MatchQuery("draft", "body")),
]
)
query_obj = table.query().nearest_to_text(query).to_query_object()
assert query_obj.full_text_query.query == query
def test_fts_query_to_json():
"""Test that FTS query to_json() produces valid JSON strings with exact format."""
@@ -1444,6 +1603,17 @@ def test_fts_query_to_json():
)
assert json_str == expected
# Test CombinedFieldsQuery
combined_fields = CombinedFieldsQuery(
"python", ["tags", "title"], boosts=[2.0, 1.0], operator=FullTextOperator.AND
)
json_str = combined_fields.to_json()
expected = (
'{"combined_fields":{"query":"python","columns":["tags","title"],'
'"boost":[2.0,1.0],"operator":"And"}}'
)
assert json_str == expected
# Test complex nested BooleanQuery
inner1 = BooleanQuery(
[
+132 -1
View File
@@ -11,9 +11,10 @@ import json
import subprocess
import sys
import textwrap
import types
import warnings
from pathlib import Path
from typing import Annotated, Optional
from typing import Annotated, Optional, get_type_hints
import pyarrow as pa
import pytest
@@ -126,6 +127,136 @@ def test_function_without_initialization_keeps_its_wire_form():
assert request["artifact"]["kind"] == "python_callable"
@pytest.mark.parametrize("annotation", ["Array", "RecordBatch"])
@pytest.mark.parametrize("kind", ["function", "class"])
def test_batch_annotations_require_explicit_schemas(annotation, kind, helper_package):
if kind == "class":
source = f"""
import pyarrow as pa
class identity:
def __call__(self, value: pa.{annotation}) -> pa.{annotation}:
return value
"""
else:
source = f"""
import pyarrow as pa
def identity(value: pa.{annotation}) -> pa.{annotation}:
return value
"""
module = helper_package("fx_batch_annotations", {"__init__.py": source})
with pytest.raises(TypeError, match="input_schema and output_schema"):
udf(module.identity)
def test_array_batch_annotations_accept_explicit_schemas():
@udf(
input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]),
output_schema=pa.int64(),
)
def identity(value: pa.Array) -> pa.Array:
return value
signature = identity.registration_request.signature
assert [(p.name, p.arrow_type, p.nullable) for p in signature.inputs] == [
("value", "int64", False)
]
assert signature.output.arrow_type == "int64"
assert signature.output.nullable is False
values = pa.array([1, 2, 3])
assert identity(values).equals(values)
@pytest.mark.parametrize("class_udf", [False, True])
@pytest.mark.parametrize("postponed", [False, True])
@pytest.mark.parametrize(
("annotation", "nullable"),
[
("BlobReader", False),
("Reader", False),
('"Reader"', False),
("Reader | None", True),
("Optional[Reader]", True),
('Optional["Reader"]', True),
("MaybeReader", True),
("lancedb.BlobReader", False),
("lancedb.BlobReader | None", True),
],
)
def test_blob_reader_annotations_resolve_in_the_artifact(
helper_package, monkeypatch, class_udf, postponed, annotation, nullable
):
definition = (
f"class read_blob:\n"
f" def __call__(self, video: {annotation}) -> int:\n"
f" return 0\n"
if class_udf
else f"def read_blob(video: {annotation}) -> int:\n return 0\n"
)
module = helper_package(
"fx_blob_annotations",
{
"__init__.py": (
("from __future__ import annotations\n" if postponed else "")
+ "import lancedb\n"
"from typing import Optional\n"
"from lancedb import BlobReader, BlobReader as Reader\n"
"from lancedb.functions import udf\n"
"MaybeReader = Optional[Reader]\n\n"
f"@udf\n{definition}"
)
},
)
request = module.read_blob.registration_request
parameter = request.signature.inputs[0]
assert parameter.arrow_type == "blob_v2"
assert parameter.blob_access == "reader"
assert parameter.nullable is nullable
# Workers provide lance_blob rather than importing the client SDK's reader.
worker = types.ModuleType("lance_blob")
worker.BlobReader = type("BlobReader", (), {})
monkeypatch.setitem(sys.modules, "lance_blob", worker)
namespace = {}
exec(compile(artifact(module.read_blob), "user_function.py", "exec"), namespace)
packaged = namespace["read_blob"]
if class_udf:
packaged = packaged.__call__
assert get_type_hints(packaged) == {
"video": Optional[worker.BlobReader] if nullable else worker.BlobReader,
"return": int,
}
def test_blob_reader_annotation_does_not_shadow_body_globals(
helper_package, monkeypatch
):
module = helper_package(
"fx_blob_annotation_globals",
{
"__init__.py": """
from lancedb import BlobReader
from lancedb.functions import udf
_lance_blob_reader = 7
@udf
def read_blob(video: BlobReader) -> int:
return _lance_blob_reader
"""
},
)
worker = types.ModuleType("lance_blob")
worker.BlobReader = type("BlobReader", (), {})
monkeypatch.setitem(sys.modules, "lance_blob", worker)
namespace = {}
exec(compile(artifact(module.read_blob), "user_function.py", "exec"), namespace)
packaged = namespace["read_blob"]
assert get_type_hints(packaged)["video"] is worker.BlobReader
assert packaged(worker.BlobReader()) == 7
@pytest.mark.parametrize(
("init", "message"),
[
@@ -114,6 +114,30 @@ class TestOAuthProvider:
"x-lancedb-credential-type": "oidc",
}
def test_zero_lifetime_token_is_refreshed(self):
"""A token that expires immediately must not be cached indefinitely."""
call_count = 0
def fetcher():
nonlocal call_count
call_count += 1
return {
"access_token": f"token{call_count}",
"expires_in": 0,
}
provider = OAuthProvider(fetcher, refresh_buffer_seconds=0)
assert provider.get_headers() == {
"Authorization": "Bearer token1",
"x-lancedb-credential-type": "oidc",
}
assert provider.get_headers() == {
"Authorization": "Bearer token2",
"x-lancedb-credential-type": "oidc",
}
assert call_count == 2
def test_missing_access_token(self):
"""Test error handling when access_token is missing."""
+103
View File
@@ -129,3 +129,106 @@ def test_generator(tmp_path: Path):
assert len(tbl) == 2
assert tbl.schema == ds.features.arrow_schema
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize("operation", ["create", "add"])
@pytest.mark.parametrize(
"selection",
["normal", "contiguous", "selected", "duplicates", "filtered", "shuffled", "empty"],
)
async def test_write_selected_hf_dataset(tmp_path, asynchronous, operation, selection):
source = datasets.Dataset.from_dict({"id": list(range(5)), "text": list("abcde")})
data = {
"normal": source,
"contiguous": source.select(range(1, 4)),
"selected": source.select([4, 1]),
"duplicates": source.select([2, 2, 0]),
"filtered": source.filter(lambda row: row["id"] % 2 == 1),
"shuffled": source.shuffle(seed=42),
"empty": source.select([]),
}[selection]
expected = data.to_list()
if asynchronous:
db = await lancedb.connect_async(tmp_path)
if operation == "create":
table = await db.create_table("selected", data)
else:
table = await db.create_table("selected", schema=data.features.arrow_schema)
await table.add(data)
actual = await table.to_arrow()
else:
db = lancedb.connect(tmp_path)
if operation == "create":
table = db.create_table("selected", data)
else:
table = db.create_table("selected", schema=data.features.arrow_schema)
table.add(data)
actual = table.to_arrow()
assert actual.to_pylist() == expected
assert actual.schema.equals(data.features.arrow_schema, check_metadata=True)
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize("operation", ["create", "add"])
async def test_write_selected_hf_splits(tmp_path, asynchronous, operation):
source = datasets.Dataset.from_dict({"id": list(range(5)), "text": list("abcde")})
data = datasets.DatasetDict(
{
"train": source.select([4, 1]),
"test": source.select([3, 0, 2]),
"empty": source.select([]),
}
)
expected = [
dict(row, split=split)
for split, dataset in data.items()
for row in dataset.to_list()
]
schema = source.features.arrow_schema.append(pa.field("split", pa.string()))
if asynchronous:
db = await lancedb.connect_async(tmp_path)
if operation == "create":
table = await db.create_table("splits", data)
else:
table = await db.create_table("splits", schema=schema)
await table.add(data)
actual = await table.to_arrow()
else:
db = lancedb.connect(tmp_path)
if operation == "create":
table = db.create_table("splits", data)
else:
table = db.create_table("splits", schema=schema)
table.add(data)
actual = table.to_arrow()
assert actual.to_pylist() == expected
assert actual.schema.equals(schema, check_metadata=True)
@pytest.mark.parametrize("format_type", [None, "numpy", "pandas", "arrow"])
@pytest.mark.parametrize("empty", [False, True])
def test_selected_hf_reader_is_rescannable(format_type, empty):
from lancedb.scannable import _register_optional_converters, to_scannable
source = datasets.Dataset.from_dict(
{"id": list(range(2105)), "text": [str(i) for i in range(2105)]}
)
indices = [] if empty else list(reversed(range(2105))) + [1, 1]
data = source.select(indices).with_format(format_type, columns=["id"])
original_format = data.format
expected = source.select(indices).to_list()
_register_optional_converters()
scannable = to_scannable(data)
assert scannable.rescannable
assert scannable.num_rows == len(expected)
for _ in range(2):
batches = list(scannable.reader())
if not empty:
assert all(batch.num_rows <= 1000 for batch in batches)
actual = pa.Table.from_batches(batches, schema=scannable.schema)
assert actual.to_pylist() == expected
assert actual.schema.equals(data.features.arrow_schema, check_metadata=True)
assert data.format == original_format
+54 -2
View File
@@ -315,13 +315,53 @@ def test_hybrid_query_offset(sync_table: Table):
assert offset_result["_rowid"].to_pylist() == full["_rowid"].to_pylist()[2:]
@pytest.mark.parametrize(
"query_vector",
[
pytest.param((0.0, 0.4), id="tuple"),
pytest.param(pa.array([0.0, 0.4], type=pa.float32()), id="pa-array"),
pytest.param(
pa.chunked_array([[0.0], [0.4]], type=pa.float32()), id="pa-chunked-array"
),
],
)
def test_hybrid_query_accepts_every_vector_container(sync_table: Table, query_vector):
# Vector search and the async hybrid API both accept tuples and pyarrow
# arrays for the query vector (``VEC`` in ``lancedb/common.py``), so the
# sync hybrid builder must accept them too.
expected = (
sync_table.search(query_type="hybrid")
.vector([0.0, 0.4])
.text("dog")
.limit(2)
.with_row_id(True)
.to_arrow()
)
result = (
sync_table.search(query_type="hybrid")
.vector(query_vector)
.text("dog")
.limit(2)
.with_row_id(True)
.to_arrow()
)
assert result["_rowid"].to_pylist() == expected["_rowid"].to_pylist()
def test_hybrid_query_default_limit(sync_table: Table):
# The vector and FTS legs match disjoint rows, so fusing their results
# yields more rows than the default limit.
new_rows = []
# Distinct distances and document lengths avoid ties in either leg,
# so comparing offset windows does not depend on tie ordering.
for i in range(20):
new_rows.append({"text": "close_vec", "vector": [0.1, 0.1]})
new_rows.append({"text": "dog", "vector": [50.0 + i, 50.0 + i]})
coordinate = 0.11 + i * 0.001
new_rows.append({"text": "close_vec", "vector": [coordinate, coordinate]})
new_rows.append(
{"text": "dog " + "padding " * (i + 1), "vector": [50.0 + i, 50.0 + i]}
)
sync_table.add(new_rows)
def query():
@@ -536,3 +576,15 @@ def test_normalize_scores():
assert pc.equal(result, expected), (
f"Expected {expected} but got {result} for invert={invert}"
)
def test_hybrid_query_rejects_query_with_vector(sync_table: Table):
# Pins the full message: the space between "hybrid search." and "But" is
# load-bearing (see the _validate_query literal concatenation).
with pytest.raises(ValueError) as excinfo:
sync_table.search("dog", query_type="hybrid").vector([0.5, -0.5]).to_arrow()
assert str(excinfo.value) == (
"You can either provide a string query in search() method "
"or set `vector()` and `text()` explicitly for hybrid search. "
"But not both."
)
+34
View File
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import os
import re
import shutil
import subprocess
@@ -31,3 +32,36 @@ def test_native_extension_does_not_link_openssl():
"the LanceDB native extension must use rustls instead of linking OpenSSL: "
f"{openssl_libraries}"
)
def test_top_level_version_comes_from_native_module():
child_code = """
import importlib.metadata
orig_version = importlib.metadata.version
def fail_version_lookup(_: str) -> str:
if _ in {"lancedb", "lancedb-compat"}:
raise AssertionError("lancedb import should not query distribution metadata")
return orig_version(_)
importlib.metadata.version = fail_version_lookup
import lancedb
import lancedb._lancedb as native_module
import lancedb.db
assert lancedb.__version__ == native_module.__version__
"""
env = os.environ.copy()
env["PYTHONPATH"] = os.pathsep.join(path for path in sys.path if path)
result = subprocess.run(
[sys.executable, "-c", child_code],
check=False,
capture_output=True,
text=True,
env=env,
)
assert result.returncode == 0, result.stderr or result.stdout
+36 -2
View File
@@ -364,6 +364,8 @@ async def test_create_vector_index(some_table: AsyncTable):
assert indices[0].columns == ["vector"]
assert indices[0].name == "vector_idx"
await some_table.prewarm_index(indices[0].name)
stats = await some_table.index_stats("vector_idx")
assert stats.index_type == "IVF_PQ"
assert stats.distance_type == "l2"
@@ -421,13 +423,45 @@ async def test_create_4bit_ivfpq_index(some_table: AsyncTable):
@pytest.mark.asyncio
async def test_create_ivfrq_index(some_table: AsyncTable):
await some_table.create_index("vector", config=IvfRq(num_bits=1))
@pytest.mark.parametrize(
"config, expected_bits",
[
pytest.param(IvfRq(), 5, id="default"),
pytest.param(IvfRq(num_bits=None), 5, id="none"),
pytest.param(IvfRq(num_bits=1), 1, id="one-bit"),
pytest.param(IvfRq(num_bits=4), 4, id="multi-bit"),
],
)
async def test_create_ivfrq_index(some_table: AsyncTable, config, expected_bits):
await some_table.create_index("vector", config=config)
indices = await some_table.list_indices()
assert len(indices) == 1
assert indices[0].index_type == "IvfRq"
assert indices[0].columns == ["vector"]
assert indices[0].name == "vector_idx"
assert indices[0].index_details["compression"]["num_bits"] == expected_bits
@pytest.mark.asyncio
async def test_read_ivfrq_index_created_with_lance(db_async, some_table: AsyncTable):
pytest.importorskip("lance")
dataset = await some_table.to_lance()
dataset.create_index(
"vector",
index_type="IVF_RQ",
metric="cosine",
num_partitions=1,
)
# Open a fresh LanceDB handle so the index is discovered from disk.
table = await db_async.open_table("some_table")
indices = await table.list_indices()
assert len(indices) == 1
assert indices[0].index_type == "IvfRq"
assert indices[0].columns == ["vector"]
results = await table.query().nearest_to(list(range(DIM))).limit(8).to_arrow()
assert len(results) == 8
@pytest.mark.asyncio
+143 -9
View File
@@ -5,12 +5,12 @@ import asyncio
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
from pathlib import Path
from threading import Thread
from urllib.parse import parse_qs, urlsplit
import lancedb
from lancedb.remote.errors import HttpError
import pytest
from utils import start_server_thread
@pytest.fixture
@@ -31,8 +31,7 @@ def listing_server():
do_POST = handle_request
with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
thread = Thread(target=server.serve_forever, daemon=True)
thread.start()
thread = start_server_thread(server, daemon=True)
try:
yield f"http://127.0.0.1:{server.server_port}", requests, responses
finally:
@@ -66,7 +65,7 @@ def response_page(kind, names, token):
]
else:
items = names
key = "views" if kind == "materialized_views" else kind
key = kind
return {key: items, "page_token": token}
@@ -85,7 +84,144 @@ async def advance(items, asynchronous):
return await items.__anext__() if asynchronous else next(items)
KINDS = ["secrets", "views", "jobs", "functions", "materialized_views"]
KINDS = ["secrets", "views", "jobs", "functions"]
@pytest.mark.asyncio
@pytest.mark.parametrize("kind", ["tables", "namespaces"])
@pytest.mark.parametrize("asynchronous", [False, True])
async def test_compatible_name_listing_pages(listing_server, kind, asynchronous):
endpoint, requests, responses = listing_server
responses.extend(
[
(200, response_page(kind, ["a", "b"], "next")),
(200, response_page(kind, ["c"], None)),
]
)
db = await connection(endpoint, asynchronous)
listing = getattr(db, "list_" + kind)(
namespace_path=["team"], page_token="start", limit=2
)
field = kind
assert len(requests) == (0 if asynchronous else 1)
if asynchronous:
with pytest.raises(RuntimeError, match="Await or iterate"):
getattr(listing, field)
assert listing.page_token == "start"
assert await listing is listing
assert len(requests) == 1
page_names = getattr(listing, field)
assert type(page_names) is list
assert page_names == ["a", "b"]
page_names.append("changed")
assert getattr(listing, field) == ["a", "b"]
assert listing.page_token == "next"
assert listing.num_page_results() == 2
assert await advance(listing, asynchronous) == "a"
assert getattr(listing, field) == ["a", "b"]
assert await advance(listing, asynchronous) == "b"
assert len(requests) == 1
assert await advance(listing, asynchronous) == "c"
assert getattr(listing, field) == ["c"]
assert listing.page_token is None
assert len(requests) == 2
assert ([item async for item in listing] if asynchronous else list(listing)) == []
if asynchronous:
assert await listing is listing
assert len(requests) == 2
@pytest.mark.asyncio
@pytest.mark.parametrize("kind", ["tables", "namespaces"])
async def test_name_listing_skips_empty_page_only_during_iteration(
listing_server, kind
):
endpoint, requests, responses = listing_server
responses.extend(
[
(200, response_page(kind, [], "next")),
(200, response_page(kind, ["a"], None)),
]
)
db = await connection(endpoint, True)
listing = getattr(db, "list_" + kind)()
await listing
assert getattr(listing, kind) == []
assert listing.page_token == "next"
assert len(requests) == 1
assert [name async for name in listing] == ["a"]
assert len(requests) == 2
@pytest.mark.asyncio
@pytest.mark.parametrize("kind", ["tables", "namespaces"])
@pytest.mark.parametrize("asynchronous", [False, True])
async def test_name_listing_zero_limit_uses_no_request(
listing_server, kind, asynchronous
):
endpoint, requests, _ = listing_server
db = await connection(endpoint, asynchronous)
listing = getattr(db, "list_" + kind)(limit=0)
if asynchronous:
assert await listing is listing
assert [name async for name in listing] == []
else:
assert list(listing) == []
assert getattr(listing, kind) == []
assert listing.page_token is None
assert requests == []
@pytest.mark.asyncio
@pytest.mark.parametrize("kind", ["tables", "namespaces"])
async def test_name_listing_failure_retains_token(listing_server, kind):
endpoint, requests, responses = listing_server
responses.append((401, {}))
db = await connection(endpoint, True)
listing = getattr(db, "list_" + kind)(page_token="retry")
with pytest.raises(HttpError):
await listing
assert listing.page_token == "retry"
with pytest.raises(HttpError):
await listing
assert [name async for name in listing] == []
assert len(requests) == 1
@pytest.mark.asyncio
@pytest.mark.parametrize("kind", ["tables", "namespaces"])
async def test_name_listing_direct_async_iteration(listing_server, kind):
endpoint, requests, responses = listing_server
responses.extend(
[
(200, response_page(kind, ["a"], "next")),
(200, response_page(kind, ["b"], None)),
]
)
db = await connection(endpoint, True)
listing = getattr(db, "list_" + kind)(limit=1)
assert requests == []
assert [name async for name in listing] == ["a", "b"]
assert getattr(listing, kind) == ["b"]
assert len(requests) == 2
@pytest.mark.asyncio
@pytest.mark.parametrize("kind", ["tables", "namespaces"])
async def test_name_listing_serializes_concurrent_advances(listing_server, kind):
endpoint, requests, responses = listing_server
responses.append((200, response_page(kind, ["a", "b"], None)))
db = await connection(endpoint, True)
listing = getattr(db, "list_" + kind)()
results = await asyncio.gather(
listing.__anext__(),
listing.__anext__(),
listing.__anext__(),
return_exceptions=True,
)
assert results[:2] == ["a", "b"]
assert isinstance(results[2], StopAsyncIteration)
assert len(requests) == 1
@pytest.mark.asyncio
@@ -99,9 +235,7 @@ async def test_listing_lazy_pages_and_resume(listing_server, kind, asynchronous)
)
db = await connection(endpoint, asynchronous)
method = getattr(db, "list_" + kind)
kwargs = (
{} if kind in ("jobs", "materialized_views") else {"namespace_path": ["team"]}
)
kwargs = {} if kind == "jobs" else {"namespace_path": ["team"]}
items = method(page_token="start/token", page_limit=2, **kwargs)
assert requests == []
assert items.page_token() == "start/token"
@@ -136,7 +270,7 @@ async def test_listing_lazy_pages_and_resume(listing_server, kind, asynchronous)
assert path.path == "/v1/jobs/list"
assert body == {"page_token": token, "limit": 2}
else:
namespace = "$" if kind == "materialized_views" else "team"
namespace = "team"
resource = kind.removesuffix("s")
assert path.path == f"/v1/namespace/{namespace}/{resource}/list"
expected = {"page_token": [token], "limit": ["2"]}
+270 -61
View File
@@ -1,15 +1,18 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import contextlib
import http.server
import json
import threading
import lancedb
import pytest
import pyarrow as pa
from lancedb.db import AsyncConnection
from lancedb.materialized_view import MaterializedViewDefinition
from lancedb.remote.db import RemoteDBConnection
from utils import start_server_thread
STABLE_ROW_IDS = {"new_table_enable_stable_row_ids": "true"}
@@ -29,34 +32,7 @@ def make_db(tmp_path):
@contextlib.contextmanager
def mock_remote_materialized_views():
requests = []
class Handler(http.server.BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def do_GET(self):
requests.append(self.path)
encoded = json.dumps({"views": ["daily_sales"]}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(encoded)))
self.end_headers()
self.wfile.write(encoded)
with http.server.HTTPServer(("localhost", 0), Handler) as server:
thread = threading.Thread(target=server.serve_forever)
thread.start()
try:
yield f"http://localhost:{server.server_address[1]}", requests
finally:
server.shutdown()
thread.join()
@contextlib.contextmanager
def mock_remote_materialized_view_create():
def mock_remote_materialized_view_refresh():
requests = []
class Handler(http.server.BaseHTTPRequestHandler):
@@ -64,50 +40,108 @@ def mock_remote_materialized_view_create():
pass
def do_POST(self):
length = int(self.headers.get("Content-Length", 0))
body = json.loads(self.rfile.read(length) or b"{}")
requests.append((self.path, body))
job_id = "mv-drop-123" if self.path.endswith("/drop") else "mv-create-123"
encoded = json.dumps({"job_id": job_id}).encode()
self.send_response(202)
requests.append(self.path)
assert self.path == "/v1/table/view/describe/"
response = {"version": 42, "schema": {"fields": []}}
encoded = json.dumps(response).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(encoded)))
self.end_headers()
self.wfile.write(encoded)
with http.server.HTTPServer(("localhost", 0), Handler) as server:
thread = threading.Thread(target=server.serve_forever)
thread.start()
with http.server.HTTPServer(("127.0.0.1", 0), Handler) as server:
thread = start_server_thread(server)
try:
yield f"http://localhost:{server.server_address[1]}", requests
yield f"http://127.0.0.1:{server.server_address[1]}", requests
finally:
server.shutdown()
thread.join()
def test_remote_list_uses_namespace_route():
with mock_remote_materialized_views() as (host, requests):
db = lancedb.connect(
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [False, True])
@pytest.mark.parametrize("background", [False, True])
@pytest.mark.parametrize("full", [False, True])
async def test_remote_refresh_reports_unknown_metrics(sync, background, full):
flight = pytest.importorskip("pyarrow.flight")
class RefreshServer(flight.FlightServerBase):
def __init__(self):
super().__init__("grpc://127.0.0.1:0")
self.commands = []
def do_get(self, context, ticket):
self.commands.append(ticket.ticket)
if b"DESCRIBE MATERIALIZED VIEW" in ticket.ticket:
return flight.RecordBatchStream(
pa.table(
{
"name": ["view"],
"query": ["SELECT * FROM source"],
}
)
)
assert b"REFRESH MATERIALIZED VIEW" in ticket.ticket
# SQL completion carries no refresh statistics.
return flight.RecordBatchStream(pa.table({"status": ["ok"]}))
with (
mock_remote_materialized_view_refresh() as (host, requests),
RefreshServer() as server,
):
options = {"full": True} if full else {}
connect = lancedb.connect if sync else lancedb.connect_async
db = connect(
"db://dev",
api_key="fake",
host_override=host,
sql_host_override=f"grpc://127.0.0.1:{server.port}",
client_config={"retry_config": {"retries": 0}},
)
assert list(db.list_materialized_views()) == ["daily_sales"]
assert requests == ["/v1/namespace/$/materialized_view/list"]
if sync:
view = db.open_materialized_view("view")
result = (
view.refresh_async(**options).wait()
if background
else view.refresh(**options)
)
else:
db = await db
view = await db.open_materialized_view("view")
if background:
job = await view.refresh_async(**options)
result = await job.wait()
else:
result = await view.refresh(**options)
def test_remote_drop_async_returns_server_job():
with mock_remote_materialized_view_create() as (host, requests):
db = lancedb.connect(
"db://dev",
api_key="fake",
host_override=host,
client_config={"retry_config": {"retries": 0}},
assert result.mode is None
assert result.rows_written is None
assert result.source_version is None
assert result.version == 42
assert repr(result) == (
"RefreshMaterializedViewResult(mode=None, rows_written=None, "
"source_version=None, version=42)"
)
job = db.drop_materialized_view_async("adults")
assert job.id == "mv-drop-123"
assert requests == [("/v1/materialized_view/adults/drop", {})]
describes = [
command
for command in server.commands
if b"DESCRIBE MATERIALIZED VIEW" in command
]
refreshes = [
command
for command in server.commands
if b"REFRESH MATERIALIZED VIEW" in command
]
assert len(describes) == 2
assert len(refreshes) == 1
assert all(
b'DESCRIBE MATERIALIZED VIEW "view"' in command for command in describes
)
(refresh,) = refreshes
assert b'REFRESH MATERIALIZED VIEW "view"' in refresh
assert (b"WITH (full = true)" in refresh) is full
assert not any("count_rows" in path for path in requests)
def test_sync_remote_create_uses_public_async_connection():
@@ -129,8 +163,21 @@ def test_sync_remote_create_uses_public_async_connection():
where=None,
limit=None,
with_no_data=False,
auto_refresh_enabled=None,
auto_refresh_interval_seconds=None,
):
calls.append((name, source, select, where, limit, with_no_data))
calls.append(
(
name,
source,
select,
where,
limit,
with_no_data,
auto_refresh_enabled,
auto_refresh_interval_seconds,
)
)
return StubAsyncMaterializedView()
async def drop_materialized_view(self, name, *, namespace_path=None):
@@ -148,14 +195,17 @@ def test_sync_remote_create_uses_public_async_connection():
where="age >= 18",
limit=10,
with_no_data=True,
auto_refresh_enabled=True,
auto_refresh_interval_seconds=0.5,
)
assert view.name == "adults"
assert calls == [("adults", "people", ["name"], "age >= 18", 10, True)]
assert calls == [("adults", "people", ["name"], "age >= 18", 10, True, True, 0.5)]
db.drop_materialized_view("adults", namespace_path=["analytics"])
assert calls[-1] == ("drop", "adults", ["analytics"])
@pytest.mark.experimental_functions
def test_create_refresh_and_query(tmp_path):
db = make_db(tmp_path)
view = db.create_materialized_view(
@@ -171,17 +221,20 @@ def test_create_refresh_and_query(tmp_path):
assert sorted(row["shout"] for row in rows) == ["ADA", "GRACE"]
@pytest.mark.experimental_functions
def test_create_and_refresh_jobs(tmp_path):
db = make_db(tmp_path)
create_job = db.create_materialized_view_async(
"adults", "people", where="age >= 18", with_no_data=True
)
assert create_job.id is None
assert create_job.job_type is None
assert create_job.wait() is None
view = db.open_materialized_view("adults")
refresh_job = view.refresh_async()
assert refresh_job.id is None
assert refresh_job.job_type is None
result = refresh_job.wait()
assert result.mode == "rebuild"
assert result.rows_written == 2
@@ -193,6 +246,7 @@ def test_create_and_refresh_jobs(tmp_path):
assert "adults" not in list(db.list_materialized_views())
@pytest.mark.experimental_functions
def test_definition_round_trips(tmp_path):
db = make_db(tmp_path)
db.create_materialized_view("adults", "people", where="age >= 18")
@@ -203,20 +257,39 @@ def test_definition_round_trips(tmp_path):
)
def test_full_refresh_after_append(tmp_path):
@pytest.mark.experimental_functions
@pytest.mark.parametrize("full", [False, True])
def test_full_refresh_after_append(tmp_path, full):
db = make_db(tmp_path)
view = db.create_materialized_view("copy", "people", with_no_data=True)
view.refresh()
db.open_table("people").add([{"name": "alan", "age": 41}])
result = view.refresh()
result = view.refresh(full=full)
assert result.mode == "rebuild"
assert result.rows_written == 4
assert result.source_version == db.open_table("people").version
assert view.table.count_rows() == 4
assert view.refresh().mode == "rebuild"
@pytest.mark.experimental_functions
def test_full_refresh_can_pin_local_source_version(tmp_path):
db = make_db(tmp_path)
source = db.open_table("people")
version = source.version
view = db.create_materialized_view("copy", "people", with_no_data=True)
source.add([{"name": "alan", "age": 41}])
result = view.refresh(full=True, source_version=version)
assert result.mode == "rebuild"
assert result.rows_written == 3
assert result.source_version == version
assert view.table.count_rows() == 3
@pytest.mark.experimental_functions
def test_full_refresh_after_update(tmp_path):
db = make_db(tmp_path)
view = db.create_materialized_view("copy", "people", with_no_data=True)
@@ -230,6 +303,7 @@ def test_full_refresh_after_update(tmp_path):
assert sorted(row["age"] for row in rows) == [8, 36, 85]
@pytest.mark.experimental_functions
def test_legacy_storage_source_update_rebuilds(tmp_path):
db = lancedb.connect(
tmp_path,
@@ -246,6 +320,7 @@ def test_legacy_storage_source_update_rebuilds(tmp_path):
assert sorted(row["age"] for row in rows) == [8, 36]
@pytest.mark.experimental_functions
def test_direct_writes_to_a_view_are_refused(tmp_path):
db = make_db(tmp_path)
view = db.create_materialized_view("copy", "people")
@@ -271,6 +346,7 @@ def test_direct_writes_to_a_view_are_refused(tmp_path):
assert view.refresh().rows_written == 4
@pytest.mark.experimental_functions
def test_list_and_not_a_view(tmp_path):
db = make_db(tmp_path)
db.create_materialized_view("adults", "people", where="age >= 18")
@@ -285,6 +361,7 @@ def test_list_and_not_a_view(tmp_path):
assert list(db.list_materialized_views()) == []
@pytest.mark.experimental_functions
def test_invalid_expression_fails_at_create(tmp_path):
db = make_db(tmp_path)
with pytest.raises(Exception, match="missing"):
@@ -292,6 +369,7 @@ def test_invalid_expression_fails_at_create(tmp_path):
assert "bad" not in db.list_tables().tables
@pytest.mark.experimental_functions
@pytest.mark.asyncio
async def test_async_create_refresh_and_open(tmp_path):
db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS)
@@ -313,6 +391,7 @@ async def test_async_create_refresh_and_open(tmp_path):
assert [item async for item in db.list_materialized_views()] == ["shouts"]
@pytest.mark.experimental_functions
@pytest.mark.asyncio
async def test_async_create_and_refresh_jobs(tmp_path):
db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS)
@@ -322,11 +401,13 @@ async def test_async_create_and_refresh_jobs(tmp_path):
"adults", "people", with_no_data=True
)
assert create_job.id is None
assert create_job.job_type is None
assert await create_job.wait() is None
view = await db.open_materialized_view("adults")
refresh_job = await view.refresh_async()
assert refresh_job.id is None
assert refresh_job.job_type is None
result = await refresh_job.wait()
assert result.mode == "rebuild"
assert result.rows_written == 1
@@ -337,6 +418,7 @@ async def test_async_create_and_refresh_jobs(tmp_path):
assert "adults" not in [item async for item in db.list_materialized_views()]
@pytest.mark.experimental_functions
@pytest.mark.asyncio
async def test_async_refresh_rebuilds(tmp_path):
db = await lancedb.connect_async(tmp_path)
@@ -351,6 +433,7 @@ async def test_async_refresh_rebuilds(tmp_path):
assert result.rows_written == 2
@pytest.mark.experimental_functions
def test_source_does_not_require_stable_row_ids(tmp_path):
db = lancedb.connect(tmp_path)
db.create_table("plain", [{"x": 1}])
@@ -358,6 +441,7 @@ def test_source_does_not_require_stable_row_ids(tmp_path):
assert view.table.count_rows() == 1
@pytest.mark.experimental_functions
def test_bare_select_names_are_quoted(tmp_path):
db = lancedb.connect(tmp_path, storage_options=STABLE_ROW_IDS)
db.create_table("odd_names", [{"order item": "widget", "select": 2}])
@@ -375,6 +459,7 @@ def test_bare_select_names_are_quoted(tmp_path):
assert rows[0]["select"] == 2
@pytest.mark.experimental_functions
def test_scalar_select_is_one_column(tmp_path):
db = make_db(tmp_path)
view = db.create_materialized_view("just_name", "people", select="name")
@@ -384,6 +469,7 @@ def test_scalar_select_is_one_column(tmp_path):
assert sorted(row["name"] for row in rows) == ["ada", "grace", "kid"]
@pytest.mark.experimental_functions
@pytest.mark.asyncio
async def test_async_scalar_select_is_one_column(tmp_path):
db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS)
@@ -394,6 +480,7 @@ async def test_async_scalar_select_is_one_column(tmp_path):
assert set(rows[0]) == {"name"}
@pytest.mark.experimental_functions
def test_limit_above_i64_max_is_refused(tmp_path):
db = make_db(tmp_path)
with pytest.raises(ValueError, match="exceeds the maximum"):
@@ -413,6 +500,7 @@ def _namespace_db(tmp_path):
)
@pytest.mark.experimental_functions
def test_namespace_connection_materialized_views(tmp_path):
db = _namespace_db(tmp_path)
db.create_table(
@@ -443,6 +531,7 @@ def test_namespace_connection_materialized_views(tmp_path):
assert list(db.list_materialized_views()) == []
@pytest.mark.experimental_functions
@pytest.mark.asyncio
async def test_async_namespace_connection_materialized_views(tmp_path):
db = lancedb.connect_namespace_async(
@@ -489,8 +578,6 @@ async def test_async_namespace_connection_materialized_views(tmp_path):
def test_stored_queries_and_legacy_layouts_are_read():
import json
import pyarrow as pa
from lancedb.materialized_view import _definition_from_schema
@@ -536,6 +623,7 @@ def test_stored_queries_and_legacy_layouts_are_read():
read(newer)
@pytest.mark.experimental_functions
def test_local_materialized_view_listing_pages_and_resume(tmp_path):
db = make_db(tmp_path)
db.create_materialized_view("a_view", "people", with_no_data=True)
@@ -550,3 +638,124 @@ def test_local_materialized_view_listing_pages_and_resume(tmp_path):
assert sorted([first, *resumed]) == ["a_view", "z_view"]
assert resumed.page_token() is None
assert list(resumed) == []
class QueryBackedCreateJob:
id = "0198f1b2-c3d4-7e5f-8123-456789abcdef"
job_type = "query"
async def wait(self):
return None
async def status(self):
return "finished"
class CapturingCreateConnection:
def __init__(self):
self.calls = []
async def create_materialized_view_async(self, name, source, **options):
self.calls.append((name, source, options))
return QueryBackedCreateJob()
@pytest.mark.parametrize(
"options",
[
{},
{"auto_refresh_enabled": True},
{"auto_refresh_enabled": False, "auto_refresh_interval_seconds": 0.5},
],
)
def test_remote_create_forwards_refresh_options_without_interval_default(options):
native = CapturingCreateConnection()
db = RemoteDBConnection.__new__(RemoteDBConnection)
db._conn = AsyncConnection(native)
job = db.create_materialized_view_async("adults", "people", **options)
assert job.id == QueryBackedCreateJob.id
assert job.job_type == "query"
assert not hasattr(job, "query_id")
assert job.wait() is None
assert job.status() == "finished"
assert native.calls == [
(
"adults",
"people",
{
"projections": None,
"filter": None,
"limit": None,
"with_no_data": False,
"auto_refresh_enabled": options.get("auto_refresh_enabled"),
"auto_refresh_interval_seconds": options.get(
"auto_refresh_interval_seconds"
),
},
)
]
@pytest.mark.asyncio
async def test_async_remote_create_keeps_interval_unspecified():
native = CapturingCreateConnection()
db = AsyncConnection(native)
job = await db.create_materialized_view_async(
"adults", "people", auto_refresh_enabled=True
)
assert job.id == QueryBackedCreateJob.id
assert job.job_type == "query"
assert not hasattr(job, "query_id")
assert await job.wait() is None
assert await job.status() == "finished"
assert native.calls[0][2]["auto_refresh_enabled"] is True
assert native.calls[0][2]["auto_refresh_interval_seconds"] is None
@pytest.mark.experimental_functions
@pytest.mark.parametrize(
"options",
[
{"auto_refresh_enabled": True},
{"auto_refresh_interval_seconds": 300},
],
)
def test_embedded_create_refuses_automatic_refresh_before_creating_view(
tmp_path, options
):
db = make_db(tmp_path)
with pytest.raises(NotImplementedError, match="requires LanceDB Distributed"):
db.create_materialized_view("adults", "people", **options)
assert "adults" not in db.table_names()
@pytest.mark.parametrize("seconds", [0, -1, float("nan"), float("inf")])
def test_remote_create_rejects_invalid_interval_without_request(seconds):
db = lancedb.connect("db://dev", api_key="fake", host_override="http://127.0.0.1:1")
with pytest.raises(ValueError, match="positive, finite"):
db.create_materialized_view_async(
"mv", "source", auto_refresh_interval_seconds=seconds
)
@pytest.mark.experimental_functions
def test_namespace_forwards_automatic_refresh_request(tmp_path):
db = lancedb.connect_namespace("dir", {"root": str(tmp_path)})
with pytest.raises(NotImplementedError, match="requires LanceDB Distributed"):
db.create_materialized_view("mv", "source", auto_refresh_enabled=True)
@pytest.mark.experimental_functions
@pytest.mark.asyncio
async def test_async_namespace_forwards_automatic_refresh_request(tmp_path):
db = lancedb.connect_namespace_async("dir", {"root": str(tmp_path)})
with pytest.raises(NotImplementedError, match="requires LanceDB Distributed"):
await db.create_materialized_view("mv", "source", auto_refresh_enabled=True)
@pytest.mark.experimental_functions
def test_embedded_explicitly_disabled_refresh_is_supported(tmp_path):
db = make_db(tmp_path)
view = db.create_materialized_view("mv", "people", auto_refresh_enabled=False)
assert view.table.count_rows() == 3
+146 -7
View File
@@ -6,15 +6,17 @@
import tempfile
import shutil
import importlib
import warnings
import http.server
import json
import threading
from urllib.parse import parse_qs, unquote, urlparse
import pytest
import pyarrow as pa
import lancedb
from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError
from utils import start_server_thread
from lancedb.listing import AsyncListing, Listing
from lancedb.materialized_view import DEFINITION_FORMAT, DEFINITION_META_KEY
from lancedb.namespace import _MAX_QUERY_K, _query_to_namespace_request
from lancedb.query import Query
from lancedb.table import AsyncTable, LanceTable
@@ -25,6 +27,125 @@ PUSHDOWN_DATA = pa.table(
)
class TestNamespaceCreateTableOptions:
@pytest.mark.parametrize("version", ["legacy", "stable"])
@pytest.mark.parametrize("empty", [False, True])
def test_deprecated_storage_version(self, tmp_path, version, empty):
db = lancedb.connect_namespace("dir", {"root": str(tmp_path / "namespace")})
data = None if empty else [{"id": 1}]
schema = pa.schema([("id", pa.int64())])
other_version = "stable" if version == "legacy" else "legacy"
options = {"new_table_data_storage_version": other_version}
control = lancedb.connect(tmp_path / "control").create_table(
"test",
data=data,
schema=schema,
storage_options={"new_table_data_storage_version": version},
)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always", DeprecationWarning)
table = db.create_table(
"test",
data=data,
schema=schema,
storage_options=options,
data_storage_version=version,
)
assert (
table.to_lance().data_storage_version
== control.to_lance().data_storage_version
)
assert table.to_arrow().to_pylist() == ([] if empty else data)
assert options == {"new_table_data_storage_version": other_version}
assert any("data_storage_version" in str(w.message) for w in caught)
@pytest.mark.asyncio
@pytest.mark.parametrize("version", ["legacy", "stable"])
@pytest.mark.parametrize("empty", [False, True])
async def test_deprecated_storage_version_async(self, tmp_path, version, empty):
root = str(tmp_path / "namespace")
db = lancedb.connect_namespace_async("dir", {"root": root})
data = None if empty else [{"id": 1}]
schema = pa.schema([("id", pa.int64())])
other_version = "stable" if version == "legacy" else "legacy"
options = {"new_table_data_storage_version": other_version}
control = lancedb.connect(tmp_path / "control").create_table(
"test",
data=data,
schema=schema,
storage_options={"new_table_data_storage_version": version},
)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always", DeprecationWarning)
table = await db.create_table(
"test",
data=data,
schema=schema,
storage_options=options,
data_storage_version=version,
)
reopened = lancedb.connect_namespace("dir", {"root": root}).open_table("test")
assert (
reopened.to_lance().data_storage_version
== control.to_lance().data_storage_version
)
assert (await table.to_arrow()).to_pylist() == ([] if empty else data)
assert options == {"new_table_data_storage_version": other_version}
assert any("data_storage_version" in str(w.message) for w in caught)
@pytest.mark.parametrize("enabled", [False, True])
@pytest.mark.parametrize("empty", [False, True])
def test_deprecated_manifest_paths(self, tmp_path, enabled, empty):
db = lancedb.connect_namespace("dir", {"root": str(tmp_path)})
data = None if empty else [{"id": 1}]
options = {"new_table_enable_v2_manifest_paths": str(not enabled).lower()}
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always", DeprecationWarning)
table = db.create_table(
"test",
data=data,
schema=pa.schema([("id", pa.int64())]),
storage_options=options,
enable_v2_manifest_paths=enabled,
)
assert table.uses_v2_manifest_paths() == enabled
assert table.to_arrow().to_pylist() == ([] if empty else data)
assert db.open_table("test").uses_v2_manifest_paths() == enabled
assert options == {
"new_table_enable_v2_manifest_paths": str(not enabled).lower()
}
assert any("enable_v2_manifest_paths" in str(w.message) for w in caught)
@pytest.mark.asyncio
@pytest.mark.parametrize("enabled", [False, True])
@pytest.mark.parametrize("empty", [False, True])
async def test_deprecated_manifest_paths_async(self, tmp_path, enabled, empty):
db = lancedb.connect_namespace_async("dir", {"root": str(tmp_path)})
data = None if empty else [{"id": 1}]
options = {"new_table_enable_v2_manifest_paths": str(not enabled).lower()}
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always", DeprecationWarning)
table = await db.create_table(
"test",
data=data,
schema=pa.schema([("id", pa.int64())]),
storage_options=options,
enable_v2_manifest_paths=enabled,
)
assert await table.uses_v2_manifest_paths() == enabled
assert (await table.to_arrow()).to_pylist() == ([] if empty else data)
reopened = await db.open_table("test")
assert await reopened.uses_v2_manifest_paths() == enabled
assert options == {
"new_table_enable_v2_manifest_paths": str(not enabled).lower()
}
assert any("enable_v2_manifest_paths" in str(w.message) for w in caught)
def _ipc_file(table: pa.Table = PUSHDOWN_DATA) -> bytes:
sink = pa.BufferOutputStream()
with pa.ipc.new_file(sink, table.schema) as writer:
@@ -146,8 +267,7 @@ def paginated_rest_namespace():
pass
with http.server.HTTPServer(("127.0.0.1", 0), Handler) as server:
thread = threading.Thread(target=server.serve_forever)
thread.start()
thread = start_server_thread(server)
try:
yield {"uri": f"http://127.0.0.1:{server.server_port}"}, requests
finally:
@@ -239,7 +359,17 @@ class TestNamespaceConnection:
def test_list_materialized_views(self):
db = lancedb.connect_namespace("dir", {"root": self.temp_dir})
db.create_table("source", [{"id": 1}])
db.create_materialized_view("view", "source", with_no_data=True)
# Model a stored view from an enabled build: listing must also work
# when local creation is disabled in the current build.
schema = pa.schema(
[("id", pa.int64())],
metadata={
DEFINITION_META_KEY: json.dumps(
{"format": DEFINITION_FORMAT, "query": "SELECT id FROM source"}
).encode()
},
)
db.create_table("view", schema=schema)
names = db.list_materialized_views(page_limit=1)
assert isinstance(names, Listing)
@@ -752,7 +882,16 @@ class TestAsyncNamespaceConnection:
async def test_list_materialized_views(self):
db = lancedb.connect_namespace_async("dir", {"root": self.temp_dir})
await db.create_table("source", [{"id": 1}])
await db.create_materialized_view("view", "source", with_no_data=True)
# Model a stored view independently of the local creation feature.
schema = pa.schema(
[("id", pa.int64())],
metadata={
DEFINITION_META_KEY: json.dumps(
{"format": DEFINITION_FORMAT, "query": "SELECT id FROM source"}
).encode()
},
)
await db.create_table("view", schema=schema)
names = db.list_materialized_views(page_limit=1)
assert isinstance(names, AsyncListing)
@@ -1065,7 +1204,7 @@ class TestPushdownOperations:
Rust so reads carry the x-lancedb-min-timestamp read-freshness header."""
db = lancedb.connect_namespace(
"rest",
{"uri": "http://localhost:12345"},
{"uri": "http://127.0.0.1:12345"},
namespace_client_pushdown_operations=["QueryTable"],
)
assert db._route_pushdown_to_rust is True
@@ -1082,7 +1221,7 @@ class TestPushdownOperations:
for the async path omitting the freshness header)."""
db = lancedb.connect_namespace_async(
"rest",
{"uri": "http://localhost:12345"},
{"uri": "http://127.0.0.1:12345"},
namespace_client_pushdown_operations=["QueryTable"],
)
assert db._route_pushdown_to_rust is True
@@ -0,0 +1,522 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import json
import os
from typing import Optional
import lancedb
import numpy as np
import pyarrow as pa
import pytest
from lancedb.embeddings import (
EmbeddingFunctionConfig,
NvidiaEmbeddings,
UntrustedEmbeddingConfigError,
get_registry,
)
from lancedb.embeddings.nvidia import MODEL_DIMENSIONS, NVIDIA_BASE_URL
from lancedb.pydantic import LanceModel, Vector
@pytest.fixture
def nvidia_api(monkeypatch):
"""Exercise the real OpenAI client against a deterministic NVIDIA endpoint."""
httpx = pytest.importorskip("httpx")
openai = pytest.importorskip("openai")
requests, responses, clients = [], [], []
original_client = openai.OpenAI
monkeypatch.setenv("NVIDIA_API_KEY", "test-nvidia-key")
registry = get_registry()
monkeypatch.setattr(registry, "_variables", {})
monkeypatch.setattr(registry, "_allowed_endpoints", set())
def respond(request):
requests.append(request)
if responses:
return responses.pop(0)
body = json.loads(request.content)
data = []
for index, text in enumerate(body["input"]):
vector = [0.0] * body["dimensions"]
vector[0 if text == "alpha" else 1] = 1.0
data.append({"index": index, "embedding": vector, "object": "embedding"})
return httpx.Response(
200,
json={
"object": "list",
"model": body["model"],
# The API's index, not response order, determines the input row.
"data": data[::-1],
"usage": {"prompt_tokens": len(data), "total_tokens": len(data)},
},
)
def client(**kwargs):
assert kwargs["max_retries"] == 0
instance = original_client(
**kwargs,
http_client=httpx.Client(
transport=httpx.MockTransport(respond), trust_env=False
),
)
clients.append(instance)
return instance
monkeypatch.setattr(openai, "OpenAI", client)
yield requests, responses
for client in clients:
client.close()
@pytest.mark.parametrize(
"name,dimensions", [(name, dims[0]) for name, dims in MODEL_DIMENSIONS.items()]
)
def test_hosted_models(nvidia_api, name, dimensions):
requests, _ = nvidia_api
func = get_registry().get("nvidia").create(name=name)
assert isinstance(func, NvidiaEmbeddings)
assert func.ndims() == dimensions
assert len(func.compute_source_embeddings(["alpha"])[0]) == dimensions
assert len(func.compute_query_embeddings("alpha")[0]) == dimensions
for request, input_type in zip(requests, ["passage", "query"]):
assert str(request.url) == f"{NVIDIA_BASE_URL}/embeddings"
assert request.headers["authorization"] == "Bearer test-nvidia-key"
assert json.loads(request.content) == {
"model": name,
"input": ["alpha"],
"dimensions": dimensions,
"encoding_format": "float",
"input_type": input_type,
"modality": "text",
"truncate": "END",
}
@pytest.mark.parametrize(
"texts",
[
["alpha", "beta", "gamma"],
np.array(["alpha", "beta", "gamma"]),
pa.array(["alpha", "beta", "gamma"]),
pa.chunked_array([["alpha"], ["beta", "gamma"]]),
],
)
def test_batching_and_response_order(nvidia_api, texts):
requests, _ = nvidia_api
func = NvidiaEmbeddings.create(dim=128, batch_size=2, truncate="NONE")
result = func.compute_source_embeddings(texts)
assert [vector[:2] for vector in result] == [[1, 0], [0, 1], [0, 1]]
assert [json.loads(request.content)["input"] for request in requests] == [
["alpha", "beta"],
["gamma"],
]
assert all(json.loads(r.content)["truncate"] == "NONE" for r in requests)
assert func.compute_source_embeddings([]) == []
assert len(requests) == 2
@pytest.mark.parametrize(
"texts",
[
["alpha", None, "", "beta"],
pa.array(["alpha", None, "", "beta"]),
],
)
def test_null_and_empty_inputs(nvidia_api, texts):
requests, _ = nvidia_api
func = NvidiaEmbeddings.create(dim=128)
result = func.compute_source_embeddings(texts)
assert [vector and vector[:2] for vector in result] == [[1, 0], None, None, [0, 1]]
assert [json.loads(r.content)["input"] for r in requests] == [["alpha", "beta"]]
assert func.compute_source_embeddings([None, ""]) == [None, None]
assert len(requests) == 1
def test_table_with_null_text(nvidia_api, tmp_path):
func = NvidiaEmbeddings.create(dim=128)
class Document(LanceModel):
text: Optional[str] = func.SourceField()
vector: Optional[Vector(func.ndims())] = func.VectorField()
db = lancedb.connect(tmp_path)
table = db.create_table("docs", schema=Document)
table.add([{"text": "alpha"}, {"text": None}], on_bad_vectors="null")
rows = table.to_arrow().to_pylist()
assert rows[0]["vector"][:2] == [1, 0]
assert rows[1]["vector"] is None
@pytest.mark.parametrize("texts", [[b"image"], [["nested"]], [123]])
def test_rejects_non_text(nvidia_api, monkeypatch, texts):
requests, _ = nvidia_api
monkeypatch.setattr("lancedb.embeddings.utils.time.sleep", pytest.fail)
func = NvidiaEmbeddings.create()
with pytest.raises(ValueError, match="text strings only"):
func.compute_source_embeddings(texts)
with pytest.raises(ValueError, match="text strings only"):
func.compute_source_embeddings_with_retry(texts)
assert requests == []
@pytest.mark.parametrize(
"options",
[
{"batch_size": 0},
{"dim": 0},
{"dim": 127},
{"dim": 2049},
{"name": "nvidia/nemotron-3.5-embed-8b", "dim": 4097},
{"name": "nvidia/Nemotron-3.5-Embed-8B-BF16"},
{"truncate": "START"},
],
)
def test_invalid_configuration(options):
with pytest.raises(ValueError):
NvidiaEmbeddings.create(**options)
@pytest.mark.parametrize(
"data,error",
[
([], "number of embeddings"),
(None, "number of embeddings"),
([{"index": 1, "embedding": [0.0] * 128}], "indices"),
([{"embedding": [0.0] * 128}], "indices"),
([{"index": 0, "embedding": [0.0]}], "finite numeric"),
([{"index": 0, "embedding": "base64"}], "finite numeric"),
([{"index": 0, "embedding": ["bad"] * 128}], "finite numeric"),
([{"index": 0}], "finite numeric"),
],
)
def test_invalid_response(nvidia_api, data, error):
import httpx
_, responses = nvidia_api
responses.append(httpx.Response(200, json={"data": data}))
with pytest.raises(ValueError, match=error):
NvidiaEmbeddings.create(dim=128).compute_source_embeddings(["alpha"])
def test_invalid_response_is_not_retried(nvidia_api, monkeypatch):
import httpx
requests, responses = nvidia_api
monkeypatch.setattr("lancedb.embeddings.utils.time.sleep", pytest.fail)
responses.append(httpx.Response(200, json={"data": []}))
func = NvidiaEmbeddings.create(dim=128)
with pytest.raises(ValueError, match="number of embeddings"):
func.compute_source_embeddings_with_retry(["alpha"])
assert len(requests) == 1
def test_missing_response_data(nvidia_api):
import httpx
_, responses = nvidia_api
responses.append(httpx.Response(200, json={}))
with pytest.raises(ValueError, match="number of embeddings"):
NvidiaEmbeddings.create().compute_query_embeddings("alpha")
@pytest.mark.parametrize("bad_value", ["NaN", "Infinity", "-Infinity"])
def test_nonfinite_response(nvidia_api, bad_value):
import httpx
_, responses = nvidia_api
# Raw JSON is needed because httpx refuses to encode non-finite numbers.
vector = ",".join([bad_value] + ["0"] * 127)
responses.append(
httpx.Response(200, text='{"data":[{"index":0,"embedding":[' + vector + "]}]}")
)
with pytest.raises(ValueError, match="finite numeric"):
NvidiaEmbeddings.create(dim=128).compute_source_embeddings(["alpha"])
def test_duplicate_indices(nvidia_api):
import httpx
_, responses = nvidia_api
responses.append(
httpx.Response(200, json={"data": [{"index": 0, "embedding": [0.0] * 128}] * 2})
)
with pytest.raises(ValueError, match="indices"):
NvidiaEmbeddings.create(dim=128).compute_source_embeddings(["alpha", "beta"])
@pytest.mark.parametrize(
"status,expected_calls", [(429, 2), (503, 2), (401, 1), (400, 1)]
)
def test_retry_policy(nvidia_api, monkeypatch, status, expected_calls):
import httpx
import openai
requests, responses = nvidia_api
monkeypatch.setattr("lancedb.embeddings.utils.time.sleep", lambda _: None)
responses.append(httpx.Response(status, json={"error": {"message": "test error"}}))
func = NvidiaEmbeddings.create(dim=128, max_retries=1)
if expected_calls == 2:
assert len(func.compute_query_embeddings_with_retry("alpha")[0]) == 128
else:
with pytest.raises(openai.APIStatusError) as error:
func.compute_query_embeddings_with_retry("alpha")
assert error.value.status_code == status
assert len(requests) == expected_calls
def test_retry_resends_only_failed_batch(nvidia_api, monkeypatch):
import httpx
requests, responses = nvidia_api
monkeypatch.setattr("lancedb.embeddings.utils.time.sleep", lambda _: None)
vector = [1.0] + [0.0] * 127
responses.append(
httpx.Response(200, json={"data": [{"index": 0, "embedding": vector}]})
)
responses.append(httpx.Response(429, json={"error": {"message": "slow down"}}))
func = NvidiaEmbeddings.create(dim=128, batch_size=1, max_retries=1)
result = func.compute_source_embeddings_with_retry(["alpha", "beta"])
assert [v[:2] for v in result] == [[1, 0], [0, 1]]
assert [json.loads(r.content)["input"] for r in requests] == [
["alpha"],
["beta"],
["beta"],
]
def test_credentials_and_metadata(nvidia_api, monkeypatch):
requests, _ = nvidia_api
registry = get_registry()
registry.set_var("nvidia-key", "secret-from-registry")
options = {
"name": "nvidia/Nemotron-3.5-Embed-8B-BF16",
"base_url": "http://localhost:8000/v1",
"dim": 2048,
"api_key": "$var:nvidia-key",
"batch_size": 2,
"truncate": "NONE",
}
func = NvidiaEmbeddings.create(**options)
config = EmbeddingFunctionConfig(
source_column="text", vector_column="vector", function=func
)
schema = pa.schema([], metadata=registry.get_table_metadata([config]))
# Round-trip the configuration through Arrow, as table schemas do.
restored_schema = pa.ipc.read_schema(pa.BufferReader(schema.serialize()))
metadata = restored_schema.metadata
assert b"secret-from-registry" not in metadata[b"embedding_functions"]
restored = registry.parse_functions(metadata)["vector"].function
assert restored.safe_model_dump() == options
restored.compute_source_embeddings(["alpha"])
restored.compute_query_embeddings("alpha")
assert str(requests[0].url) == "http://localhost:8000/v1/embeddings"
assert requests[0].headers["authorization"] == "Bearer secret-from-registry"
assert json.loads(requests[0].content)["model"] == options["name"]
assert [json.loads(r.content)["input_type"] for r in requests] == [
"passage",
"query",
]
monkeypatch.setattr(registry, "_allowed_endpoints", set())
blocked = registry.parse_functions(metadata)["vector"].function
with pytest.raises(UntrustedEmbeddingConfigError):
blocked.compute_query_embeddings("alpha")
registry.allow_endpoint(options["base_url"])
assert isinstance(
registry.parse_functions(metadata)["vector"].function, NvidiaEmbeddings
)
with pytest.raises(ValueError, match="Sensitive key"):
NvidiaEmbeddings.create(api_key="hardcoded-secret")
def test_missing_key_and_unauthenticated_nim(nvidia_api, monkeypatch):
from lancedb.embeddings.utils import MissingApiKeyError
requests, _ = nvidia_api
# The hosted key in NVIDIA_API_KEY is not sent to custom endpoints.
func = NvidiaEmbeddings.create(
name="nvidia/Nemotron-3.5-Embed-1B-BF16",
base_url="http://localhost:8000/v1",
dim=128,
)
func.compute_query_embeddings("alpha")
assert requests[0].headers["authorization"] == "Bearer not-required"
monkeypatch.delenv("NVIDIA_API_KEY")
with pytest.raises(MissingApiKeyError, match="NVIDIA_API_KEY"):
NvidiaEmbeddings.create().compute_query_embeddings_with_retry("alpha")
assert len(requests) == 1
@pytest.mark.parametrize("name", MODEL_DIMENSIONS)
def test_local_table_document_query_and_reopen(nvidia_api, tmp_path, name):
requests, _ = nvidia_api
func = NvidiaEmbeddings.create(name=name, dim=128)
class Document(LanceModel):
text: str = func.SourceField()
vector: Vector(func.ndims()) = func.VectorField()
db = lancedb.connect(tmp_path)
table = db.create_table("docs", schema=Document, data=[{"text": "alpha"}])
table.add([{"text": "beta"}])
reopened = lancedb.connect(tmp_path).open_table("docs")
assert reopened.schema.metadata == table.schema.metadata
assert isinstance(reopened.embedding_functions["vector"].function, NvidiaEmbeddings)
assert reopened.search("alpha").limit(1).to_list()[0]["text"] == "alpha"
assert [json.loads(request.content)["input_type"] for request in requests] == [
"passage",
"passage",
"query",
]
@pytest.mark.parametrize("name", MODEL_DIMENSIONS)
def test_remote_table_document_query_and_reopen(nvidia_api, name):
from test_remote_db import mock_lancedb_connection, read_json_body, send_json
requests, _ = nvidia_api
func = NvidiaEmbeddings.create(name=name, dim=128)
config = EmbeddingFunctionConfig(
source_column="text", vector_column="vector", function=func
)
writes, queries = [], []
def handler(request):
if "/create/" in request.path or "/insert/" in request.path:
if request.headers.get("Transfer-Encoding") == "chunked":
body = bytearray()
while True:
size = int(request.rfile.readline(), 16)
if size == 0:
request.rfile.readline()
break
body.extend(request.rfile.read(size))
request.rfile.read(2)
else:
body = request.rfile.read(int(request.headers["Content-Length"]))
writes.append(pa.ipc.open_stream(body).read_all())
send_json(request, {})
elif "/describe/" in request.path:
send_json(
request,
{
"version": 1,
"schema": {
"fields": [
{
"name": "text",
"type": {"type": "string"},
"nullable": True,
},
{
"name": "vector",
"nullable": True,
"type": {
"type": "fixed_size_list",
"length": 128,
"fields": [
{
"name": "item",
"type": {"type": "float"},
"nullable": True,
}
],
},
},
],
"metadata": {
k.decode(): v.decode()
for k, v in writes[0].schema.metadata.items()
},
},
},
)
elif "/query/" in request.path:
queries.append(read_json_body(request))
result = pa.table({"text": ["alpha"], "_distance": [0.0]})
request.send_response(200)
request.send_header("Content-Type", "application/vnd.apache.arrow.file")
request.end_headers()
with pa.ipc.new_file(request.wfile, result.schema) as writer:
writer.write_table(result)
else:
request.send_response(404)
request.end_headers()
with mock_lancedb_connection(handler) as db:
table = db.create_table(
"docs", data=[{"text": "alpha"}], embedding_functions=[config]
)
table.add([{"text": "beta"}])
reopened = db.open_table("docs")
assert reopened.schema.metadata == writes[0].schema.metadata
assert reopened.search("alpha").limit(1).to_list()[0]["text"] == "alpha"
assert len(writes) == 2
assert writes[0]["vector"].to_pylist()[0] == [1.0] + [0.0] * 127
assert writes[1]["vector"].to_pylist()[0] == [0.0, 1.0] + [0.0] * 126
assert queries[0]["vector"] == [1.0] + [0.0] * 127
assert [json.loads(r.content)["input_type"] for r in requests] == [
"passage",
"passage",
"query",
]
@pytest.mark.asyncio
async def test_async_local_table(nvidia_api, tmp_path):
requests, _ = nvidia_api
func = NvidiaEmbeddings.create(dim=128)
class Document(LanceModel):
text: str = func.SourceField()
vector: Vector(func.ndims()) = func.VectorField()
with await lancedb.connect_async(tmp_path) as db:
table = await db.create_table("docs", schema=Document)
await table.add([{"text": "alpha"}, {"text": "beta"}])
reopened = await db.open_table("docs")
results = await (await reopened.search("alpha")).limit(1).to_list()
assert results[0]["text"] == "alpha"
assert [json.loads(r.content)["input_type"] for r in requests] == [
"passage",
"query",
]
@pytest.mark.slow
@pytest.mark.skipif(
not os.environ.get("NVIDIA_API_KEY"), reason="NVIDIA_API_KEY not set"
)
@pytest.mark.parametrize("name", MODEL_DIMENSIONS)
def test_nvidia_live(name, tmp_path):
"""Five small requests per model, with retries disabled for free-tier tests."""
pytest.importorskip("openai")
func = NvidiaEmbeddings.create(name=name, max_retries=0)
passages = ["Paris is the capital of France.", "Bananas are yellow fruit."]
question = "What is the capital of France?"
class Document(LanceModel):
text: str = func.SourceField()
vector: Vector(func.ndims()) = func.VectorField()
db = lancedb.connect(tmp_path)
table = db.create_table(
"docs", schema=Document, data=[{"text": text} for text in passages]
)
table.add([{"text": "Saturn is a planet with rings."}])
reopened = lancedb.connect(tmp_path).open_table("docs")
assert reopened.schema.metadata == table.schema.metadata
assert reopened.schema.field("vector").type.list_size == func.ndims()
result = reopened.search(question).limit(1).to_list()[0]
assert result["text"] == passages[0]
assert len(result["vector"]) == func.ndims()
assert np.isfinite(result["vector"]).all()
reduced = NvidiaEmbeddings.create(name=name, dim=128, max_retries=0)
vectors = reduced.compute_source_embeddings_with_retry(passages)
query = reduced.compute_query_embeddings_with_retry(question)[0]
assert np.shape(vectors) == (2, 128)
assert np.shape(query) == (128,)
assert np.dot(query, vectors[0]) > np.dot(query, vectors[1])
@@ -0,0 +1,126 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import json
import numpy as np
import pyarrow as pa
import pytest
from pydantic import ValidationError
from lancedb.embeddings import get_registry
@pytest.fixture
def ollama_embeddings():
httpx = pytest.importorskip("httpx")
pytest.importorskip("ollama")
requests = []
def respond(request):
body = json.loads(request.content)
requests.append(body)
if body["model"] == "missing-model":
return httpx.Response(404, json={"error": "model not found"})
return httpx.Response(
200,
json={
"embeddings": [
[float(index), float(len(text))]
for index, text in enumerate(body["input"])
]
},
)
function = (
get_registry()
.get("ollama")
.create(
name="nomic-embed-text",
options={"num_ctx": 4096},
keep_alive="10m",
ollama_client_kwargs={
"transport": httpx.MockTransport(respond),
"trust_env": False,
},
)
)
yield function, requests
function._ollama_client._client.close()
@pytest.mark.parametrize(
"texts",
[
pytest.param(["hello", "世界"], id="list"),
pytest.param(np.array(["hello", "世界"]), id="numpy-unicode"),
pytest.param(np.array(["hello", "世界"], dtype=object), id="numpy-object"),
pytest.param(
np.array([b"hello", "世界".encode("utf-8")]), id="numpy-utf8-bytes"
),
pytest.param([b"hello", "世界".encode("utf-8")], id="list-utf8-bytes"),
pytest.param(np.array(["hello", "unused", "世界"])[::2], id="numpy-slice"),
pytest.param(pa.array(["hello", "世界"]), id="arrow"),
pytest.param(pa.chunked_array([["hello"], ["世界"]]), id="chunked-arrow"),
],
)
def test_ollama_source_embeddings_inputs(ollama_embeddings, texts):
function, requests = ollama_embeddings
assert function.compute_source_embeddings(texts) == [[0.0, 5.0], [1.0, 2.0]]
assert requests == [
{
"model": "nomic-embed-text",
"input": ["hello", "世界"],
"options": {"num_ctx": 4096},
"keep_alive": "10m",
}
]
@pytest.mark.parametrize(
"texts",
[
pytest.param(np.array([["hello"], ["world"]]), id="numpy-two-dimensional"),
pytest.param([["hello"], ["world"]], id="list-two-dimensional"),
pytest.param(np.array([b"\xff"]), id="numpy-invalid-utf8"),
pytest.param([b"\xff"], id="list-invalid-utf8"),
],
)
def test_ollama_source_embeddings_rejects_invalid_input_locally(
ollama_embeddings, texts
):
function, requests = ollama_embeddings
with pytest.raises(ValidationError, match="valid string"):
function.compute_source_embeddings(texts)
assert requests == []
def test_ollama_generate_embeddings_empty_array(ollama_embeddings):
function, requests = ollama_embeddings
assert function.generate_embeddings(np.array([], dtype=str)) == []
assert len(requests) == 1
assert requests[0]["input"] == []
def test_ollama_query_embeddings(ollama_embeddings):
function, requests = ollama_embeddings
assert function.compute_query_embeddings("hello") == [[0.0, 5.0]]
assert len(requests) == 1
assert requests[0]["input"] == ["hello"]
def test_ollama_source_embeddings_preserves_api_error(ollama_embeddings):
ollama = pytest.importorskip("ollama")
function, requests = ollama_embeddings
function.name = "missing-model"
with pytest.raises(ollama.ResponseError, match="model not found") as error:
function.compute_source_embeddings(np.array(["hello"]))
assert error.value.status_code == 404
assert len(requests) == 1
@@ -0,0 +1,66 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import json
from types import SimpleNamespace
import pyarrow as pa
import pytest
from lancedb.rerankers import OpenaiReranker
def reranker_replying(documents):
"""Return an OpenaiReranker whose chat client replies with these documents."""
reply = json.dumps({"documents": documents})
def create(**kwargs):
message = SimpleNamespace(content=reply)
return SimpleNamespace(choices=[SimpleNamespace(message=message)])
reranker = OpenaiReranker(api_key="test-key")
reranker.__dict__["_client"] = SimpleNamespace(
chat=SimpleNamespace(completions=SimpleNamespace(create=create))
)
return reranker
def vector_results():
return pa.table(
{
"id": [1, 2, 3],
"text": ["dogs bark", "cats purr", "birds sing"],
"_distance": [0.1, 0.2, 0.3],
}
)
def test_scores_stay_with_their_rows_when_the_model_reorders():
reranker = reranker_replying(
[
{"content": "cats purr", "relevance_score": 0.9},
{"content": "birds sing", "relevance_score": 0.5},
{"content": "dogs bark", "relevance_score": 0.1},
]
)
result = reranker.rerank_vector("which animal purrs?", vector_results())
assert result.select(["id", "text"]).to_pylist() == [
{"id": 2, "text": "cats purr"},
{"id": 3, "text": "birds sing"},
{"id": 1, "text": "dogs bark"},
]
assert result["_relevance_score"].to_pylist() == pytest.approx([0.9, 0.5, 0.1])
def test_a_row_the_model_leaves_out_raises():
reranker = reranker_replying(
[
{"content": "cats purr", "relevance_score": 0.9},
{"content": "dogs bark", "relevance_score": 0.1},
]
)
with pytest.raises(ValueError, match="1 of 3"):
reranker.rerank_vector("which animal purrs?", vector_results())
@@ -0,0 +1,38 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import pytest
from lancedb.rerankers import OpenaiReranker
@pytest.mark.parametrize(
"explicit_key, environment_key, expected_key",
[
("explicit-test-key", "environment-test-key", "explicit-test-key"),
("explicit-test-key", None, "explicit-test-key"),
(None, "environment-test-key", "environment-test-key"),
],
)
def test_openai_reranker_api_key_precedence(
monkeypatch, explicit_key, environment_key, expected_key
):
pytest.importorskip("openai")
if environment_key is None:
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
else:
monkeypatch.setenv("OPENAI_API_KEY", environment_key)
reranker = OpenaiReranker(api_key=explicit_key)
client = reranker._client
try:
assert client.api_key == expected_key
finally:
client.close()
def test_openai_reranker_requires_api_key(monkeypatch):
pytest.importorskip("openai")
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
with pytest.raises(ValueError, match="OPENAI_API_KEY not set"):
OpenaiReranker()._client
+4 -2
View File
@@ -32,8 +32,10 @@ def test_pyo3_abi_matches_minimum_supported_python():
expected_abi = f"abi3-py{major}{minor}"
configured_abis = re.findall(r'"(abi3-py\d+)"', cargo_manifest)
assert configured_abis == [expected_abi, expected_abi], (
"the pyo3 runtime and build ABI features must both match requires-python"
# PyO3 0.29 configures the ABI through the runtime dependency; its
# build-config crate no longer exposes ABI features.
assert configured_abis == [expected_abi], (
"the pyo3 runtime ABI feature must match requires-python"
)
+84
View File
@@ -161,6 +161,76 @@ def test_split_random_with_seed(mem_db):
assert data1["split_id"] == data2["split_id"]
def test_bootstrap_sample_fixed(mem_db):
"""Output row count is num_samples, not the input row count, and splits divide
it evenly."""
tbl = mem_db.create_table("test_table", pa.table({"x": range(20)}))
permutation_tbl = (
permutation_builder(tbl).bootstrap_sample(1000, fixed=4, seed=42).execute()
)
assert permutation_tbl.count_rows() == 1000
data = permutation_tbl.search(None).to_arrow().to_pydict()
split_ids = data["split_id"]
assert set(split_ids) == {0, 1, 2, 3}
for split_id in range(4):
assert split_ids.count(split_id) == 250
# Every sampled row_id must still be one of the 20 real rows.
assert set(data["row_id"]).issubset(set(range(20)))
def test_bootstrap_sample_draws_with_replacement(mem_db):
"""Sampling more rows than exist must produce repeats."""
tbl = mem_db.create_table("test_table", pa.table({"x": range(5)}))
permutation_tbl = (
permutation_builder(tbl).bootstrap_sample(500, fixed=1, seed=1).execute()
)
data = permutation_tbl.search(None).to_arrow().to_pydict()
assert len(data["row_id"]) == 500
# Only 5 distinct rows exist, so with 500 draws every one of them must repeat.
for row_id in range(5):
assert data["row_id"].count(row_id) > 1
def test_bootstrap_sample_with_seed_is_reproducible(mem_db):
tbl = mem_db.create_table("test_table", pa.table({"x": range(50)}))
perm1 = permutation_builder(tbl).bootstrap_sample(200, fixed=2, seed=42).execute()
perm2 = permutation_builder(tbl).bootstrap_sample(200, fixed=2, seed=42).execute()
data1 = perm1.search(None).to_arrow().to_pydict()
data2 = perm2.search(None).to_arrow().to_pydict()
assert data1["row_id"] == data2["row_id"]
assert data1["split_id"] == data2["split_id"]
def test_bootstrap_sample_respects_filter(mem_db):
tbl = mem_db.create_table("test_table", pa.table({"x": range(20)}))
permutation_tbl = (
permutation_builder(tbl)
.filter("x >= 15")
.bootstrap_sample(100, fixed=1, seed=7)
.execute()
)
data = permutation_tbl.search(None).to_arrow().to_pydict()
assert len(data["row_id"]) == 100
assert set(data["row_id"]).issubset(set(range(15, 20)))
def test_bootstrap_sample_requires_exactly_one_size_arg(mem_db):
tbl = mem_db.create_table("test_table", pa.table({"x": range(10)}))
with pytest.raises(ValueError):
permutation_builder(tbl).bootstrap_sample(10).execute()
with pytest.raises(ValueError):
permutation_builder(tbl).bootstrap_sample(
10, ratios=[0.5, 0.5], fixed=2
).execute()
def test_split_hash(mem_db):
"""Test hash-based splitting."""
tbl = mem_db.create_table(
@@ -741,6 +811,13 @@ def test_rename_column(some_permutation: Permutation):
some_permutation.rename_column("non_existent", "new_value")
def test_rename_column_keeps_position(some_permutation: Permutation):
renamed = some_permutation.rename_column("id", "new_id")
assert renamed.schema == pa.schema([("new_id", pa.int64()), ("value", pa.int64())])
batch = renamed.with_format("arrow").__getitems__([0])
assert batch.schema.names == ["new_id", "value"]
def test_rename_columns(some_permutation: Permutation):
assert some_permutation.rename_columns({"value": "new_value"}).schema == pa.schema(
[("id", pa.int64()), ("new_value", pa.int64())]
@@ -1327,3 +1404,10 @@ def test_permutation_over_remote_table():
]
assert_server_safe_row_id_requests(server)
def test_from_tables_split_without_permutation_table(mem_db):
tbl = mem_db.create_table("test_table", pa.table({"id": range(10)}))
with pytest.raises(ValueError, match="permutation on split `train` because no"):
Permutation.from_tables(tbl, split="train")
+17
View File
@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import pyarrow as pa
import pyarrow.compute as pc
import lancedb
from lancedb.integrations.pyarrow import PyarrowDatasetAdapter
@@ -48,3 +49,19 @@ def test_dataset_adapter(tmp_path):
assert adapter.head(10).num_rows == 0
assert adapter.scanner().projected_schema == pa.schema({"x": pa.int64()})
def test_dataset_adapter_expression_filter(tmp_path):
data = pa.table({"x": [1, 2, 3, 4], "y": [5, 6, 7, 8]})
conn = lancedb.connect(tmp_path)
tbl = conn.create_table("test", data)
adapter = PyarrowDatasetAdapter(tbl)
filt = pc.field("x") > 2
assert adapter.count_rows(filt) == 2
assert adapter.to_table(filter=filt) == data.slice(2, 2)
assert adapter.head(1, filter=filt) == data.slice(2, 1)
# The filter can reference a column that is not projected
assert adapter.to_table(columns=["y"], filter=filt) == pa.table({"y": [7, 8]})
assert adapter.scanner(filter=filt).count_rows() == 2
+131
View File
@@ -200,6 +200,27 @@ def test_bare_generic_raises_type_error():
pydantic_to_schema(TestModel)
def test_tuple_with_mixed_element_types_raises_type_error():
# An Arrow list has one element type, so Tuple[int, str] has no Arrow
# equivalent. It used to map to list<int64> and fail later, on write.
class TestModel(pydantic.BaseModel):
pair: Tuple[int, str]
with pytest.raises(TypeError, match="same type"):
pydantic_to_schema(TestModel)
def test_homogeneous_tuples_map_to_lists():
class TestModel(pydantic.BaseModel):
pair: Tuple[int, int]
many: Tuple[float, ...]
schema = pydantic_to_schema(TestModel)
assert schema.field("pair").type == pa.list_(pa.int64())
assert schema.field("many").type == pa.list_(pa.float64())
def test_nested_struct_list_optional():
class SplitInfo(pydantic.BaseModel):
start_frame: int
@@ -415,6 +436,67 @@ def test_nullable_vector():
assert schema == pa.schema([pa.field("vec", pa.list_(pa.float32(), 16), True)])
@pytest.mark.parametrize("vector_type", [Vector, MultiVector])
@pytest.mark.parametrize(
"value_type, values",
[
(pa.int64(), [-(2**53 + 1), 2**53 + 3]),
(pa.uint64(), [2**53 + 1, 2**64 - 1]),
(pa.int8(), [-128, 127]),
(pa.uint8(), [0, 255]),
(pa.float32(), [1.25, 2.5]),
(pa.float64(), [1.25, 2.5]),
],
)
def test_typed_vector_round_trip(tmp_path, vector_type, value_type, values):
import lancedb
annotation = vector_type(2, value_type=value_type)
expected = [values, values] if vector_type is MultiVector else values
class Row(LanceModel):
id: int
payload: annotation
row = Row(id=1, payload=expected)
table = lancedb.connect(tmp_path).create_table("typed_vectors", [row], schema=Row)
table.add([Row(id=2, payload=expected)])
assert table.schema == Row.to_arrow_schema()
assert table.search().to_arrow().to_pylist() == [
{"id": 1, "payload": expected},
{"id": 2, "payload": expected},
]
assert json.loads(row.model_dump_json())["payload"] == expected
@pytest.mark.parametrize("vector_type", [Vector, MultiVector])
@pytest.mark.parametrize("nullable", [False, True])
def test_integer_vector_validation(vector_type, nullable):
annotation = vector_type(2, value_type=pa.int64(), nullable=nullable)
class Row(LanceModel):
payload: annotation
def shape(values):
return [values] if vector_type is MultiVector else values
assert Row.to_arrow_schema().field("payload").nullable is nullable
assert Row(payload=shape([1.0, -2.0])).model_dump()["payload"] == shape([1, -2])
with pytest.raises(pydantic.ValidationError, match="valid integer"):
Row(payload=shape([1.5, 2]))
with pytest.raises(pydantic.ValidationError):
Row(payload=shape([1]))
with pytest.raises(pydantic.ValidationError):
Row(payload=shape([1, 2, 3]))
with pytest.raises(pydantic.ValidationError):
Row(payload=None)
class OptionalRow(LanceModel):
payload: Optional[annotation] = None
assert OptionalRow(payload=None).payload is None
def test_bare_vector_raises_clear_error():
namespace = {
"__name__": "test_model_without_pyarrow",
@@ -733,3 +815,52 @@ def test_enum_types():
assert schema.field("priority").type == pa.int64()
assert schema.field("opt_status").type == pa.dictionary(pa.int32(), pa.utf8())
assert schema.field("opt_status").nullable
def test_plain_enum_values_are_written(mem_db):
"""Members of an Enum without a str/int mixin are written as their values."""
class Color(Enum):
RED = "red"
BLUE = "blue"
class Priority(Enum):
LOW = 1
HIGH = 2
class Tag(LanceModel):
color: Color
class TestModel(LanceModel):
color: Color
priority: Priority
opt_color: Optional[Color] = None
colors: List[Color]
tag: Tag
vector: Vector(2)
rows = [
TestModel(
color=Color.RED,
priority=Priority.HIGH,
opt_color=Color.BLUE,
colors=[Color.BLUE, Color.RED],
tag=Tag(color=Color.BLUE),
vector=[1.0, 2.0],
),
TestModel(
color=Color.BLUE,
priority=Priority.LOW,
colors=[],
tag=Tag(color=Color.RED),
vector=[3.0, 4.0],
),
]
tbl = mem_db.create_table("test", schema=TestModel)
tbl.add(rows)
assert tbl.to_arrow().select(["color", "priority", "opt_color"]).to_pylist() == [
{"color": "red", "priority": 2, "opt_color": "blue"},
{"color": "blue", "priority": 1, "opt_color": None},
]
assert tbl.search().to_pydantic(TestModel) == rows
@@ -0,0 +1,128 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import lancedb
import pytest
from pydantic import BaseModel, Field
from lancedb.pydantic import LanceModel
class Details(BaseModel):
label: str
transient: str = Field(default="nested default", exclude=True)
class Row(LanceModel):
id: int
details: Details
transient: str = Field(default="local default", exclude=True)
generated: list[str] = Field(default_factory=lambda: ["local"], exclude=True)
retained: str = Field(default="persisted", exclude=False)
def rows():
return [
Row(
id=i,
details=Details(label=str(i), transient="private"),
transient="private",
generated=["private"],
)
for i in (1, 2)
]
def assert_schema(schema):
assert schema.names == ["id", "details", "retained"]
assert [field.name for field in schema.field("details").type] == ["label"]
assert Row.field_names() == ["id", "details", "transient", "generated", "retained"]
def assert_restored(restored):
assert sorted(row.id for row in restored) == [1, 2]
for row in restored:
assert row.transient == "local default"
assert row.generated == ["local"]
assert row.details.transient == "nested default"
assert row.details.label == str(row.id)
assert row.retained == "persisted"
@pytest.mark.parametrize("explicit_schema", [False, True])
def test_excluded_fields_round_trip(tmp_path, explicit_schema):
data = rows()
kwargs = {"schema": Row} if explicit_schema else {}
db = lancedb.connect(tmp_path)
table = db.create_table("rows", data=data[:1], **kwargs)
table.add(data[1:])
assert_schema(table.schema)
reopened = lancedb.connect(tmp_path).open_table("rows")
assert_restored(reopened.search().to_pydantic(Row))
assert data[0].transient == "private"
assert data[0].generated == ["private"]
@pytest.mark.asyncio
@pytest.mark.parametrize("explicit_schema", [False, True])
async def test_excluded_fields_round_trip_async(tmp_path, explicit_schema):
data = rows()
kwargs = {"schema": Row} if explicit_schema else {}
db = await lancedb.connect_async(tmp_path)
table = await db.create_table("rows", data=data[:1], **kwargs)
await table.add(data[1:])
assert_schema(await table.schema())
reopened_db = await lancedb.connect_async(tmp_path)
reopened = await reopened_db.open_table("rows")
assert_restored(await reopened.query().to_pydantic(Row))
assert data[0].details.transient == "private"
@pytest.mark.parametrize("excluded", ["transient", "source", "vector"])
def test_excluded_fields_keep_embedding_metadata_consistent(
tmp_path, monkeypatch, excluded
):
from lancedb.embeddings.base import TextEmbeddingFunction
from lancedb.embeddings.registry import get_registry
from lancedb.pydantic import Vector
calls = []
class LocalEmbedding(TextEmbeddingFunction):
def ndims(self):
return 2
def generate_embeddings(self, texts):
calls.extend(texts)
return [[1.0, 0.0] for _ in texts]
registry = get_registry()
monkeypatch.setattr(registry, "_functions", registry._functions.copy())
registry.register("test-excluded-fields")(LocalEmbedding)
function = LocalEmbedding.create(max_retries=0)
class EmbeddedRow(LanceModel):
text: str = function.SourceField(default="alpha", exclude=excluded == "source")
vector: Vector(2) = function.VectorField(
default_factory=lambda: [1.0, 0.0], exclude=excluded == "vector"
)
transient: str = Field(default="local", exclude=True)
configs = EmbeddedRow.parse_embedding_functions()
assert len(configs) == (1 if excluded == "transient" else 0)
db = lancedb.connect(tmp_path)
data = [{"text": "alpha"}] if excluded == "transient" else [EmbeddedRow()]
table = db.create_table("embeddings", schema=EmbeddedRow, data=data)
assert "transient" not in table.schema.names
assert ("text" in table.schema.names) == (excluded != "source")
assert ("vector" in table.schema.names) == (excluded != "vector")
reopened = lancedb.connect(tmp_path).open_table("embeddings")
assert len(reopened.embedding_functions) == len(configs)
restored = reopened.search().to_pydantic(EmbeddedRow)
assert restored[0].text == "alpha"
assert restored[0].vector == [1.0, 0.0]
assert restored[0].transient == "local"
if excluded == "transient":
assert calls == ["alpha"]
assert reopened.search("alpha").limit(1).to_list()[0]["text"] == "alpha"
else:
assert calls == []
+102 -3
View File
@@ -675,10 +675,10 @@ def test_blob_v2_vector_projection_and_plain_scan_options(tmp_db, monkeypatch):
query = table.search().where("id = 1")
def fail_to_arrow(*args, **kwargs):
raise AssertionError("the native scanner should handle bytes with flatten")
def fail_to_lance(*args, **kwargs):
raise AssertionError("blob v2 bytes should not open a pylance dataset")
monkeypatch.setattr(query, "to_arrow", fail_to_arrow)
monkeypatch.setattr(table, "to_lance", fail_to_lance)
assert query.to_pandas(blob_mode="bytes", flatten=True)["blob"].tolist() == [b"one"]
flattened_lazy = table.search().where("id = 1").to_pandas(flatten=True)
@@ -833,6 +833,28 @@ def test_with_row_id(table: lancedb.table.Table):
assert rs["_rowid"].to_pylist() == [0, 1]
def test_filter_preserves_deeply_nested_struct_fields(tmp_db):
# Regression test for https://github.com/lancedb/lancedb/issues/2217.
data = [
{
"item": "test",
"sub_obj": {
"second_sub_obj": [
{
"third_sub_obj": {"int_val": 1},
"str_val": "test",
}
]
},
}
]
table = tmp_db.create_table("deeply_nested_struct", data=data)
result = table.search().where("item = 'test'").limit(1).to_arrow()
assert result.to_pylist() == data
def test_blob_v2_query_omits_auto_row_id(tmp_db):
table = _create_blob_v2_query_table(tmp_db, "test_blob_v2_omits_auto_rowid")
@@ -1955,6 +1977,56 @@ def test_query_serialization_sync(table: lancedb.table.Table):
check_set_props(q, full_text_query=FullTextSearchQuery(columns=[], query="foo"))
@pytest.mark.asyncio
@pytest.mark.parametrize("query_type", ["plain", "fts", "vector"])
@pytest.mark.parametrize("fast_search", [False, True])
@pytest.mark.parametrize("postfilter", [False, True])
async def test_query_serialization_async_search_options(
table_async: AsyncTable, query_type, fast_search, postfilter
):
query = table_async.query().where("id = 1")
if query_type == "fts":
query = query.nearest_to_text(MatchQuery("dog", "text"))
elif query_type == "vector":
query = query.nearest_to([1.0, 2.0])
if fast_search:
query = query.fast_search()
if postfilter:
query = query.postfilter()
serialized = query.to_query_object()
assert serialized.fast_search is (True if fast_search else None)
default_postfilter = False if query_type == "vector" else None
assert serialized.postfilter is (True if postfilter else default_postfilter)
@pytest.mark.asyncio
@pytest.mark.parametrize("fast_search", [False, True])
async def test_query_serialization_async_fast_search_execution(
table_async, fast_search
):
await table_async.create_index("text", config=FTS())
await table_async.add(
[
{
"id": 3,
"vector": [5.0, 6.0],
"str_field": "c",
"float_field": 3.0,
"text": "unindexed dog",
}
]
)
query = table_async.query().nearest_to_text(MatchQuery("unindexed", "text"))
if fast_search:
query = query.fast_search()
expected_ids = [] if fast_search else [3]
assert [row["id"] for row in await query.to_list()] == expected_ids
restored = table_async._sync_query_to_async(query.to_query_object())
assert [row["id"] for row in await restored.to_list()] == expected_ids
@pytest.mark.asyncio
async def test_query_serialization_async(table_async: AsyncTable):
# Simple queries
@@ -2302,6 +2374,33 @@ def test_take_queries(tmp_path):
]
def test_take_queries_with_row_id(tmp_path):
db = lancedb.connect(tmp_path)
table = db.create_table("test", pa.table({"idx": range(100)}))
by_row_id = table.take_row_ids([5, 2, 17], with_row_id=True).to_arrow()
assert "_rowid" in by_row_id.column_names
by_offset = table.take_offsets([5, 2, 17], with_row_id=True).to_arrow()
assert "_rowid" in by_offset.column_names
# The column is opt-in and must stay out of the default projection.
assert "_rowid" not in table.take_row_ids([5, 2, 17]).to_arrow().column_names
@pytest.mark.asyncio
async def test_take_queries_with_row_id_async(tmp_path):
db = await lancedb.connect_async(tmp_path)
table = await db.create_table("test", pa.table({"idx": range(100)}))
by_row_id = await table.take_row_ids([5, 2, 17], with_row_id=True).to_arrow()
assert "_rowid" in by_row_id.column_names
by_offset = await table.take_offsets([5, 2, 17], with_row_id=True).to_arrow()
assert "_rowid" in by_offset.column_names
default = await table.take_row_ids([5, 2, 17]).to_arrow()
assert "_rowid" not in default.column_names
def test_take_queries_to_batches(tmp_path):
# Regression test for the sync take-query path: `to_batches` previously
# raised ``AttributeError: 'AsyncTakeQuery' object has no attribute
@@ -0,0 +1,83 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
from datetime import timedelta
import lancedb
import pytest
from lance_namespace import connect as connect_namespace_client
from lancedb import _lancedb
from lancedb.namespace import LanceNamespaceDBConnection
@pytest.mark.parametrize("seconds", [-1.0, -0.000001])
@pytest.mark.parametrize("kind", ["sync", "namespace", "namespace_async", "client"])
def test_negative_read_consistency_interval(tmp_path, seconds, kind):
interval = timedelta(seconds=seconds)
with pytest.raises(ValueError, match="read_consistency_interval"):
if kind == "sync":
lancedb.connect(tmp_path, read_consistency_interval=interval)
elif kind == "client":
client = connect_namespace_client("dir", {"root": str(tmp_path)})
LanceNamespaceDBConnection(client, read_consistency_interval=interval)
else:
connect = (
lancedb.connect_namespace
if kind == "namespace"
else lancedb.connect_namespace_async
)
connect("dir", {"root": str(tmp_path)}, read_consistency_interval=interval)
@pytest.mark.asyncio
@pytest.mark.parametrize("seconds", [-1.0, -0.000001])
async def test_negative_async_read_consistency_interval(tmp_path, seconds):
with pytest.raises(ValueError, match="read_consistency_interval"):
await lancedb.connect_async(
tmp_path, read_consistency_interval=timedelta(seconds=seconds)
)
@pytest.mark.asyncio
@pytest.mark.parametrize("seconds", [float("nan"), float("inf"), -float("inf"), 1e30])
@pytest.mark.parametrize("kind", ["connect", "namespace", "client"])
async def test_binding_rejects_invalid_read_consistency_interval(
tmp_path, seconds, kind
):
with pytest.raises(ValueError, match="read_consistency_interval"):
if kind == "connect":
await _lancedb.connect(str(tmp_path), read_consistency_interval=seconds)
elif kind == "namespace":
_lancedb.connect_namespace(
"dir", {"root": str(tmp_path)}, read_consistency_interval=seconds
)
else:
client = connect_namespace_client("dir", {"root": str(tmp_path)})
_lancedb.connect_namespace_client(client, read_consistency_interval=seconds)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"interval", [None, timedelta(0), timedelta(microseconds=1), timedelta(seconds=5)]
)
async def test_valid_read_consistency_intervals(tmp_path, interval):
db = lancedb.connect(tmp_path / "sync", read_consistency_interval=interval)
assert db.read_consistency_interval == interval
db.close()
db = await lancedb.connect_async(
tmp_path / "async", read_consistency_interval=interval
)
assert await db.get_read_consistency_interval() == interval
db.close()
db = lancedb.connect_namespace(
"dir", {"root": str(tmp_path / "namespace")}, read_consistency_interval=interval
)
assert db.read_consistency_interval == interval
db.close()
client = connect_namespace_client("dir", {"root": str(tmp_path / "client")})
db = LanceNamespaceDBConnection(client, read_consistency_interval=interval)
assert db.read_consistency_interval == interval
db.close()
+600 -75
View File
@@ -5,11 +5,14 @@ import contextlib
from datetime import timedelta
import http.server
import io
import inspect
import json
import multiprocessing as mp
import pickle
import re
import subprocess
import sys
import textwrap
import threading
import time
from unittest.mock import MagicMock, patch
@@ -31,6 +34,7 @@ from lancedb.remote import ClientConfig
from lancedb.remote.errors import HttpError, RetryError
import pytest
import pyarrow as pa
from utils import start_server_thread
def make_mock_http_handler(handler):
@@ -51,46 +55,17 @@ def test_connect_rejects_invalid_cloud_dns_hostname(db_name):
@contextlib.contextmanager
def mock_lancedb_connection(handler):
def mock_lancedb_connection(handler, **client_config):
with http.server.HTTPServer(
("localhost", 0), make_mock_http_handler(handler)
("127.0.0.1", 0), make_mock_http_handler(handler)
) as server:
port = server.server_address[1]
handle = threading.Thread(target=server.serve_forever)
handle.start()
handle = start_server_thread(server)
db = lancedb.connect(
"db://dev",
api_key="fake",
host_override=f"http://localhost:{port}",
client_config={
"retry_config": {"retries": 2},
"timeout_config": {
"connect_timeout": 1,
},
},
)
try:
yield db
finally:
server.shutdown()
handle.join()
@contextlib.asynccontextmanager
async def mock_lancedb_connection_async(handler, **client_config):
with http.server.HTTPServer(
("localhost", 0), make_mock_http_handler(handler)
) as server:
port = server.server_address[1]
handle = threading.Thread(target=server.serve_forever)
handle.start()
db = await lancedb.connect_async(
"db://dev",
api_key="fake",
host_override=f"http://localhost:{port}",
host_override=f"http://127.0.0.1:{port}",
client_config={
"retry_config": {"retries": 2},
"timeout_config": {
@@ -107,6 +82,129 @@ async def mock_lancedb_connection_async(handler, **client_config):
handle.join()
@contextlib.asynccontextmanager
async def mock_lancedb_connection_async(handler, **client_config):
with http.server.HTTPServer(
("127.0.0.1", 0), make_mock_http_handler(handler)
) as server:
port = server.server_address[1]
handle = start_server_thread(server)
db = await lancedb.connect_async(
"db://dev",
api_key="fake",
host_override=f"http://127.0.0.1:{port}",
client_config={
"retry_config": {"retries": 2},
"timeout_config": {
"connect_timeout": 1,
},
**client_config,
},
)
try:
yield db
finally:
server.shutdown()
handle.join()
@pytest.fixture
def existence_handler(method, identifier, status):
def handler(request):
resource = "namespace" if method == "namespace_exists" else "table"
resource_id = "$".join(identifier) or "$"
suffix = "/" if resource == "table" else ""
assert request.command == "POST"
assert request.path == f"/v1/{resource}/{resource_id}/describe{suffix}"
assert request.headers["x-api-key"] == "fake"
assert request.headers["X-Exists-Test"] == "present"
request.send_response(status)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(b"{}" if status == 200 else b"lookup failed")
return handler
@pytest.mark.parametrize(
"method,identifier",
[
("namespace_exists", []),
("namespace_exists", ["ns"]),
("namespace_exists", ["parent", "ns"]),
("table_exists", ["table"]),
("table_exists", ["parent", "ns", "table"]),
],
)
@pytest.mark.parametrize("status", [200, 404, 403, 507])
def test_remote_exists(method, identifier, status, existence_handler):
from lancedb.remote.header import StaticHeaderProvider
provider = StaticHeaderProvider({"X-Exists-Test": "present"})
with mock_lancedb_connection(existence_handler, header_provider=provider) as db:
if status in (200, 404):
assert getattr(db, method)(identifier) is (status == 200)
else:
with pytest.raises(HttpError) as exc_info:
getattr(db, method)(identifier)
assert exc_info.value.status_code == status
@pytest.mark.asyncio
@pytest.mark.parametrize(
"method,identifier",
[
("namespace_exists", []),
("namespace_exists", ["parent", "ns"]),
("table_exists", ["table"]),
("table_exists", ["parent", "ns", "table"]),
],
)
@pytest.mark.parametrize("status", [200, 404, 403, 507])
async def test_async_remote_exists(method, identifier, status, existence_handler):
from lancedb.remote.header import StaticHeaderProvider
provider = StaticHeaderProvider({"X-Exists-Test": "present"})
async with mock_lancedb_connection_async(
existence_handler, header_provider=provider
) as db:
if status in (200, 404):
assert await getattr(db, method)(identifier) is (status == 200)
else:
with pytest.raises(HttpError) as exc_info:
await getattr(db, method)(identifier)
assert exc_info.value.status_code == status
@pytest.mark.parametrize("table_id", [[], ["invalid/name"]])
def test_remote_table_exists_rejects_invalid_identifier(table_id):
requests = []
with mock_lancedb_connection(lambda request: requests.append(request.path)) as db:
with pytest.raises(ValueError):
db.table_exists(table_id)
assert requests == []
def test_remote_table_exists_rechecks_cached_table():
requests = []
def handler(request):
requests.append(request.path)
request.send_response(200 if len(requests) == 1 else 404)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(b"{}")
with mock_lancedb_connection(handler) as db:
table_id = ["ns", "table"]
assert db.table_exists(table_id) is True
assert db.table_exists(table_id) is False
assert table_id == ["ns", "table"]
assert requests == ["/v1/table/ns$table/describe/"] * 2
def paginated_table_listing_handler(request):
url = urlparse(request.path)
assert url.path in {
@@ -561,16 +659,15 @@ def test_remote_table_open_does_not_require_picklable_client_config():
request.end_headers()
with http.server.HTTPServer(
("localhost", 0), make_mock_http_handler(handler)
("127.0.0.1", 0), make_mock_http_handler(handler)
) as server:
port = server.server_address[1]
handle = threading.Thread(target=server.serve_forever)
handle.start()
handle = start_server_thread(server)
try:
db = lancedb.connect(
"db://dev",
api_key="fake",
host_override=f"http://localhost:{port}",
host_override=f"http://127.0.0.1:{port}",
client_config={
"retry_config": {"retries": 0},
"timeout_config": {"connect_timeout": 2, "read_timeout": 2},
@@ -765,6 +862,15 @@ def test_create_table_embedding_functions(with_schema):
]
def test_create_table_positional_parameters_match_base_contract():
from lancedb.db import DBConnection
from lancedb.remote.db import RemoteDBConnection
expected = list(inspect.signature(DBConnection.create_table).parameters)[:9]
actual = list(inspect.signature(RemoteDBConnection.create_table).parameters)[:9]
assert actual == expected
def test_create_table_exist_ok():
def handler(request):
if request.path == "/v1/table/test/create/?mode=exist_ok":
@@ -801,6 +907,43 @@ def test_create_table_exist_ok_with_mode_overwrite():
assert table is not None
@pytest.mark.asyncio
@pytest.mark.parametrize(
"timeout_config",
[{"read_timeout": 0.5}, {"timeout": 0.5, "read_timeout": 5}],
)
async def test_create_table_timeout_is_actionable(timeout_config):
release_response = threading.Event()
received = {}
def handler(request):
received["path"] = request.path
received["request_id"] = request.headers["x-request-id"]
release_response.wait(timeout=5)
request.close_connection = True
async with mock_lancedb_connection_async(
handler, timeout_config=timeout_config
) as db:
batch = pa.record_batch({"id": [1, 2]})
reader = pa.RecordBatchReader.from_batches(batch.schema, [batch])
try:
with pytest.raises(HttpError) as exc_info:
await db.create_table("test", reader)
finally:
release_response.set()
error = exc_info.value
assert "timed out" in str(error)
assert "client_config.timeout_config.read_timeout" in str(error)
assert "client_config.timeout_config.timeout" in str(error)
assert "LANCE_CLIENT_READ_TIMEOUT" in str(error)
assert received["path"] == "/v1/table/test/create/?mode=create"
assert error.request_id == received["request_id"]
assert error.status_code is None
assert isinstance(error.__cause__, HttpError)
@pytest.mark.asyncio
async def test_http_error():
request_id_holder = {"request_id": None}
@@ -857,10 +1000,116 @@ def test_table_unimplemented_functions():
with mock_lancedb_connection(handler) as db:
table = db.create_table("test", [{"id": 1}])
with pytest.raises(NotImplementedError):
table.to_arrow()
with pytest.raises(NotImplementedError):
table.to_pandas()
for method in ["to_arrow", "to_pandas", "to_polars"]:
with pytest.raises(NotImplementedError) as exc_info:
getattr(table, method)()
message = str(exc_info.value)
assert method in message
assert "not" in message and "supported" in message
assert "LanceDB Distributed" in message
assert "cloud" not in message.lower()
assert f"search().{method}()" in message
@pytest.mark.parametrize("method", ["to_arrow", "to_pandas"])
@pytest.mark.parametrize("blob_mode", ["lazy", "descriptions", "bytes", "invalid"])
def test_remote_conversion_blob_mode_errors(method, blob_mode):
with blob_remote_table() as table:
if blob_mode == "invalid":
with pytest.raises(ValueError, match="blob_mode must be one of"):
getattr(table, method)(blob_mode=blob_mode)
else:
with pytest.raises(NotImplementedError) as error:
getattr(table, method)(blob_mode=blob_mode)
assert f"search().{method}()" in str(error.value)
@pytest.mark.asyncio
@pytest.mark.parametrize("version", [None, 1])
@pytest.mark.parametrize("expose_location", [False, True])
async def test_remote_to_lance_rejection(
tmp_path, version, expose_location, monkeypatch
):
import lance
location = tmp_path / "test.lance"
lance.write_dataset(pa.table({"id": [1]}), location)
lance.write_dataset(pa.table({"id": [2]}), location, mode="append")
requests = []
def fail_dataset(*args, **kwargs):
raise AssertionError("remote storage must not be opened")
monkeypatch.setattr(lance, "dataset", fail_dataset)
def handler(request):
requests.append(request.path)
assert request.path == "/v1/table/test/describe/"
content_len = int(request.headers.get("Content-Length", 0))
body = json.loads(request.rfile.read(content_len)) if content_len else {}
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
response = {
"version": body.get("version") or 2,
"schema": {"fields": []},
}
if expose_location:
response["location"] = str(location)
request.wfile.write(json.dumps(response).encode())
options = {"default_scan_options": {"with_row_id": True}}
with mock_lancedb_connection(handler) as db:
table = db.open_table("test", version=version)
opened_requests = list(requests)
with pytest.raises(NotImplementedError) as sync_error:
table.to_lance(**options)
assert requests == opened_requests
async with mock_lancedb_connection_async(handler) as db:
table = await db.open_table("test", version=version)
opened_requests = list(requests)
with pytest.raises(NotImplementedError) as async_error:
await table.to_lance(**options)
assert requests == opened_requests
assert "to_lance() is not supported in LanceDB Distributed" in str(sync_error.value)
assert "query the server" in str(sync_error.value)
assert str(sync_error.value) == str(async_error.value)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"method, kwargs",
[
("drop_all_tables", {}),
("drop_all_tables", {"namespace_path": []}),
("drop_all_tables", {"namespace_path": ["team"]}),
("drop_database", {}),
],
)
async def test_remote_drop_all_tables_not_supported(method, kwargs):
requests = []
def handler(request):
requests.append(request.path)
request.send_response(500)
request.end_headers()
with mock_lancedb_connection(handler) as db:
with pytest.raises(NotImplementedError) as sync_error:
getattr(db, method)(**kwargs)
async with mock_lancedb_connection_async(handler) as db:
with pytest.raises(NotImplementedError) as async_error:
await getattr(db, method)(**kwargs)
assert "Dropping all tables is not currently supported in the remote API" in str(
sync_error.value
)
assert "drop_table" in str(sync_error.value)
assert str(sync_error.value) == str(async_error.value)
assert requests == []
def test_table_to_pandas_not_supported():
@@ -1039,8 +1288,9 @@ def test_table_create_indices():
# Test create_fts_index with custom name (legacy method)
with pytest.warns(DeprecationWarning, match="create_fts_index"):
table.create_fts_index(
"text",
field_names="text",
wait_timeout=timedelta(seconds=2),
tokenizer_name="en_stem",
block_size=256,
custom_stop_words=["cloud"],
name="custom_fts_idx",
@@ -1049,6 +1299,8 @@ def test_table_create_indices():
# Test create_index with custom name (legacy form: vector_column_name kwarg)
with pytest.warns(DeprecationWarning, match="create_index"):
table.create_index(
"cosine",
2,
vector_column_name="vector",
wait_timeout=timedelta(seconds=10),
name="custom_vector_idx",
@@ -1061,7 +1313,8 @@ def test_table_create_indices():
scalar_req = received_requests[0]
assert "name" in scalar_req
assert scalar_req["name"] == "custom_scalar_idx"
assert scalar_req["replace"] is False
# The wire protocol omits replace=True (the server default).
assert "replace" not in scalar_req
# Check FTS index request has custom name
fts_req = received_requests[1]
@@ -1070,18 +1323,39 @@ def test_table_create_indices():
assert fts_req["replace"] is False
assert fts_req["block_size"] == 256
assert fts_req["custom_stop_words"] == ["cloud"]
assert fts_req["language"] == "English"
assert fts_req["stem"] is True
# Check vector index request has custom name
vector_req = received_requests[2]
assert "name" in vector_req
assert vector_req["name"] == "custom_vector_idx"
assert "replace" not in vector_req
assert vector_req["metric_type"] == "cosine"
assert vector_req["num_partitions"] == 2
with pytest.warns(DeprecationWarning, match="create_index"):
table.create_index(
index_type="IVF_HNSW_SQ",
num_partitions=1,
m=10,
ef_construction=50,
max_iterations=12,
sample_rate=64,
)
tuned_req = received_requests[-1]
assert tuned_req["index_type"] == "IVF_HNSW_SQ"
assert tuned_req["num_partitions"] == 1
assert tuned_req["m"] == 10
assert tuned_req["ef_construction"] == 50
assert tuned_req["max_iterations"] == 12
assert tuned_req["sample_rate"] == 64
table.wait_for_index(["custom_scalar_idx"], timedelta(seconds=2))
table.wait_for_index(
["custom_fts_idx", "custom_vector_idx"], timedelta(seconds=2)
)
table.drop_index("custom_vector_idx")
table.drop_index(name="custom_vector_idx")
table.drop_index("custom_scalar_idx")
table.drop_index("custom_fts_idx")
@@ -1477,7 +1751,10 @@ def test_remote_json_fts_config(server_version):
assert request["block_size"] == 256
def test_remote_create_index_new_api(caplog):
@pytest.mark.parametrize(
"rq_kwargs", [{}, {"num_bits": None}, {"num_bits": 1}, {"num_bits": 4}]
)
def test_remote_create_index_new_api(caplog, rq_kwargs):
received_requests = []
def handler(request):
@@ -1550,7 +1827,7 @@ def test_remote_create_index_new_api(caplog):
table.create_index("category", config=BTree())
table.create_index("text", config=FTS(block_size=256))
# IvfRq via new API
table.create_index("vector", config=IvfRq(distance_type="l2"))
table.create_index("vector", config=IvfRq(distance_type="l2", **rq_kwargs))
table.create_index(
"vector", config=IvfPq(distance_type="l2"), replace=False
)
@@ -1575,11 +1852,16 @@ def test_remote_create_index_new_api(caplog):
"vector",
]
assert received_requests[2]["block_size"] == 256
if rq_kwargs.get("num_bits") is None:
assert "num_bits" not in received_requests[3]
else:
assert received_requests[3]["num_bits"] == rq_kwargs["num_bits"]
assert received_requests[4]["replace"] is False
assert received_requests[5]["replace"] is False
assert "replace is not supported" not in caplog.text
assert caplog.messages == [
"GPU accelerator is not supported for remote tables and will be ignored."
"GPU accelerator is not supported in LanceDB Distributed "
"and will be ignored."
]
@@ -1637,7 +1919,7 @@ def test_remote_unsupported_operations_sync(method, args, kwargs, operation):
with pytest.raises(NotImplementedError) as error:
getattr(table, method)(*args, **kwargs)
expected = f"LanceDBError: not supported: {operation} is not supported "
expected += "for remote tables."
expected += "in LanceDB Distributed."
if operation == "IVF_HNSW_PQ":
expected += " Please use IVF_HNSW_SQ instead."
assert str(error.value) == expected
@@ -1655,7 +1937,7 @@ async def test_remote_unsupported_operations_async(method, args, kwargs, operati
with pytest.raises(NotImplementedError) as error:
await getattr(table, method)(*args, **kwargs)
expected = f"LanceDBError: not supported: {operation} is not supported "
expected += "for remote tables."
expected += "in LanceDB Distributed."
if operation == "IVF_HNSW_PQ":
expected += " Please use IVF_HNSW_SQ instead."
assert str(error.value) == expected
@@ -1667,7 +1949,7 @@ def test_remote_unsupported_legacy_hnsw_pq():
with pytest.warns(DeprecationWarning, match="create_index"):
with pytest.raises(
NotImplementedError,
match="IVF_HNSW_PQ is not supported for remote tables. "
match="IVF_HNSW_PQ is not supported in LanceDB Distributed. "
"Please use IVF_HNSW_SQ instead.",
):
table.create_index(
@@ -1675,21 +1957,25 @@ def test_remote_unsupported_legacy_hnsw_pq():
)
def test_remote_python_only_messages(caplog):
def test_remote_python_only_messages():
with mock_lancedb_connection(remote_unsupported_handler) as db:
with caplog.at_level("INFO"):
table = db.open_table("test", storage_options={}, index_cache_size=1)
assert "storage_options is ignored for remote tables" in caplog.text
assert "index_cache_size is ignored for remote tables" in caplog.text
for method in ["to_arrow", "to_pandas"]:
for options in [{"storage_options": {}}, {"index_cache_size": 1}]:
with pytest.raises(NotImplementedError, match=next(iter(options))):
db.open_table("test", **options)
table = db.open_table("test")
for method in ["to_arrow", "to_pandas", "to_polars"]:
with pytest.raises(NotImplementedError) as error:
getattr(table, method)()
assert str(error.value) == f"{method}() is not supported for remote tables."
assert str(error.value) == (
f"{method}() is not supported in LanceDB Distributed. "
f"Use table.search().{method}() instead."
)
for method in ["compact_files", "cleanup_old_versions"]:
with pytest.warns(UserWarning) as warning:
getattr(table, method)()
assert (
str(warning[0].message) == f"{method}() is a no-op for remote tables."
str(warning[0].message)
== f"{method}() is a no-op in LanceDB Distributed."
)
@@ -1793,6 +2079,79 @@ def test_table_wait_for_index_timeout():
table.wait_for_index(["id_idx"], timedelta(seconds=1))
def _jieba_fts_handler(request):
"""Serve a table with a ``jieba/default`` FTS index and no other state."""
if request.path == "/v1/table/test/describe/":
body = {
"version": 1,
"schema": {
"fields": [
{"name": "text", "type": {"type": "string"}, "nullable": True}
]
},
}
elif request.path == "/v1/table/test/index/list/":
index_details = {
"base_tokenizer": "jieba/default",
"language": "English",
"with_position": False,
"max_token_length": 40,
"lower_case": True,
"stem": False,
"remove_stop_words": False,
"ascii_folding": False,
}
body = {
"indexes": [
{
"index_name": "text_idx",
"columns": ["text"],
"index_type": "FTS",
"index_details": json.dumps(index_details),
}
]
}
else:
request.send_response(404)
request.end_headers()
return
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(json.dumps(body).encode())
_MODEL_FILES_ERROR = (
r"(?s)Invalid directory path.*"
r"full text search index 'text_idx'.*"
r"tokenize\(\) runs on the client.*'jieba/default'.*"
r"LANCE_LANGUAGE_MODEL_HOME.*match the files the server uses"
)
def test_remote_tokenize_model_backed_without_model_files(tmp_path, monkeypatch):
monkeypatch.setenv("LANCE_LANGUAGE_MODEL_HOME", str(tmp_path))
with mock_lancedb_connection(_jieba_fts_handler) as db:
table = db.open_table("test")
with pytest.raises(ValueError, match=_MODEL_FILES_ERROR):
table.tokenize("我们是中国人", index_name="text_idx")
with pytest.raises(ValueError, match=_MODEL_FILES_ERROR):
table.tokenize("我们是中国人", column="text")
@pytest.mark.asyncio
async def test_remote_tokenize_model_backed_without_model_files_async(
tmp_path, monkeypatch
):
monkeypatch.setenv("LANCE_LANGUAGE_MODEL_HOME", str(tmp_path))
async with mock_lancedb_connection_async(_jieba_fts_handler) as db:
table = await db.open_table("test")
with pytest.raises(ValueError, match=_MODEL_FILES_ERROR):
await table.tokenize("我们是中国人", index_name="text_idx")
with pytest.raises(ValueError, match=_MODEL_FILES_ERROR):
await table.tokenize("我们是中国人", column="text")
def test_stats():
stats = {
"total_bytes": 38,
@@ -2152,6 +2511,23 @@ def test_head():
assert data == pa.table({"id": [1, 2, 3]})
def test_remote_take_row_ids_with_row_id():
bodies = []
def handler(body):
bodies.append(body)
return pa.table({"id": [1, 2], "_rowid": pa.array([0, 1], pa.uint64())})
with query_test_table(handler) as table:
result = table.take_row_ids([0, 1], with_row_id=True).to_arrow()
assert "_rowid" in result.column_names
assert bodies[-1]["with_row_id"] is True
with query_test_table(handler) as table:
table.take_row_ids([0, 1]).to_arrow()
assert "with_row_id" not in bodies[-1]
def test_query_sync_minimal():
def handler(body):
assert body == {
@@ -2871,17 +3247,16 @@ def test_header_provider_with_sync_connection():
# Create connection with custom client config
with http.server.HTTPServer(
("localhost", 0), make_mock_http_handler(handler)
("127.0.0.1", 0), make_mock_http_handler(handler)
) as server:
port = server.server_address[1]
handle = threading.Thread(target=server.serve_forever)
handle.start()
handle = start_server_thread(server)
try:
db = lancedb.connect(
"db://dev",
api_key="fake",
host_override=f"http://localhost:{port}",
host_override=f"http://127.0.0.1:{port}",
client_config={
"retry_config": {"retries": 2},
"timeout_config": {"connect_timeout": 1},
@@ -3085,7 +3460,7 @@ def _remote_fork_child(port: int, queue) -> None:
db = lancedb.connect(
"db://dev",
api_key="fake",
host_override=f"http://localhost:{port}",
host_override=f"http://127.0.0.1:{port}",
client_config={
"retry_config": {"retries": 0},
"timeout_config": {"connect_timeout": 2, "read_timeout": 2},
@@ -3119,17 +3494,16 @@ def test_remote_connection_after_fork():
request.end_headers()
request.wfile.write(b'{"tables": []}')
server = http.server.HTTPServer(("localhost", 0), make_mock_http_handler(handler))
server = http.server.HTTPServer(("127.0.0.1", 0), make_mock_http_handler(handler))
port = server.server_address[1]
server_thread = threading.Thread(target=server.serve_forever)
server_thread.start()
server_thread = start_server_thread(server)
try:
# Hit the server in the parent first so the runtime + LOOP are warm
# before fork; a fresh child must still succeed.
parent_db = lancedb.connect(
"db://dev",
api_key="fake",
host_override=f"http://localhost:{port}",
host_override=f"http://127.0.0.1:{port}",
client_config={
"retry_config": {"retries": 0},
"timeout_config": {"connect_timeout": 2, "read_timeout": 2},
@@ -3185,15 +3559,14 @@ def test_inherited_remote_table_reopens_after_fork():
request.send_response(404)
request.end_headers()
server = http.server.HTTPServer(("localhost", 0), make_mock_http_handler(handler))
server = http.server.HTTPServer(("127.0.0.1", 0), make_mock_http_handler(handler))
port = server.server_address[1]
server_thread = threading.Thread(target=server.serve_forever)
server_thread.start()
server_thread = start_server_thread(server)
try:
db = lancedb.connect(
"db://dev",
api_key="fake",
host_override=f"http://localhost:{port}",
host_override=f"http://127.0.0.1:{port}",
client_config={
"retry_config": {"retries": 0},
"timeout_config": {"connect_timeout": 2, "read_timeout": 2},
@@ -3254,6 +3627,128 @@ BLOB_DESCRIBE_RESPONSE = {
}
@pytest.mark.parametrize("use_async", [False, True])
@pytest.mark.parametrize("with_pylance", [False, True])
@pytest.mark.parametrize("nested", [False, True])
def test_remote_schema_restores_blob_extensions(use_async, with_pylance, nested):
description = json.loads(json.dumps(BLOB_DESCRIBE_RESPONSE))
without_ranges = description["schema"]["fields"].pop()
without_ranges["name"] = "without_ranges"
image = json.loads(json.dumps(without_ranges))
image["name"] = "image"
image["nullable"] = False
image["metadata"]["lance-encoding:blob-inline-size-threshold"] = "8192"
image["type"]["fields"].extend(
{"name": name, "type": {"type": "uint64"}, "nullable": True}
for name in ("position", "size")
)
plain = {
"name": "plain",
"type": image["type"],
"nullable": True,
"metadata": {"app-key": "app-value"},
}
fields = [image, without_ranges, plain]
if nested:
fields = [
{
"name": "nested",
"type": {"type": "struct", "fields": fields},
"nullable": False,
},
{
"name": "images",
"type": {"type": "list", "fields": [image]},
"nullable": True,
},
]
description["schema"]["fields"].extend(fields)
description["schema"]["metadata"] = {"schema-key": "schema-value"}
def handler(request):
assert request.path == "/v1/table/test/describe/"
send_json(request, description)
# A fresh interpreter must read the schema before blob() or a pylance import
# registers the extension type and hides the original failure.
script = textwrap.dedent(
"""\
import asyncio
import importlib.abc
import sys
import pyarrow as pa
if sys.argv[3] == "False":
class NoLance(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, NoLance())
import lancedb
assert "lance.blob" not in sys.modules
options = dict(api_key="fake", host_override=sys.argv[1])
async def read_schema():
db = await lancedb.connect_async("db://dev", **options)
table = await db.open_table("test")
return await table.schema()
if sys.argv[2] == "True":
schema = asyncio.run(read_schema())
else:
db = lancedb.connect("db://dev", **options)
schema = db.open_table("test").schema
assert schema.metadata == {b"schema-key": b"schema-value"}
assert schema.field("id") == pa.field("id", pa.int64(), nullable=False)
if sys.argv[4] == "True":
assert not schema.field("nested").nullable
fields = schema.field("nested").type
assert schema.field("images").type.value_field.equals(
fields.field("image"), check_metadata=True
)
else:
fields = schema
image = fields.field("image")
assert isinstance(image.type, pa.ExtensionType), image
assert image.type == lancedb.blob("x").type
assert type(image.type) is lancedb.BlobType
assert not image.nullable
assert image.metadata == {
b"lance-encoding:blob-inline-size-threshold": b"8192"
}
plain = fields.field("plain")
assert plain.type == image.type.storage_type
assert plain.metadata == {b"app-key": b"app-value"}
without_ranges = fields.field("without_ranges")
assert isinstance(without_ranges.type, pa.ExtensionType), without_ranges
assert type(without_ranges.type) is lancedb.BlobType
assert without_ranges.type.storage_type == pa.struct([
pa.field("data", pa.large_binary()), pa.field("uri", pa.string())
])
assert without_ranges.nullable
"""
)
with mock_lancedb_connection(handler) as db:
result = subprocess.run(
[
sys.executable,
"-c",
script,
db.host_override,
str(use_async),
str(with_pylance),
str(nested),
],
capture_output=True,
text=True,
timeout=30,
)
assert result.returncode == 0, result.stderr
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
@pytest.mark.parametrize("mode", ["merge", "overwrite"])
@@ -3400,14 +3895,17 @@ def blob_descriptor_take_table():
@contextlib.contextmanager
def blob_remote_table(*, server_version=Version("0.5.0")):
def blob_remote_table(*, server_version=Version("0.5.0"), location=None):
def handler(request):
if request.path == "/v1/table/test/describe/":
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.send_header("phalanx-version", str(server_version))
request.end_headers()
request.wfile.write(json.dumps(BLOB_DESCRIBE_RESPONSE).encode())
response = dict(BLOB_DESCRIBE_RESPONSE)
if location is not None:
response["location"] = str(location)
request.wfile.write(json.dumps(response).encode())
elif request.path.startswith("/v1/table/test/blob/image/"):
path = request.path.partition("?")[0]
row_id = int(path.split("/")[-2])
@@ -3442,7 +3940,6 @@ def blob_remote_table(*, server_version=Version("0.5.0")):
if columns == ["id"]:
response_table = blob_query_response_table().select(["id"])
else:
assert body["with_row_id"] is True
if columns == ["image"]:
# Blob handles are sized from a descriptor take.
assert body["filter"].startswith("_rowid IN")
@@ -3455,6 +3952,8 @@ def blob_remote_table(*, server_version=Version("0.5.0")):
)
else:
response_table = blob_query_response_table()
if not body.get("with_row_id", False):
response_table = response_table.drop(["_rowid"])
request.send_response(200)
request.send_header("Content-Type", "application/vnd.apache.arrow.file")
request.send_header("x-lancedb-version", "1")
@@ -3489,6 +3988,32 @@ def test_remote_blob_columns_and_fetch():
assert blobs.to_pylist() == [b"alpha", None, b"gamma"]
@pytest.mark.parametrize("blob_mode", ["descriptions", "bytes", "lazy"])
def test_sync_remote_blob_pandas_avoids_storage_access(
tmp_path, monkeypatch, blob_mode
):
import lance
location = tmp_path / "remote.lance"
lance.write_dataset(pa.table({"id": [7], "image": [b"server-owned"]}), location)
def fail_dataset(*args, **kwargs):
raise AssertionError("remote storage must not be opened")
monkeypatch.setattr(lance, "dataset", fail_dataset)
with blob_remote_table(location=location) as table:
monkeypatch.setattr(table, "to_lance", fail_dataset)
query = table.search().select(["id", "image"])
if blob_mode == "descriptions":
df = query.to_pandas(blob_mode=blob_mode)
assert df["id"].tolist() == [1, 2, 3]
assert "_rowid" not in df.columns
assert df["image"][0]["size"] == 5
else:
with pytest.raises(NotImplementedError, match="stable table snapshot"):
query.to_pandas(blob_mode=blob_mode)
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_remote_fetch_blob_ranges(use_async):
@@ -3534,7 +4059,7 @@ async def test_async_remote_to_lance_rejects_storage_access(monkeypatch):
raise AssertionError("remote table URI must not be requested")
monkeypatch.setattr(table, "uri", fail_uri)
with pytest.raises(NotImplementedError, match="remote tables"):
with pytest.raises(NotImplementedError, match="LanceDB Distributed"):
await table.to_lance()
+156
View File
@@ -0,0 +1,156 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import inspect
from urllib.parse import parse_qs, urlparse
import lancedb
import pyarrow as pa
import pytest
from test_remote_db import mock_lancedb_connection, mock_lancedb_connection_async
@pytest.mark.parametrize("uri", ["memory://", "db://dev"])
def test_unknown_connect_options(uri):
with pytest.raises(ValueError, match="Unknown keyword arguments.*bogus"):
lancedb.connect(uri, api_key="fake", bogus=1)
@pytest.mark.parametrize("option", ["session", "manifest_enabled"])
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.asyncio
async def test_remote_connect_rejects_local_options(option, asynchronous):
value = lancedb.Session() if option == "session" else True
with pytest.raises(NotImplementedError, match=option):
if asynchronous:
await lancedb.connect_async("db://dev", api_key="fake", **{option: value})
else:
lancedb.connect("db://dev", api_key="fake", **{option: value})
def test_remote_create_signature():
from lancedb.db import DBConnection
from lancedb.remote.db import RemoteDBConnection
expected = inspect.signature(DBConnection.create_table).parameters
actual = inspect.signature(RemoteDBConnection.create_table).parameters
assert list(actual) == list(expected)
for name in expected:
assert actual[name].kind == expected[name].kind
if name == "mode":
# Remote connections retain their existing server-default mode.
assert actual[name].default is None
else:
assert actual[name].default == expected[name].default
def test_remote_create_positional_mode():
modes = []
def handler(request):
assert urlparse(request.path).path == "/v1/table/ct_pos/create/"
modes.append(parse_qs(urlparse(request.path).query)["mode"])
request.send_response(200)
request.end_headers()
with mock_lancedb_connection(handler) as db:
data = [{"value": 1}]
db.create_table("ct_pos", data, None, "overwrite")
db.create_table("ct_pos", data, None, "overwrite")
db.create_table("ct_pos", data, None, "create", True)
with pytest.raises(ValueError, match="Invalid mode"):
db.create_table("ct_pos", data, None, "drop")
assert modes == [["overwrite"], ["overwrite"], ["exist_ok"]]
CREATE_OPTIONS = [
{"new_table_data_storage_version": "2.0"},
{"new_table_enable_v2_manifest_paths": "false"},
{"bogus_option_xyz": "1"},
]
@pytest.mark.parametrize("storage_options", CREATE_OPTIONS)
@pytest.mark.parametrize("empty", [False, True])
@pytest.mark.asyncio
async def test_remote_create_rejects_write_options(storage_options, empty):
requests = []
def handler(request):
requests.append(request.path)
request.send_response(200)
request.end_headers()
kwargs = {"schema": pa.schema([("value", pa.int64())])}
if not empty:
kwargs["data"] = [{"value": 1}]
async with mock_lancedb_connection_async(handler) as db:
with pytest.raises(
NotImplementedError, match="write_options.*LanceDB Distributed"
):
await db.create_table("t", storage_options=storage_options, **kwargs)
assert requests == []
@pytest.mark.parametrize(
"options",
[
{"data_storage_version": "2.0"},
{"enable_v2_manifest_paths": False},
{"storage_options": {"x": "1"}},
],
)
def test_sync_remote_create_rejects_write_options(options):
requests = []
def handler(request):
requests.append(request.path)
request.send_response(200)
request.end_headers()
with mock_lancedb_connection(handler) as db:
with pytest.raises(NotImplementedError, match="LanceDB Distributed"):
db.create_table("t", [{"value": 1}], **options)
assert requests == []
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize(
"options", [{"index_cache_size": 10}, {"storage_options": {"x": "y"}}]
)
@pytest.mark.asyncio
async def test_remote_open_rejects_local_options(options, asynchronous):
requests = []
def handler(request):
requests.append(request.path)
request.send_response(200)
request.end_headers()
request.wfile.write(b'{"version": 1, "schema": {"fields": []}}')
if asynchronous:
async with mock_lancedb_connection_async(handler) as db:
with pytest.raises(NotImplementedError, match="LanceDB Distributed"):
await db.open_table("t", **options)
else:
with mock_lancedb_connection(handler) as db:
with pytest.raises(NotImplementedError, match="LanceDB Distributed"):
db.open_table("t", **options)
assert requests == []
@pytest.mark.asyncio
async def test_remote_open_rejects_location():
requests = []
def handler(request):
requests.append(request.path)
request.send_response(200)
request.end_headers()
request.wfile.write(b'{"version": 1, "schema": {"fields": []}}')
async with mock_lancedb_connection_async(handler) as db:
with pytest.raises(NotImplementedError, match="location.*LanceDB Distributed"):
await db.open_table("t", location="/tmp/zzz")
assert requests == []
@@ -0,0 +1,74 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import sys
import types
import pytest
from lancedb.rerankers import CohereReranker, VoyageAIReranker
RERANKERS = [
pytest.param("cohere", "COHERE_API_KEY", CohereReranker, {}, id="cohere"),
pytest.param(
"voyageai",
"VOYAGE_API_KEY",
VoyageAIReranker,
{"model_name": "rerank-2.5"},
id="voyageai",
),
]
def fake_sdk(monkeypatch, module_name):
"""Replace the SDK module with one whose Client records the API key."""
keys = []
def client(api_key=None):
keys.append(api_key)
return object()
module = types.ModuleType(module_name)
module.Client = client
monkeypatch.setitem(sys.modules, module_name, module)
return keys
@pytest.mark.parametrize("module_name, env_var, reranker_cls, kwargs", RERANKERS)
@pytest.mark.parametrize(
"explicit_key, environment_key, expected_key",
[
("explicit-test-key", "environment-test-key", "explicit-test-key"),
("explicit-test-key", None, "explicit-test-key"),
(None, "environment-test-key", "environment-test-key"),
],
)
def test_reranker_api_key_precedence(
monkeypatch,
module_name,
env_var,
reranker_cls,
kwargs,
explicit_key,
environment_key,
expected_key,
):
keys = fake_sdk(monkeypatch, module_name)
if environment_key is None:
monkeypatch.delenv(env_var, raising=False)
else:
monkeypatch.setenv(env_var, environment_key)
reranker_cls(api_key=explicit_key, **kwargs)._client
assert keys == [expected_key]
@pytest.mark.parametrize("module_name, env_var, reranker_cls, kwargs", RERANKERS)
def test_reranker_requires_api_key(
monkeypatch, module_name, env_var, reranker_cls, kwargs
):
keys = fake_sdk(monkeypatch, module_name)
monkeypatch.delenv(env_var, raising=False)
with pytest.raises(ValueError, match=f"{env_var} not set"):
reranker_cls(**kwargs)._client
assert keys == []
+199
View File
@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import os
from unittest.mock import MagicMock
import random
import lancedb
@@ -427,6 +428,38 @@ def test_rrf_multivector_ranks_each_result_list():
assert result["_rowid"].to_pylist() == [2, 1, 3]
@pytest.mark.parametrize("reranker_cls", [RRFReranker, MRRReranker])
def test_rank_fusion_return_score_all_keeps_both_scores(reranker_cls):
# A row found by both searches must keep its vector `_distance` and its FTS
# `_score` when the reranker is asked to return all scores.
vector_results = pa.table(
{
"_rowid": pa.array([1, 2], type=pa.uint64()),
"text": ["a", "b"],
"_distance": pa.array([0.1, 0.2], type=pa.float32()),
}
)
fts_results = pa.table(
{
"_rowid": pa.array([2, 3], type=pa.uint64()),
"text": ["b", "c"],
"_score": pa.array([5.0, 4.0], type=pa.float32()),
}
)
result = reranker_cls(return_score="all").rerank_hybrid(
"query", vector_results, fts_results
)
rows = {row["_rowid"]: row for row in result.to_pylist()}
assert rows[1]["_distance"] == pytest.approx(0.1)
assert rows[1]["_score"] is None
assert rows[2]["_distance"] == pytest.approx(0.2)
assert rows[2]["_score"] == pytest.approx(5.0)
assert rows[3]["_distance"] is None
assert rows[3]["_score"] == pytest.approx(4.0)
def test_rrf_reranker_distance():
data = pa.table(
{
@@ -547,6 +580,24 @@ def test_openai_reranker(tmp_path):
_run_test_reranker(reranker, table, "single player experience", None, schema)
def test_openai_reranker_does_not_send_temperature():
reranker = OpenaiReranker(api_key="test-key")
create = MagicMock()
create.return_value.choices = [
MagicMock(
message=MagicMock(
content='{"documents": [{"content": "a", "relevance_score": 0.5}]}'
)
)
]
reranker.__dict__["_client"] = MagicMock()
reranker.__dict__["_client"].chat.completions.create = create
reranker._rerank(pa.table({"text": ["a"]}), "query")
assert "temperature" not in create.call_args.kwargs
@pytest.mark.skipif(
os.environ.get("JINA_API_KEY") is None, reason="JINA_API_KEY not set"
)
@@ -785,6 +836,154 @@ def test_empty_hybrid_result_reranker():
assert "_rowid" in result.column_names
@pytest.mark.parametrize("norm", ["score", "rank"])
def test_hybrid_return_all_restores_original_scores(norm):
from lancedb.query import LanceHybridQueryBuilder
vector_results = pa.table(
{
"text": ["a", "b", "c"],
"_rowid": pa.array([0, 1, 2], type=pa.uint64()),
"_distance": pa.array([0.5, 2.5, 10.0], type=pa.float32()),
}
)
fts_results = pa.table(
{
"text": ["b", "a"],
"_rowid": pa.array([1, 0], type=pa.uint64()),
"_score": pa.array([3.25, 1.75], type=pa.float32()),
}
)
result = LanceHybridQueryBuilder._combine_hybrid_results(
fts_results=fts_results,
vector_results=vector_results,
norm=norm,
fts_query="query",
reranker=RRFReranker(return_score="all"),
limit=10,
with_row_ids=True,
)
# The raw distances and scores are returned, not the normalized values
# or ranks used for reranking.
rows = {row["_rowid"]: row for row in result.to_pylist()}
assert rows[0]["_distance"] == 0.5
assert rows[1]["_distance"] == 2.5
assert rows[2]["_distance"] == 10.0
assert rows[0]["_score"] == 1.75
assert rows[1]["_score"] == 3.25
assert rows[2]["_score"] is None
@pytest.mark.parametrize("return_score", ["relevance", "all"])
@pytest.mark.parametrize("first_row_id", [1, 2**63])
@pytest.mark.parametrize("score_type", [pa.float32(), pa.float64()])
def test_model_reranker_preserves_arrow_schema(
mocker, return_score, first_row_id, score_type
):
common_schema = pa.schema(
[
pa.field("_rowid", pa.uint64()),
pa.field("text", pa.string()),
pa.field("vector", pa.list_(pa.float32(), 2)),
],
metadata={b"source": b"reranker-test"},
)
vector_results = pa.Table.from_pylist(
[
{
"_rowid": first_row_id,
"text": "vector",
"vector": [1, 0],
"_distance": 0.1,
},
{
"_rowid": first_row_id + 1,
"text": "both",
"vector": [0, 1],
"_distance": 0.2,
},
],
schema=common_schema.append(pa.field("_distance", score_type)),
)
fts_results = pa.Table.from_pylist(
[
{
"_rowid": first_row_id + 1,
"text": "both",
"vector": [0, 1],
"_score": 0.9,
},
{
"_rowid": first_row_id + 2,
"text": "fts",
"vector": [1, 1],
"_score": 0.8,
},
],
schema=common_schema.append(pa.field("_score", score_type)),
)
reranker = CohereReranker(return_score=return_score)
reranker._client = mocker.Mock()
reranker._client.rerank.return_value.results = [
mocker.Mock(index=index, relevance_score=score)
for index, score in [(2, 0.9), (1, 0.8), (0, 0.7)]
]
result = reranker.rerank_hybrid("query", vector_results, fts_results)
assert result.select(common_schema.names).schema.equals(
common_schema, check_metadata=True
)
assert result["_rowid"].to_pylist() == [
first_row_id + 2,
first_row_id + 1,
first_row_id,
]
assert result["text"].to_pylist() == ["fts", "both", "vector"]
if return_score == "all":
assert (
result["_distance"]
.combine_chunks()
.equals(pa.array([None, 0.2, 0.1], type=score_type))
)
assert (
result["_score"]
.combine_chunks()
.equals(pa.array([0.8, 0.9, None], type=score_type))
)
@pytest.mark.parametrize("return_score", ["relevance", "all"])
def test_model_reranker_empty_results_preserve_schema(mocker, return_score):
common_schema = pa.schema(
[
("_rowid", pa.uint64()),
("text", pa.string()),
("vector", pa.list_(pa.float32(), 2)),
],
metadata={b"source": b"reranker-test"},
)
vector_results = pa.Table.from_pylist(
[], schema=common_schema.append(pa.field("_distance", pa.float32()))
)
fts_results = pa.Table.from_pylist(
[], schema=common_schema.append(pa.field("_score", pa.float32()))
)
reranker = CohereReranker(return_score=return_score)
reranker._client = mocker.Mock()
result = reranker.rerank_hybrid("query", vector_results, fts_results)
assert len(result) == 0
assert result.select(common_schema.names).schema.equals(
common_schema, check_metadata=True
)
assert result.schema.field("_relevance_score").type == pa.float32()
reranker._client.rerank.assert_not_called()
def test_cross_encoder_reranker_return_all(tmp_path):
pytest.importorskip("sentence_transformers")
reranker = CrossEncoderReranker(return_score="all")
+10
View File
@@ -36,3 +36,13 @@ def test_session_cache_configuration(tmp_path):
assert final_cache_size > initial_cache_size # Cache should have grown
assert final_cache_items >= initial_cache_items # Items should not decrease
assert initial_cache_size < index_cache_size + metadata_cache_size
def test_connection_session_returns_supplied_session(tmp_path):
"""Sync connections must expose the session they were opened with."""
db = lancedb.connect(tmp_path)
assert db.session is None
session = lancedb.Session()
db = lancedb.connect(tmp_path, session=session)
assert db.session is session
+17 -3
View File
@@ -137,9 +137,23 @@ async def test_async_namespace_connection_rejects_sql(tmp_path):
await connection.describe_query(NIL_QUERY_ID)
def test_describe_query_requires_uuid():
with pytest.raises(TypeError, match="UUID"):
remote_connection().describe_query(str(NIL_QUERY_ID))
@pytest.mark.asyncio
@pytest.mark.parametrize("identity", [NIL_QUERY_ID, str(NIL_QUERY_ID)])
async def test_describe_query_accepts_uuid_and_job_id_string(identity):
calls = []
class NativeConnection:
async def describe_query(self, query_id):
calls.append(query_id)
connection = AsyncConnection(NativeConnection())
await connection.describe_query(identity)
assert calls == [NIL_QUERY_ID]
def test_describe_query_rejects_registry_job_id():
with pytest.raises(ValueError, match="UUID"):
remote_connection().describe_query("registry-job-id")
@pytest.mark.parametrize(
+170
View File
@@ -0,0 +1,170 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
from datetime import timedelta
import json
from urllib.parse import parse_qs, urlparse
import lancedb
from lancedb.table import Table
import pytest
from test_remote_db import mock_lancedb_connection
@pytest.fixture
def legacy_table():
"""Implement the pre-existing abstract API without the two new members."""
def unsupported(self, *args, **kwargs):
raise NotImplementedError
def update_field_metadata(self, updates):
self.metadata_updates.append(updates)
return object() # The deprecated wrapper must not expose this result.
# Supply concrete implementations through normal ABC class creation. Leave
# namespace and replace_field_metadata inherited, as an old subclass would.
implementations = {
name: unsupported
for name in Table.__abstractmethods__
if name not in {"namespace", "replace_field_metadata"}
}
implementations.update(
name=property(lambda self: "legacy"),
update_field_metadata=update_field_metadata,
)
legacy_class = type("LegacyTable", (Table,), implementations)
table = legacy_class()
table.metadata_updates = []
return table
def test_legacy_table_namespace_and_id(legacy_table):
assert legacy_table.namespace == []
assert legacy_table.id == "legacy"
namespace = legacy_table.namespace
namespace.append("changed")
assert legacy_table.namespace == []
assert legacy_table.id == "legacy"
def test_legacy_table_replace_field_metadata(legacy_table):
with pytest.warns(DeprecationWarning, match="update_field_metadata"):
result = legacy_table.replace_field_metadata("nested.field", {"a": "b"})
assert result is None
assert legacy_table.metadata_updates == [
{"path": "nested.field", "metadata": {"a": "b"}, "replace": True}
]
def respond(request, body):
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(json.dumps(body).encode())
def test_remote_uri():
with mock_lancedb_connection(lambda request: respond(request, {})) as db:
assert db.uri == "db://dev"
@pytest.mark.parametrize("attribute", ["session", "read_consistency_interval"])
def test_remote_unsupported_properties(attribute):
with mock_lancedb_connection(lambda request: respond(request, {})) as db:
with pytest.raises(NotImplementedError, match=attribute):
getattr(db, attribute)
@pytest.mark.parametrize("tables", [[], ["first", "last"]])
def test_remote_len_and_contains_follow_pages(tables):
requests = []
def handler(request):
requests.append(request.path)
query = parse_qs(urlparse(request.path).query)
if tables and "page_token" not in query:
respond(request, {"tables": [tables[0]], "page_token": "opaque-next"})
else:
if tables:
assert query["page_token"] == ["opaque-next"]
respond(request, {"tables": tables[1:]})
with mock_lancedb_connection(handler) as db:
assert len(db) == len(tables)
assert ("last" in db) == bool(tables)
assert "missing" not in db
requests.clear()
assert ("first" in db) == bool(tables)
assert len(requests) == 1
@pytest.mark.parametrize("namespace", [[], ["parent", "child"]])
def test_remote_table_identifiers(namespace):
def handler(request):
respond(request, {"version": 1, "schema": {"fields": []}})
with mock_lancedb_connection(handler) as db:
table = db.open_table("rfm", namespace_path=namespace)
assert table.namespace == namespace
assert table.id == "$".join(namespace + ["rfm"])
def test_remote_replace_field_metadata():
updates = []
def handler(request):
if request.path.endswith("/describe/"):
respond(request, {"version": 1, "schema": {"fields": []}})
else:
assert request.path == "/v1/table/rfm/update_field_metadata/"
body = request.rfile.read(int(request.headers["Content-Length"]))
updates.append(json.loads(body))
respond(request, {"version": 2})
with mock_lancedb_connection(handler) as db:
table = db.open_table("rfm")
with pytest.warns(DeprecationWarning, match="update_field_metadata"):
assert table.replace_field_metadata("id", {"a": "b"}) is None
assert updates == [
{"updates": [{"path": "id", "metadata": {"a": "b"}, "replace": True}]}
]
@pytest.mark.parametrize("custom_session", [False, True])
def test_local_properties_and_metadata(tmp_path, custom_session):
supplied = lancedb.Session() if custom_session else None
db = lancedb.connect(
tmp_path, session=supplied, read_consistency_interval=timedelta(seconds=5)
)
session = db.session
assert session is supplied
before = session.size_bytes if session is not None else 0
table = db.create_table("rfm", [{"id": i} for i in range(3)])
assert table.to_arrow().num_rows == 3
if supplied is not None:
assert supplied.size_bytes > before
assert db.read_consistency_interval == timedelta(seconds=5)
assert table.namespace == []
assert table.id == "rfm"
with pytest.warns(DeprecationWarning):
table.replace_field_metadata("id", {"old": "value"})
with pytest.warns(DeprecationWarning):
table.replace_field_metadata("id", {"a": "b"})
assert table.schema.field("id").metadata == {b"a": b"b"}
def test_namespace_connection_properties_remain_writable(tmp_path):
session = lancedb.Session()
interval = timedelta(seconds=5)
with lancedb.connect_namespace(
"dir",
{"root": str(tmp_path)},
session=session,
read_consistency_interval=interval,
) as db:
assert db.session is session
assert db.read_consistency_interval == interval
db.read_consistency_interval = timedelta(0)
assert db.read_consistency_interval == timedelta(0)
+794 -8
View File
@@ -14,8 +14,8 @@ from concurrent.futures import ThreadPoolExecutor
from datetime import date, datetime, timedelta
from decimal import Decimal, localcontext
from time import sleep
from typing import List
from unittest.mock import patch
from typing import Any, List
from unittest.mock import MagicMock, patch
import lancedb
from lancedb import table as table_module
@@ -59,6 +59,124 @@ def _blob_v2_table(db: DBConnection, name: str):
return table
@pytest.mark.parametrize(
"threshold",
[
"inline_size_threshold",
"dedicated_size_threshold",
"pack_file_size_threshold",
],
)
@pytest.mark.parametrize(
"value,error",
[
(-1, ValueError),
(True, TypeError),
(False, TypeError),
(1.5, TypeError),
("8192", TypeError),
(ctypes.c_size_t(-1).value + 1, OverflowError),
],
)
def test_blob_thresholds_reject_invalid_values(threshold, value, error):
# Also runs in CI with pylance actually uninstalled.
with pytest.raises(error, match=f"{threshold} must"):
lancedb.blob("blob", **{threshold: value})
@pytest.mark.parametrize(
"threshold", ["dedicated_size_threshold", "pack_file_size_threshold"]
)
def test_blob_thresholds_reject_zero_for_positive_thresholds(threshold):
with pytest.raises(ValueError, match=f"{threshold} must be positive"):
lancedb.blob("blob", **{threshold: 0})
def test_blob_thresholds_accept_integer_boundaries():
maximum = ctypes.c_size_t(-1).value
field = lancedb.blob(
"blob",
nullable=False,
inline_size_threshold=0,
dedicated_size_threshold=maximum,
pack_file_size_threshold=maximum,
)
assert not field.nullable
assert field.metadata == {
b"lance-encoding:blob-inline-size-threshold": b"0",
b"lance-encoding:blob-dedicated-size-threshold": str(maximum).encode(),
b"lance-encoding:blob-pack-file-size-threshold": str(maximum).encode(),
}
def test_blob_thresholds_control_writes_after_reopen(tmp_path):
# Keep this in test_table.py: CI runs it without pylance or pandas installed.
field = lancedb.blob(
"blob",
inline_size_threshold=4,
dedicated_size_threshold=12,
pack_file_size_threshold=8,
)
metadata = {
b"lance-encoding:blob-inline-size-threshold": b"4",
b"lance-encoding:blob-dedicated-size-threshold": b"12",
b"lance-encoding:blob-pack-file-size-threshold": b"8",
}
assert field.metadata == metadata
schema = pa.schema([pa.field("id", pa.int64()), field])
db = lancedb.connect(tmp_path)
table = db.create_table("blobs", schema=schema)
# Every payload fits in the default inline tier; custom thresholds must
# instead send the larger values to packed and dedicated storage.
rows = [
{"id": 0, "blob": b"a" * 2},
{"id": 1, "blob": b"b" * 8},
{"id": 2, "blob": b"c" * 16},
{"id": 3, "blob": b"d" * 8},
]
def check_writes(table, expected):
assert table.schema.field("blob").metadata.items() >= metadata.items()
hits = table.search().with_row_id(True).limit(10).to_arrow()
actual = {row["id"]: row for row in hits.to_pylist()}
assert actual.keys() == {row["id"] for row in expected}
for row in expected:
size = len(row["blob"])
descriptor = actual[row["id"]]["blob"]
assert descriptor["size"] == size
assert descriptor["kind"] == (2 if size > 12 else 1 if size > 4 else 0)
row_ids = [actual[row["id"]]["_rowid"] for row in expected]
assert table.fetch_blobs("blob", row_ids).to_pylist() == [
row["blob"] for row in expected
]
# Two packed values reach the configured sidecar limit independently.
packed = [
actual[row["id"]]["blob"] for row in expected if len(row["blob"]) == 8
]
assert len({desc["blob_id"] for desc in packed}) == len(packed)
table.add(rows)
check_writes(table, rows)
table = lancedb.connect(tmp_path).open_table("blobs")
check_writes(table, rows)
updates = [
{"id": 0, "blob": b"e" * 16},
{"id": 1, "blob": b"f" * 2},
{"id": 2, "blob": b"g" * 8},
{"id": 3, "blob": b"h" * 8},
{"id": 4, "blob": b"i" * 16},
]
result = (
table.merge_insert("id")
.when_matched_update_all()
.when_not_matched_insert_all()
.execute(updates)
)
assert result.num_updated_rows == 4
assert result.num_inserted_rows == 1
check_writes(lancedb.connect(tmp_path).open_table("blobs"), updates)
async def _blob_v2_table_async(db: AsyncConnection, name: str):
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("blob")])
table = await db.create_table(name, schema=schema)
@@ -280,6 +398,30 @@ def test_create_table_infers_large_int_vectors(mem_db: DBConnection):
assert vector_column.to_pylist() == [[0.0, 300.0]]
def test_create_table_all_null_vector_column(mem_db: DBConnection):
# A vector column can legitimately arrive with every value null, e.g. when
# the embeddings have not been computed yet. The dimension is unknowable in
# that case, so schema inference must not crash and should leave the column
# as a variable-length list rather than a fixed-size one.
data = pa.table(
{
"id": pa.array([1, 2]),
"vector": pa.array([None, None], type=pa.list_(pa.float32())),
}
)
table = mem_db.create_table("all_null_vector", data=data)
vector_field = table.schema.field("vector")
assert pa.types.is_list(vector_field.type)
assert vector_field.type.value_type == pa.float32()
result = table.to_arrow()
assert result.num_rows == 2
assert result.column("vector").to_pylist() == [None, None]
assert table.count_rows() == 2
@pytest.mark.asyncio
async def test_create_table_async_infers_large_int_vectors(
mem_db_async: AsyncConnection,
@@ -518,6 +660,30 @@ def test_add(mem_db: DBConnection):
_add(table, schema)
def test_add_from_iterator_that_queries_table(mem_db: DBConnection):
source = mem_db.create_table("source", data=pa.table({"id": range(16)}))
target = mem_db.create_table("target", schema=source.schema)
def batches():
for _ in range(5):
yield source.search().limit(10).to_arrow()
target.add(batches())
assert target.count_rows() == 50
def test_create_table_from_iterator_that_queries_table(mem_db: DBConnection):
source = mem_db.create_table("source", data=pa.table({"id": range(16)}))
def batches():
yield source.search().limit(10).to_arrow()
target = mem_db.create_table("target", data=batches())
assert target.count_rows() == 10
def test_add_releases_arrow_buffers_without_gc(mem_db: DBConnection):
"""Regression test for https://github.com/lancedb/lancedb/issues/2512."""
schema = pa.schema([pa.field("x", pa.int64())])
@@ -1251,6 +1417,7 @@ def test_branches_preserve_namespace(tmp_path):
"lance"
) # namespace_path routes through lance's DirectoryNamespace
db = lancedb.connect(tmp_path)
db.create_namespace(["ns1"])
table = db.create_table("t", [{"id": 1}], namespace_path=["ns1"])
assert table.namespace == ["ns1"]
@@ -1585,6 +1752,47 @@ def test_create_index_async_returns_done_job(mem_db: DBConnection):
job.cancel()
@pytest.mark.parametrize(
"rq_kwargs", [{}, {"num_bits": None}, {"num_bits": 1}, {"num_bits": 4}]
)
@patch("lancedb.table.LanceTable.to_lance")
def test_create_ivfrq_index_accelerator(mock_to_lance, mem_db: DBConnection, rq_kwargs):
from lancedb.index import IvfRq
table = mem_db.create_table("test", [{"vector": [1.0] * 8}])
torch = MagicMock()
torch.cuda.is_available.return_value = True
with patch.dict(sys.modules, {"torch": torch}):
table.create_index("vector", config=IvfRq(accelerator="cuda", **rq_kwargs))
kwargs = mock_to_lance.return_value.create_index.call_args.kwargs
assert kwargs["index_type"] == "IVF_RQ"
assert kwargs["accelerator"] == "cuda"
if rq_kwargs.get("num_bits") is None:
assert "num_bits" not in kwargs
else:
assert kwargs["num_bits"] == rq_kwargs["num_bits"]
@pytest.mark.parametrize("method", ["create_index", "create_index_async"])
@pytest.mark.parametrize("wait_timeout", ["invalid", 1, []])
def test_create_index_invalid_wait_timeout(mem_db: DBConnection, method, wait_timeout):
table = mem_db.create_table("invalid_timeout", [{"id": 1}])
with pytest.raises(TypeError):
getattr(table, method)("id", config=BTree(), wait_timeout=wait_timeout)
assert table.list_indices() == []
@pytest.mark.parametrize("method", ["create_index", "create_index_async"])
@pytest.mark.parametrize("wait_timeout", [None, timedelta(seconds=1)])
def test_create_index_valid_wait_timeout(mem_db: DBConnection, method, wait_timeout):
table = mem_db.create_table("valid_timeout", [{"id": 1}])
result = getattr(table, method)("id", config=BTree(), wait_timeout=wait_timeout)
if result is not None:
result.wait()
assert len(table.list_indices()) == 1
@patch("lancedb.table.AsyncTable.create_index")
def test_create_index_method(mock_create_index, mem_db: DBConnection):
table = mem_db.create_table(
@@ -1725,6 +1933,51 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
)
@pytest.mark.parametrize("api", ["legacy", "unified"])
@pytest.mark.parametrize("cuda_failure", ["unavailable", "init_error"])
def test_create_index_cuda_failure_suggests_cpu(
api, cuda_failure, mem_db: DBConnection
):
table = mem_db.create_table(
f"test_cuda_unavailable_{api}",
data=[{"vector": [3.1, 4.1]}, {"vector": [5.9, 26.5]}],
)
torch = MagicMock()
torch.cuda.is_available.return_value = cuda_failure == "init_error"
if cuda_failure == "init_error":
torch.cuda.init.side_effect = RuntimeError("CUDA driver initialization failed")
with (
patch.dict(sys.modules, {"torch": torch}),
patch.object(table, "to_lance") as to_lance,
):
if api == "legacy":
with (
pytest.warns(DeprecationWarning, match="create_index"),
pytest.raises(RuntimeError, match="accelerator=None.*CPU"),
):
table.create_index(
metric="dot",
num_partitions=1,
num_sub_vectors=1,
vector_column_name="vector",
accelerator="cuda",
)
else:
with pytest.raises(RuntimeError, match="accelerator=None.*CPU"):
table.create_index(
"vector",
config=IvfPq(
distance_type="dot",
num_partitions=1,
num_sub_vectors=1,
accelerator="cuda",
),
)
to_lance.return_value.create_index.assert_not_called()
@patch("lancedb.table.AsyncTable.create_index")
def test_create_index_name_and_train_parameters(
mock_create_index, mem_db: DBConnection
@@ -1940,6 +2193,71 @@ def test_add_with_nans(mem_db: DBConnection):
assert np.allclose(filled_vectors[22.0], np.array([5.0, 0.0]))
@pytest.mark.parametrize("operation", ["create", "append", "overwrite"])
@pytest.mark.parametrize("input_type", ["pandas", "rows", "arrow"])
@pytest.mark.parametrize("on_bad_vectors", [None, "error", "drop", "fill", "null"])
def test_write_vectors_with_null_elements(
mem_db: DBConnection, operation, input_type, on_bad_vectors
):
schema = pa.schema({"vector": pa.list_(pa.float32(), 2), "id": pa.int64()})
vectors = [[3.0, 4.0], [np.nan, 1.0], [np.nan, np.nan]]
if input_type == "pandas":
pd = pytest.importorskip("pandas")
data = pd.DataFrame(
{
"vector": [np.array(v, dtype=np.float32) for v in vectors],
"id": [0, 1, 2],
}
)
else:
# Pandas turns the NaNs above into null child elements. Explicit nulls
# in other input formats must follow the same bad-vector policy.
data = [
{"vector": [3.0, 4.0], "id": 0},
{"vector": [None, 1.0], "id": 1},
{"vector": [None, None], "id": 2},
]
if input_type == "arrow":
data = pa.Table.from_pylist(data, schema=schema)
options = {} if on_bad_vectors is None else {"on_bad_vectors": on_bad_vectors}
if on_bad_vectors == "fill":
options["fill_value"] = 42.0
table = None
if operation != "create":
table = mem_db.create_table("test", schema=schema)
def write():
if operation == "create":
return mem_db.create_table("test", data=data, schema=schema, **options)
table.add(data, mode=operation, **options)
return table
if on_bad_vectors in (None, "error"):
# Create/overwrite can wrap errors from lazy Arrow readers in RuntimeError.
expected_error = (
ValueError if operation == "append" else (ValueError, RuntimeError)
)
with pytest.raises(expected_error, match="NaN|null"):
write()
if table is not None:
assert table.count_rows() == 0
return
table = write()
if on_bad_vectors == "drop":
expected = [{"vector": [3.0, 4.0], "id": 0}]
else:
expected = [
{"vector": [3.0, 4.0], "id": 0},
{"vector": [42.0, 1.0] if on_bad_vectors == "fill" else None, "id": 1},
{"vector": [42.0, 42.0] if on_bad_vectors == "fill" else None, "id": 2},
]
assert table.to_arrow().to_pylist() == expected
def test_add_with_empty_fixed_size_list_drops_bad_rows(mem_db: DBConnection):
class Schema(LanceModel):
text: str
@@ -2612,6 +2930,57 @@ def test_update_with_arrow_scalar(mem_db: DBConnection):
assert table.to_arrow()["vector"].to_pylist() == [[1.0, 2.0, 3.0, 4.0]]
@pytest.mark.asyncio
@pytest.mark.parametrize("async_api", [False, True])
@pytest.mark.parametrize("entries", [[("o'brien", 4), ("nil", None)], [], None])
async def test_update_map_arrow_scalar(tmp_path, async_api, entries):
map_type = pa.map_(pa.string(), pa.int64())
data = pa.table(
{
"id": [1, 2],
"attrs": pa.array([[("original", 1)], entries], type=map_type),
}
)
if async_api:
db = await lancedb.connect_async(tmp_path)
table = await db.create_table("maps", data)
source = await table.query().where("id = 2").to_arrow()
result = await table.update({"attrs": source["attrs"][0]}, where="id = 1")
actual = await table.query().to_arrow()
else:
db = lancedb.connect(tmp_path)
table = db.create_table("maps", data)
source = table.search().where("id = 2").to_arrow()
result = table.update(values={"attrs": source["attrs"][0]}, where="id = 1")
actual = table.to_arrow()
assert result.rows_updated == 1
assert actual.schema.field("attrs").type == map_type
assert actual.sort_by("id")["attrs"].to_pylist() == [entries, entries]
@pytest.mark.parametrize(
"map_type, entries",
[
(pa.map_(pa.int64(), pa.string()), []),
(
pa.map_(pa.string(), pa.map_(pa.string(), pa.int64())),
[("outer", [("inner", 3)]), ("null", None)],
),
],
)
def test_update_typed_map_arrow_scalar(mem_db: DBConnection, map_type, entries):
table = mem_db.create_table(
"maps",
pa.table({"id": [1, 2], "attrs": pa.array([None, entries], type=map_type)}),
)
scalar = table.search().where("id = 2").to_arrow()["attrs"][0]
result = table.update(values={"attrs": scalar}, where="id = 1")
actual = table.to_arrow().sort_by("id")["attrs"]
assert result.rows_updated == 1
assert actual.type == map_type
assert actual.to_pylist() == [entries, entries]
@pytest.mark.parametrize("use_arrow_scalar", [False, True])
@pytest.mark.parametrize(
"decimal_type, value",
@@ -3597,26 +3966,42 @@ def test_create_f16_table_from_arrow_data(mem_db: DBConnection):
assert "s-2" in expected["text"].to_pylist()
def test_create_f16_table(mem_db: DBConnection):
@pytest.mark.parametrize("accelerator", [None, "cuda"])
def test_create_f16_table(tmp_path, accelerator):
if accelerator == "cuda":
torch = pytest.importorskip("torch")
if not torch.cuda.is_available():
pytest.skip("CUDA not available")
class MyTable(LanceModel):
text: str
vector: Vector(32, value_type=pa.float16())
rng = np.random.default_rng(42)
vectors = rng.standard_normal((512, 32)).astype(np.float16)
df = pa.table(
{
"text": [f"s-{i}" for i in range(512)],
"vector": [rng.standard_normal(32).astype(np.float16) for _ in range(512)],
"vector": list(vectors),
}
)
table = mem_db.create_table(
db = lancedb.connect(tmp_path)
table = db.create_table(
"f16_tbl",
schema=MyTable,
)
table.add(df)
table.create_index(num_partitions=2, num_sub_vectors=2)
table.create_index(
"vector",
config=IvfPq(
num_partitions=2,
num_sub_vectors=2,
accelerator=accelerator,
),
)
query = df["vector"][2].as_py()
# Match the issue's float64 query against an explicitly typed float16 column.
query = vectors[2].astype(np.float64)
expected = table.search(query).limit(2).to_arrow()
assert "s-2" in expected["text"].to_pylist()
@@ -3673,6 +4058,42 @@ def test_multiple_vector_columns(mem_db: DBConnection):
assert result1["text"][0] != result2["text"][0]
@pytest.mark.parametrize(
"query",
[
(0.0, 0.0),
pa.array([0.0, 0.0]),
pa.chunked_array([[0.0], [0.0]]),
],
)
@pytest.mark.parametrize("query_type", ["auto", "vector"])
def test_sync_search_accepts_supported_vector_containers(
mem_db: DBConnection, query, query_type
):
schema = pa.schema(
[
pa.field("id", pa.int64()),
pa.field("small", pa.list_(pa.float32(), 2)),
pa.field("large", pa.list_(pa.float32(), 3)),
]
)
table = mem_db.create_table(
"supported_vector_containers",
data=pa.table(
{
"id": [1, 2],
"small": [[0.0, 0.0], [1.0, 1.0]],
"large": [[1.0, 1.0, 1.0], [0.0, 0.0, 0.0]],
},
schema=schema,
),
)
result = table.search(query, query_type=query_type).limit(1).to_arrow()
assert result["id"].to_pylist() == [1]
def test_create_scalar_index(mem_db: DBConnection):
vec_array = pa.array(
[[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]], pa.list_(pa.float32(), 2)
@@ -4378,6 +4799,58 @@ async def test_alter_columns_rejects_invalid_async(
assert await table.schema() == initial_schema
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize("list_type", [pa.list_, pa.large_list])
@pytest.mark.parametrize(
"value_type, values, inferred_type",
[
(pa.float64(), [1.25, 2.5], pa.float32()),
(pa.int32(), [0, 255], pa.uint8()),
(pa.int32(), [-1, 256], pa.float32()),
],
)
async def test_inferred_vector_field_metadata(
tmp_db: DBConnection,
tmp_db_async: AsyncConnection,
asynchronous,
list_type,
value_type,
values,
inferred_type,
):
metadata = {
"lancedb:description": "Embedding values",
"lancedb:tag:model": "test-model",
}
schema = pa.schema(
[
pa.field(
"vector", list_type(value_type), nullable=False, metadata=metadata
),
pa.field("text", pa.string(), metadata={"description": "Source text"}),
],
metadata={"description": "Source dataset"},
)
rows = [{"vector": values, "text": "first"}, {"vector": values, "text": "second"}]
data = pa.Table.from_pylist(rows, schema=schema)
if asynchronous:
await tmp_db_async.create_table("vector_metadata", data=data)
table = await tmp_db_async.open_table("vector_metadata")
actual_schema = await table.schema()
actual_data = await table.to_arrow()
else:
tmp_db.create_table("vector_metadata", data=data)
table = tmp_db.open_table("vector_metadata")
actual_schema = table.schema
actual_data = table.to_arrow()
expected_schema = schema.set(
0, schema.field("vector").with_type(pa.list_(inferred_type, 2))
)
assert actual_schema.equals(expected_schema, check_metadata=True)
assert actual_data.to_pylist() == rows
def test_update_field_metadata(mem_db: DBConnection):
data = pa.table({"id": [0, 1], "category": ["a", "b"]})
table = mem_db.create_table("my_table", data=data)
@@ -4542,6 +5015,134 @@ async def test_optimize(mem_db_async: AsyncConnection):
assert await table.query().to_arrow() == pa.table({"x": [[1], [2]]})
@pytest.mark.asyncio
async def test_optimize_compaction_options(mem_db_async: AsyncConnection):
table = await mem_db_async.create_table("test", data=[{"x": 1}])
await table.add([{"x": 2}])
stats = await table.optimize(
compaction_options={
"target_rows_per_fragment": 1,
"batch_size": 1,
"num_threads": 1,
}
)
assert stats.compaction.fragments_removed == 0
assert stats.compaction.fragments_added == 0
stats = await table.optimize(compaction_options={"target_rows_per_fragment": 3})
assert stats.compaction.fragments_removed == 2
assert stats.compaction.fragments_added == 1
with pytest.raises(ValueError, match="Invalid compaction option: unknown"):
await table.optimize(compaction_options={"unknown": 1})
def test_optimize_compaction_options_sync(mem_db: DBConnection):
table = mem_db.create_table("test", data=[{"x": 1}])
with pytest.raises(ValueError, match="target_rows_per_fragment must be between"):
table.optimize(compaction_options={"target_rows_per_fragment": 0})
@pytest.mark.parametrize("option", ["max_source_rows", "max_source_bytes"])
@pytest.mark.asyncio
async def test_optimize_compaction_source_limits(
mem_db_async: AsyncConnection, option: str
):
table = await mem_db_async.create_table("test", data=[{"x": 1}])
await table.add([{"x": 2}])
stats = await table.optimize(
compaction_options={
"target_rows_per_fragment": 3,
option: 1,
}
)
assert stats.compaction.fragments_removed == 0
assert stats.compaction.fragments_added == 0
@pytest.mark.asyncio
async def test_optimize_compaction_data_storage_version(
mem_db_async: AsyncConnection,
):
table = await mem_db_async.create_table("test", data=[{"x": 1}])
await table.add([{"x": 2}])
stats = await table.optimize(
compaction_options={
"target_rows_per_fragment": 3,
"data_storage_version": "2.2",
}
)
assert stats.compaction.fragments_removed == 2
assert stats.compaction.fragments_added == 1
table = await mem_db_async.create_table("cross_family", data=[{"x": 1}])
await table.add([{"x": 2}])
with pytest.raises(ValueError, match="V1 and V2 storage versions cannot be mixed"):
await table.optimize(
compaction_options={
"target_rows_per_fragment": 3,
"data_storage_version": "legacy",
}
)
@pytest.mark.asyncio
async def test_optimize_compaction_excluded_fragments(mem_db_async: AsyncConnection):
table = await mem_db_async.create_table("test", data=[{"x": 1}])
await table.add([{"x": 2}])
stats = await table.optimize(
compaction_options={
"target_rows_per_fragment": 3,
"excluded_fragment_ids": [0],
}
)
assert stats.compaction.fragments_removed == 0
assert stats.compaction.fragments_added == 0
stats = await table.optimize(compaction_options={"target_rows_per_fragment": 3})
assert stats.compaction.fragments_removed == 2
assert stats.compaction.fragments_added == 1
@pytest.mark.parametrize(
("option", "value", "message"),
[
("target_rows_per_fragment", 0, "must be between 1 and 4294967295"),
("max_rows_per_group", 0, "must be between 1 and 4294967295"),
("batch_size", 0, "must be between 1 and 4294967295"),
("num_threads", 0, "must be greater than 0"),
("target_rows_per_fragment", 2**32, "must be between 1 and 4294967295"),
("max_rows_per_group", 2**32, "must be between 1 and 4294967295"),
("batch_size", 2**32, "must be between 1 and 4294967295"),
("io_buffer_size", 2**63, "must be at most 9223372036854775807"),
("max_source_rows", 0, "must be greater than 0"),
("max_source_bytes", 0, "must be greater than 0"),
("data_storage_version", "invalid", "Unknown Lance storage version: invalid"),
(
"excluded_fragment_ids",
[-1],
"must contain values between 0 and 4294967295",
),
(
"excluded_fragment_ids",
[2**32],
"must contain values between 0 and 4294967295",
),
],
)
@pytest.mark.asyncio
async def test_optimize_compaction_options_validation(
mem_db_async: AsyncConnection, option: str, value: Any, message: str
):
table = await mem_db_async.create_table("test", data=[{"x": 1}])
with pytest.raises(ValueError, match=message):
await table.optimize(compaction_options={option: value})
@pytest.mark.asyncio
async def test_optimize_delete_unverified(tmp_db_async: AsyncConnection, tmp_path):
table = await tmp_db_async.create_table(
@@ -4592,6 +5193,57 @@ def test_optimize_warns_on_zero_cleanup_sync(mem_db: DBConnection):
assert all("concurrent" in str(w.message) for w in seen)
def test_optimize_retains_tagged_versions(tmp_db: DBConnection):
# A tagged version older than the cleanup cutoff must be retained, not make
# optimize() fail part-way (after compaction, before the index step).
table = tmp_db.create_table(
"test", data=pa.table({"id": list(range(100)), "text": ["a"] * 100})
)
table.create_index("id", config=BTree())
table.tags.create("release-1", table.version)
tagged_version = table.version
for i in range(3):
table.add(pa.table({"id": [1000 + i], "text": ["new"]}))
assert table.stats()["fragment_stats"]["num_fragments"] == 4
assert table.index_stats("id_idx").num_unindexed_rows == 3
sleep(1.1)
table.optimize(cleanup_older_than=timedelta(seconds=1))
# The index step ran after the prune step
assert table.index_stats("id_idx").num_unindexed_rows == 0
# It stays optimizable
table.optimize(cleanup_older_than=timedelta(seconds=1))
assert table.stats()["fragment_stats"]["num_fragments"] == 1
# Untagged old versions were pruned, the tagged one was retained
versions = [v["version"] for v in table.list_versions()]
assert tagged_version in versions
for added in range(tagged_version + 1, tagged_version + 4):
assert added not in versions
assert len(table) == 103
table.checkout("release-1")
assert len(table) == 100
assert table.to_arrow().num_rows == 100
@pytest.mark.asyncio
async def test_optimize_retains_tagged_versions_async(tmp_db_async: AsyncConnection):
table = await tmp_db_async.create_table("test", data=[{"x": [1]}])
await table.tags.create("keep", await table.version())
await table.add(data=[{"x": [2]}])
await table.add(data=[{"x": [3]}])
sleep(1.1)
stats = await table.optimize(cleanup_older_than=timedelta(seconds=1))
assert stats.prune.old_versions_removed >= 1
await table.checkout("keep")
assert await table.count_rows() == 1
assert await table.query().to_arrow() == pa.table({"x": [[1]]})
def test_replace_field_metadata(tmp_path):
db = lancedb.connect(tmp_path)
table = db.create_table("my_table", data=[{"x": 0}])
@@ -4647,6 +5299,81 @@ def test_stats(mem_db: DBConnection):
assert stats_with_index["fragment_stats"]["num_fragments"] == 1
@pytest.mark.parametrize("iterable_type", [iter, tuple])
@pytest.mark.parametrize("empty", [False, True])
@pytest.mark.parametrize("with_schema", [False, True])
def test_create_table_recordbatch_iterable(
mem_db: DBConnection, iterable_type, empty, with_schema
):
schema = pa.schema([pa.field("id", pa.int64())])
batches = [] if empty else [pa.RecordBatch.from_pydict({"id": [1]}, schema)]
data = iterable_type(batches)
if empty and not with_schema:
with pytest.raises(ValueError, match="empty iterable without a schema"):
mem_db.create_table("test", data=data)
return
table = mem_db.create_table(
"test", data=data, schema=schema if with_schema else None
)
assert table.schema == schema
assert table.to_arrow().to_pylist() == ([] if empty else [{"id": 1}])
@pytest.mark.asyncio
@pytest.mark.parametrize("iterable_type", [iter, tuple])
@pytest.mark.parametrize("empty", [False, True])
@pytest.mark.parametrize("with_schema", [False, True])
async def test_create_table_recordbatch_iterable_async(
mem_db_async: AsyncConnection, iterable_type, empty, with_schema
):
schema = pa.schema([pa.field("id", pa.int64())])
batches = [] if empty else [pa.RecordBatch.from_pydict({"id": [1]}, schema)]
data = iterable_type(batches)
if empty and not with_schema:
with pytest.raises(ValueError, match="empty iterable without a schema"):
await mem_db_async.create_table("test", data=data)
return
table = await mem_db_async.create_table(
"test", data=data, schema=schema if with_schema else None
)
assert await table.schema() == schema
assert (await table.to_arrow()).to_pylist() == ([] if empty else [{"id": 1}])
@pytest.mark.parametrize("iterable_type", [iter, tuple])
@pytest.mark.parametrize("on_bad_vectors", ["error", "drop", "fill", "null"])
def test_add_empty_recordbatch_iterable(
mem_db: DBConnection, iterable_type, on_bad_vectors
):
table = mem_db.create_table("test", [{"id": 1}])
if on_bad_vectors == "error":
# The default scannable path still requires an input schema. This
# fix does not change its validation policy for schema-less input.
with pytest.raises(ValueError, match="empty iterator"):
table.add(iterable_type([]), on_bad_vectors=on_bad_vectors)
else:
# Sanitization has the existing table schema available.
table.add(iterable_type([]), on_bad_vectors=on_bad_vectors)
assert table.to_arrow().to_pylist() == [{"id": 1}]
@pytest.mark.asyncio
@pytest.mark.parametrize("iterable_type", [iter, tuple])
@pytest.mark.parametrize("on_bad_vectors", ["error", "drop", "fill", "null"])
async def test_add_empty_recordbatch_iterable_async(
mem_db_async: AsyncConnection, iterable_type, on_bad_vectors
):
table = await mem_db_async.create_table("test", [{"id": 1}])
if on_bad_vectors == "error":
with pytest.raises(ValueError, match="empty iterator"):
await table.add(iterable_type([]), on_bad_vectors=on_bad_vectors)
else:
await table.add(iterable_type([]), on_bad_vectors=on_bad_vectors)
assert (await table.to_arrow()).to_pylist() == [{"id": 1}]
def test_create_table_empty_list_with_schema(mem_db: DBConnection):
"""Test creating table with empty list data and schema
@@ -4763,6 +5490,7 @@ async def test_async_search_runs_embedding_on_dedicated_executor(
)
@pytest.mark.experimental_functions
def test_computed_column_declare_and_refresh(tmp_path):
db = lancedb.connect(tmp_path)
table = db.create_table("computed", [{"x": 1}, {"x": 2}])
@@ -4786,6 +5514,7 @@ def test_computed_column_rejects_transforms_and_computed_together(tmp_path):
table.add_columns({"a": "x + 1"}, computed={"b": "x * 2"})
@pytest.mark.experimental_functions
def test_computed_column_blob_projection_inherits_semantics(tmp_path):
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
db = lancedb.connect(tmp_path)
@@ -4809,6 +5538,7 @@ def test_computed_column_blob_projection_inherits_semantics(tmp_path):
assert copied.to_pylist() == [b"hello", b"", None]
@pytest.mark.experimental_functions
@pytest.mark.asyncio
async def test_computed_column_async(tmp_path):
db = await lancedb.connect_async(tmp_path)
@@ -4823,10 +5553,13 @@ async def test_computed_column_async(tmp_path):
def test_function_errors_are_remote_only(tmp_path):
db = lancedb.connect(tmp_path)
table = db.create_table("t", [{"x": 1}])
with pytest.raises(NotImplementedError, match="LanceDB Cloud and Enterprise"):
with pytest.raises(
NotImplementedError, match="recorded only in LanceDB Distributed"
):
table.function_errors()
@pytest.mark.experimental_functions
def test_refresh_column_async_returns_job(tmp_path):
db = lancedb.connect(tmp_path)
table = db.create_table("computed_job", [{"x": 1}, {"x": 2}])
@@ -4855,6 +5588,7 @@ def test_refresh_column_async_returns_job(tmp_path):
table.refresh_column_async("x")
@pytest.mark.experimental_functions
@pytest.mark.asyncio
async def test_refresh_column_async_job_async_table(tmp_path):
db = await lancedb.connect_async(tmp_path)
@@ -4869,3 +5603,55 @@ async def test_refresh_column_async_job_async_table(tmp_path):
assert result.published_version == 4
assert await job.status() == "finished"
assert (await table.to_arrow())["tripled"].to_pylist() == [9]
@pytest.mark.experimental_functions
@pytest.mark.parametrize("interval", [None, 300])
def test_computed_auto_refresh_options(tmp_path, interval):
db = lancedb.connect(tmp_path)
table = db.create_table("refresh_options", [{"x": 1}])
before = table.version
table.add_columns(
computed={"doubled": "x * 2", "tripled": "x * 3"},
auto_refresh_enabled=False,
auto_refresh_interval_seconds=interval,
)
assert table.version == before + 1
for column in ("doubled", "tripled"):
metadata = table.schema.field(column).metadata
assert metadata[b"computed_column.auto_refresh_enabled"] == b"false"
if interval is None:
assert b"computed_column.auto_refresh_interval_seconds" not in metadata
else:
assert metadata[b"computed_column.auto_refresh_interval_seconds"] == b"300"
table.refresh_column("doubled")
assert table.to_arrow()["doubled"].to_pylist() == [2]
@pytest.mark.parametrize("value", [0, -1, True, 1.5, "300", 2**64])
def test_computed_auto_refresh_rejects_invalid_interval(tmp_path, value):
table = lancedb.connect(tmp_path).create_table("invalid_options", [{"x": 1}])
with pytest.raises(ValueError, match="auto_refresh_interval_seconds"):
table.add_columns(
computed={"doubled": "x * 2"}, auto_refresh_interval_seconds=value
)
assert table.schema.names == ["x"]
def test_auto_refresh_options_require_computed_columns(tmp_path):
table = lancedb.connect(tmp_path).create_table("invalid_kind", [{"x": 1}])
with pytest.raises(ValueError, match="require computed"):
table.add_columns({"doubled": "x * 2"}, auto_refresh_enabled=True)
@pytest.mark.experimental_functions
@pytest.mark.asyncio
async def test_async_computed_auto_refresh_uses_server_interval(tmp_path):
db = await lancedb.connect_async(tmp_path)
table = await db.create_table("server_interval", [{"x": 1}])
before = await table.version()
await table.add_columns(computed={"doubled": "x * 2"})
assert await table.version() == before + 1
metadata = (await table.schema()).field("doubled").metadata
assert metadata[b"computed_column.auto_refresh_enabled"] == b"true"
assert b"computed_column.auto_refresh_interval_seconds" not in metadata
@@ -0,0 +1,253 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
from datetime import timedelta
import inspect
from unittest.mock import AsyncMock, MagicMock
import lancedb
from lancedb.expr import col
from lancedb.index import BTree, FTS, HnswSq, IvfPq
from lancedb.remote.table import RemoteTable
from lancedb.table import LanceTable, Table
import pyarrow as pa
import pytest
@pytest.mark.parametrize(
"method",
[
"delete",
"drop_index",
"index_stats",
"create_index",
"create_scalar_index",
"create_fts_index",
"search",
"cleanup_old_versions",
"compact_files",
"optimize",
"to_polars",
],
)
def test_sync_table_signatures(method):
"""A Table call must bind the same arguments on either backend."""
def parameters(cls):
return [
(p.name, p.kind, p.default)
for p in inspect.signature(getattr(cls, method)).parameters.values()
]
assert parameters(Table) == parameters(LanceTable) == parameters(RemoteTable)
@pytest.fixture(params=[LanceTable, RemoteTable], ids=["local", "remote"])
def sync_table(request, monkeypatch):
"""Exercise real sync wrappers with a recording async backend."""
handle = MagicMock()
handle.name = "test"
handle.create_index = AsyncMock()
handle.delete = AsyncMock()
handle.drop_index = AsyncMock()
handle.index_stats = AsyncMock()
if request.param is RemoteTable:
table = RemoteTable(handle, "test_db")
else:
table = LanceTable.__new__(LanceTable)
table._table = handle
monkeypatch.setattr(table, "_ensure_no_legacy_fts_index", lambda: None)
return table, handle
def test_sync_keyword_names(sync_table):
table, handle = sync_table
predicate = col("id") == 1
table.delete(where=predicate)
handle.delete.assert_awaited_once()
expected = predicate._inner if isinstance(table, LanceTable) else predicate
assert handle.delete.await_args.args[0] is expected
table.drop_index(name="vector_idx")
handle.drop_index.assert_awaited_once_with("vector_idx")
table.index_stats(index_name="vector_idx")
handle.index_stats.assert_awaited_once_with("vector_idx")
def test_legacy_vector_positional_arguments(sync_table):
table, handle = sync_table
with pytest.warns(DeprecationWarning):
table.create_index("cosine", 2)
args, kwargs = handle.create_index.await_args
assert args == ("vector",)
assert isinstance(kwargs["config"], IvfPq)
assert kwargs["config"].distance_type == "cosine"
assert kwargs["config"].num_partitions == 2
assert kwargs["replace"] is True
def test_vector_tuning_options(sync_table):
table, handle = sync_table
timeout = timedelta(seconds=2)
with pytest.warns(DeprecationWarning):
table.create_index(
index_type="IVF_HNSW_SQ",
num_partitions=1,
m=10,
ef_construction=50,
max_iterations=12,
sample_rate=64,
target_partition_size=1000,
wait_timeout=timeout,
name="custom_idx",
replace=False,
train=False,
)
kwargs = handle.create_index.await_args.kwargs
config = kwargs.pop("config")
assert isinstance(config, HnswSq)
for name, value in {
"num_partitions": 1,
"m": 10,
"ef_construction": 50,
"max_iterations": 12,
"sample_rate": 64,
"target_partition_size": 1000,
}.items():
assert getattr(config, name) == value
assert kwargs == dict(
wait_timeout=timeout, name="custom_idx", replace=False, train=False
)
def test_scalar_defaults_and_wait_timeout(sync_table):
table, handle = sync_table
timeout = timedelta(seconds=2)
with pytest.warns(DeprecationWarning):
table.create_scalar_index("id", wait_timeout=timeout)
kwargs = handle.create_index.await_args.kwargs
assert isinstance(kwargs["config"], BTree)
assert kwargs["replace"] is True
assert kwargs["wait_timeout"] == timeout
def test_fts_tokenizer_and_wait_timeout(sync_table):
table, handle = sync_table
timeout = timedelta(seconds=2)
with pytest.warns(DeprecationWarning):
table.create_fts_index(
field_names="text",
tokenizer_name="en_stem",
replace=True,
wait_timeout=timeout,
custom_stop_words=["example"],
)
args, kwargs = handle.create_index.await_args
assert args == ("text",)
assert kwargs["replace"] is True
assert kwargs["wait_timeout"] == timeout
config = kwargs["config"]
assert isinstance(config, FTS)
assert config.language == "English"
assert config.stem is True
assert config.custom_stop_words == ["example"]
@pytest.mark.parametrize(
"kwargs, message",
[
({"use_tantivy": True}, "Tantivy-based FTS has been removed"),
({"ordering_field_names": "id"}, "ordering_field_names"),
({"writer_heap_size": 123}, "writer_heap_size"),
({"tokenizer_name": "invalid"}, "Invalid tokenizer name"),
],
)
def test_fts_unsupported_options(sync_table, kwargs, message):
table, handle = sync_table
with pytest.warns(DeprecationWarning), pytest.raises(ValueError, match=message):
table.create_fts_index("text", **kwargs)
handle.create_index.assert_not_awaited()
@pytest.mark.parametrize(
"method, kwargs",
[
(
"cleanup_old_versions",
{"older_than": timedelta(days=1), "delete_unverified": True},
),
("compact_files", {"target_rows_per_fragment": 1000}),
],
)
def test_remote_maintenance_options_warn(method, kwargs):
table = RemoteTable(MagicMock(name="test"), "test_db")
with pytest.warns(UserWarning, match="no-op"):
getattr(table, method)(**kwargs)
def test_remote_optimize_options():
handle = MagicMock()
handle.optimize = AsyncMock(side_effect=NotImplementedError("remote optimize"))
table = RemoteTable(handle, "test_db")
age = timedelta(days=1)
with pytest.raises(NotImplementedError, match="remote optimize"):
table.optimize(cleanup_older_than=age, delete_unverified=True, retrain=True)
handle.optimize.assert_awaited_once_with(
cleanup_older_than=age, delete_unverified=True, retrain=True
)
@pytest.mark.parametrize(
"method, old, new, value",
[
("delete", "predicate", "where", "id = 1"),
("drop_index", "index_name", "name", "vector_idx"),
("index_stats", "index_uuid", "index_name", "vector_idx"),
("create_fts_index", "column", "field_names", "text"),
],
)
def test_deprecated_remote_keywords(method, old, new, value):
handle = MagicMock()
handle.name = "test"
target = "create_index" if method == "create_fts_index" else method
setattr(handle, target, AsyncMock())
table = RemoteTable(handle, "test_db")
with pytest.warns(DeprecationWarning, match=f"{old} is deprecated"):
getattr(table, method)(**{old: value})
assert getattr(handle, target).await_args.args == (value,)
with pytest.raises(TypeError, match="Cannot specify both"):
getattr(table, method)(**{old: value, new: value})
@pytest.mark.parametrize("remote_wrapper", [False, True], ids=["local", "remote"])
def test_sync_search_and_polars(tmp_path, remote_wrapper):
"""Use the native engine through both sync wrappers, without a cloud service."""
local = lancedb.connect(tmp_path).create_table(
"test",
[{"id": 1, "text": "quick fox", "vector": [1.0, 1.0]}],
)
table = RemoteTable(local._table, "test_db") if remote_wrapper else local
table.create_index("text", config=FTS())
assert table.search("quick", query_type="fts").to_arrow()["id"].to_pylist() == [1]
# Both backends must accept the deprecated ordering argument in the same slot.
with pytest.warns(DeprecationWarning, match="ordering_field_name"):
table.search("quick", None, "fts", "id", ["text"])
fast = table.search([1.0, 1.0], fast_search=True).to_arrow()
assert len(fast) == 0 # No vector index: fast_search excludes unindexed rows.
assert table.search([1.0, 1.0]).to_arrow()["id"].to_pylist() == [1]
if remote_wrapper:
with pytest.raises(NotImplementedError, match=r"table.search\(\).to_polars"):
table.to_polars(batch_size=1)
assert table.search().to_polars()["id"].to_list() == [1]
else:
assert table.to_polars(batch_size=1).collect()["id"].to_list() == [1]
table.delete(where="id = 1")
assert table.count_rows() == 0
def test_index_replacement_defaults(tmp_path):
local = lancedb.connect(tmp_path).create_table("test", pa.table({"id": [1]}))
table = RemoteTable(local._table, "test_db")
for sync in [local, table]:
with pytest.warns(DeprecationWarning):
sync.create_scalar_index("id")
assert len(list(table.list_indices())) == 1

Some files were not shown because too many files have changed in this diff Show More