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

# Conflicts:
#	rust/lancedb/src/remote/table.rs
This commit is contained in:
Will Jones
2026-11-16 18:05:33 +00:00
218 changed files with 27953 additions and 2913 deletions
+2 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "lancedb-python"
version = "0.42.0-beta.10"
version = "0.42.0-beta.16"
publish = false
edition.workspace = true
description = "Python bindings for LanceDB"
@@ -37,6 +37,7 @@ pyo3-async-runtimes = { version = "0.29", features = [
"tokio-runtime",
] }
reqwest.workspace = true
rattler_conda_types = { version = "0.58.3", default-features = false }
pin-project.workspace = true
futures.workspace = true
serde.workspace = true
+183
View File
@@ -0,0 +1,183 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Measure fetch_blobs RSS in a fresh client process against real HTTP.
Run with the uv environment's Python. The server lives in a separate process so
payload generation and Arrow serialization are excluded from the client's RSS.
Each row contains 1 MiB; requests over the server's 64 MiB limit are split by the
SDK. Example: python benchmarks/bench_fetch_blobs_rss.py --rows 48 144
"""
import argparse
import json
import resource
import subprocess
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
def serve(batch_rows, row_mib):
import pyarrow as pa
payload = b"x" * (row_mib << 20)
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *args):
pass
def respond(self, status, data, content_type="application/json"):
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(data)))
self.send_header("phalanx-version", "0.5.0")
self.send_header("x-lancedb-version", "1")
self.end_headers()
for offset in range(0, len(data), 8192):
self.wfile.write(data[offset : offset + 8192])
def do_POST(self):
length = int(self.headers.get("Content-Length", 0))
request_body = self.rfile.read(length)
if self.path.endswith("/describe/"):
self.do_GET()
return
body = json.loads(request_body)
count = len(body["row_ids"])
if count * row_mib > 64:
self.respond(
400,
b"fetch_blobs accepts at most 67108864 total blob bytes",
)
return
schema = pa.schema([pa.field("image", pa.large_binary())])
sink = pa.BufferOutputStream()
with pa.ipc.new_stream(sink, schema) as writer:
for start in range(0, count, batch_rows):
array = pa.array(
[payload] * min(batch_rows, count - start),
type=pa.large_binary(),
)
writer.write_batch(pa.record_batch([array], schema=schema))
self.respond(200, sink.getvalue(), "application/vnd.apache.arrow.stream")
def do_GET(self):
if "/blob/image/" in self.path:
start, end = map(int, self.headers["Range"][6:].split("-"))
body = memoryview(payload)[start : end + 1]
self.send_response(206)
self.send_header("Content-Length", str(len(body)))
self.send_header("Content-Range", f"bytes {start}-{end}/{len(payload)}")
self.send_header("x-lancedb-version", "1")
self.end_headers()
for offset in range(0, len(body), 8192):
self.wfile.write(body[offset : offset + 8192])
return
self.respond(
200,
json.dumps(
{
"table": "test",
"version": 1,
"schema": {"fields": []},
}
).encode(),
)
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
print(server.server_port, flush=True)
server.serve_forever()
def client(port, rows, row_mib):
import lancedb
db = lancedb.connect(
"db://rss-test", api_key="test", host_override=f"http://127.0.0.1:{port}"
)
table = db.open_table("test")
# Reset the Linux high-water mark after imports and connection setup.
with open("/proc/self/clear_refs", "w") as reset:
reset.write("5")
def memory_kib(field):
with open("/proc/self/status") as status:
return next(
int(line.split()[1]) for line in status if line.startswith(field + ":")
)
before = memory_kib("VmRSS")
values = table.fetch_blobs("image", list(range(rows)))
peak = memory_kib("VmHWM")
assert len(values) == rows
assert values.buffers()[2].size == rows * (row_mib << 20)
# Inspect slices without copying the result to Python bytes.
for i in (0, rows - 1):
assert values.slice(i, 1).buffers()[2][i * (row_mib << 20)] == ord("x")
print(
json.dumps(
{
"rows": rows,
"payload_mib": rows * row_mib,
"baseline_rss_kib": before,
"peak_rss_kib": peak,
"peak_delta_kib": peak - before,
"peak_delta_per_payload": (peak - before) / (rows * row_mib * 1024),
"rusage_maxrss_kib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
}
),
flush=True,
)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--rows", nargs="+", type=int, default=[48, 144])
parser.add_argument("--batch-rows", type=int, default=48)
parser.add_argument("--row-mib", type=int, default=1)
parser.add_argument("--serve", action="store_true")
parser.add_argument("--client", type=int)
args = parser.parse_args()
if args.serve:
serve(args.batch_rows, args.row_mib)
elif args.client is not None:
client(args.client, args.rows[0], args.row_mib)
else:
server = subprocess.Popen(
[
sys.executable,
__file__,
"--serve",
"--batch-rows",
str(args.batch_rows),
"--row-mib",
str(args.row_mib),
],
stdout=subprocess.PIPE,
text=True,
)
try:
port = server.stdout.readline().strip()
for rows in args.rows:
subprocess.run(
[
sys.executable,
__file__,
"--client",
port,
"--rows",
str(rows),
"--row-mib",
str(args.row_mib),
],
check=True,
)
finally:
server.terminate()
server.wait()
if __name__ == "__main__":
main()
+1 -1
View File
@@ -64,7 +64,7 @@ tests = [
"polars>=0.19, <=1.32.3",
"pyarrow>=16",
"pyarrow-stubs>=16.0",
"pylance==15.0.0b16",
"pylance==15.0.0b22",
"requests>=2.31.0",
"datafusion>=54,<55",
"opentelemetry-sdk>=1.30.0",
+18
View File
@@ -17,6 +17,16 @@ __version__ = str(_Version(_native_version))
from ._lancedb import connect as lancedb_connect
from ._lancedb import FtsToken
from ._lancedb import (
FunctionColumnAutoRefreshStatus as FunctionColumnAutoRefreshStatus,
)
from ._lancedb import (
FunctionColumnLastRefreshJob as FunctionColumnLastRefreshJob,
)
from ._lancedb import FunctionColumnStatus as FunctionColumnStatus
from ._lancedb import (
FunctionColumnVersionStatus as FunctionColumnVersionStatus,
)
from ._lancedb import FunctionErrorFragment as FunctionErrorFragment
from ._lancedb import FunctionErrorRecord as FunctionErrorRecord
from ._lancedb import FunctionErrors as FunctionErrors
@@ -41,11 +51,15 @@ from .functions import (
FunctionApplication as FunctionApplication,
FunctionBinding as FunctionBinding,
FunctionDefinition as FunctionDefinition,
FunctionEnvironment as FunctionEnvironment,
FunctionRegistrationRequest as FunctionRegistrationRequest,
FunctionRetryPolicy as FunctionRetryPolicy,
FunctionVersion as FunctionVersion,
HuggingFaceModel as HuggingFaceModel,
PythonRuntimeSpec as PythonRuntimeSpec,
ResolvedEnvironment as ResolvedEnvironment,
ResolvedEnvironmentProvenance as ResolvedEnvironmentProvenance,
ResolvedPackage as ResolvedPackage,
RefreshColumnResult as RefreshColumnResult,
function as function,
udf as udf,
@@ -660,6 +674,10 @@ __all__ = [
"AsyncTable",
"CompactionOptions",
"FtsToken",
"FunctionColumnAutoRefreshStatus",
"FunctionColumnLastRefreshJob",
"FunctionColumnStatus",
"FunctionColumnVersionStatus",
"col",
"Expr",
"func",
+19
View File
@@ -35,6 +35,15 @@ FetchBlobsSync = Callable[[str, list[int]], pa.Array | pa.ChunkedArray]
FetchBlobsAsync = Callable[[str, list[int]], Awaitable[pa.Array | pa.ChunkedArray]]
def _validate_blob_buffer_size(size: Optional[int]) -> Optional[int]:
if size is None:
return None
size = operator.index(size)
if size < 0:
raise ValueError("buffer_size must be non-negative")
return size
def _normalize_blob_descriptor(value):
if isinstance(value, pa.Scalar):
value = value.as_py()
@@ -58,6 +67,16 @@ class BlobFile(io.RawIOBase):
def __init__(self, inner) -> None:
self._inner = inner
def set_buffer_size(self, size: int) -> None:
"""Set sequential read-ahead bytes (default 512 KiB); 0 disables it.
Changing the size discards unused prefetched bytes without moving the
cursor. Explicit ``read_range`` and ``read_ranges`` bypass read-ahead.
"""
if self.closed:
raise ValueError("set_buffer_size of closed file")
self._inner.set_buffer_size(_validate_blob_buffer_size(size))
async def aread(self) -> bytes:
if self.closed:
raise ValueError("read of closed file")
+118 -10
View File
@@ -117,7 +117,7 @@ class PyExpr:
def expr_col(name: str) -> PyExpr: ...
def expr_lit(
value: Union[bool, int, float, str, bytes, date, datetime, Decimal],
value: Union[bool, int, float, str, bytes, date, datetime, Decimal, None],
) -> PyExpr: ...
def expr_func(name: str, args: List[PyExpr]) -> PyExpr: ...
@@ -185,9 +185,14 @@ class Connection(object):
limit: Optional[int],
) -> list[str]: ... # Deprecated: Use list_tables instead
async def open_job(self, job_id: str) -> Job: ...
async def server_info(self) -> str: ...
async def list_gpu_classes(self) -> list[GpuClass]: ...
async def create_function_async(
self, request_json: str, namespace_path: Optional[List[str]] = None
self,
request_json: str,
namespace_path: Optional[List[str]] = None,
*,
exist_ok: bool = False,
) -> Job: ...
async def get_function(
self,
@@ -228,7 +233,12 @@ class Connection(object):
self, name: str, namespace_path: Optional[List[str]] = None
) -> None: ...
async def create_secret(
self, name: str, value: str, namespace_path: Optional[List[str]] = None
self,
name: str,
value: str,
namespace_path: Optional[List[str]] = None,
*,
exist_ok: bool = False,
) -> None: ...
async def alter_secret(
self, name: str, value: str, namespace_path: Optional[List[str]] = None
@@ -247,7 +257,12 @@ class Connection(object):
self, name: str, namespace_path: Optional[List[str]] = None
) -> Tuple[str, int, int]: ...
async def create_view(
self, name: str, query: str, namespace_path: Optional[List[str]] = None
self,
name: str,
query: str,
namespace_path: Optional[List[str]] = None,
*,
exist_ok: bool = False,
) -> Tuple[str, List[str], str, str, List[str], pa.Schema]: ...
async def describe_view(
self, name: str, namespace_path: Optional[List[str]] = None
@@ -285,7 +300,19 @@ class Connection(object):
page_limit: Optional[int] = None,
) -> NameListing: ...
def list_jobs(
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
self,
*,
page_token: Optional[str] = None,
page_limit: Optional[int] = None,
table: Optional[str] = None,
namespace_path: Optional[List[str]] = None,
state: Optional[
Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
] = None,
job_type: Optional[str] = None,
job_types: Optional[List[str]] = None,
created_at_gte_millis: Optional[int] = None,
created_at_lt_millis: Optional[int] = None,
) -> JobListing: ...
async def cancel_job(self, job_id: str) -> bool: ...
async def pause_job(self, job_id: str) -> str: ...
@@ -332,6 +359,8 @@ class Connection(object):
source_version: Optional[int] = None,
source_tag: Optional[str] = None,
is_shallow: bool = True,
*,
exist_ok: bool = False,
) -> Table: ...
async def rename_table(
self,
@@ -343,24 +372,30 @@ class Connection(object):
async def create_materialized_view(
self,
name: str,
source: str,
source: Optional[str] = None,
projections: Optional[List[Tuple[str, str]]] = None,
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,
*,
query: Optional[str] = None,
exist_ok: bool = False,
) -> Table: ...
async def create_materialized_view_async(
self,
name: str,
source: str,
source: Optional[str] = None,
projections: Optional[List[Tuple[str, str]]] = None,
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,
*,
query: Optional[str] = None,
exist_ok: bool = False,
) -> Job: ...
def list_materialized_views(
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
@@ -392,6 +427,7 @@ class BlobFile:
def seek(self, position: int) -> None: ...
def tell(self) -> int: ...
def size(self) -> int: ...
def set_buffer_size(self, size: int) -> None: ...
def read_range(self, offset: int, length: int) -> bytes: ...
def read_ranges(self, ranges: list[tuple[int, int]]) -> list[bytes]: ...
def read_up_to(self, length: int) -> bytes: ...
@@ -412,6 +448,8 @@ class Job:
) -> Optional[str]: ...
async def cancel(self) -> None: ...
async def refresh(self) -> None: ...
async def timeline(self) -> str: ...
async def stats(self) -> Optional[str]: ...
async def events(
self,
*,
@@ -537,7 +575,14 @@ class Table:
progress: Optional[Any] = None,
write_parallelism: Optional[int] = None,
allow_external_blob_outside_bases: bool = False,
retries: Optional[int] = None,
) -> AddResult: ...
async def execute_merge_insert(
self,
data: pa.RecordBatchReader,
parameters: Dict[str, Any],
retries: Optional[int] = None,
) -> MergeResult: ...
async def update(
self, updates: Dict[str, str], where: Optional[str]
) -> UpdateResult: ...
@@ -565,6 +610,7 @@ class Table:
*,
name: Optional[str],
train: Optional[bool],
exist_ok: bool = False,
): ...
async def create_index_async(
self,
@@ -589,6 +635,7 @@ class Table:
*,
name: Optional[str],
train: Optional[bool],
exist_ok: bool = False,
) -> Job: ...
async def list_versions(self) -> List[Dict[str, Any]]: ...
async def version(self) -> int: ...
@@ -634,6 +681,8 @@ class Table:
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[dict[str, int]] = None,
supervisor_resources: Optional[dict[str, int]] = None,
planning_workers: Optional[dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[str] = None,
@@ -654,6 +703,8 @@ class Table:
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[dict[str, int]] = None,
supervisor_resources: Optional[dict[str, int]] = None,
planning_workers: Optional[dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[str] = None,
@@ -671,6 +722,13 @@ class Table:
column: Optional[str] = None,
limit: Optional[int] = None,
) -> FunctionErrors: ...
async def column_statuses(
self, column: Optional[str] = None
) -> list[FunctionColumnStatus]: ...
async def column_status(self, column: str) -> FunctionColumnStatus: ...
async def wait_column_fresh(
self, column: str, timeout: Optional[timedelta] = None
) -> FunctionColumnStatus: ...
async def refresh_materialized_view(
self,
source_version: Optional[int] = None,
@@ -734,7 +792,12 @@ class Table:
def take_row_ids(self, row_ids: list[int]) -> TakeQuery: ...
async def blob_columns(self) -> list[str]: ...
async def fetch_blobs(
self, column: str, row_ids: list[int]
self,
column: str,
row_ids: list[int],
*,
version: Optional[int] = None,
snapshot_identity: Optional[str] = None,
) -> pa.LargeBinaryArray: ...
async def fetch_blob_ranges(
self,
@@ -742,9 +805,11 @@ class Table:
requests: Sequence[Sequence[int]],
) -> pa.LargeBinaryArray: ...
async def fetch_blob_files(
self, column: str, row_ids: list[int]
self, column: str, row_ids: list[int], buffer_size: Optional[int] = None
) -> list[Optional[BlobFile]]: ...
async def open_blob_file(self, descriptor: str) -> BlobFile: ...
async def open_blob_file(
self, descriptor: str, buffer_size: Optional[int] = None
) -> BlobFile: ...
def vector_search(self) -> VectorQuery: ...
class Tags:
@@ -878,6 +943,7 @@ class FTSQuery:
def add_query_vector(self, query_vec: pa.Array) -> None: ...
def nearest_to(self, query_vec: pa.Array) -> HybridQuery: ...
def order_by(self, ordering: Optional[List[ColumnOrdering]]): ...
async def count_rows(self) -> int: ...
async def output_schema(self) -> pa.Schema: ...
async def execute(
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
@@ -1088,6 +1154,46 @@ class FunctionErrors:
fragments: list[FunctionErrorFragment]
truncated: bool
class FunctionColumnVersionStatus:
name: str
namespace_path: list[str]
object_id: str
location: str
version: str
manifest_digest: str
class FunctionColumnLastRefreshJob:
job_id: str
state: str
automatic: Optional[bool]
completed_at_millis: Optional[int]
failure: Optional[JobFailureInfo]
class FunctionColumnAutoRefreshStatus:
enabled: bool
interval_seconds: Optional[int]
active_job_id: Optional[str]
state: str
failure_streak: int
effective_cooldown_millis: Optional[int]
blocked_reason: Optional[str]
next_run_at_millis: Optional[int]
next_run_at_reason: Optional[str]
class FunctionColumnStatus:
column: str
binding_id: str
function: FunctionColumnVersionStatus
table_version: int
rows: int
fresh: int
stale: int
never_computed: int
failed: int
last_refresh_job: Optional[FunctionColumnLastRefreshJob]
last_failure_job: Optional[FunctionColumnLastRefreshJob]
auto_refresh: FunctionColumnAutoRefreshStatus
class RefreshMaterializedViewResult:
@staticmethod
def from_json(value: str) -> RefreshMaterializedViewResult: ...
@@ -1179,6 +1285,7 @@ async def connect_catalog(
sql_host_override: Optional[str] = None,
read_consistency_interval: Optional[float] = None,
oauth_config: Optional[Any] = None,
storage_options: Optional[dict[str, str]] = None,
) -> Catalog: ...
class NameListing:
@@ -1262,3 +1369,4 @@ class AuthzObject:
def __repr__(self) -> str: ...
def validate_function_retry_policy(json: str) -> None: ...
def _validate_conda_requirement(requirement: str) -> None: ...
+144 -10
View File
@@ -3,13 +3,17 @@
"""Remote catalogs manage databases."""
from functools import cached_property
import os
import warnings
from concurrent.futures import ThreadPoolExecutor
from datetime import timedelta
from functools import cached_property
from typing import Any, AsyncIterator, Iterator, Optional, Union
from . import _lancedb
from .background_loop import LOOP
from .authz import AsyncAuthorization, Authorization
from .common import URI, sanitize_uri
from .db import AsyncConnection, DBConnection
from .remote import ClientConfig, OAuthConfig
from .remote.db import RemoteDBConnection
@@ -163,12 +167,14 @@ class Catalog:
client_config=None,
sql_host_override: Optional[str] = None,
oauth_config: Optional[OAuthConfig] = None,
storage_options: Optional[dict[str, str]] = None,
):
self._inner = inner
self._api_key = api_key
self._client_config = client_config
self._sql_host_override = sql_host_override
self._oauth_config = oauth_config
self._storage_options = storage_options
@cached_property
def authz(self) -> Authorization:
@@ -198,6 +204,7 @@ class Catalog:
self._client_config,
self._oauth_config,
self._sql_host_override,
self._storage_options,
)
def list_databases(
@@ -227,28 +234,71 @@ class Catalog:
async def connect_catalog_async(
endpoint: str,
uri: Optional[URI] = None,
*,
api_key: Optional[str] = None,
client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None,
region: Optional[str] = None,
host_override: Optional[str] = None,
sql_host_override: Optional[str] = None,
read_consistency_interval: Optional[timedelta] = None,
client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None,
storage_options: Optional[dict[str, str]] = None,
session: Optional[_lancedb.Session] = None,
manifest_enabled: bool = False,
namespace_client_properties: Optional[dict[str, str]] = None,
oauth_config: Optional[OAuthConfig] = None,
) -> AsyncCatalog:
"""Connect to an HTTP(S) server's root catalog.
"""Connect to a server's root catalog using database connection settings.
``host_override`` selects the HTTP(S) catalog endpoint when provided; otherwise
``uri`` must be an HTTP(S) endpoint. A ``db://`` URI can be shared with
[connect_async][lancedb.connect_async] when ``host_override`` is set: the URI's
database is ignored and requests target the root catalog.
``region`` is ignored with a warning when supplied. Catalog connections use
the explicit endpoint rather than a region-derived Cloud (legacy) endpoint.
``api_key`` defaults to the ``LANCEDB_API_KEY`` environment variable.
Embedded-only ``session``, ``manifest_enabled`` and
``namespace_client_properties`` are not supported.
Root requests omit database-selection headers. API key, client configuration,
OAuth, and table read consistency settings are inherited by opened databases.
OAuth, storage options, and table read consistency settings are inherited by
opened databases.
Database names containing slashes remain single logical names.
Set ``sql_host_override`` to the SQL service endpoint to execute SQL through
returned connections when the catalog endpoint uses HTTPS.
"""
if region is not None:
warnings.warn(
"region is ignored by connect_catalog_async; the catalog endpoint "
"is selected by host_override or uri.",
UserWarning,
stacklevel=2,
)
for name, value in (
("session", session),
("manifest_enabled", manifest_enabled or None),
("namespace_client_properties", namespace_client_properties),
):
if value is not None:
raise NotImplementedError(
f"{name} is not supported for catalog connections"
)
endpoint = host_override if host_override is not None else uri
if endpoint is None:
raise ValueError("uri or host_override is required for catalog connections")
if isinstance(client_config, dict):
client_config = ClientConfig(**client_config)
if client_config is None:
client_config = ClientConfig()
if (
api_key is None
and oauth_config is None
and client_config.header_provider is None
):
api_key = os.environ.get("LANCEDB_API_KEY")
inner = await _lancedb.connect_catalog(
endpoint,
sanitize_uri(endpoint),
api_key=api_key,
client_config=client_config,
sql_host_override=sql_host_override,
@@ -258,32 +308,115 @@ async def connect_catalog_async(
else None
),
oauth_config=oauth_config,
storage_options=storage_options,
)
return AsyncCatalog(inner)
def connect_catalog(
endpoint: str,
uri: Optional[URI] = None,
*,
api_key: Optional[str] = None,
client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None,
region: Optional[str] = None,
host_override: Optional[str] = None,
sql_host_override: Optional[str] = None,
read_consistency_interval: Optional[timedelta] = None,
request_thread_pool: Optional[Union[int, ThreadPoolExecutor]] = None,
client_config: Optional[Union[ClientConfig, dict[str, Any]]] = None,
storage_options: Optional[dict[str, str]] = None,
session: Optional[_lancedb.Session] = None,
manifest_enabled: bool = False,
namespace_client_impl: Optional[str] = None,
namespace_client_properties: Optional[dict[str, str]] = None,
namespace_client_pushdown_operations: Optional[list[str]] = None,
oauth_config: Optional[OAuthConfig] = None,
**kwargs: Any,
) -> Catalog:
"""Connect synchronously to an HTTP(S) server's root catalog.
"""Connect synchronously to a root catalog using database connection settings.
See [connect_catalog_async][lancedb.connect_catalog_async] for options.
The inputs match [connect][lancedb.connect]; ``region`` is ignored with a
warning when supplied. Namespace client options and embedded session settings
are not supported. ``request_thread_pool`` is deprecated and unused, as in
``connect``.
Local filesystem and object-store catalogs are not supported.
Examples
--------
```python
settings = {"api_key": "secret", "host_override": "https://my-server.example"}
catalog = lancedb.connect_catalog("db://analytics", **settings)
db = lancedb.connect("db://analytics", **settings)
```
"""
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}")
for name, value in (
("namespace_client_impl", namespace_client_impl),
("namespace_client_pushdown_operations", namespace_client_pushdown_operations),
):
if value is not None:
raise NotImplementedError(
f"{name} is not supported for catalog connections"
)
if region is not None:
warnings.warn(
"region is ignored by connect_catalog; the catalog endpoint "
"is selected by host_override or uri.",
UserWarning,
stacklevel=2,
)
if request_thread_pool is not None:
warnings.warn(
"request_thread_pool is no longer used and will be removed in "
"a future release.",
DeprecationWarning,
stacklevel=2,
)
if isinstance(client_config, dict):
client_config = ClientConfig(**client_config)
if client_config is None:
client_config = ClientConfig()
for name, field in (
("connection_timeout", "connect_timeout"),
("read_timeout", "read_timeout"),
):
if kwargs.get(name) is not None:
warnings.warn(
f"{name} is deprecated and will be removed in a future release. "
f"Please use client_config.timeout_config.{field} instead.",
DeprecationWarning,
stacklevel=2,
)
setattr(
client_config.timeout_config,
field,
timedelta(seconds=kwargs[name]),
)
if (
api_key is None
and oauth_config is None
and client_config.header_provider is None
):
api_key = os.environ.get("LANCEDB_API_KEY")
return Catalog(
LOOP.run(
connect_catalog_async(
endpoint,
uri,
api_key=api_key,
host_override=host_override,
client_config=client_config,
sql_host_override=sql_host_override,
read_consistency_interval=read_consistency_interval,
storage_options=storage_options,
session=session,
manifest_enabled=manifest_enabled,
namespace_client_properties=namespace_client_properties,
oauth_config=oauth_config,
)
),
@@ -291,4 +424,5 @@ def connect_catalog(
client_config=client_config,
sql_host_override=sql_host_override,
oauth_config=oauth_config,
storage_options=storage_options,
)
File diff suppressed because it is too large Load Diff
+18 -5
View File
@@ -29,6 +29,8 @@ from lancedb._lancedb import PyExpr, expr_col, expr_lit, expr_func
__all__ = ["Expr", "col", "lit", "func"]
_NOT_LITERAL = object()
_STR_TO_PA_TYPE: dict = {
"bool": pa.bool_(),
"boolean": pa.bool_(),
@@ -92,9 +94,16 @@ class Expr:
# for dict keys / set membership.
__hash__ = None # type: ignore[assignment]
def __init__(self, inner: PyExpr, *, column_path: str | None = None) -> None:
def __init__(
self,
inner: PyExpr,
*,
column_path: str | None = None,
literal_value: object = _NOT_LITERAL,
) -> None:
self._inner = inner
self._column_path = column_path
self._literal_value = literal_value
def __bool__(self) -> bool:
# An Expr describes a predicate that the query engine evaluates per row,
@@ -301,14 +310,16 @@ def col(name: str) -> Expr:
return Expr(expr_col(name), column_path=name)
def lit(value: Union[bool, int, float, str, bytes, date, datetime, Decimal]) -> Expr:
def lit(
value: Union[bool, int, float, str, bytes, date, datetime, Decimal, None],
) -> Expr:
"""Create a literal (constant) value expression.
Parameters
----------
value:
A Python ``bool``, ``int``, ``float``, ``str``, ``bytes``, ``date``,
``datetime``, or ``Decimal``.
``datetime``, ``Decimal``, or ``None`` for SQL NULL.
Examples
--------
@@ -316,10 +327,12 @@ def lit(value: Union[bool, int, float, str, bytes, date, datetime, Decimal]) ->
>>> col("price") * lit(1.1)
Expr((price * 1.1))
"""
if not isinstance(value, (bool, int, float, str, bytes, date, datetime, Decimal)):
if value is not None and not isinstance(
value, (bool, int, float, str, bytes, date, datetime, Decimal)
):
raise TypeError(f"Unsupported literal type: {type(value).__name__}")
return Expr(expr_lit(value))
return Expr(expr_lit(value), literal_value=value)
def func(name: str, *args: ExprLike) -> Expr:
File diff suppressed because it is too large Load Diff
+159 -7
View File
@@ -4,9 +4,13 @@
"""Handles to asynchronous registry jobs, SQL queries, and local operations."""
import asyncio
import logging
import reprlib
import time
from contextlib import suppress
from datetime import timedelta
from os import PathLike
from pathlib import Path
from typing import Any, Callable, Generic, Optional, TypeVar, cast
import pyarrow as pa
@@ -15,6 +19,7 @@ from lancedb.background_loop import LOOP
from . import _lancedb
from ._lancedb import JobDescription, JobFailureInfo, JobInfo, _append_doc_url
from .functions import RefreshColumnResult
from .remote.errors import HttpError, RetryError
T = TypeVar("T")
@@ -50,11 +55,13 @@ def _timeout_message(
)
def _normalize_job_progress(progress):
def _normalize_job_progress(progress, *, query=False):
"""Normalize ``wait(progress=...)`` using the same convention as writes."""
if progress is True:
from tqdm.auto import tqdm
if query:
return tqdm(bar_format="Query{postfix} [{elapsed}]"), True
return tqdm(unit=" rows"), True
if progress is False or progress is None:
return None, False
@@ -62,6 +69,7 @@ def _normalize_job_progress(progress):
_ETA_MAX_SAMPLE_INTERVAL_MILLIS = 10 * 60 * 1_000
_QUERY_PROGRESS_INTERVAL_SECONDS = 1.0
def _progress_eta(previous, current):
@@ -200,6 +208,7 @@ class AsyncJob(Generic[T]):
self._inner = inner
self._result_decoder = result_decoder
self._last_progress_snapshot = None
self._created_at = time.monotonic()
def _enrich_progress(self, snapshot):
enriched = _with_progress_eta(self._last_progress_snapshot, snapshot)
@@ -232,17 +241,29 @@ class AsyncJob(Generic[T]):
async def progress(self) -> Optional[dict[str, Any]]:
"""Fetch a structured progress snapshot.
Registry jobs always report lifecycle fields. Queue metadata and
counters are included when supplied by the server. Older servers may
Registry jobs always report lifecycle fields. SQL query handles report
lifecycle state and ``client_elapsed_time_millis``, measured since this
handle was created. They do not expose server build phases or logs.
Queue metadata and counters are included when supplied by the server.
Older servers may
omit counters, and in-process operations return ``None``. A missing
counter is unknown rather than zero. This is additive to :meth:`status`,
whose string contract is unchanged.
"""
if self._inner is None:
return None
await self._inner.status()
state = await self._inner.status()
description = getattr(self._inner, "_description", None)
if description is None or description.progress is None:
if self.job_type == "query":
return {
"job_id": self.id,
"job_type": "query",
"state": state,
"client_elapsed_time_millis": int(
(time.monotonic() - self._created_at) * 1_000
),
}
return None
return self._enrich_progress(description.progress)
@@ -267,6 +288,13 @@ class AsyncJob(Generic[T]):
new execution epoch or smaller plan resets the bar to that plan.
``False`` preserves the original wait behavior.
For SQL-backed Function registration, progress shows the query's
lifecycle state and client elapsed time. It observes the existing
query handle while its original waiter runs; it does not resubmit or
cancel the registration. Detailed bake phases and build logs are not
available from the current query handle. Failure exceptions retain the
server's cause and request identifiers.
Raises `JobFailedError` if the operation failed, `JobCancelledError`
if it was cancelled, and `TimeoutError` if `timeout` elapses first.
Transient connection and read errors are retried with capped exponential
@@ -282,7 +310,10 @@ class AsyncJob(Generic[T]):
"""
if self._inner is None:
return cast(T, None)
progress_obj, owns = _normalize_job_progress(progress)
query_progress = (
progress is not False and progress is not None and self.job_type == "query"
)
progress_obj, owns = _normalize_job_progress(progress, query=query_progress)
progress_callback = _job_progress_callback(progress_obj, self._enrich_progress)
last_error = None
@@ -308,13 +339,46 @@ class AsyncJob(Generic[T]):
await asyncio.sleep(delay)
delay = min(delay * 2, 30.0)
async def observe_query():
async def report():
try:
snapshot = await self.progress()
if snapshot is not None:
progress_callback(snapshot)
except Exception:
logging.getLogger(__name__).warning(
"job progress observer failed", exc_info=True
)
waiter = asyncio.create_task(wait_with_retries())
try:
while not waiter.done():
await report()
await asyncio.wait(
{waiter}, timeout=_QUERY_PROGRESS_INTERVAL_SECONDS
)
try:
return await waiter
finally:
await report()
finally:
if not waiter.done():
waiter.cancel()
with suppress(asyncio.CancelledError):
await waiter
wait_for_result = (
observe_query
if query_progress and progress_callback is not None
else wait_with_retries
)
try:
try:
if timeout is None:
result = await wait_with_retries()
result = await wait_for_result()
else:
result = await asyncio.wait_for(
wait_with_retries(), timeout.total_seconds()
wait_for_result(), timeout.total_seconds()
)
except asyncio.TimeoutError as error:
if last_error is None:
@@ -422,6 +486,57 @@ class AsyncJob(Generic[T]):
description = self._inner._description if self._inner is not None else None
return getattr(description, name) if description is not None else None
async def stats(self) -> Optional[str]:
"""Return a printable run report for this Function job.
The report includes recorded phase timings, finishing-supervisor slot
occupancy, all-attempt split execution and batch latency, and accepted-row
throughput. Each call reads the current server report.
Returns ``None`` while the job is running or if no recorded profile is
available, without waiting for completion. Missing measurements remain
unavailable rather than becoming zero. The server formats the report;
the SDK returns it verbatim.
Requires a server-side Function job and a server supporting run reports.
Local operations and SQL query handles do not support this operation.
Unsupported operations raise ``NotImplementedError`` or a server error.
This method returns text; use ``print`` to display it.
Examples
--------
>>> print(await job.stats()) # doctest: +SKIP
"""
if self._inner is None:
raise NotImplementedError(
"job statistics require a server-side Function job"
)
return await self._inner.stats()
async def export_timeline(self, path: str | PathLike[str]) -> None:
"""Write a fresh recorded Function job timeline as Chrome trace JSON.
Open the file in Perfetto or Chrome tracing. The recording contains
retained split spans grouped by worker and timestamped job phases.
Batch counts and latency statistics are included as details; individual
batch timestamps are not recorded. Running jobs export a partial snapshot
without waiting or cancelling. Download again to include later work.
Requires a server-side Function job and a server supporting timeline
export. Unsupported operations raise ``NotImplementedError`` or a server
error. The destination is overwritten only after the trace is fetched.
Filesystem errors propagate to the caller.
Examples
--------
>>> await job.export_timeline("refresh.trace.json") # doctest: +SKIP
"""
if self._inner is None:
raise NotImplementedError(
"job timeline export requires a server-side Function job"
)
trace = await self._inner.timeline()
await asyncio.to_thread(Path(path).write_text, trace, encoding="utf-8")
async def events(
self,
*,
@@ -621,6 +736,37 @@ class Job(Generic[T]):
def _field(self, name: str) -> Optional[Any]:
return getattr(self._inner, name) if self._inner is not None else None
def stats(self) -> Optional[str]:
"""Return a printable Function job run report.
See [AsyncJob.stats][lancedb.job.AsyncJob.stats] for metrics and availability.
Examples
--------
>>> print(job.stats()) # doctest: +SKIP
"""
if self._inner is None:
raise NotImplementedError(
"job statistics require a server-side Function job"
)
return LOOP.run(self._inner.stats())
def export_timeline(self, path: str | PathLike[str]) -> None:
"""Write Chrome trace JSON for this Function job.
See :meth:`AsyncJob.export_timeline`. Open the file in Perfetto or
Chrome tracing.
Examples
--------
>>> job.export_timeline("refresh.trace.json") # doctest: +SKIP
"""
if self._inner is None:
raise NotImplementedError(
"job timeline export requires a server-side Function job"
)
return LOOP.run(self._inner.export_timeline(path))
def events(
self,
*,
@@ -649,3 +795,9 @@ def _typed_job(
) -> AsyncJob[T]:
"""Bind an internal JSON-producing job to its public result model."""
return AsyncJob(inner, result_decoder)
def _opened_job(inner: "_lancedb.Job") -> AsyncJob:
if inner.job_type in ("function_refresh", "computed_refresh", "refresh_column"):
return _typed_job(inner, RefreshColumnResult.from_json)
return AsyncJob(inner)
+78 -2
View File
@@ -6,7 +6,19 @@
from __future__ import annotations
import asyncio
from typing import Any, AsyncIterator, Callable, Generic, Iterator, Optional, TypeVar
from collections import deque
from itertools import islice
from operator import index
from typing import (
Any,
AsyncIterator,
Callable,
Generic,
Iterator,
Optional,
TypeVar,
overload,
)
from .background_loop import LOOP
@@ -59,29 +71,85 @@ class Listing(Iterator[T], Generic[T]):
print(name)
Use ``list(connection.list_views())`` to collect all results.
Indexes and slices refer to the remaining items and do not consume them.
A bounded forward slice, such as ``listing[:5]``, fetches only enough pages
to reach its stop. ``len(listing)``, negative indexes, and open-ended or
reverse slices fetch and cache all remaining results. Iteration then drains
that cache. These operations may perform requests and raise request errors.
"""
def __init__(self, inner: AsyncListing[T]):
self._inner = inner
self._buffer: deque[T] = deque()
def __iter__(self) -> Listing[T]:
return self
def __next__(self) -> T:
if self._buffer:
return self._buffer.popleft()
try:
return LOOP.run(self._inner.__anext__())
except StopAsyncIteration:
raise StopIteration from None
def _fill(self, count: Optional[int]) -> None:
while count is None or len(self._buffer) < count:
try:
item = LOOP.run(self._inner.__anext__())
except StopAsyncIteration:
return
self._buffer.append(item)
def __len__(self) -> int:
"""Fetch and cache every remaining item, returning the remaining count."""
self._fill(None)
return len(self._buffer)
def __bool__(self) -> bool:
self._fill(1)
return bool(self._buffer)
@overload
def __getitem__(self, key: int) -> T: ...
@overload
def __getitem__(self, key: slice) -> list[T]: ...
def __getitem__(self, key: int | slice) -> T | list[T]:
"""Read remaining items without consuming them; bounded slices stay lazy."""
if isinstance(key, slice):
start = 0 if key.start is None else index(key.start)
stop = None if key.stop is None else index(key.stop)
step = 1 if key.step is None else index(key.step)
if step == 0:
raise ValueError("slice step cannot be zero")
if start >= 0 and stop is not None and stop >= 0 and step > 0:
if start >= stop:
return []
self._fill(stop)
start, stop, step = key.indices(len(self._buffer))
return list(
islice(self._buffer, start, stop, min(step, len(self._buffer) + 1))
)
self._fill(None)
return list(self._buffer)[key]
position = index(key)
self._fill(None if position < 0 else position + 1)
return self._buffer[position]
def num_page_results(self) -> int:
"""Return the number of cached items available without another request."""
return self._inner.num_page_results()
return len(self._buffer) + self._inner.num_page_results()
def page_token(self) -> Optional[str]:
"""Return the next request's token.
See [AsyncListing.page_token][lancedb.listing.AsyncListing.page_token]
for initial, cached, final-page, and error behavior.
Indexing, slicing, and counting can also advance this token; drain all
``num_page_results()`` cached items before resuming from it.
"""
return self._inner.page_token()
@@ -175,6 +243,9 @@ class _AsyncPagedNameListing(AsyncIterator[str]):
class AsyncTableListing(_AsyncPagedNameListing):
"""Awaitable table iterator; awaiting loads one page.
Iteration fetches all pages. The ``tables`` attribute contains only the
current page, so use ``await db.table_exists([name])`` for existence checks.
For example::
page = await db.list_tables(limit=20)
@@ -229,6 +300,10 @@ class _PagedNameListing(Iterator[str]):
class TableListing(_PagedNameListing):
"""Table iterator retaining the current page as a list.
Iteration fetches all pages. The ``tables`` attribute contains only the
current page, so use ``db.table_exists([name])`` or ``name in db`` for
existence checks. Use ``list(db.list_tables())`` to collect all names.
For example::
page = db.list_tables(limit=20)
@@ -239,6 +314,7 @@ class TableListing(_PagedNameListing):
@property
def tables(self) -> list[str]:
"""A copy of the table names in the most recently fetched page."""
return self._inner.tables
@@ -134,6 +134,16 @@ def _quote_identifier(name: str) -> str:
return f"`{escaped}`"
def _validate_create_materialized_view(source, query, select, where, limit):
if query is not None:
if any(value is not None for value in (source, select, where, limit)):
raise ValueError(
"query cannot be combined with source, select, where or limit"
)
elif source is None:
raise ValueError("either source or query must be provided")
def normalize_select(select: SelectArg) -> Optional[List[Tuple[str, str]]]:
"""``select`` items may be a column name, an ``(alias, expression)`` pair,
or a dict of the same. A bare name projects itself and is quoted, so any
+21 -2
View File
@@ -161,6 +161,8 @@ class LanceMergeInsertBuilder(object):
on_bad_vectors: str = "error",
fill_value: float = 0.0,
timeout: Optional[timedelta] = None,
*,
retries: Optional[int] = None,
) -> MergeInsertResult:
"""
Executes the merge insert operation
@@ -189,7 +191,22 @@ class LanceMergeInsertBuilder(object):
first attempt will not be cancelled.
When this is set, the timeout is enforced on all attempts, including
the first.
the first. For remote tables it is sent as a server execution timeout;
it does not extend HTTP read or proxy idle timeouts, or prove that a
failed request did not commit.
retries: int, optional
Override the remote retry budget for this execution only (0 to 255).
Use ``execute(new_data, retries=0)`` to disable even retries after
precommit conflicts (409) or rate limits (429). This does not change
connection-wide/read budgets or local transaction conflict retries.
By default, remote calls use the connection's
[RetryConfig][lancedb.remote.RetryConfig]. Its ``statuses`` (also set
through ``LANCE_CLIENT_RETRY_STATUSES``) selects candidates within
the retry budget; it never permits replay of ambiguous merge outcomes.
In particular, 502, ordinary 503, and 504 are never replayed, even if
configured. Reconcile table contents before manually repeating a merge
whose commit outcome is unknown.
Returns
-------
@@ -198,4 +215,6 @@ class LanceMergeInsertBuilder(object):
"""
if timeout is not None:
self._timeout = timeout
return self._table._do_merge(self, new_data, on_bad_vectors, fill_value)
return self._table._do_merge(
self, new_data, on_bad_vectors, fill_value, retries=retries
)
+69 -10
View File
@@ -10,6 +10,7 @@ through a namespace abstraction.
from __future__ import annotations
import json
import sys
import warnings
from typing import Any, Dict, Iterable, List, Optional, Union
@@ -39,6 +40,9 @@ from lance_namespace_urllib3_client.models.query_table_request_vector import (
QueryTableRequestVector,
)
from lance_namespace_urllib3_client.models.string_fts_query import StringFtsQuery
from lance_namespace_urllib3_client.models.structured_fts_query import (
StructuredFtsQuery,
)
from lance_namespace.errors import (
NamespaceNotEmptyError,
NamespaceNotFoundError,
@@ -78,6 +82,7 @@ from lancedb.materialized_view import (
SelectArg,
)
from lancedb.table import AsyncTable, LanceTable, Table
from lancedb.query import MatchQuery, MultiMatchQuery, PhraseQuery
from lancedb.util import validate_table_name
from lancedb.common import DATA
from lancedb.pydantic import LanceModel
@@ -178,6 +183,26 @@ def _query_to_namespace_request(
full_text_query_request = QueryTableRequestFullTextQuery(
string_query=StringFtsQuery(query=fts_query)
)
elif getattr(fts_query, "operator", None) is not None:
columns = fts_query.columns or []
text = fts_query.query
if len(text) >= 2 and text.startswith('"') and text.endswith('"'):
if len(columns) > 1:
raise ValueError(
"Phrase queries cannot be used with multiple columns."
)
structured = PhraseQuery(text[1:-1], columns[0] if columns else None)
elif len(columns) > 1:
structured = MultiMatchQuery(text, columns, operator=fts_query.operator)
else:
structured = MatchQuery(
text, columns[0] if columns else None, operator=fts_query.operator
)
full_text_query_request = QueryTableRequestFullTextQuery(
structured_query=StructuredFtsQuery.from_dict(
{"query": json.loads(structured.to_json())}
)
)
elif hasattr(fts_query, "query"):
full_text_query_request = QueryTableRequestFullTextQuery(
string_query=StringFtsQuery(
@@ -579,12 +604,15 @@ class LanceNamespaceDBConnection(DBConnection):
If limit is None, return all table names; zero returns an empty list.
.. deprecated::
Use :meth:`list_tables` instead, which provides proper pagination support.
Iterate over :meth:`list_tables` to get all names, or use
:meth:`table_exists` to check for a particular table. The listing's
``tables`` attribute contains only one page.
"""
import warnings
warnings.warn(
"table_names() is deprecated, use list_tables() instead",
"table_names() is deprecated, iterate list_tables() for all names "
"or use table_exists([name]) to check existence",
DeprecationWarning,
stacklevel=2,
)
@@ -693,14 +721,16 @@ class LanceNamespaceDBConnection(DBConnection):
def create_materialized_view(
self,
name: str,
source: MaterializedViewSource,
source: Optional[MaterializedViewSource] = None,
*,
query: Optional[str] = None,
select: "SelectArg" = None,
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,
exist_ok: bool = False,
) -> "MaterializedView":
"""Define a materialized view over a table in the root namespace.
See
@@ -712,12 +742,14 @@ class LanceNamespaceDBConnection(DBConnection):
self._inner.create_materialized_view(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
exist_ok=exist_ok,
)
).name
)
@@ -727,25 +759,29 @@ class LanceNamespaceDBConnection(DBConnection):
def create_materialized_view_async(
self,
name: str,
source: MaterializedViewSource,
source: Optional[MaterializedViewSource] = None,
*,
query: Optional[str] = None,
select: "SelectArg" = None,
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,
exist_ok: bool = False,
) -> Job[None]:
job = LOOP.run(
self._inner.create_materialized_view_async(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
exist_ok=exist_ok,
)
)
return Job(job)
@@ -1015,6 +1051,8 @@ class LanceNamespaceDBConnection(DBConnection):
bool
True if the table exists, False otherwise.
"""
if self._route_pushdown_to_rust:
return LOOP.run(self._inner.table_exists(table_id))
request = TableExistsRequest(id=table_id)
try:
self._namespace_client.table_exists(request)
@@ -1030,7 +1068,11 @@ class LanceNamespaceDBConnection(DBConnection):
limit: Optional[int] = None,
) -> TableListing:
"""
List all tables in this database with pagination support.
Iterate over all tables in this database, fetching pages as needed.
The ``tables`` attribute contains only the current page (100 names by
default). Iterate over the listing to visit all pages, or use
``table_exists([name])`` to check for a particular table.
Parameters
----------
@@ -1227,12 +1269,15 @@ class AsyncLanceNamespaceDBConnection:
If limit is None, return all table names; zero returns an empty list.
.. deprecated::
Use :meth:`list_tables` instead, which provides proper pagination support.
Iterate over :meth:`list_tables` to get all names, or use
:meth:`table_exists` to check for a particular table. The listing's
``tables`` attribute contains only one page.
"""
import warnings
warnings.warn(
"table_names() is deprecated, use list_tables() instead",
"table_names() is deprecated, iterate list_tables() for all names "
"or use table_exists([name]) to check existence",
DeprecationWarning,
stacklevel=2,
)
@@ -1327,25 +1372,29 @@ class AsyncLanceNamespaceDBConnection:
async def create_materialized_view(
self,
name: str,
source: MaterializedViewSource,
source: Optional[MaterializedViewSource] = None,
*,
query: Optional[str] = None,
select: "SelectArg" = None,
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,
exist_ok: bool = False,
) -> "AsyncMaterializedView":
"""Define a materialized view over a table in the root namespace."""
view = await self._inner.create_materialized_view(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
exist_ok=exist_ok,
)
# Reopen through the namespace so the view's table carries the
# namespace client and pushdown configuration a bare inner table lacks.
@@ -1354,25 +1403,29 @@ class AsyncLanceNamespaceDBConnection:
async def create_materialized_view_async(
self,
name: str,
source: MaterializedViewSource,
source: Optional[MaterializedViewSource] = None,
*,
query: Optional[str] = None,
select: "SelectArg" = None,
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,
exist_ok: bool = False,
) -> AsyncJob[None]:
"""Submit materialized-view creation and return its job."""
return await self._inner.create_materialized_view_async(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
with_no_data=with_no_data,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
exist_ok=exist_ok,
)
async def open_materialized_view(self, name: str) -> "AsyncMaterializedView":
@@ -1614,6 +1667,8 @@ class AsyncLanceNamespaceDBConnection:
bool
True if the table exists, False otherwise.
"""
if self._route_pushdown_to_rust:
return await self._inner.table_exists(table_id)
request = TableExistsRequest(id=table_id)
try:
self._namespace_client.table_exists(request)
@@ -1628,7 +1683,11 @@ class AsyncLanceNamespaceDBConnection:
limit: Optional[int] = None,
) -> AsyncTableListing:
"""
List all tables in this database with pagination support.
Iterate over all tables in this database, fetching pages as needed.
The ``tables`` attribute contains only the current page (100 names by
default). Iterate over the listing to visit all pages, or use
``table_exists([name])`` to check for a particular table.
Parameters
----------
+226 -39
View File
@@ -4,6 +4,7 @@
from __future__ import annotations
import asyncio
import re
from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor
from datetime import timedelta
@@ -41,7 +42,7 @@ from .rerankers.base import Reranker
from .rerankers.rrf import RRFReranker
from .rerankers.util import check_reranker_result
from .schema import blob_column_paths, is_blob_like_field, schema_has_blob_field
from .util import _validate_query_vector, flatten_columns, get_uri_scheme
from .util import _validate_query_vector, add_note, flatten_columns, get_uri_scheme
from . import _wal_hybrid # WAL-PK-FUSION: delete.
from ._blob import (
BLOB_MODE_TO_HANDLING,
@@ -194,20 +195,57 @@ def _unsupported_blob_pandas_error(reason: str) -> RuntimeError:
)
def _supports_local_blob_fetch(
def _supports_blob_fetch(
async_table: "AsyncTable", pushdown_operations: Iterable[str]
) -> bool:
# Remote tables and QueryTable pushdown answer queries on a server, so a
# fetch through this handle could read another version.
return async_table._inner._is_native() and "QueryTable" not in pushdown_operations
# Remote queries carry their producing snapshot in response metadata.
# Namespace QueryTable pushdown has no equivalent snapshot contract.
return (
not async_table._inner._is_native() or "QueryTable" not in pushdown_operations
)
def _remote_blob_snapshot(schema: pa.Schema) -> tuple[int, str]:
value = (schema.metadata or {}).get(b"lancedb:query_version", b"")
if not value.isdigit() or not 0 < int(value) < 2**64:
raise NotImplementedError(
"blob_mode='bytes' requires a stable table snapshot: the query response "
"has a missing, invalid, or inconsistent x-lancedb-query-version header. "
"Upgrade the server and use a table without Realtime/MemWAL, or use "
"blob_mode='descriptions'."
)
identity = (schema.metadata or {}).get(b"lancedb:query_snapshot", b"")
if not re.fullmatch(rb"v1:[0-9a-f]{64}", identity):
raise NotImplementedError(
"blob_mode='bytes' requires a trustworthy query snapshot identity: "
"missing or unsupported x-lancedb-query-snapshot. Upgrade the server "
"on every serving node, or use blob_mode='descriptions'."
)
return int(value), identity.decode("ascii")
def _merge_query_snapshot(result: pa.Table, *sources: pa.Table) -> pa.Table:
"""Preserve a snapshot only when every query leg used the same identity."""
keys = (b"lancedb:query_version", b"lancedb:query_snapshot")
snapshots = {
tuple((source.schema.metadata or {}).get(key) for key in keys)
for source in sources
}
metadata = dict(result.schema.metadata or {})
for key in keys:
metadata.pop(key, None)
snapshot = next(iter(snapshots)) if len(snapshots) == 1 else None
if snapshot is not None and all(value is not None for value in snapshot):
metadata.update(zip(keys, snapshot))
return result.replace_schema_metadata(metadata)
def _blob_bytes_without_snapshot_error() -> NotImplementedError:
return NotImplementedError(
"blob_mode='bytes' cannot safely materialize blob columns without a "
"stable table snapshot. LanceDB Enterprise and namespace QueryTable pushdown "
"run the query on a server, so the blob fetch could read another table "
"version. Use blob_mode='descriptions' to inspect descriptors. To read "
"stable table snapshot. Namespace QueryTable pushdown does not bind "
"the query and blob fetches to one table version. "
"Use blob_mode='descriptions' to inspect descriptors. To read "
"payloads, select row IDs with with_row_id(True), then call "
"table.fetch_blobs(column, row_ids) or table.fetch_blob_files(column, "
"row_ids). Keep the source unchanged between selection and fetching."
@@ -835,10 +873,29 @@ class FullTextSearchQuery(pydantic.BaseModel):
query: str | FullTextQuery
If a string, it is treated as a MatchQuery.
If a FullTextQuery object, it is used directly.
operator: FullTextOperator, optional
Combine terms in a string query using AND or OR (the default).
Quoted strings keep phrase semantics regardless of the operator.
"""
columns: Optional[List[str]] = None
query: Union[str, FullTextQuery]
operator: Optional[FullTextOperator] = None
@pydantic.model_validator(mode="after")
def _validate_operator(self) -> Self:
if self.operator is not None and not isinstance(self.query, str):
raise ValueError("operator requires a string full-text query")
return self
def _add_fts_position_error_note(error: Exception) -> None:
if "position is not found but required for phrase queries" in str(error):
add_note(
error,
"Phrase queries require an index built with positions. Rebuild it with "
"table.create_index(column, config=FTS(with_position=True), replace=True).",
)
class Query(pydantic.BaseModel):
@@ -1109,6 +1166,7 @@ class LanceQueryBuilder(ABC):
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
fast_search: bool = None,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> Self:
"""
Create a query builder based on the given query and query type.
@@ -1133,6 +1191,10 @@ class LanceQueryBuilder(ABC):
fast_search: bool
Skip flat search of unindexed data.
"""
if operator is not None:
operator = FullTextOperator(operator)
if not isinstance(query, str) or query_type not in ("auto", "fts"):
raise ValueError("operator requires a string full-text query")
if query_type != "fts":
_validate_query_vector(query)
@@ -1163,6 +1225,9 @@ class LanceQueryBuilder(ABC):
table, query, query_type, vector_column_name
)
if operator is not None and query_type != "fts":
raise ValueError("operator requires a string full-text query")
if query_type == "hybrid":
return LanceHybridQueryBuilder(
table, query, vector_column_name, fts_columns=fts_columns
@@ -1176,7 +1241,7 @@ class LanceQueryBuilder(ABC):
ordering_field_name=ordering_field_name,
fts_columns=fts_columns,
fast_search=fast_search,
)
).operator(operator)
if isinstance(query, (list, tuple)):
query = np.array(query, dtype=np.float32)
@@ -1297,9 +1362,9 @@ class LanceQueryBuilder(ABC):
columns without pylance. Other local blob v2 queries return
descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads
in ``"bytes"`` mode, through :meth:`to_arrow`.
LanceDB Enterprise blob queries support only ``"descriptions"`` until a
stable
table snapshot can bind the query and blob fetches.
Enterprise queries support ``"bytes"`` at the query response's
snapshot and ``"descriptions"`` without payload reads. Remote
``"lazy"`` handles are not supported.
**kwargs
Forwarded to pyarrow.Table.to_pandas after query execution and
optional flattening.
@@ -1307,6 +1372,10 @@ class LanceQueryBuilder(ABC):
validate_blob_mode(blob_mode)
if _is_remote_query_table(self._table):
blob_sources = self._validated_blob_sources(blob_mode)
if blob_mode == "bytes":
return flatten_columns(
self.to_arrow(timeout=timeout, blob_mode=blob_mode), flatten
).to_pandas(**kwargs)
return _finish_remote_pandas(
self.to_arrow(timeout=timeout),
blob_mode=blob_mode,
@@ -1629,7 +1698,8 @@ class LanceQueryBuilder(ABC):
_query_is_plain_blob_scan(query)
and getattr(self, "_reranker", None) is None
and not _query_needs_lance_scanner(self)
and _supports_local_blob_fetch(
and self._table._table._inner._is_native()
and _supports_blob_fetch(
self._table._table,
getattr(self._table, "_pushdown_operations", ()),
)
@@ -1650,11 +1720,12 @@ class LanceQueryBuilder(ABC):
if blob_mode != "bytes":
return blob_sources
reject_unfetchable_blob_columns(schema, self._columns, blob_sources)
if blob_sources and not _supports_local_blob_fetch(
if blob_sources and not _supports_blob_fetch(
self._table._table, getattr(self._table, "_pushdown_operations", ())
):
raise _blob_bytes_without_snapshot_error()
reject_unmatched_blob_outputs(self._blob_output_schema(), blob_sources)
if not _is_remote_query_table(self._table):
reject_unmatched_blob_outputs(self._blob_output_schema(), blob_sources)
return blob_sources
def _blob_output_schema(self) -> pa.Schema:
@@ -1667,9 +1738,20 @@ class LanceQueryBuilder(ABC):
return tbl
if blob_mode == "descriptions":
return strip_auto_row_ids(tbl, blob_sources)
return replace_blob_columns_with_bytes_sync(
tbl, blob_sources, self._table.fetch_blobs
)
reject_unmatched_blob_outputs(tbl.schema, blob_sources)
if _is_remote_query_table(self._table) and blob_sources:
version, identity = _remote_blob_snapshot(tbl.schema)
async def fetch_at_version(column, row_ids):
return await self._table._table._inner.fetch_blobs(
column, row_ids, version=version, snapshot_identity=identity
)
def fetch_blobs(column, row_ids):
return LOOP.run(fetch_at_version(column, row_ids))
else:
fetch_blobs = self._table.fetch_blobs
return replace_blob_columns_with_bytes_sync(tbl, blob_sources, fetch_blobs)
def _finalize_blob_query_table(
self,
@@ -2386,6 +2468,7 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
rs_table = result_set.read_all()
result_set = self._reranker.rerank_vector(self._str_query, rs_table)
check_reranker_result(result_set)
result_set = _merge_query_snapshot(result_set, rs_table)
# convert result_set back to RecordBatchReader
result_set = pa.RecordBatchReader.from_batches(
result_set.schema, result_set.to_batches()
@@ -2507,6 +2590,7 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
super().__init__(table)
self._query = query
self._phrase_query = False
self._operator: Optional[FullTextOperator] = None
# Deprecated compatibility parameter. Native FTS ordering is now
# configured through order_by(); LanceQueryBuilder.create emits the warning.
_ = ordering_field_name
@@ -2516,6 +2600,36 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
fts_columns = [fts_columns]
self._fts_columns = fts_columns
def operator(
self, operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]]
) -> LanceFtsQueryBuilder:
"""Combine terms in a string query with ``"AND"`` or ``"OR"``.
The default is OR. AND requires every term to match. For example,
``table.search("gripper closed", query_type="fts").operator("AND")``.
Structured queries specify their own operators. Quoted strings and
``phrase_query()`` retain their phrase semantics.
"""
if operator is not None and not isinstance(self._query, str):
raise ValueError("operator requires a string full-text query")
self._operator = FullTextOperator(operator) if operator is not None else None
return self
def count_rows(self) -> int:
"""Count all full-text matches satisfying the query's filter.
Ignores limit, offset, selection, ordering, and reranking. ``fast_search``
still restricts the count to indexed data. This streams matching scores
without loading document columns and may scan every match.
For example, ``table.search("gripper closed", query_type="fts",``
``operator="AND").where("active = true").count_rows()``.
"""
self._table._ensure_no_legacy_fts_index()
query = self._table._table._sync_query_to_async(self.to_query_object())
assert isinstance(query, AsyncFTSQuery)
return LOOP.run(query.count_rows())
def phrase_query(self, phrase_query: bool = True) -> LanceFtsQueryBuilder:
"""Set whether to use phrase query.
@@ -2572,7 +2686,9 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
fragment_ids=self._fragment_ids,
use_rte=self._use_rte,
full_text_query=FullTextSearchQuery(
query=self._query_with_phrase_semantics(), columns=self._fts_columns
query=self._query_with_phrase_semantics(),
columns=self._fts_columns,
operator=self._operator,
),
offset=self._offset,
fast_search=self._fast_search,
@@ -2599,8 +2715,10 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
query = self._query_for_scan(blob_sources)
results = self._table._execute_query(query, timeout=timeout).read_all()
if self._reranker is not None:
source = results
results = self._reranker.rerank_fts(self._query, results)
check_reranker_result(results)
results = _merge_query_snapshot(results, source)
return self._finalize_blob_query_table(
results, blob_mode=blob_mode, blob_sources=blob_sources
)
@@ -2847,6 +2965,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
with_row_ids=True,
offset=self._offset,
)
results = _merge_query_snapshot(results, fts_results, vector_results)
return self._finish_hybrid_results(
results, blob_mode=blob_mode, blob_sources=blob_sources
)
@@ -3559,9 +3678,8 @@ class AsyncQueryBase(object):
_query_is_plain_blob_scan(query)
and getattr(self, "_reranker", None) is None
and not _query_needs_lance_scanner(self)
and _supports_local_blob_fetch(
self._table, self._table._pushdown_operations
)
and self._table._inner._is_native()
and _supports_blob_fetch(self._table, self._table._pushdown_operations)
)
def select(self, columns: Union[List[str], dict[str, str]]) -> Self:
@@ -3766,11 +3884,14 @@ class AsyncQueryBase(object):
if blob_mode != "bytes":
return blob_sources
reject_unfetchable_blob_columns(schema, projection, blob_sources)
if blob_sources and not _supports_local_blob_fetch(
if blob_sources and not _supports_blob_fetch(
self._table, self._table._pushdown_operations
):
raise _blob_bytes_without_snapshot_error()
reject_unmatched_blob_outputs(await self._blob_output_schema(), blob_sources)
if self._table._inner._is_native():
reject_unmatched_blob_outputs(
await self._blob_output_schema(), blob_sources
)
return blob_sources
async def _blob_output_schema(self) -> pa.Schema:
@@ -3783,9 +3904,21 @@ class AsyncQueryBase(object):
return tbl
if blob_mode == "descriptions":
return strip_auto_row_ids(tbl, blob_sources)
return await replace_blob_columns_with_bytes(
tbl, blob_sources, self._table.fetch_blobs
)
reject_unmatched_blob_outputs(tbl.schema, blob_sources)
if (
self._table is not None
and not self._table._inner._is_native()
and blob_sources
):
version, identity = _remote_blob_snapshot(tbl.schema)
async def fetch_blobs(column, row_ids):
return await self._table._inner.fetch_blobs(
column, row_ids, version=version, snapshot_identity=identity
)
else:
fetch_blobs = self._table.fetch_blobs
return await replace_blob_columns_with_bytes(tbl, blob_sources, fetch_blobs)
async def to_arrow(
self,
@@ -3811,7 +3944,8 @@ class AsyncQueryBase(object):
``fetch_blobs`` reads. ``"descriptions"`` returns them without it.
``"bytes"`` returns payload bytes for supported row-addressable blob
columns and raises for blobs inside lists.
LanceDB Enterprise and namespace query pushdown refuse ``"bytes"``.
Enterprise queries fetch bytes at the version reported by the query
response. Namespace query pushdown refuses ``"bytes"``.
"""
blob_sources = await self._validated_blob_sources(blob_mode)
if blob_mode == "bytes" and blob_sources:
@@ -3893,9 +4027,9 @@ class AsyncQueryBase(object):
columns without pylance. Other local blob v2 queries return
descriptors in ``"lazy"`` and ``"descriptions"`` modes, or payloads
in ``"bytes"`` mode, through :meth:`to_arrow`.
LanceDB Enterprise blob queries support only ``"descriptions"`` until a
stable
table snapshot can bind the query and blob fetches.
Enterprise queries support ``"bytes"`` at the query response's
snapshot and ``"descriptions"`` without payload reads. Remote
``"lazy"`` handles are not supported.
**kwargs
Forwarded to pyarrow.Table.to_pandas after query execution and
optional flattening.
@@ -3903,6 +4037,9 @@ class AsyncQueryBase(object):
validate_blob_mode(blob_mode)
if self._table is not None and not self._table._inner._is_native():
await self._validated_blob_sources(blob_mode)
if blob_mode == "bytes":
tbl = await self.to_arrow(timeout=timeout, blob_mode=blob_mode)
return flatten_columns(tbl, flatten).to_pandas(**kwargs)
return await self._remote_to_pandas(
flatten=flatten, timeout=timeout, blob_mode=blob_mode, **kwargs
)
@@ -4366,7 +4503,11 @@ class AsyncQuery(AsyncStandardQuery):
)
def nearest_to_text(
self, query: str | FullTextQuery, columns: Union[str, List[str], None] = None
self,
query: str | FullTextQuery,
columns: Union[str, List[str], None] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> AsyncFTSQuery:
"""
Find the documents that are most relevant to the given text query.
@@ -4387,7 +4528,11 @@ class AsyncQuery(AsyncStandardQuery):
columns: str or list of str, default None
The columns to search in. If None, all indexed columns are searched.
For now only one column can be searched at a time.
operator: "AND" or "OR", optional
Combine terms in a string query. Defaults to OR. Quoted strings use
phrase semantics and require an index built with positions.
"""
fts_query = FullTextSearchQuery(query=query, operator=operator)
if isinstance(columns, str):
columns = [columns]
if columns is None:
@@ -4395,7 +4540,13 @@ class AsyncQuery(AsyncStandardQuery):
if isinstance(query, str):
return AsyncFTSQuery(
self._inner.nearest_to_text({"query": query, "columns": columns}),
self._inner.nearest_to_text(
{
"query": query,
"columns": columns,
"operator": fts_query.operator,
}
),
self._table,
)
# FullTextQuery object
@@ -4410,6 +4561,22 @@ class AsyncFTSQuery(AsyncStandardQuery):
self._inner = inner
self._reranker = None
async def count_rows(self) -> int:
"""Count all full-text matches satisfying the query's filter.
Ignores limit, offset, selection, ordering, and reranking. ``fast_search``
still restricts the count to indexed data. Matching scores are streamed
without loading document columns, so counting may scan every match.
For example, ``await table.query().nearest_to_text("gripper closed",``
``operator="AND").where("active = true").count_rows()``.
"""
try:
return await self._inner.count_rows()
except Exception as error:
_add_fts_position_error_note(error)
raise
def get_query(self) -> str:
return self._inner.get_query()
@@ -4503,12 +4670,20 @@ class AsyncFTSQuery(AsyncStandardQuery):
timeout: Optional[timedelta] = None,
blob_sources: Optional[dict[str, str]] = None,
) -> AsyncRecordBatchReader:
reader = await super()._execute_batches(
timeout=timeout, blob_sources=blob_sources
)
results = pa.Table.from_batches(await reader.read_all(), reader.schema)
try:
reader = await super()._execute_batches(
max_batch_length=max_batch_length,
timeout=timeout,
blob_sources=blob_sources,
)
results = pa.Table.from_batches(await reader.read_all(), reader.schema)
except Exception as error:
_add_fts_position_error_note(error)
raise
if self._reranker:
source = results
results = self._reranker.rerank_fts(self.get_query(), results)
results = _merge_query_snapshot(results, source)
return AsyncRecordBatchReader(results, max_batch_length=max_batch_length)
@@ -4782,7 +4957,11 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
return self
def nearest_to_text(
self, query: str | FullTextQuery, columns: Union[str, List[str], None] = None
self,
query: str | FullTextQuery,
columns: Union[str, List[str], None] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> AsyncHybridQuery:
"""
Find the documents that are most relevant to the given text query,
@@ -4807,7 +4986,10 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
columns: str or list of str, default None
The columns to search in. If None, all indexed columns are searched.
For now only one column can be searched at a time.
operator: "AND" or "OR", optional
Combine terms in a string query. Defaults to OR.
"""
fts_query = FullTextSearchQuery(query=query, operator=operator)
if isinstance(columns, str):
columns = [columns]
if columns is None:
@@ -4815,7 +4997,9 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
if isinstance(query, str):
return AsyncHybridQuery(
self._inner.nearest_to_text({"query": query, "columns": columns}),
self._inner.nearest_to_text(
{"query": query, "columns": columns, "operator": fts_query.operator}
),
self._table,
)
# FullTextQuery object
@@ -4835,7 +5019,9 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
)
results = pa.Table.from_batches(await reader.read_all(), reader.schema)
if self._reranker:
source = results
results = self._reranker.rerank_vector(self._query_string, results)
results = _merge_query_snapshot(results, source)
return AsyncRecordBatchReader(results, max_batch_length=max_batch_length)
@@ -5027,6 +5213,7 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
):
result = result.drop(["_rowid"])
result = _merge_query_snapshot(result, fts_results, vector_results)
return AsyncRecordBatchReader(result, max_batch_length=max_batch_length)
async def explain_plan(self, verbose: Optional[bool] = False):
+106 -17
View File
@@ -4,6 +4,8 @@
from __future__ import annotations
from lancedb.server_info import ServerInfo
from dataclasses import replace
from datetime import timedelta
import json
@@ -214,6 +216,7 @@ class RemoteDBConnection(DBConnection):
client_config,
oauth_config,
sql_host_override,
storage_options,
):
config = (
ClientConfig(**client_config)
@@ -233,7 +236,7 @@ class RemoteDBConnection(DBConnection):
result.region = "us-east-1"
result.host_override = endpoint
result.sql_host_override = sql_host_override
result.storage_options = None
result.storage_options = storage_options
result.client_config = replace(config, extra_headers=headers)
result._catalog_oauth = oauth_config is not None
result._conn = inner
@@ -430,7 +433,11 @@ class RemoteDBConnection(DBConnection):
page_token: Optional[str] = None,
limit: Optional[int] = None,
) -> TableListing:
"""List a page of tables in this database.
"""Iterate over all tables in this database, fetching pages as needed.
The ``tables`` attribute contains only the current page (100 names by
default). Iterate over the listing to visit all pages, or use
``table_exists([name])`` to check for a particular table.
Parameters
----------
@@ -468,7 +475,9 @@ class RemoteDBConnection(DBConnection):
"""List the names of all tables in the database.
.. deprecated::
Use :meth:`list_tables` instead, which provides proper pagination support.
Iterate over :meth:`list_tables` to get all names, or use
:meth:`table_exists` to check for a particular table. The listing's
``tables`` attribute contains only one page.
Parameters
----------
@@ -488,7 +497,8 @@ class RemoteDBConnection(DBConnection):
import warnings
warnings.warn(
"table_names() is deprecated, use list_tables() instead",
"table_names() is deprecated, iterate list_tables() for all names "
"or use table_exists([name]) to check existence",
DeprecationWarning,
stacklevel=2,
)
@@ -566,6 +576,7 @@ class RemoteDBConnection(DBConnection):
source_version: Optional[int] = None,
source_tag: Optional[str] = None,
is_shallow: bool = True,
exist_ok: bool = False,
) -> Table:
"""Clone a table from a source table.
@@ -585,6 +596,8 @@ class RemoteDBConnection(DBConnection):
is_shallow: bool, default True
Whether to perform a shallow clone (True) or deep clone (False).
Currently only shallow clone is supported.
exist_ok: bool, default False
Return the existing target unchanged instead of cloning over it.
Returns
-------
@@ -602,6 +615,7 @@ class RemoteDBConnection(DBConnection):
source_version=source_version,
source_tag=source_tag,
is_shallow=is_shallow,
exist_ok=exist_ok,
)
)
return RemoteTable(
@@ -782,12 +796,14 @@ class RemoteDBConnection(DBConnection):
def create_materialized_view(
self,
name: str,
source: MaterializedViewSource,
source: Optional[MaterializedViewSource] = None,
*,
query: Optional[str] = None,
select: SelectArg = None,
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
exist_ok: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> MaterializedView:
@@ -797,10 +813,12 @@ class RemoteDBConnection(DBConnection):
self._conn.create_materialized_view(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
with_no_data=with_no_data,
exist_ok=exist_ok,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
)
@@ -818,12 +836,14 @@ class RemoteDBConnection(DBConnection):
def create_materialized_view_async(
self,
name: str,
source: MaterializedViewSource,
source: Optional[MaterializedViewSource] = None,
*,
query: Optional[str] = None,
select: SelectArg = None,
where: Optional[str] = None,
limit: Optional[int] = None,
with_no_data: bool = False,
exist_ok: bool = False,
auto_refresh_enabled: Optional[bool] = None,
auto_refresh_interval_seconds: Optional[float] = None,
) -> Job[None]:
@@ -831,10 +851,12 @@ class RemoteDBConnection(DBConnection):
self._conn.create_materialized_view_async(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
with_no_data=with_no_data,
exist_ok=exist_ok,
auto_refresh_enabled=auto_refresh_enabled,
auto_refresh_interval_seconds=auto_refresh_interval_seconds,
)
@@ -958,6 +980,13 @@ class RemoteDBConnection(DBConnection):
"""
return Job(LOOP.run(self._conn.open_job(job_id)))
@override
def server_info(self) -> ServerInfo:
"""Read the responding server's build information. See
[DBConnection.server_info][lancedb.db.DBConnection.server_info].
"""
return LOOP.run(self._conn.server_info())
@override
def list_gpu_classes(self) -> List[GpuClass]:
"""List configured Function GPU classes. See
@@ -971,11 +1000,17 @@ class RemoteDBConnection(DBConnection):
definition: FunctionDefinition,
*,
secrets: Optional[Sequence[EnvVarSecret]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
refresh_lock: bool = False,
) -> Job[FunctionVersion]:
job = LOOP.run(
self._conn.create_function_async(
definition, secrets=secrets, namespace_path=namespace_path
definition,
secrets=secrets,
exist_ok=exist_ok,
namespace_path=namespace_path,
refresh_lock=refresh_lock,
)
)
return Job(job)
@@ -1066,6 +1101,7 @@ class RemoteDBConnection(DBConnection):
azure_client_secret_secret: Optional[Union[str, SecretReference]] = None,
gcp_credentials_json_secret: Optional[Union[str, SecretReference]] = None,
huggingface_token_secret: Optional[Union[str, SecretReference]] = None,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> StorageIntegrationInfo:
return LOOP.run(
@@ -1083,6 +1119,7 @@ class RemoteDBConnection(DBConnection):
azure_client_secret_secret=azure_client_secret_secret,
gcp_credentials_json_secret=gcp_credentials_json_secret,
huggingface_token_secret=huggingface_token_secret,
exist_ok=exist_ok,
namespace_path=namespace_path,
)
)
@@ -1121,9 +1158,18 @@ class RemoteDBConnection(DBConnection):
@override
def create_secret(
self, name: str, value: str, *, namespace_path: Optional[List[str]] = None
self,
name: str,
value: str,
*,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> None:
LOOP.run(self._conn.create_secret(name, value, namespace_path=namespace_path))
LOOP.run(
self._conn.create_secret(
name, value, exist_ok=exist_ok, namespace_path=namespace_path
)
)
@override
def alter_secret(
@@ -1167,10 +1213,17 @@ class RemoteDBConnection(DBConnection):
@override
def create_view(
self, name: str, query: str, *, namespace_path: Optional[List[str]] = None
self,
name: str,
query: str,
*,
exist_ok: bool = False,
namespace_path: Optional[List[str]] = None,
) -> ViewDescription:
return LOOP.run(
self._conn.create_view(name, query, namespace_path=namespace_path)
self._conn.create_view(
name, query, exist_ok=exist_ok, namespace_path=namespace_path
)
)
@override
@@ -1271,16 +1324,52 @@ class RemoteDBConnection(DBConnection):
@override
def list_jobs(
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
self,
*,
page_token: Optional[str] = None,
page_limit: Optional[int] = None,
table: Optional[str] = None,
namespace_path: Optional[List[str]] = None,
state: Optional[
Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
] = None,
job_type: Optional[str] = None,
job_types: Optional[List[str]] = None,
created_at_gte_millis: Optional[int] = None,
created_at_lt_millis: Optional[int] = None,
) -> Listing[JobInfo]:
"""List server-side jobs across the database's tables.
"""List server-side jobs, optionally filtered before pagination.
Returns a lazy iterator. ``page_limit`` limits each request, not the total;
``page_token`` resumes from a saved token. Requests and errors occur during
iteration. See [pagination state][lancedb.listing.AsyncListing].
``table`` names a table in ``namespace_path`` (the root by default).
Listings include all branches of the table. A namespace filter requires
``table``.
``state`` uses registry states such as ``in_progress``, ``succeeded``,
``failed``, ``timed_out``, and ``canceled``, rather than the SDK's
``running``/``finished`` labels. Set either ``job_type`` or ``job_types``.
Creation-time bounds are Unix milliseconds, inclusive at
``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``.
Returns a lazy iterator. ``page_limit`` limits each request, not the total.
Resume a ``page_token`` with the same filters. Requests and errors occur
during iteration. See [pagination state][lancedb.listing.AsyncListing].
For example, to inspect up to five jobs without fetching all history::
jobs = db.list_jobs(table="events", page_limit=5)
first_five = jobs[:5]
"""
return Listing(
self._conn.list_jobs(page_token=page_token, page_limit=page_limit)
self._conn.list_jobs(
page_token=page_token,
page_limit=page_limit,
table=table,
namespace_path=namespace_path,
state=state,
job_type=job_type,
job_types=job_types,
created_at_gte_millis=created_at_gte_millis,
created_at_lt_millis=created_at_lt_millis,
)
)
@override
+57 -4
View File
@@ -34,6 +34,7 @@ from lancedb._lancedb import (
DeleteResult,
DropColumnsResult,
FtsToken,
FunctionColumnStatus,
IndexConfig,
RTEWriteSpec,
MergeResult,
@@ -64,6 +65,7 @@ from lancedb.embeddings import EmbeddingFunctionRegistry
from lancedb.table import _normalize_progress
from ..query import (
FullTextOperator,
AnalyzePlanDistributedMetrics,
DocumentGranularity,
FullTextQuery,
@@ -368,6 +370,7 @@ class RemoteTable(Table):
index_type: ScalarIndexType = "BTREE",
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
):
"""Create a scalar index on a column.
@@ -394,6 +397,7 @@ class RemoteTable(Table):
self._table.create_index(
column,
replace=replace,
exist_ok=exist_ok,
config=config,
wait_timeout=wait_timeout,
name=name,
@@ -432,6 +436,7 @@ class RemoteTable(Table):
document_granularity: DocumentGranularity = DocumentGranularity.ROW,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
):
"""Create a full-text search index on a column.
@@ -491,6 +496,7 @@ class RemoteTable(Table):
self._table.create_index(
field_names,
replace=replace,
exist_ok=exist_ok,
config=config,
name=name,
wait_timeout=wait_timeout,
@@ -515,6 +521,7 @@ class RemoteTable(Table):
replace: bool = ...,
wait_timeout: Optional[timedelta] = ...,
name: Optional[str] = ...,
exist_ok: bool = ...,
train: bool = ...,
) -> None: ...
@@ -540,6 +547,7 @@ class RemoteTable(Table):
*,
wait_timeout: Optional[timedelta] = ...,
name: Optional[str] = ...,
exist_ok: bool = ...,
train: bool = ...,
target_partition_size: Optional[int] = ...,
) -> None: ...
@@ -571,6 +579,7 @@ class RemoteTable(Table):
config: Optional[IndexConfigType] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
target_partition_size: Optional[int] = None,
):
@@ -674,6 +683,7 @@ class RemoteTable(Table):
self._table.create_index(
column,
replace=replace,
exist_ok=exist_ok,
config=config,
wait_timeout=wait_timeout,
name=name,
@@ -689,6 +699,7 @@ class RemoteTable(Table):
replace: Optional[bool] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
) -> Job:
"""Create an index, returning a handle to the indexing job.
@@ -701,6 +712,7 @@ class RemoteTable(Table):
self._table.create_index_async(
column,
replace=replace,
exist_ok=exist_ok,
config=config,
wait_timeout=wait_timeout,
name=name,
@@ -718,6 +730,7 @@ class RemoteTable(Table):
progress: Optional[Union[bool, Callable, Any]] = None,
write_parallelism: Optional[int] = None,
allow_external_blob_outside_bases: bool = False,
retries: Optional[int] = None,
) -> AddResult:
"""Add more data to the [Table][lancedb.table.Table].
@@ -752,6 +765,9 @@ class RemoteTable(Table):
using too much memory.
allow_external_blob_outside_bases: bool, default False
Not supported in LanceDB Enterprise. Setting this raises.
retries: int, optional
Override the retry budget for this call (0 to 255). Zero disables
retries, including multipart parts. Ambiguous commits are never replayed.
Returns
-------
@@ -769,6 +785,7 @@ class RemoteTable(Table):
progress=progress,
write_parallelism=write_parallelism,
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
retries=retries,
)
)
finally:
@@ -783,6 +800,8 @@ class RemoteTable(Table):
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
fast_search: Optional[bool] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> LanceQueryBuilder:
"""Create a search query to find the nearest neighbors
of the given query vector. We currently support
@@ -841,6 +860,10 @@ class RemoteTable(Table):
- *default None*, which leaves fast search disabled.
operator: "AND" or "OR", optional
Combine terms in a string full-text query; the default is OR.
Use ``query_type="fts"`` when the table also has embeddings.
Returns
-------
LanceQueryBuilder
@@ -877,6 +900,7 @@ class RemoteTable(Table):
ordering_field_name=ordering_field_name,
fts_columns=fts_columns or [],
fast_search=fast_search,
operator=operator,
)
def _execute_query(
@@ -929,9 +953,10 @@ class RemoteTable(Table):
new_data: DATA,
on_bad_vectors: str,
fill_value: float,
retries: Optional[int] = None,
) -> MergeResult:
return LOOP.run(
self._table._do_merge(merge, new_data, on_bad_vectors, fill_value)
self._table._do_merge(merge, new_data, on_bad_vectors, fill_value, retries)
)
@_deprecated_keyword("predicate", "where")
@@ -1148,6 +1173,8 @@ class RemoteTable(Table):
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
supervisor_resources: Optional[Dict[str, int]] = None,
planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -1167,6 +1194,8 @@ class RemoteTable(Table):
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
supervisor_resources=supervisor_resources,
planning_workers=planning_workers,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
@@ -1189,6 +1218,8 @@ class RemoteTable(Table):
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
supervisor_resources: Optional[Dict[str, int]] = None,
planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -1209,6 +1240,8 @@ class RemoteTable(Table):
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
supervisor_resources=supervisor_resources,
planning_workers=planning_workers,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
@@ -1233,6 +1266,19 @@ class RemoteTable(Table):
self._table.function_errors(job_id=job_id, column=column, limit=limit)
)
def column_statuses(
self, column: Optional[str] = None
) -> list[FunctionColumnStatus]:
return LOOP.run(self._table.column_statuses(column=column))
def column_status(self, column: str) -> FunctionColumnStatus:
return LOOP.run(self._table.column_status(column))
def wait_fresh(
self, column: str, timeout: Optional[timedelta] = None
) -> FunctionColumnStatus:
return LOOP.run(self._table.wait_fresh(column, timeout))
def alter_columns(
self, *alterations: Iterable[Dict[str, str]]
) -> AlterColumnsResult:
@@ -1406,13 +1452,20 @@ class RemoteTable(Table):
self,
column: str,
row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table],
*,
buffer_size: Optional[int] = None,
) -> "list[Optional[BlobFile]]":
return LOOP.run(self._table.fetch_blob_files(column, row_ids))
return LOOP.run(
self._table.fetch_blob_files(column, row_ids, buffer_size=buffer_size)
)
def open_blob_file(
self, descriptor: Union[dict, pa.StructScalar, None]
self,
descriptor: Union[dict, pa.StructScalar, None],
*,
buffer_size: Optional[int] = None,
) -> Optional[BlobFile]:
return LOOP.run(self._table.open_blob_file(descriptor))
return LOOP.run(self._table.open_blob_file(descriptor, buffer_size=buffer_size))
def head(self, n=5) -> pa.Table:
"""
+33
View File
@@ -0,0 +1,33 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Remote server build information returned as JSON-compatible dictionaries."""
from typing import Optional, TypedDict
class ServerBuildInfo(TypedDict):
"""Immutable identity compiled into a server executable."""
release: str
git_sha: str
build_date: Optional[str]
class ServerInfo(TypedDict):
"""The responding query node and its configured Function runtime.
``query_node`` can be ``None`` when the executable has no build metadata.
``build_date`` is a UTC RFC 3339 timestamp when known. During a rolling
upgrade, separate requests can reach different query-node builds.
Configured images do not establish the version of a running job.
"""
query_node: Optional[ServerBuildInfo]
lance_version: str
lancedb_version: str
function_worker_protocol_version: int
configured_query_node_image: Optional[str]
configured_job_worker_image: Optional[str]
configured_sql_job_image: Optional[str]
configured_gpu_worker_image: Optional[str]
+343 -22
View File
@@ -35,11 +35,12 @@ from urllib.parse import urlparse
from lancedb.scannable import _hf_batches, _register_optional_converters, to_scannable
from . import __version__
from ._lancedb import _parse_field_path
from ._lancedb import FunctionColumnStatus, _parse_field_path
from ._blob import (
BlobFile,
_normalize_blob_descriptor,
_normalize_blob_row_ids,
_validate_blob_buffer_size,
_wrap_blob_files,
strip_auto_row_ids,
validate_blob_mode,
@@ -90,6 +91,7 @@ from .functions import (
from .merge import LanceMergeInsertBuilder
from .pydantic import LanceModel, model_to_dict
from .query import (
FullTextOperator,
AnalyzePlanDistributedMetrics,
AsyncFTSQuery,
AsyncHybridQuery,
@@ -137,6 +139,11 @@ def _requires_local_namespace_execution(query: Query) -> bool:
or query.take_row_ids is not None
or query.search_effort is not None
or query.approx_mode is not None
or (
query.full_text_query is not None
and query.fast_search is True
and query.vector is None
)
)
@@ -167,6 +174,36 @@ def _validate_index_accelerator(accelerator: Any) -> None:
raise RuntimeError(_CUDA_UNAVAILABLE_MESSAGE) from err
def _create_accelerated_index(dataset, *, exist_ok=False, name=None, **options):
if exist_ok:
parts = _parse_field_path(options["column"])
default_name = ".".join(parts)
if any("." in part for part in parts):
default_name = ".".join(
"`" + part.replace("`", "``") + "`"
if any(
not character.isalnum() and character != "_" for character in part
)
else part
for part in parts
)
name = name or f"{default_name}_idx"
dataset.checkout_latest()
if any(index["name"] == name for index in dataset.list_indices()):
return
options["replace"] = False
options["name"] = name
_validate_index_accelerator(options.get("accelerator"))
try:
dataset.create_index(**options)
except Exception:
if exist_ok:
dataset.checkout_latest()
if any(index["name"] == name for index in dataset.list_indices()):
return
raise
def _polars_predicate_pushdown_barrier(frame: Any) -> Any:
"""Return a Polars frame unchanged while blocking predicate pushdown."""
return frame
@@ -1113,7 +1150,14 @@ def _align_field(field: pa.Field, target_field: pa.Field) -> pa.Field:
if not any(child.name in ("data", "uri") for child in source_type):
raise ValueError(
f"blob struct input for column '{field.name}' must contain "
"a 'data' or 'uri' child"
"a 'data' or 'uri' child. A blob query returns an SDK "
"descriptor in this shape, and a descriptor is not payload "
"bytes. Use blob_mode='bytes' to materialize payloads, or "
"inspect descriptors with blob_mode='descriptions'. To copy "
"payloads, select row IDs with with_row_id(True), then call "
"table.fetch_blobs(column, row_ids) or "
"table.fetch_blob_files(column, row_ids). Keep the source "
"unchanged between selection and fetching."
)
elif not _can_coerce_to_blob(source_type) and not isinstance(
source_type, pa.ExtensionType
@@ -1833,6 +1877,7 @@ class Table(ABC):
replace: bool = ...,
wait_timeout: Optional[timedelta] = ...,
name: Optional[str] = ...,
exist_ok: bool = ...,
train: bool = ...,
) -> None: ...
@@ -1858,6 +1903,7 @@ class Table(ABC):
*,
wait_timeout: Optional[timedelta] = ...,
name: Optional[str] = ...,
exist_ok: bool = ...,
train: bool = ...,
target_partition_size: Optional[int] = ...,
) -> None: ...
@@ -1889,6 +1935,7 @@ class Table(ABC):
config: Optional[IndexConfigType] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
target_partition_size: Optional[int] = None,
):
@@ -1912,6 +1959,9 @@ class Table(ABC):
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS.
replace : bool, default True
Whether to replace an existing index on this column.
exist_ok : bool, default False
Preserve the existing index with the requested or derived name.
Takes precedence over replace and keeps its definition and build.
wait_timeout : timedelta, optional
LanceDB Enterprise only: how long to wait for the index build to finish.
If not set, the call returns once the build is scheduled.
@@ -1967,6 +2017,7 @@ class Table(ABC):
replace: Optional[bool] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
) -> Job:
"""Create an index, returning a handle to the indexing job.
@@ -2059,6 +2110,7 @@ class Table(ABC):
index_type: ScalarIndexType = "BTREE",
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
):
"""Create a scalar index on a column.
@@ -2143,6 +2195,7 @@ class Table(ABC):
document_granularity: DocumentGranularity = DocumentGranularity.ROW,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
):
"""Create a full-text search index on the table.
@@ -2255,6 +2308,7 @@ class Table(ABC):
progress: Optional[Union[bool, Callable, Any]] = None,
write_parallelism: Optional[int] = None,
allow_external_blob_outside_bases: bool = False,
retries: Optional[int] = None,
) -> AddResult:
"""Add more data to the [Table][lancedb.table.Table].
@@ -2315,6 +2369,10 @@ class Table(ABC):
Store blob URIs that sit outside registered blob bases. The row
keeps a reference, so the object has to stay readable. Local
tables only.
retries: int, optional
Override the remote retry budget for this call (0 to 255). Zero
disables retries, including multipart parts. Ambiguous commits are
never replayed. Ignored by LanceDB Embedded.
Returns
-------
@@ -2398,6 +2456,8 @@ class Table(ABC):
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
fast_search: Optional[bool] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> 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/)
@@ -2461,6 +2521,10 @@ class Table(ABC):
- If `query` is a string, then the query type is "vector" if the
table has embedding functions else the query type is "fts"
operator: "AND" or "OR", optional
Combine terms in a string full-text query; the default is OR.
Use ``query_type="fts"`` when the table also has embeddings.
Returns
-------
LanceQueryBuilder
@@ -2655,8 +2719,12 @@ class Table(ABC):
results are returned.
Row IDs can be obtained from a query with ``with_row_id(True)``.
LanceDB Enterprise reads the requested ranges through version-pinned blob
handles using HTTP byte-range requests.
LanceDB Enterprise uses the batched endpoint when the server advertises
support, partitioning at 1024 ranges and 64 MiB, including individual
larger ranges. Older servers use descriptor queries and BlobFile range
reads. Both protocols read one exact branch and version without changing
the table's checkout. Errors from an advertised endpoint propagate without
switching protocols. The final output occupies memory.
"""
@abstractmethod
@@ -2664,6 +2732,8 @@ class Table(ABC):
self,
column: str,
row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table],
*,
buffer_size: Optional[int] = None,
) -> "list[Optional[BlobFile]]":
"""Open lazy, seekable :class:`~lancedb._blob.BlobFile` handles.
@@ -2673,6 +2743,8 @@ class Table(ABC):
``pyarrow.Table`` carrying row identity via ``_rowid`` or a
``_lance_row_id`` field on the blob descriptor. Null blob values return
``None``. LanceDB Enterprise requires server version 0.5.0 or newer.
``buffer_size`` controls sequential read-ahead in bytes (default 512 KiB).
Set it to 0 for sparse reads. Explicit range reads bypass this buffer.
``_rowid`` values stay valid after compaction when the table has stable
row ids.
@@ -2682,7 +2754,10 @@ class Table(ABC):
@abstractmethod
def open_blob_file(
self, descriptor: Union[dict, pa.StructScalar, None]
self,
descriptor: Union[dict, pa.StructScalar, None],
*,
buffer_size: Optional[int] = None,
) -> Optional[BlobFile]:
"""Open a seekable file from a SQL ``blob_descriptor`` result.
@@ -2691,6 +2766,7 @@ class Table(ABC):
not change this table's checkout. Null descriptors return ``None``.
Payload bytes load only when the returned handle is read. An external
blob with an unspecified size may require a metadata request on opening.
``buffer_size`` controls sequential read-ahead (default 512 KiB; 0 disables).
```python
rows = db.execute_query(
@@ -2701,7 +2777,9 @@ class Table(ABC):
```
"""
def open_blob_files(self, descriptors: Iterable) -> Iterator[Optional[BlobFile]]:
def open_blob_files(
self, descriptors: Iterable, *, buffer_size: Optional[int] = None
) -> Iterator[Optional[BlobFile]]:
"""Iterate over lazy files from descriptor dictionaries or Arrow scalars.
Accepts an Arrow array/chunked array or any iterable. Opens each handle
@@ -2716,7 +2794,10 @@ class Table(ABC):
```
"""
for descriptor in descriptors:
yield self.open_blob_file(descriptor)
if buffer_size is None:
yield self.open_blob_file(descriptor)
else:
yield self.open_blob_file(descriptor, buffer_size=buffer_size)
@abstractmethod
def _execute_query(
@@ -2748,6 +2829,7 @@ class Table(ABC):
new_data: DATA,
on_bad_vectors: OnBadVectorsType,
fill_value: float,
retries: Optional[int] = None,
) -> MergeResult: ...
@abstractmethod
@@ -3196,6 +3278,8 @@ class Table(ABC):
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
supervisor_resources: Optional[Dict[str, int]] = None,
planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -3253,6 +3337,17 @@ class Table(ABC):
CPU-only budget. This budget cannot be combined with the top-level
``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
reject it.
supervisor_resources: dict[str, int], optional
CPU, memory, and ephemeral-storage limits for the Function refresh
supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and
``ephemeral_storage_bytes``; all are required and positive.
LanceDB Enterprise only; local refreshes reject it.
planning_workers: dict[str, object], optional
Resources and sizing for the Function refresh planning fleet.
``resources`` has the same keys as ``supervisor_resources``; the
other keys are ``max_workers``, ``rows_per_worker`` and
``fragments_per_worker``. LanceDB Enterprise only; local refreshes
reject it.
gpu_class: str, optional
GPU class for Function workers. Must be a lowercase name of 1-63
letters, digits, or hyphens, without a leading or trailing hyphen.
@@ -3305,6 +3400,8 @@ class Table(ABC):
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
supervisor_resources: Optional[Dict[str, int]] = None,
planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -3361,6 +3458,17 @@ class Table(ABC):
CPU-only budget. This budget cannot be combined with the top-level
``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
reject it.
supervisor_resources: dict[str, int], optional
CPU, memory, and ephemeral-storage limits for the Function refresh
supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and
``ephemeral_storage_bytes``; all are required and positive.
LanceDB Enterprise only; local refreshes reject it.
planning_workers: dict[str, object], optional
Resources and sizing for the Function refresh planning fleet.
``resources`` has the same keys as ``supervisor_resources``; the
other keys are ``max_workers``, ``rows_per_worker`` and
``fragments_per_worker``. LanceDB Enterprise only; local refreshes
reject it.
gpu_class: str, optional
GPU class for Function workers. Must be a lowercase name of 1-63
letters, digits, or hyphens, without a leading or trailing hyphen.
@@ -3504,6 +3612,36 @@ class Table(ABC):
... print("listing stopped at the limit")
"""
@abstractmethod
def column_statuses(
self, column: Optional[str] = None
) -> list[FunctionColumnStatus]:
"""Return exact status for Function-backed output columns.
All statuses describe one server table version. ``column=None`` returns
every Function output. This operation is available on LanceDB
Enterprise tables. A table handle pinned to an exact version requests
that version; a latest handle retains the normal read-freshness
behavior.
"""
@abstractmethod
def column_status(self, column: str) -> FunctionColumnStatus:
"""Return exact status for one Function-backed output column."""
@abstractmethod
def wait_fresh(
self, column: str, timeout: Optional[timedelta] = None
) -> FunctionColumnStatus:
"""Poll until the column has no stale or never-computed rows.
Rows already failed remain visible in the returned status and do not
keep this method waiting. The method never submits or cancels work.
Transport errors and unrecoverable status-evidence errors propagate.
A typed finalization-pending response is retried; arbitrary failure
responses are not.
"""
@abstractmethod
def alter_columns(self, *alterations: Iterable[Dict[str, str]]):
"""
@@ -3968,13 +4106,20 @@ class LanceTable(Table):
self,
column: str,
row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table],
*,
buffer_size: Optional[int] = None,
) -> "list[Optional[BlobFile]]":
return LOOP.run(self._table.fetch_blob_files(column, row_ids))
return LOOP.run(
self._table.fetch_blob_files(column, row_ids, buffer_size=buffer_size)
)
def open_blob_file(
self, descriptor: Union[dict, pa.StructScalar, None]
self,
descriptor: Union[dict, pa.StructScalar, None],
*,
buffer_size: Optional[int] = None,
) -> Optional[BlobFile]:
return LOOP.run(self._table.open_blob_file(descriptor))
return LOOP.run(self._table.open_blob_file(descriptor, buffer_size=buffer_size))
@property
def tags(self) -> Tags:
@@ -4258,6 +4403,7 @@ class LanceTable(Table):
replace: bool = ...,
wait_timeout: Optional[timedelta] = ...,
name: Optional[str] = ...,
exist_ok: bool = ...,
train: bool = ...,
) -> None: ...
@@ -4283,6 +4429,7 @@ class LanceTable(Table):
*,
wait_timeout: Optional[timedelta] = ...,
name: Optional[str] = ...,
exist_ok: bool = ...,
train: bool = ...,
target_partition_size: Optional[int] = ...,
) -> None: ...
@@ -4314,6 +4461,7 @@ class LanceTable(Table):
config: Optional[IndexConfigType] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
target_partition_size: Optional[int] = None,
):
@@ -4337,6 +4485,9 @@ class LanceTable(Table):
BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, FTS.
replace : bool, default True
Whether to replace an existing index on this column.
exist_ok : bool, default False
Preserve the existing index with the requested or derived name.
Takes precedence over replace and keeps its definition and build.
wait_timeout : timedelta, optional
Timeout to wait for async indexing to complete.
name : str, optional
@@ -4405,8 +4556,10 @@ class LanceTable(Table):
# Handle accelerator through pylance
if accelerator is not None:
dataset = self.to_lance()
_validate_index_accelerator(accelerator)
dataset.create_index(
_create_accelerated_index(
dataset,
exist_ok=exist_ok,
name=name,
column=column,
index_type=index_type,
metric=metric,
@@ -4432,7 +4585,6 @@ class LanceTable(Table):
if acc is not None:
# Dispatch to pylance for GPU acceleration
dataset = self.to_lance()
_validate_index_accelerator(acc)
index_type_map = {
"IvfFlat": "IVF_FLAT",
"IvfSq": "IVF_SQ",
@@ -4449,7 +4601,10 @@ class LanceTable(Table):
if num_bits is not None:
quantization_kwargs["num_bits"] = num_bits
dataset.create_index(
_create_accelerated_index(
dataset,
exist_ok=exist_ok,
name=name,
column=column,
index_type=lance_index_type,
metric=getattr(config, "distance_type", "l2"),
@@ -4471,6 +4626,7 @@ class LanceTable(Table):
self._table.create_index(
column,
replace=replace,
exist_ok=exist_ok,
config=config,
wait_timeout=wait_timeout,
name=name,
@@ -4486,6 +4642,7 @@ class LanceTable(Table):
replace: Optional[bool] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
) -> Job:
"""Create an index, returning a handle to the indexing job.
@@ -4504,6 +4661,7 @@ class LanceTable(Table):
self._table.create_index_async(
column,
replace=replace,
exist_ok=exist_ok,
config=config,
wait_timeout=wait_timeout,
name=name,
@@ -4624,6 +4782,7 @@ class LanceTable(Table):
index_type: ScalarIndexType = "BTREE",
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
):
"""Create a scalar index on a column.
@@ -4650,6 +4809,7 @@ class LanceTable(Table):
self._table.create_index(
column,
replace=replace,
exist_ok=exist_ok,
config=config,
wait_timeout=wait_timeout,
name=name,
@@ -4687,6 +4847,7 @@ class LanceTable(Table):
document_granularity: DocumentGranularity = DocumentGranularity.ROW,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
):
"""Create a full-text search index on a column.
@@ -4748,6 +4909,7 @@ class LanceTable(Table):
self._table.create_index(
field_names,
replace=replace,
exist_ok=exist_ok,
config=config,
name=name,
wait_timeout=wait_timeout,
@@ -4770,6 +4932,7 @@ class LanceTable(Table):
progress: Optional[Union[bool, Callable, Any]] = None,
write_parallelism: Optional[int] = None,
allow_external_blob_outside_bases: bool = False,
retries: Optional[int] = None,
) -> AddResult:
"""Add data to the table.
If vector columns are missing and the table
@@ -4801,6 +4964,10 @@ class LanceTable(Table):
allow_external_blob_outside_bases: bool, default False
Allow blob URIs outside registered bases. See :meth:`Table.add`.
LanceDB Embedded only.
retries: int, optional
Override the remote retry budget for this call (0 to 255). Zero
disables retries, including multipart parts. Ambiguous commits are
never replayed. Ignored by LanceDB Embedded.
Returns
-------
@@ -4818,6 +4985,7 @@ class LanceTable(Table):
progress=progress,
write_parallelism=write_parallelism,
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
retries=retries,
)
)
finally:
@@ -4912,6 +5080,8 @@ class LanceTable(Table):
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
fast_search: Optional[bool] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> LanceVectorQueryBuilder: ...
@overload
@@ -4923,6 +5093,8 @@ class LanceTable(Table):
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
fast_search: Optional[bool] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> LanceFtsQueryBuilder: ...
@overload
@@ -4936,6 +5108,8 @@ class LanceTable(Table):
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
fast_search: Optional[bool] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> LanceHybridQueryBuilder: ...
@overload
@@ -4947,6 +5121,8 @@ class LanceTable(Table):
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
fast_search: Optional[bool] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> LanceEmptyQueryBuilder: ...
def search(
@@ -4959,6 +5135,8 @@ class LanceTable(Table):
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
fast_search: Optional[bool] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> 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/)
@@ -5019,6 +5197,10 @@ class LanceTable(Table):
If None then the search is performed on all indexed columns.
For now, only one column can be searched at a time.
operator: "AND" or "OR", optional
Combine terms in a string full-text query; the default is OR.
Use ``query_type="fts"`` when the table also has embeddings.
Returns
-------
LanceQueryBuilder
@@ -5044,6 +5226,7 @@ class LanceTable(Table):
ordering_field_name=ordering_field_name,
fts_columns=fts_columns or [],
fast_search=fast_search,
operator=operator,
)
@classmethod
@@ -5295,9 +5478,10 @@ class LanceTable(Table):
new_data: DATA,
on_bad_vectors: OnBadVectorsType,
fill_value: float,
retries: Optional[int] = None,
) -> MergeResult:
return LOOP.run(
self._table._do_merge(merge, new_data, on_bad_vectors, fill_value)
self._table._do_merge(merge, new_data, on_bad_vectors, fill_value, retries)
)
@property
@@ -5510,6 +5694,8 @@ class LanceTable(Table):
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
supervisor_resources: Optional[Dict[str, int]] = None,
planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -5532,6 +5718,8 @@ class LanceTable(Table):
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
supervisor_resources=supervisor_resources,
planning_workers=planning_workers,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
@@ -5554,6 +5742,8 @@ class LanceTable(Table):
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
supervisor_resources: Optional[Dict[str, int]] = None,
planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -5578,6 +5768,8 @@ class LanceTable(Table):
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
supervisor_resources=supervisor_resources,
planning_workers=planning_workers,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
@@ -5604,6 +5796,19 @@ class LanceTable(Table):
self._table.function_errors(job_id=job_id, column=column, limit=limit)
)
def column_statuses(
self, column: Optional[str] = None
) -> list[FunctionColumnStatus]:
return LOOP.run(self._table.column_statuses(column=column))
def column_status(self, column: str) -> FunctionColumnStatus:
return LOOP.run(self._table.column_status(column))
def wait_fresh(
self, column: str, timeout: Optional[timedelta] = None
) -> FunctionColumnStatus:
return LOOP.run(self._table.wait_fresh(column, timeout))
def alter_columns(
self, *alterations: Iterable[Dict[str, str]]
) -> AlterColumnsResult:
@@ -6727,6 +6932,7 @@ class AsyncTable:
] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
):
"""Create an index to speed up queries
@@ -6757,6 +6963,9 @@ class AsyncTable:
If not set, the call returns once the build is scheduled.
name: str, optional
The name of the index. If not provided, a default name will be generated.
exist_ok: bool, default False
Preserve an existing index with the requested or derived name. This
takes precedence over replace and keeps its definition and build.
train: bool, default True
Whether to train the index with existing data. Vector indices always train
with existing data.
@@ -6812,6 +7021,7 @@ class AsyncTable:
column,
index=config,
replace=replace,
exist_ok=exist_ok,
wait_timeout=wait_timeout,
name=name,
train=train,
@@ -6849,6 +7059,7 @@ class AsyncTable:
] = None,
wait_timeout: Optional[timedelta] = None,
name: Optional[str] = None,
exist_ok: bool = False,
train: bool = True,
) -> AsyncJob:
"""Create an index, returning a handle to the indexing job.
@@ -6867,6 +7078,7 @@ class AsyncTable:
column,
index=config,
replace=replace,
exist_ok=exist_ok,
wait_timeout=wait_timeout,
name=name,
train=train,
@@ -7016,6 +7228,7 @@ class AsyncTable:
progress: Optional[Union[bool, Callable, Any]] = None,
write_parallelism: Optional[int] = None,
allow_external_blob_outside_bases: bool = False,
retries: Optional[int] = None,
) -> AddResult:
"""Add more data to the [AsyncTable][lancedb.table.AsyncTable].
@@ -7054,6 +7267,10 @@ class AsyncTable:
allow_external_blob_outside_bases: bool, default False
Allow blob URIs outside registered bases. See :meth:`Table.add`.
LanceDB Embedded only.
retries: int, optional
Override the remote retry budget for this call (0 to 255). Zero
disables retries, including multipart parts. Ambiguous commits are
never replayed. Ignored by LanceDB Embedded.
"""
schema = await self.schema()
@@ -7108,6 +7325,7 @@ class AsyncTable:
progress=progress,
write_parallelism=write_parallelism,
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
retries=retries,
)
except RuntimeError as e:
if "Cast error" in str(e):
@@ -7192,6 +7410,8 @@ class AsyncTable:
query_type: QueryType = "auto",
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> AsyncQuery: ...
@overload
@@ -7202,6 +7422,8 @@ class AsyncTable:
query_type: Literal["auto"] = ...,
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> Union[AsyncHybridQuery, AsyncFTSQuery, AsyncVectorQuery]: ...
@overload
@@ -7212,6 +7434,8 @@ class AsyncTable:
query_type: Literal["hybrid"] = ...,
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> AsyncHybridQuery: ...
@overload
@@ -7222,6 +7446,8 @@ class AsyncTable:
query_type: Literal["auto"] = ...,
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> AsyncVectorQuery: ...
@overload
@@ -7232,6 +7458,8 @@ class AsyncTable:
query_type: Literal["fts"] = ...,
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> AsyncFTSQuery: ...
@overload
@@ -7242,6 +7470,8 @@ class AsyncTable:
query_type: Literal["vector"] = ...,
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> AsyncVectorQuery: ...
async def search(
@@ -7253,6 +7483,8 @@ class AsyncTable:
query_type: QueryType = "auto",
ordering_field_name: Optional[str] = None,
fts_columns: Optional[Union[str, List[str]]] = None,
*,
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
) -> Union[AsyncQuery, AsyncHybridQuery, AsyncFTSQuery, AsyncVectorQuery]:
"""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/)
@@ -7296,12 +7528,20 @@ class AsyncTable:
- If `query` is a string, then the query type is "vector" if the
table has embedding functions else the query type is "fts"
operator: "AND" or "OR", optional
Combine terms in a string full-text query; the default is OR.
Use ``query_type="fts"`` when the table also has embeddings.
Returns
-------
AsyncQuery, AsyncHybridQuery, AsyncFTSQuery, or AsyncVectorQuery
A query builder object representing the query.
"""
if operator is not None:
operator = FullTextOperator(operator)
if not isinstance(query, str) or query_type not in ("auto", "fts"):
raise ValueError("operator requires a string full-text query")
if query is None:
return self.query()
@@ -7420,13 +7660,17 @@ class AsyncTable:
)
vector_query = await make_embedding(embedding_conf, query)
if operator is not None and query_type != "fts":
raise ValueError("operator requires a string full-text query")
if query_type == "vector":
builder = self.query().nearest_to(vector_query)
if vector_column_name:
builder = builder.column(vector_column_name)
return builder
elif query_type == "fts":
return self.query().nearest_to_text(query, columns=fts_columns)
return self.query().nearest_to_text(
query, columns=fts_columns, operator=operator
)
elif query_type == "hybrid":
builder = self.query().nearest_to(vector_query)
if vector_column_name:
@@ -7536,7 +7780,9 @@ class AsyncTable:
if query.full_text_query:
async_query = async_query.nearest_to_text(
query.full_text_query.query, query.full_text_query.columns
query.full_text_query.query,
query.full_text_query.columns,
operator=query.full_text_query.operator,
)
return async_query
@@ -7595,6 +7841,7 @@ class AsyncTable:
new_data: DATA,
on_bad_vectors: OnBadVectorsType,
fill_value: float,
retries: Optional[int] = None,
) -> MergeResult:
schema = await self.schema()
if on_bad_vectors is None:
@@ -7626,6 +7873,7 @@ class AsyncTable:
use_rte=merge._use_rte,
validate_single_shard=merge._validate_single_shard,
),
retries=retries,
)
async def delete(self, where: Union[str, Expr]) -> DeleteResult:
@@ -7961,6 +8209,8 @@ class AsyncTable:
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
supervisor_resources: Optional[Dict[str, int]] = None,
planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -8018,6 +8268,17 @@ class AsyncTable:
CPU-only budget. This budget cannot be combined with the top-level
``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
reject it.
supervisor_resources: dict[str, int], optional
CPU, memory, and ephemeral-storage limits for the Function refresh
supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and
``ephemeral_storage_bytes``; all are required and positive.
LanceDB Enterprise only; local refreshes reject it.
planning_workers: dict[str, object], optional
Resources and sizing for the Function refresh planning fleet.
``resources`` has the same keys as ``supervisor_resources``; the
other keys are ``max_workers``, ``rows_per_worker`` and
``fragments_per_worker``. LanceDB Enterprise only; local refreshes
reject it.
gpu_class: str, optional
GPU class for Function workers. Must be a lowercase name of 1-63
letters, digits, or hyphens, without a leading or trailing hyphen.
@@ -8065,6 +8326,8 @@ class AsyncTable:
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
supervisor_resources=supervisor_resources,
planning_workers=planning_workers,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=None
@@ -8168,6 +8431,32 @@ class AsyncTable:
job_id=job_id, column=column, limit=limit
)
async def column_statuses(
self, column: Optional[str] = None
) -> list[FunctionColumnStatus]:
"""Return exact status for Function-backed output columns.
All results describe one server table version. ``column=None`` returns
every Function output. A handle pinned to an exact version requests
that version.
"""
return await self._inner.column_statuses(column=column)
async def column_status(self, column: str) -> FunctionColumnStatus:
"""Return exact status for one Function-backed output column."""
return await self._inner.column_status(column)
async def wait_fresh(
self, column: str, timeout: Optional[timedelta] = None
) -> FunctionColumnStatus:
"""Poll until no stale or never-computed rows remain.
Failed rows do not block completion. Server and transport errors are
not retried. Only the typed finalization-pending response is retried
with bounded backoff; arbitrary 500 responses surface immediately.
"""
return await self._inner.wait_column_fresh(column, timeout)
async def refresh_column_async(
self,
column: str,
@@ -8177,6 +8466,8 @@ class AsyncTable:
max_concurrency: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
resource_budget: Optional[Dict[str, int]] = None,
supervisor_resources: Optional[Dict[str, int]] = None,
planning_workers: Optional[Dict[str, Any]] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -8233,6 +8524,17 @@ class AsyncTable:
CPU-only budget. This budget cannot be combined with the top-level
``gpu_count`` shorthand. LanceDB Enterprise only; local refreshes
reject it.
supervisor_resources: dict[str, int], optional
CPU, memory, and ephemeral-storage limits for the Function refresh
supervisor pod. Keys are ``cpu_millis``, ``memory_bytes`` and
``ephemeral_storage_bytes``; all are required and positive.
LanceDB Enterprise only; local refreshes reject it.
planning_workers: dict[str, object], optional
Resources and sizing for the Function refresh planning fleet.
``resources`` has the same keys as ``supervisor_resources``; the
other keys are ``max_workers``, ``rows_per_worker`` and
``fragments_per_worker``. LanceDB Enterprise only; local refreshes
reject it.
gpu_class: str, optional
GPU class for Function workers. Must be a lowercase name of 1-63
letters, digits, or hyphens, without a leading or trailing hyphen.
@@ -8297,6 +8599,8 @@ class AsyncTable:
max_concurrency=max_concurrency,
publication_interval_rows=publication_interval_rows,
resource_budget=resource_budget,
supervisor_resources=supervisor_resources,
planning_workers=planning_workers,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=None
@@ -8545,32 +8849,49 @@ class AsyncTable:
column: str,
requests: Sequence[Sequence[int]],
) -> pa.LargeBinaryArray:
"""Materialize row-specific byte ranges.
See [Table.fetch_blob_ranges][lancedb.table.Table.fetch_blob_ranges].
"""
return await self._inner.fetch_blob_ranges(column, list(requests))
async def fetch_blob_files(
self,
column: str,
row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table],
*,
buffer_size: Optional[int] = None,
) -> "list[Optional[BlobFile]]":
"""Open handles with configurable read-ahead.
See [Table.fetch_blob_files][lancedb.table.Table.fetch_blob_files].
"""
buffer_size = _validate_blob_buffer_size(buffer_size)
handles = await self._inner.fetch_blob_files(
column, _normalize_blob_row_ids(row_ids, column)
column, _normalize_blob_row_ids(row_ids, column), buffer_size
)
return _wrap_blob_files(handles)
async def open_blob_file(
self, descriptor: Union[dict, pa.StructScalar, None]
self,
descriptor: Union[dict, pa.StructScalar, None],
*,
buffer_size: Optional[int] = None,
) -> Optional[BlobFile]:
"""Open a snapshot-bound descriptor as a seekable file.
See [Table.open_blob_file][lancedb.table.Table.open_blob_file].
"""
buffer_size = _validate_blob_buffer_size(buffer_size)
descriptor = _normalize_blob_descriptor(descriptor)
if descriptor is None:
return None
return BlobFile(await self._inner.open_blob_file(json.dumps(descriptor)))
return BlobFile(
await self._inner.open_blob_file(json.dumps(descriptor), buffer_size)
)
async def open_blob_files(
self, descriptors: Iterable
self, descriptors: Iterable, *, buffer_size: Optional[int] = None
) -> AsyncIterator[Optional[BlobFile]]:
"""Asynchronously iterate over files in descriptor order, preserving nulls.
@@ -8585,7 +8906,7 @@ class AsyncTable:
```
"""
for descriptor in descriptors:
yield await self.open_blob_file(descriptor)
yield await self.open_blob_file(descriptor, buffer_size=buffer_size)
@property
def tags(self) -> AsyncTags:
+18
View File
@@ -1135,6 +1135,24 @@ def test_copy_blob_subset_preserves_payloads_nulls_and_empty_values(tmp_path):
assert sorted(copied, key=lambda row: row["id"]) == rows[:3]
def test_copy_blob_descriptor_rows_explains_payload_materialization(tmp_path):
db = lancedb.connect(tmp_path)
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")])
source = db.create_table("source", data=[{"id": 1, "image": b"one"}], schema=schema)
hits = source.search().where("id = 1").to_arrow()
with pytest.raises(ValueError, match="must contain a 'data' or 'uri' child") as exc:
db.create_table("copy", data=hits, schema=schema)
message = str(exc.value)
assert "blob_mode='bytes'" in message
assert "blob_mode='descriptions'" in message
assert "with_row_id(True)" in message
assert "fetch_blobs(column, row_ids)" in message
assert "fetch_blob_files(column, row_ids)" in message
assert not db.table_exists(["copy"])
def test_fetch_blobs_round_trip():
table = _blob_table(
"round_trip",
+236
View File
@@ -0,0 +1,236 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import json
import threading
from contextlib import contextmanager
from urllib.parse import urlparse
import pyarrow as pa
import pytest
import lancedb
from test_remote_db import (
BLOB_DESCRIBE_RESPONSE,
blob_descriptor_take_table,
mock_lancedb_connection,
)
@contextmanager
def remote_buffer_table(*, http_requests=None, truncate_first=False):
payload = bytes(range(256)) * 4096
requests = []
def handler(request):
path = urlparse(request.path).path
if http_requests is not None:
http_requests.append(path)
if path.endswith("/describe/"):
body = json.dumps(BLOB_DESCRIBE_RESPONSE).encode()
content_type = "application/json"
elif path.endswith("/query/"):
data = json.loads(
request.rfile.read(int(request.headers["Content-Length"]))
)
assert data["columns"] == ["image"]
table = blob_descriptor_take_table().slice(0, 1)
images = table["image"].combine_chunks()
images = pa.StructArray.from_arrays(
[
images.field("kind"),
images.field("position"),
pa.array([len(payload)], pa.uint64()),
images.field("blob_id"),
images.field("blob_uri"),
],
fields=list(images.type),
)
table = table.set_column(0, table.schema.field(0), images)
sink = pa.BufferOutputStream()
with pa.ipc.new_stream(sink, table.schema) as writer:
writer.write_table(table)
body = sink.getvalue().to_pybytes()
content_type = "application/vnd.apache.arrow.stream"
else:
assert path == "/v1/table/test/blob/image/10/bytes"
assert "version=1" in request.path
start, end = map(int, request.headers["Range"][6:].split("-"))
requests.append((start, end + 1))
body = payload[start : end + 1]
if truncate_first and len(requests) == 1:
body = body[:5]
request.send_response(206)
request.send_header("Content-Range", f"bytes {start}-{end}/{len(payload)}")
request.send_header("Content-Length", str(len(body)))
request.end_headers()
request.wfile.write(body)
return
request.send_response(200)
request.send_header("Content-Type", content_type)
request.send_header("Content-Length", str(len(body)))
request.send_header("phalanx-version", "0.5.0")
request.send_header("x-lancedb-version", "1")
request.end_headers()
request.wfile.write(body)
with mock_lancedb_connection(handler, blob_request_concurrency=1) as db:
yield db.open_table("test"), payload, requests
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
@pytest.mark.parametrize("buffer_size", [None, 0, 8, 512 * 1024])
async def test_remote_read_ahead_over_http(use_async, buffer_size):
with remote_buffer_table() as (table, payload, requests):
if use_async:
files = await table._table.fetch_blob_files(
"image", [10], buffer_size=buffer_size
)
else:
files = table.fetch_blob_files("image", [10], buffer_size=buffer_size)
file = files[0]
assert requests == []
assert file.read(2) == payload[:2]
window = 512 * 1024 if buffer_size is None else max(buffer_size, 2)
assert requests == [(0, window)]
assert file.read(2) == payload[2:4]
assert len(requests) == (2 if buffer_size == 0 else 1)
file.seek(1)
assert file.read(1) == payload[1:2]
assert len(requests) == (3 if buffer_size == 0 else 1)
before = len(requests)
assert file.read_range(0, 1) == payload[:1]
assert len(requests) == before + 1
assert requests[-1] == (0, 1)
assert file.tell() == 2
file.set_buffer_size(0)
assert file.read(1) == payload[2:3]
assert requests[-1] == (2, 3)
file.set_buffer_size(16)
assert file.read(1) == payload[3:4]
assert requests[-1] == (3, 19)
file.seek(len(payload) - 1)
assert file.read(4) == payload[-1:]
assert requests[-1] == (len(payload) - 1, len(payload))
before = len(requests)
assert file.read(1) == b""
assert len(requests) == before
file.close()
with pytest.raises(ValueError, match="closed"):
file.set_buffer_size(0)
def test_short_prefetch_over_http_preserves_cursor():
with remote_buffer_table(truncate_first=True) as (table, payload, requests):
file = table.fetch_blob_files("image", [10], buffer_size=8)[0]
with pytest.raises(RuntimeError, match="returned 5 bytes, expected 8"):
file.read(6)
assert file.tell() == 0
assert file.read(3) == payload[:3]
assert file.tell() == 3
assert requests == [(0, 8), (0, 8)]
file.close()
def test_idle_prefetch_releases_http_concurrency_slot():
with remote_buffer_table() as (table, payload, requests):
first, second = table.fetch_blob_files("image", [10, 10])
assert first.read(1) == payload[:1]
results = []
errors = []
def read_other():
try:
results.append(second.read(1))
except Exception as error:
errors.append(error)
reader = threading.Thread(target=read_other, daemon=True)
reader.start()
reader.join(timeout=2)
completed_while_first_idle = not reader.is_alive()
first.close()
reader.join(timeout=2)
second.close()
assert completed_while_first_idle, (
"idle prefetch retained the HTTP request slot"
)
assert not errors
assert results == [payload[:1]]
assert requests == [(0, 512 * 1024), (0, 512 * 1024)]
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_local_buffer_configuration_through_python(tmp_path, use_async):
db = lancedb.connect(tmp_path)
table = db.create_table(
"blobs", [{"image": b"0123456789"}], schema=pa.schema([lancedb.blob("image")])
)
row_ids = table.search().with_row_id(True).to_arrow()["_rowid"]
if use_async:
files = await table._table.fetch_blob_files("image", row_ids, buffer_size=0)
else:
files = table.fetch_blob_files("image", row_ids, buffer_size=0)
file = files[0]
assert file.read(2) == b"01"
file.set_buffer_size(4)
assert file.read(2) == b"23"
file.seek(1)
assert file.read(3) == b"123"
assert file.read_range(8, 2) == b"89"
with pytest.raises(ValueError, match="non-negative"):
file.set_buffer_size(-1)
with pytest.raises(TypeError):
file.set_buffer_size(1.5)
file.close()
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_open_descriptor_files_forward_buffer_size(use_async):
with remote_buffer_table() as (table, payload, requests):
descriptor = {
"kind": 1,
"position": 0,
"size": len(payload),
"blob_id": 0,
"blob_uri": "",
"source": {
"uri": "s3://bucket/test.lance",
"version": 1,
"committed_at_micros": 1,
"column": "image",
"row_reference": 10,
"row_is_address": False,
},
}
if use_async:
files = [
file
async for file in table._table.open_blob_files(
[None, descriptor], buffer_size=8
)
]
else:
files = list(table.open_blob_files([None, descriptor], buffer_size=8))
assert files[0] is None
assert files[1].read(1) == payload[:1]
assert requests == [(0, 8)]
files[1].close()
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_invalid_buffer_size_rejects_before_http(use_async):
http_requests = []
with remote_buffer_table(http_requests=http_requests) as (table, _, requests):
http_requests.clear()
with pytest.raises(ValueError, match="non-negative"):
if use_async:
await table._table.fetch_blob_files("image", [10], buffer_size=-1)
else:
table.fetch_blob_files("image", [10], buffer_size=-1)
assert requests == []
assert http_requests == []
+380
View File
@@ -0,0 +1,380 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Exercise the public sync/async range APIs over bounded loopback HTTP."""
import asyncio
import hashlib
import json
from pathlib import Path
import socket
import threading
import lancedb._lancedb as native
import pyarrow as pa
import pytest
from lancedb.remote.errors import HttpError, TableNotFoundError
from test_remote_db import mock_lancedb_connection
MIB = 1024 * 1024
IDENTITY = "v1:" + "a" * 64
ROUTE = "/v1/table/test/fetch_blob_ranges/"
def payload(row, offset, length, version):
pattern = bytes((row * 17 + i + version) % 251 for i in range(251))
start = offset % 251
return (pattern * ((start + length + 250) // 251))[start : start + length]
class RangeServer:
def __init__(self, fault=None):
self.fault = fault
self.calls = []
self.fetches = []
self.identities = []
self.stalled = threading.Event()
self.release = threading.Event()
def __call__(self, request):
request.connection.settimeout(15)
size = int(request.headers.get("Content-Length", 0))
assert size <= 256 * 1024
body = json.loads(request.rfile.read(size) or b"{}")
self.calls.append((request.command, request.path, body))
if request.path in (
"/v1/table/test/describe/",
"/v1/table/test/branches/list/",
):
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.send_header("phalanx-version", "1.13.0-beta.0")
if request.path.endswith("/describe/"):
request.send_header("x-lancedb-blob-ranges", "1")
request.end_headers()
response = (
{
"branches": {
"experiment": {
"parentBranch": None,
"parentVersion": 1,
"createAt": 1,
"manifestSize": 1,
}
}
}
if request.path.endswith("branches/list/")
else {"version": 8, "schema": {"fields": []}}
)
request.wfile.write(json.dumps(response).encode())
return
assert (request.command, request.path) == ("POST", ROUTE)
self.fetches.append(body)
self.identities.append(request.headers.get("x-lancedb-query-snapshot"))
assert body["column"] == "image"
assert body["branch"] == "experiment"
ranges = body["ranges"]
assert len(ranges) <= 1024
assert sum(r["length"] for r in ranges) <= 64 * MIB
version = body["version"] or (7 if len(self.fetches) == 1 else 8)
values = [
None
if r["row_id"] == 20
else payload(r["row_id"], r["offset"], r["length"], version)
for r in ranges
]
fault = (
self.fault
if len(self.fetches) > 1 or str(self.fault).startswith("first-")
else None
)
if fault in ("recreated", "gone"):
request.send_response(400 if fault == "recreated" else 404)
request.end_headers()
request.wfile.write(
b"query snapshot identity mismatch: source gone or replaced"
)
return
if fault == "stall" and len(self.fetches) == 2:
request.send_response(200)
request.send_header("Content-Type", "application/vnd.apache.arrow.stream")
request.send_header("x-lancedb-version", str(version))
request.send_header("x-lancedb-query-snapshot", IDENTITY)
request.end_headers()
request.wfile.flush()
self.stalled.set()
assert self.release.wait(15), "test did not release stalled response"
return
if fault == "structured400":
request.send_response(400)
request.send_header("x-lancedb-error-code", "invalid_input")
request.end_headers()
request.wfile.write(b'{"error":"range exceeds blob size"}')
return
if isinstance(fault, int):
request.send_response(fault)
request.end_headers()
request.wfile.write(b"ordinary server failure")
return
if fault == "disconnect":
request.connection.shutdown(socket.SHUT_RDWR)
return
column = "wrong" if fault == "column" else "value"
data_type = pa.binary() if fault == "type" else pa.large_binary()
if fault == "count":
values = []
elif fault == "length":
values = [b""]
batch = pa.table({column: pa.array(values, type=data_type)})
sink = pa.BufferOutputStream()
with pa.ipc.new_stream(sink, batch.schema) as writer:
writer.write_table(batch, max_chunksize=257)
ipc = sink.getvalue().to_pybytes()
if fault == "eos":
ipc = ipc[:-8]
elif fault == "body":
ipc = ipc[: len(ipc) // 2]
request.send_response(200)
request.send_header("Content-Type", "application/vnd.apache.arrow.stream")
if fault != "version":
request.send_header("x-lancedb-version", str(version))
if fault not in ("missing-identity", "first-missing-identity"):
identity = (
"broken"
if fault == "first-invalid-identity"
else "v1:" + "b" * 64
if fault == "wrong-identity"
else IDENTITY
)
request.send_header("x-lancedb-query-snapshot", identity)
request.send_header(
"Content-Length", str(len(ipc) + (10 if fault == "transport" else 0))
)
request.end_headers()
for i in range(0, len(ipc), 8192):
request.wfile.write(ipc[i : i + 8192])
async def fetch(table, requests, use_async):
result = table.fetch_blob_ranges("image", requests)
return await result if use_async else result
def api(db, use_async, version=None):
table = db.open_table("test", branch="experiment", version=version)
return table._table if use_async else table
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
@pytest.mark.parametrize("version", [None, 3])
async def test_range_sdk_order_snapshot_and_overwrite(use_async, version):
handler = RangeServer()
with mock_lancedb_connection(handler) as db:
table = api(db, use_async, version)
requests = [(20 if i % 9 == 0 else 10 + i % 7, i, i % 4) for i in range(1025)]
requests += [(10, 0, 0), (10, 2, 3), (10, 2, 3)]
result = await fetch(table, requests, use_async)
assert isinstance(result, pa.LargeBinaryArray)
assert result.to_pylist() == [
None if row == 20 else payload(row, offset, length, version or 7)
for row, offset, length in requests
]
assert [b["version"] for b in handler.fetches] == [version, version or 7]
result = await fetch(table, [(10, 0, 1)], use_async)
assert result.to_pylist() == [payload(10, 0, 1, version or 8)]
assert handler.fetches[-1]["version"] == version
assert len(handler.fetches) == 3
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_range_sdk_cached_reopen_negotiates_capability(use_async):
handler = RangeServer()
with mock_lancedb_connection(handler) as db:
for version in (7, 8):
table = api(db, use_async)
result = await fetch(table, [(10, 0, 1)], use_async)
assert result.to_pylist() == [payload(10, 0, 1, version)]
assert len(handler.fetches) == 2
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_range_sdk_large_single_and_aggregate_budget(use_async):
handler = RangeServer()
with mock_lancedb_connection(handler) as db:
table = api(db, use_async)
requests = [
(10, 3, 33 * MIB),
(30, 7, 33 * MIB),
(40, 11, 70 * MIB),
(20, 0, 2**64 - 1),
]
# The loopback server advances latest after the first partition.
result = await fetch(table, requests, use_async)
assert len(result) == 4
for i, (row, offset, length) in enumerate(requests[:3]):
expected = payload(row, offset, length, 7)
assert (
hashlib.sha256(result[i].as_buffer()).digest()
== hashlib.sha256(expected).digest()
)
assert len(result[i].as_buffer()) == length
assert result[3].as_py() is None
assert len(handler.fetches) == 3
assert [b["version"] for b in handler.fetches] == [None, 7, 7]
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
@pytest.mark.parametrize(
"fault",
[
"type",
"column",
"count",
"length",
"eos",
"body",
"transport",
"version",
"disconnect",
401,
403,
404,
429,
500,
],
)
async def test_range_sdk_later_failure_rejects_entire_call(use_async, fault):
handler = RangeServer(fault=fault)
with mock_lancedb_connection(
handler, retry_config={"retries": 2, "connect_retries": 2, "read_retries": 2}
) as db:
table = api(db, use_async)
with pytest.raises(Exception) as exc:
await fetch(table, [(10, 0, 1)] * 1025, use_async)
if fault == 404:
assert isinstance(exc.value, TableNotFoundError)
assert isinstance(exc.value.__cause__, HttpError)
assert exc.value.__cause__.status_code == 404
else:
assert not isinstance(exc.value, ValueError)
if isinstance(fault, int):
assert exc.value.status_code == fault
assert len(handler.fetches) == 2
assert all(
path in ("/v1/table/test/describe/", "/v1/table/test/branches/list/", ROUTE)
for _, path, _ in handler.calls
)
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_range_sdk_structured_400_preserves_value_error(use_async):
handler = RangeServer(fault="structured400")
with mock_lancedb_connection(handler) as db:
table = api(db, use_async)
with pytest.raises(ValueError, match="range exceeds blob size"):
await fetch(table, [(10, 0, 1)] * 1025, use_async)
assert len(handler.fetches) == 2
@pytest.mark.asyncio
async def test_range_sdk_async_cancel_releases_only_request_permit():
handler = RangeServer(fault="stall")
with mock_lancedb_connection(handler, blob_request_concurrency=1) as db:
table = api(db, True)
pending = asyncio.create_task(fetch(table, [(10, 0, 1)] * 2049, True))
try:
assert await asyncio.to_thread(handler.stalled.wait, 10)
pending.cancel()
with pytest.raises(asyncio.CancelledError):
await pending
assert len(handler.fetches) == 2
result = await asyncio.wait_for(fetch(table, [(10, 0, 1)], True), 5)
assert result.to_pylist() == [payload(10, 0, 1, 8)]
assert len(handler.fetches) == 3
finally:
pending.cancel()
handler.release.set()
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_range_sdk_integer_validation_and_empty_zero_io(use_async):
handler = RangeServer()
with mock_lancedb_connection(handler) as db:
table = api(db, use_async)
before = len(handler.calls)
assert (await fetch(table, [], use_async)).to_pylist() == []
for request in [
(-1, 0, 1),
(2**64, 0, 1),
(10, -1, 1),
(10, 0, -1),
(10, 0, 2**64),
(10, 0.5, 1),
(20, 2**64 - 1, 1),
(10, 0),
]:
with pytest.raises((ValueError, OverflowError, TypeError)):
await fetch(table, [request], use_async)
assert len(handler.calls) == before
def test_range_sdk_loaded_artifact_identity():
artifact = Path(native.__file__).resolve()
digest = hashlib.sha256()
with artifact.open("rb") as source:
for chunk in iter(lambda: source.read(1024 * 1024), b""):
digest.update(chunk)
print(f"loaded native artifact={artifact} sha256={digest.hexdigest()}")
assert artifact.is_file()
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
@pytest.mark.parametrize(
"fault", ["missing-identity", "wrong-identity", "recreated", "gone"]
)
@pytest.mark.parametrize("huge", [False, True])
async def test_range_sdk_original_identity_survives_every_partition(
use_async, fault, huge
):
handler = RangeServer(fault=fault)
with mock_lancedb_connection(handler) as db:
table = api(db, use_async)
requests = [(10, 0, 64 * MIB + 1)] if huge else [(10, 0, 1)] * 1025
error = (
ValueError
if fault == "recreated"
else TableNotFoundError
if fault == "gone"
else NotImplementedError
)
with pytest.raises(
error, match="snapshot identity" if fault != "gone" else None
):
await fetch(table, requests, use_async)
assert handler.identities == [None, IDENTITY]
assert len(handler.fetches) == 2
assert [body["version"] for body in handler.fetches] == [None, 7]
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
@pytest.mark.parametrize("fault", ["first-missing-identity", "first-invalid-identity"])
async def test_range_sdk_bulk_requires_identity_before_payload_acceptance(
use_async, fault
):
handler = RangeServer(fault=fault)
with mock_lancedb_connection(handler) as db:
table = api(db, use_async)
before = len(handler.calls)
with pytest.raises(NotImplementedError, match="snapshot identity"):
await fetch(table, [(10, 0, 1)] * 1025, use_async)
assert len(handler.fetches) == 1
assert len(handler.calls) == before + 1
+175 -1
View File
@@ -2,7 +2,9 @@
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from datetime import timedelta
import json
import warnings
import pytest
@@ -62,6 +64,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server):
endpoint,
api_key="secret",
sql_host_override="invalid://localhost",
storage_options={"azure_storage_account_name": "catalog-account"},
client_config={
"extra_headers": {
"X-LanceDB-Database": "wrong",
@@ -80,6 +83,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server):
assert db.table_names() == []
restored = lancedb.deserialize_conn(db.serialize())
assert restored.sql_host_override == "invalid://localhost"
assert restored.storage_options == {"azure_storage_account_name": "catalog-account"}
for connection in (db, restored):
with pytest.raises(ValueError, match="sql_host_override must use"):
connection.execute_query_async("SELECT 1")
@@ -98,6 +102,7 @@ def test_catalog_sync_scope_and_serialization(catalog_server):
)
assert "x-lancedb-database-prefix" not in headers
assert headers["x-api-key"] == "secret"
assert headers["x-azure-storage-account-name"] == "catalog-account"
@pytest.mark.asyncio
@@ -114,7 +119,9 @@ async def test_catalog_async_and_errors(catalog_server):
]
)
catalog = await lancedb.connect_catalog_async(
endpoint, sql_host_override="invalid://localhost"
endpoint,
sql_host_override="invalid://localhost",
storage_options={"account_name": "async-account"},
)
assert isinstance(catalog, lancedb.AsyncCatalog)
db = await catalog.connect_database("analytics")
@@ -130,6 +137,9 @@ async def test_catalog_async_and_errors(catalog_server):
await catalog.drop_database("full")
await catalog.drop_database("missing", ignore_missing=True)
assert requests[4][2] == {"mode": "Fail", "behavior": "Restrict"}
for _, headers, _ in requests:
headers = {key.lower(): value for key, value in headers.items()}
assert headers["x-azure-storage-account-name"] == "async-account"
@pytest.mark.parametrize("endpoint", ["/tmp/catalog", "s3://bucket", "db://db"])
@@ -138,6 +148,170 @@ def test_catalog_requires_remote_endpoint(endpoint):
lancedb.connect_catalog(endpoint)
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize("region", ["us-east-1", "not-a-region"])
@pytest.mark.asyncio
async def test_catalog_accepts_database_connection_settings(
catalog_server, asynchronous, region
):
endpoint, requests, responses = catalog_server
responses.extend([(200, {"namespaces": []}), (200, {"tables": []})])
settings = {
"uri": "db://analytics",
"api_key": "shared-secret",
"region": region,
"host_override": endpoint,
"sql_host_override": "invalid://localhost",
"read_consistency_interval": timedelta(seconds=5),
"client_config": {"extra_headers": {"x-shared-setting": "shared"}},
"storage_options": {"azure_storage_account_name": "shared-account"},
"session": None,
"manifest_enabled": False,
"namespace_client_properties": None,
}
if not asynchronous:
settings.update(
request_thread_pool=None,
namespace_client_impl=None,
namespace_client_pushdown_operations=None,
)
with pytest.warns(
UserWarning, match="region is ignored by connect_catalog"
) as caught:
catalog = (
await lancedb.connect_catalog_async(**settings)
if asynchronous
else lancedb.connect_catalog(**settings)
)
assert len(caught) == 1
assert catalog.uri == endpoint
assert (
[name async for name in catalog.list_databases()]
if asynchronous
else list(catalog.list_databases())
) == []
db = (
await lancedb.connect_async(**settings)
if asynchronous
else lancedb.connect(**settings)
)
assert (await db.table_names() if asynchronous else db.table_names()) == []
root_headers = {key.lower(): value for key, value in requests[0][1].items()}
db_headers = {key.lower(): value for key, value in requests[1][1].items()}
for headers in (root_headers, db_headers):
assert headers["x-api-key"] == "shared-secret"
assert headers["x-shared-setting"] == "shared"
assert headers["x-azure-storage-account-name"] == "shared-account"
assert "x-lancedb-database" not in root_headers
assert db_headers["x-lancedb-database"] == "analytics"
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize("host_only", [False, True])
@pytest.mark.asyncio
async def test_catalog_default_region_is_silent_and_api_key_uses_environment(
catalog_server, monkeypatch, asynchronous, host_only
):
endpoint, requests, responses = catalog_server
monkeypatch.setenv("LANCEDB_API_KEY", "environment-secret")
responses.extend([(200, {}), (200, {"tables": []})])
settings = {"host_override": endpoint} if host_only else {"uri": endpoint}
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
catalog = (
await lancedb.connect_catalog_async(**settings)
if asynchronous
else lancedb.connect_catalog(**settings)
)
assert caught == []
assert catalog.uri == endpoint
db = (
await catalog.connect_database("analytics")
if asynchronous
else catalog.connect_database("analytics")
)
if not asynchronous:
db = lancedb.deserialize_conn(db.serialize())
assert (await db.table_names() if asynchronous else db.table_names()) == []
for _, headers, _ in requests:
headers = {key.lower(): value for key, value in headers.items()}
assert headers["x-api-key"] == "environment-secret"
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.asyncio
async def test_catalog_host_override_selects_endpoint(catalog_server, asynchronous):
endpoint, _, _ = catalog_server
settings = {"uri": "https://unused.example", "host_override": endpoint}
catalog = (
await lancedb.connect_catalog_async(**settings)
if asynchronous
else lancedb.connect_catalog(**settings)
)
assert catalog.uri == endpoint
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize(
"options, message",
[
({}, "uri or host_override is required"),
({"session": object()}, "session"),
({"manifest_enabled": True}, "manifest_enabled"),
({"namespace_client_properties": {}}, "namespace_client_properties"),
],
)
@pytest.mark.asyncio
async def test_catalog_rejects_unsupported_connection_settings(
catalog_server, asynchronous, options, message
):
_, requests, _ = catalog_server
error = NotImplementedError if options else ValueError
with pytest.raises(error, match=message):
if asynchronous:
await lancedb.connect_catalog_async(**options)
else:
lancedb.connect_catalog(**options)
assert requests == []
@pytest.mark.parametrize(
"options, error, message",
[
(
{"namespace_client_impl": "dir"},
NotImplementedError,
"namespace_client_impl",
),
(
{"namespace_client_pushdown_operations": []},
NotImplementedError,
"namespace_client_pushdown_operations",
),
({"unknown_option": True}, ValueError, "Unknown keyword arguments"),
],
)
def test_catalog_rejects_unsupported_sync_settings(options, error, message):
with pytest.raises(error, match=message):
lancedb.connect_catalog(**options)
def test_catalog_accepts_deprecated_sync_settings(catalog_server):
endpoint, _, responses = catalog_server
responses.append((200, {}))
with pytest.warns(DeprecationWarning) as caught:
catalog = lancedb.connect_catalog(
endpoint,
request_thread_pool=2,
connection_timeout=5,
read_timeout=10,
)
assert len(caught) == 3
db = catalog.connect_database("analytics")
assert db.client_config.timeout_config.connect_timeout == timedelta(seconds=5)
assert db.client_config.timeout_config.read_timeout == timedelta(seconds=10)
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.asyncio
@pytest.mark.parametrize("page_token,page_limit", [(None, None), ("start/token", 2)])
@@ -0,0 +1,36 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import pytest
import lancedb
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
async def test_clone_exist_ok_preserves_target(tmp_path, asynchronous):
source_uri = str(tmp_path / "source.lance")
if asynchronous:
db = await lancedb.connect_async(tmp_path)
await db.create_table("source", [{"id": 1}])
table = await db.clone_table("target", source_uri, exist_ok=True)
assert (await table.to_arrow()).to_pylist() == [{"id": 1}]
await table.add([{"id": 2}])
version = await table.version()
with pytest.raises(ValueError, match="already exists"):
await db.clone_table("target", source_uri)
kept = await db.clone_table("target", "missing.lance", exist_ok=True)
assert await kept.version() == version
assert (await kept.to_arrow()).to_pylist() == [{"id": 1}, {"id": 2}]
else:
db = lancedb.connect(tmp_path)
db.create_table("source", [{"id": 1}])
table = db.clone_table("target", source_uri, exist_ok=True)
assert table.to_arrow().to_pylist() == [{"id": 1}]
table.add([{"id": 2}])
version = table.version
with pytest.raises(ValueError, match="already exists"):
db.clone_table("target", source_uri)
kept = db.clone_table("target", "missing.lance", exist_ok=True)
assert kept.version == version
assert kept.to_arrow().to_pylist() == [{"id": 1}, {"id": 2}]
+35 -11
View File
@@ -282,9 +282,7 @@ async def test_table_listing_defaults_and_zero_limit(tmp_path):
assert empty.page_token is None
def test_db_contains_stops_after_matching_table_page(
tmp_db: lancedb.DBConnection, monkeypatch
):
def test_db_len_includes_all_table_pages(tmp_db: lancedb.DBConnection, monkeypatch):
calls = []
pages = {
None: SimpleNamespace(tables=["table_0", "table_1"], page_token="next"),
@@ -297,18 +295,44 @@ def test_db_contains_stops_after_matching_table_page(
monkeypatch.setattr(tmp_db, "list_tables", list_tables)
assert "table_1" in tmp_db
assert calls == [None]
calls.clear()
assert "table_2" in tmp_db
assert calls == [None, "next"]
calls.clear()
assert len(tmp_db) == 3
assert calls == [None, "next"]
@pytest.mark.asyncio
@pytest.mark.parametrize("namespace_path", [[], ["analytics", "nested"]])
async def test_local_table_exists_without_listing(
tmp_path, monkeypatch, namespace_path
):
db = lancedb.connect(tmp_path)
for depth in range(1, len(namespace_path) + 1):
db.create_namespace(namespace_path[:depth])
db.create_table("events", data=[{"id": 1}], namespace_path=namespace_path)
if not namespace_path:
for idx in range(100):
(tmp_path / f"a{idx:03}.lance").mkdir()
assert "events" not in db.list_tables().tables
adb = await lancedb.connect_async(tmp_path)
def fail_listing(*args, **kwargs):
raise AssertionError("Existence checks must not list tables")
monkeypatch.setattr(db, "list_tables", fail_listing)
monkeypatch.setattr(adb, "list_tables", fail_listing)
table_id = namespace_path + ["events"]
assert db.table_exists(table_id) is True
assert await adb.table_exists(table_id) is True
assert db.table_exists(namespace_path + ["missing"]) is False
assert await adb.table_exists(namespace_path + ["missing"]) is False
assert ("events" in db) is (not namespace_path)
assert "missing" not in db
assert table_id == namespace_path + ["events"]
db.drop_table("events", namespace_path=namespace_path)
assert db.table_exists(table_id) is False
assert await adb.table_exists(table_id) is False
@pytest.mark.asyncio
async def test_table_names_async(tmp_path):
db = lancedb.connect(tmp_path)
@@ -2,17 +2,19 @@
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import json
import warnings
from collections import UserDict
from pathlib import Path
from types import MappingProxyType
import pytest
from lancedb import col
from lancedb import col, lit
import lancedb.functions as functions
from lancedb.functions import (
FunctionApplication,
FunctionBinding,
FunctionImage,
FunctionVersion,
PythonRuntimeSpec,
SecretBinding,
@@ -34,7 +36,7 @@ FIXTURES = (
def fixture(name: str) -> str:
return (FIXTURES / name).read_text()
return (FIXTURES / name).read_text(encoding="utf-8")
def job_result(name: str) -> dict:
@@ -58,6 +60,7 @@ def assert_no_secret_values(value):
def test_public_function_values_are_in_api_reference():
assert "LiteralInputBinding" in functions.__all__
docs = Path(__file__).parents[3] / "docs" / "src" / "python" / "python.md"
rendered = docs.read_text()
for name in functions.__all__:
@@ -148,6 +151,91 @@ def test_function_version_identity_is_immutable_and_exact():
FunctionVersion(**{**value, "version": invalid})
@pytest.mark.parametrize("gpu", [False, True])
def test_image_inspection_is_concise_warning_free_and_preserves_wire_state(gpu):
value = job_result("remote_function_job.json")["image"]
value["descriptor"]["future_metadata"] = "x" * 100_000
if gpu:
value["descriptor"]["requires"]["capabilities"] = [
{
"type": "lance.cuda",
"version": 1,
"device_count": 1,
"cuda_toolkit": "12.4",
}
]
image = FunctionImage(**value)
with warnings.catch_warnings():
warnings.simplefilter("error", DeprecationWarning)
details = image.describe()
rendered = repr(image)
assert "manifest_digest=" in str(image)
encoded = json.loads(image.to_canonical_json())
assert details == {
"manifest_digest": value["manifest_digest"],
"python_version": "3.12.14",
"requires_gpu": gpu,
"cuda_toolkit": "12.4" if gpu else None,
"platforms": None,
"base_image": None,
"size_bytes": None,
}
assert len(rendered) < 350
assert f"requires_gpu={gpu}" in rendered
assert "future_metadata" not in rendered
assert encoded == value
@pytest.mark.parametrize(
"descriptor",
[
{},
{"format_version": 2, "requires": {"capabilities": []}},
{"format_version": 1, "requires": {"capabilities": [None]}},
{"python": {"version": {"future": "x" * 100_000}}},
],
)
def test_image_inspection_leaves_missing_or_unrecognized_metadata_unknown(descriptor):
image = FunctionImage(
manifest_digest="sha256:example", descriptor=descriptor, source=True
)
assert image.describe()["requires_gpu"] is None
assert image.describe()["python_version"] is None
assert len(repr(image)) < 350
@pytest.mark.parametrize(
"case", json.loads(fixture("runtime_identity.json")), ids=lambda case: case["name"]
)
def test_runtime_digests_match_server_golden_values(case):
runtime = PythonRuntimeSpec.from_json(json.dumps(case["runtime"]))
assert runtime.digest == case["digest"]
assert (
PythonRuntimeSpec.from_json(runtime.to_canonical_json()).digest
== runtime.digest
)
def test_unknown_runtime_digest_fails_closed():
runtime = PythonRuntimeSpec.from_json('{"kind":"python_v3","future":"value"}')
with pytest.raises(ValueError, match="cannot digest unknown runtime kind"):
runtime.digest
@pytest.mark.parametrize("runtime_digest", [None, "sha256:runtime-inputs"])
def test_function_version_preserves_runtime_digest(runtime_digest):
value = job_result("remote_function_job.json")
legacy = FunctionVersion.from_json(json.dumps(value))
assert legacy.runtime_digest is None
assert "runtime_digest" not in json.loads(legacy.to_canonical_json())
value["runtime_digest"] = runtime_digest
version = FunctionVersion.from_json(json.dumps(value))
assert version.runtime_digest == runtime_digest
assert FunctionVersion.from_json(version.to_canonical_json()) == version
with pytest.raises((TypeError, ValueError)):
version.runtime_digest = "sha256:changed"
@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")
@@ -254,6 +342,67 @@ def test_function_version_binding_validates_names_and_direct_columns():
version(text=col("text").lower())
@pytest.mark.parametrize("constant", [16, 8, True, "prompt", None, 2**64 - 1])
def test_function_version_binds_direct_literals_without_changing_identity(constant):
value = job_result("remote_function_job.json")
value["signature"]["inputs"].append(
{
"name": "option",
"arrow_type": "bool"
if type(constant) is bool
else "utf8"
if isinstance(constant, str)
else "uint64"
if constant == 2**64 - 1
else "int64",
"nullable": True,
}
)
version = FunctionVersion.from_json(json.dumps(value))
expression = lit(constant)
application = version(text=col("body"), option=expression)
encoded = json.loads(application.to_canonical_json())
assert encoded["inputs"] == [
{"parameter": "text", "kind": "column", "value": {"path": "body"}},
{"parameter": "option", "kind": "literal", "value": constant},
]
assert application.function.version == version.version
assert application.function.object_id == version.object_id
assert application.function.manifest_digest == version.image.manifest_digest
assert FunctionApplication.from_json(application.to_canonical_json()) == application
if constant is None:
assert expression.to_sql() == "NULL"
if type(constant) is int:
assert expression.to_sql() == str(constant)
def test_function_literals_reject_expressions_and_unsupported_values():
version = FunctionVersion.from_json(
json.dumps(job_result("remote_function_job.json"))
)
with pytest.raises(TypeError, match="direct col"):
version(text=lit(16) + lit(8))
with pytest.raises(ValueError, match="floating-point Function literals"):
version(text=lit(1.5))
with pytest.raises(TypeError, match="unsupported Function literal type"):
version(text=lit(b"data"))
def test_function_literal_binding_preserves_null_and_rejects_duplicate_parameters():
value = json.loads((FIXTURES / "remote_function_binding.json").read_text())
value["inputs"] = value["inputs"][:1]
value["literal_inputs"] = [{"parameter": "body", "value": None}]
binding = FunctionBinding.from_json(json.dumps(value))
assert binding.literal_inputs[0].value is None
assert json.loads(binding.to_canonical_json())["literal_inputs"] == [
{"parameter": "body", "value": None}
]
assert FunctionBinding.from_json(binding.to_canonical_json()) == binding
value["literal_inputs"][0]["parameter"] = "title"
with pytest.raises(ValueError, match="input parameters must be unique"):
FunctionBinding.from_json(json.dumps(value))
def test_function_version_keeps_named_struct_outputs_in_one_application():
value = job_result("remote_function_job.json")
value["name"] = "text_features"
@@ -9,7 +9,7 @@ import functools
import importlib.util
import inspect
import types
from datetime import date
from datetime import date, datetime, timedelta
import http.server
import json
import os
@@ -18,15 +18,19 @@ import subprocess
import sys
import typing
import urllib.parse
from typing import Optional
import warnings
from decimal import Decimal
from typing import Annotated, Optional
import pyarrow as pa
import pytest
import lancedb
from lancedb import BlobReader
from lancedb.db import AsyncConnection
from lancedb.db import AsyncConnection, DBConnection, LanceDBConnection
from lancedb.functions import (
FunctionRegistrationRequest,
FunctionSignature,
FunctionVersion,
HuggingFaceModel,
PythonRuntimeSpec,
@@ -80,6 +84,63 @@ def analyze_caption(caption: str) -> str:
return caption.strip()
def _function_version_with_resolved_environment():
version = json.loads(
(FIXTURES / "remote_function_version.canonical.json").read_text()
)
version["runtime"] = json.loads(
normalize_score.registration_request.runtime.to_canonical_json()
)
version["resolved_environment"] = {
"packages": [
{
"name": "torch",
"version": "2.9.0+cu130",
"source": "https://packages.example/simple",
},
{"name": "transformers", "version": "4.57.1"},
],
"provenance": {
"configured_index_urls": ["https://packages.example/simple"],
"configured_find_links": ["https://downloads.example/wheels"],
"resolved_indexes": ["https://packages.example/simple"],
"cuda_toolkit": "12.8",
"torch_version": "torch==2.9.0+cu130",
},
"warnings": [
"transformers resolved to transformers==4.57.1 but is not pinned "
"exactly; add transformers==4.57.1 to pin it."
],
}
return version
def _function_version_with_resolved_environments():
version = json.loads(
(FIXTURES / "remote_function_version.canonical.json").read_text()
)
version["runtime"] = json.loads(
normalize_score.registration_request.runtime.to_canonical_json()
)
version["resolved_environments"] = {
"linux/amd64": {
"packages": [
{
"name": "torch",
"version": "2.9.0+cu130",
"source": "https://packages.example/simple",
}
],
"warnings": ["amd64 environment warning"],
},
"linux/arm64": {
"packages": [],
"warnings": ["arm64 environment warning"],
},
}
return version
def test_scalar_function_matches_shared_registration_golden_and_remains_callable():
assert isinstance(normalize_score, FunctionDefinition)
assert normalize_score(25.0) == 0.25
@@ -96,6 +157,118 @@ def test_scalar_function_matches_shared_registration_golden_and_remains_callable
}
def test_refresh_lock_is_a_registration_option_not_part_of_identity():
default = normalize_score.registration_request
old_json = default.to_canonical_json()
assert "refresh_lock" not in json.loads(old_json)
refreshed = default.with_refresh_lock(True)
payload = json.loads(refreshed.to_canonical_json())
assert payload["refresh_lock"] is True
assert (
FunctionRegistrationRequest.from_json(
refreshed.to_canonical_json()
).refresh_lock
is True
)
assert refreshed.artifact.digest == default.artifact.digest
assert refreshed.runtime.digest == default.runtime.digest
assert default.with_refresh_lock(False).to_canonical_json() == old_json
with pytest.raises(ValueError, match="refresh_lock must be a boolean"):
default.with_refresh_lock(1)
@pytest.mark.asyncio
@pytest.mark.parametrize("exist_ok", [False, True])
async def test_async_create_function_forwards_refresh_lock(exist_ok):
calls = []
class Inner:
async def create_function_async(
self, request_json, namespace_path=None, *, exist_ok=False
):
calls.append((json.loads(request_json), namespace_path, exist_ok))
return object()
connection = object.__new__(AsyncConnection)
connection._inner = Inner()
await connection.create_function_async(normalize_score)
await connection.create_function_async(
normalize_score, refresh_lock=True, exist_ok=exist_ok, namespace_path=["team"]
)
with pytest.raises(ValueError, match="refresh_lock must be a boolean"):
await connection.create_function_async(normalize_score, refresh_lock=1)
assert len(calls) == 2
assert "refresh_lock" not in calls[0][0]
assert calls[0][1:] == (None, False)
assert calls[1][0]["refresh_lock"] is True
assert calls[1][1:] == (["team"], exist_ok)
@pytest.mark.parametrize("exist_ok", [False, True])
def test_sync_create_function_paths_forward_refresh_lock(exist_ok):
calls = []
class AsyncInner:
async def create_function_async(
self,
definition,
*,
secrets=None,
exist_ok=False,
namespace_path=None,
refresh_lock=False,
):
calls.append(("wrapped", refresh_lock, namespace_path, exist_ok))
return object()
for connection_type in (LanceDBConnection, RemoteDBConnection):
connection = object.__new__(connection_type)
connection._conn = AsyncInner()
connection.create_function_async(
normalize_score,
refresh_lock=True,
exist_ok=exist_ok,
namespace_path=["team"],
)
class BlockingConnection:
def create_function_async(
self,
definition,
*,
secrets=None,
exist_ok=False,
namespace_path=None,
refresh_lock=False,
):
calls.append(("blocking", refresh_lock, namespace_path, exist_ok))
class ImmediateJob:
def wait(self):
return "version"
return ImmediateJob()
blocking = BlockingConnection()
assert (
DBConnection.create_function(
blocking,
normalize_score,
refresh_lock=True,
exist_ok=exist_ok,
namespace_path=["team"],
)
== "version"
)
assert calls == [
("wrapped", True, ["team"], exist_ok),
("wrapped", True, ["team"], exist_ok),
("blocking", True, ["team"], exist_ok),
]
def test_function_declares_pinned_hugging_face_models():
model = HuggingFaceModel(
repo="sentence-transformers/all-MiniLM-L6-v2",
@@ -658,9 +831,11 @@ def test_function_image_requires_digest_reference(image):
def test_function_gpu_marker_uses_gpu_runtime():
@function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g")
def double_on_gpu(value: int) -> int:
return value * 2
with pytest.warns(UserWarning, match="uses a scalar callable"):
@function(pip=["cupy-cuda12x"], gpu=True, gpu_class="a10g")
def double_on_gpu(value: int) -> int:
return value * 2
request = json.loads(double_on_gpu.registration_request.to_canonical_json())
assert request["runtime"]["kind"] == "python_v2"
@@ -710,6 +885,60 @@ def test_function_gpu_marker_uses_gpu_runtime():
)
class _GpuScalarFunction:
def __call__(self, value: str) -> int:
return len(value)
class _GpuArrayFunction:
def __call__(self, value: pa.Array) -> pa.Array:
return value
def test_gpu_scalar_warning_names_the_vectorized_alternative():
with pytest.warns(UserWarning, match="model batch is not inferred"):
@function(gpu=True)
def scalar_embedding(value: str) -> list[int]:
return [len(value)]
input_schema = pa.schema([pa.field("value", pa.string(), nullable=False)])
with pytest.warns(UserWarning, match="uses a scalar callable"):
class_scalar = function(_GpuScalarFunction, gpu=True)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
@function(
gpu=True, input_schema=input_schema, output_schema=pa.list_(pa.int64())
)
def array_embedding(value: pa.Array) -> pa.Array:
return value
@function(
gpu=True, input_schema=input_schema, output_schema=pa.list_(pa.int64())
)
def record_batch_embedding(value: pa.RecordBatch) -> pa.Array:
return value.column(0)
@function
def cpu_scalar(value: str) -> int:
return len(value)
class_embedding = function(
_GpuArrayFunction,
gpu=True,
input_schema=input_schema,
output_schema=pa.list_(pa.int64()),
)
assert not caught
assert array_embedding.registration_request.batch_size is None
assert record_batch_embedding.registration_request.batch_size is None
assert cpu_scalar.registration_request.batch_size is None
assert class_scalar.registration_request.batch_size is None
assert class_embedding.registration_request.batch_size is None
def test_unknown_runtime_discards_payload_before_known_field_validation():
for payload in [
{
@@ -826,12 +1055,10 @@ def test_canonical_arrow_type_prefers_the_compact_grammar():
== "large_list<float32>"
)
for outside in [
pa.timestamp("us"),
pa.decimal128(10, 2),
pa.binary(4),
pa.duration("s"),
pa.time32("s"),
pa.time64("us"),
pa.list_(pa.float32(), 0),
pa.list_(pa.timestamp("us")),
]:
with pytest.raises(TypeError, match="unsupported Arrow type"):
_canonical_arrow_type(outside)
@@ -888,7 +1115,7 @@ def test_function_rejects_a_module_level_namespace_alias(tmp_path):
spec = importlib.util.spec_from_file_location("aliasing_udfs", module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
with pytest.raises(ValueError, match="dynamic namespace access"):
with pytest.raises(ValueError, match="imports from namespace-access modules"):
function(module.score)
@@ -899,7 +1126,6 @@ def test_function_rejects_a_module_level_namespace_alias(tmp_path):
"eval('THRESHOLD')",
"(lambda g: g()['THRESHOLD'])(globals)",
"__import__('sys').modules[__name__].THRESHOLD",
"sys.modules[__name__].THRESHOLD",
],
)
def test_function_rejects_dynamic_namespace_access(access):
@@ -911,9 +1137,7 @@ def test_function_rejects_dynamic_namespace_access(access):
)
with pytest.raises(ValueError, match="dynamic namespace access"):
_package_from_text(
"def score(value: int) -> int:\n"
" import sys\n"
f" return value + {access}\n"
f"def score(value: int) -> int:\n return value + {access}\n"
)
@@ -1160,6 +1384,340 @@ def test_explicit_arrow_schema_is_deterministic():
assert signature.output.nullable is False
def test_timestamp_annotation_and_explicit_schema_serialization():
for unit in ("s", "ms", "us", "ns"):
for timezone in (None, "UTC", "America/New_York", "+08:00", "-05:00"):
encoded = json.loads(_canonical_arrow_type(pa.timestamp(unit, tz=timezone)))
if unit == "us" and timezone is None:
assert encoded == {"type": "timestamp"}
else:
suffix = timezone if timezone is not None else "-"
assert encoded == {"type": f"timestamp:{unit}:{suffix}"}
with pytest.raises(TypeError, match="reserved for no timezone"):
_canonical_arrow_type(pa.timestamp("us", tz="-"))
@function
def normalize(
ts: Annotated[datetime, pa.timestamp("ns", tz="UTC")],
) -> Annotated[datetime, pa.timestamp("ns", tz="UTC")]:
return ts
signature = normalize.registration_request.signature
assert json.loads(signature.inputs[0].arrow_type) == {"type": "timestamp:ns:UTC"}
assert json.loads(signature.output.arrow_type) == {"type": "timestamp:ns:UTC"}
round_trip = FunctionSignature.from_json(signature.to_canonical_json())
assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type
assert round_trip.output.arrow_type == signature.output.arrow_type
@function
def optional_timestamp(
ts: Optional[Annotated[datetime, pa.timestamp("ms", tz="UTC")]],
) -> int:
return 0
optional_input = optional_timestamp.registration_request.signature.inputs[0]
assert optional_input.nullable is True
assert json.loads(optional_input.arrow_type) == {"type": "timestamp:ms:UTC"}
@function
def legacy(ts: datetime) -> datetime:
return ts
legacy_signature = legacy.registration_request.signature
assert json.loads(legacy_signature.inputs[0].arrow_type) == {"type": "timestamp"}
assert json.loads(legacy_signature.output.arrow_type) == {"type": "timestamp"}
legacy_round_trip = FunctionSignature.from_json(
legacy_signature.to_canonical_json()
)
assert legacy_round_trip.inputs[0].arrow_type == '{"type":"timestamp"}'
input_schema = pa.schema(
[pa.field("ts", pa.timestamp("ms", tz="America/New_York"), nullable=True)]
)
output_schema = pa.schema(
[
pa.field("ts", pa.timestamp("ns", tz="+08:00"), nullable=True),
pa.field("elapsed", pa.duration("ms"), nullable=False),
]
)
@function(input_schema=input_schema, output_schema=output_schema)
def nested(ts):
return {"ts": ts, "elapsed": None}
nested_signature = nested.registration_request.signature
assert nested_signature.inputs[0].nullable is True
assert json.loads(nested_signature.inputs[0].arrow_type) == {
"type": "timestamp:ms:America/New_York"
}
assert nested_signature.output.kind == "named_struct"
assert nested_signature.output.fields[0].nullable is True
assert json.loads(nested_signature.output.fields[0].arrow_type) == {
"type": "timestamp:ns:+08:00"
}
assert json.loads(nested_signature.output.fields[1].arrow_type) == {
"type": "duration:ms"
}
list_type = pa.list_(pa.field("item", pa.timestamp("ms", tz="UTC"), nullable=False))
assert json.loads(_canonical_arrow_type(list_type)) == {
"type": "list",
"fields": [
{
"name": "item",
"nullable": False,
"type": {"type": "timestamp:ms:UTC"},
}
],
}
def test_duration_annotation_and_explicit_schema_serialization():
for unit in ("s", "ms", "us", "ns"):
encoded = json.loads(_canonical_arrow_type(pa.duration(unit)))
expected = (
{"type": "duration"} if unit == "us" else {"type": f"duration:{unit}"}
)
assert encoded == expected
@function
def elapsed(
value: Annotated[timedelta, pa.duration("s")],
) -> Annotated[timedelta, pa.duration("ns")]:
return value
signature = elapsed.registration_request.signature
assert json.loads(signature.inputs[0].arrow_type) == {"type": "duration:s"}
assert json.loads(signature.output.arrow_type) == {"type": "duration:ns"}
round_trip = FunctionSignature.from_json(signature.to_canonical_json())
assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type
assert round_trip.output.arrow_type == signature.output.arrow_type
@function
def optional_elapsed(
value: Optional[Annotated[timedelta, pa.duration("ms")]],
) -> int:
return 0
optional_input = optional_elapsed.registration_request.signature.inputs[0]
assert optional_input.nullable is True
assert json.loads(optional_input.arrow_type) == {"type": "duration:ms"}
with pytest.raises(
TypeError, match="timedelta Function annotations require an explicit unit"
):
@function
def missing(value: timedelta) -> timedelta:
return value
input_schema = pa.schema([pa.field("elapsed", pa.duration("ms"), nullable=True)])
output_schema = pa.field("result", pa.duration("us"), nullable=False)
@function(input_schema=input_schema, output_schema=output_schema)
def explicit(elapsed: timedelta) -> timedelta:
return elapsed
explicit_signature = explicit.registration_request.signature
assert explicit_signature.inputs[0].nullable is True
assert json.loads(explicit_signature.inputs[0].arrow_type) == {
"type": "duration:ms"
}
assert json.loads(explicit_signature.output.arrow_type) == {"type": "duration"}
explicit_round_trip = FunctionSignature.from_json(
explicit_signature.to_canonical_json()
)
assert explicit_round_trip.output.arrow_type == '{"type":"duration"}'
def test_map_annotation_and_explicit_schema_serialization():
@function
def map_round_trip(values: dict[str, int]) -> dict[str, int]:
return values
signature = map_round_trip.registration_request.signature
expected = {
"type": "map",
"fields": [
{
"name": "entries",
"nullable": False,
"type": {
"type": "struct",
"fields": [
{
"name": "key",
"nullable": False,
"type": {"type": "utf8"},
},
{
"name": "value",
"nullable": False,
"type": {"type": "int64"},
},
],
},
}
],
}
assert json.loads(signature.inputs[0].arrow_type) == expected
assert json.loads(signature.output.arrow_type) == expected
round_trip = FunctionSignature.from_json(signature.to_canonical_json())
assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type
assert round_trip.output.arrow_type == signature.output.arrow_type
@function
def nullable_values(
values: dict[str, Optional[int]],
) -> dict[str, Optional[int]]:
return values
nullable_signature = nullable_values.registration_request.signature
nullable_map = json.loads(nullable_signature.inputs[0].arrow_type)
assert nullable_map["fields"][0]["type"]["fields"][1] == {
"name": "value",
"nullable": True,
"type": {"type": "int64"},
}
input_schema = pa.schema(
[
pa.field(
"values",
pa.map_(pa.string(), pa.field("custom", pa.int64(), nullable=True)),
nullable=False,
)
]
)
output_schema = pa.field(
"result",
pa.map_(pa.string(), pa.field("value", pa.int64(), nullable=False)),
nullable=False,
)
@function(input_schema=input_schema, output_schema=output_schema)
def explicit(values):
return {}
explicit_signature = explicit.registration_request.signature
explicit_input = json.loads(explicit_signature.inputs[0].arrow_type)
assert explicit_input["fields"][0]["type"]["fields"][1] == {
"name": "custom",
"nullable": True,
"type": {"type": "int64"},
}
explicit_output = json.loads(explicit_signature.output.arrow_type)
assert explicit_output["fields"][0]["type"]["fields"][1]["nullable"] is False
def test_map_rejects_unsupported_boundaries():
with pytest.raises(TypeError, match="map keys_sorted=true"):
_canonical_arrow_type(pa.map_(pa.string(), pa.int64(), keys_sorted=True))
with pytest.raises(TypeError, match="map keys must be non-nullable utf8"):
_canonical_arrow_type(pa.map_(pa.int64(), pa.int64()))
with pytest.raises(TypeError, match="Blob v2 fields nested under"):
_canonical_arrow_type(pa.map_(pa.string(), lancedb.blob("image").type))
with pytest.raises(TypeError, match="map keys must be str"):
@function
def invalid_keys(values: dict[int, int]) -> int:
return 0
def test_decimal_annotation_and_explicit_schema_serialization():
@function
def price(
amount: Annotated[Decimal, pa.decimal128(10, 2)],
) -> Annotated[Decimal, pa.decimal256(50, 4)]:
return Decimal("1.0000")
signature = price.registration_request.signature
assert json.loads(signature.inputs[0].arrow_type) == {
"type": "decimal128",
"length": 10002,
}
assert json.loads(signature.output.arrow_type) == {
"type": "decimal256",
"length": 50004,
}
round_trip = FunctionSignature.from_json(signature.to_canonical_json())
assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type
assert round_trip.output.arrow_type == signature.output.arrow_type
assert json.loads(_canonical_arrow_type(pa.decimal128(10, -2))) == {
"type": "decimal128",
"length": 9998,
}
decimal_map = json.loads(
_canonical_arrow_type(pa.map_(pa.string(), pa.decimal128(10, 2)))
)
assert decimal_map["fields"][0]["type"]["fields"][1]["type"] == {
"type": "decimal128",
"length": 10002,
}
input_schema = pa.schema([pa.field("amount", pa.decimal128(12, 2), nullable=False)])
output_schema = pa.field("result", pa.decimal256(60, 6), nullable=False)
@function(input_schema=input_schema, output_schema=output_schema)
def explicit(amount: Decimal) -> Decimal:
return amount
explicit_signature = explicit.registration_request.signature
assert json.loads(explicit_signature.inputs[0].arrow_type) == {
"type": "decimal128",
"length": 12002,
}
assert json.loads(explicit_signature.output.arrow_type) == {
"type": "decimal256",
"length": 60006,
}
with pytest.raises(
TypeError, match="Decimal Function annotations require precision and scale"
):
@function
def missing(amount: Decimal) -> Decimal:
return amount
def test_nullable_scalar_output_annotation_and_explicit_schema():
input_schema = pa.schema([pa.field("value", pa.int64(), nullable=False)])
@function(input_schema=input_schema)
def optional_annotation(value: int) -> Optional[int]:
return None if value == 0 else value * 2
@function(input_schema=input_schema)
def optional_union(value: int) -> int | None:
return None if value == 0 else value * 2
@function(
input_schema=input_schema,
output_schema=pa.field("result", pa.int64(), nullable=True),
)
def explicit_schema(value: int):
return None if value == 0 else value * 2
for definition in (optional_annotation, optional_union, explicit_schema):
signature = definition.registration_request.signature
assert (signature.output.kind, signature.output.arrow_type) == (
"scalar",
"int64",
)
assert signature.output.nullable is True
assert json.loads(signature.to_canonical_json())["output"] == {
"kind": "scalar",
"arrow_type": "int64",
"nullable": True,
}
assert (
FunctionSignature.from_json(signature.to_canonical_json()).output.nullable
is True
)
def test_blob_fields_use_the_scalar_function_semantic_type():
@function(
input_schema=pa.schema([lancedb.blob("image", nullable=False)]),
@@ -1794,12 +2352,6 @@ def test_annotation_and_explicit_schema_validation_fail_closed():
def unsupported(value: set[str]) -> str:
return ""
with pytest.raises(ValueError, match="output must be non-nullable"):
@function
def nullable_output(value: int) -> Optional[int]:
return value
with pytest.raises(TypeError, match=r"missing Function annotations: \['return'\]"):
@function(input_schema=pa.schema([pa.field("value", pa.int64())]))
@@ -1819,10 +2371,25 @@ def test_annotation_and_explicit_schema_validation_fail_closed():
@function(
input_schema=pa.schema([pa.field("value", pa.int64())]),
output_schema=pa.field("result", pa.int64(), nullable=True),
output_schema=pa.field(
"result",
pa.struct([pa.field("value", pa.int64(), nullable=False)]),
nullable=True,
),
)
def nullable_explicit(value):
return value
def nullable_struct(value):
return {"value": value}
with pytest.raises(
ValueError, match="Blob v2 Function output must be non-nullable"
):
@function(
input_schema=pa.schema([lancedb.blob("image", nullable=False)]),
output_schema=lancedb.blob("result", nullable=True),
)
def nullable_blob(image):
return image
for invalid_field in [
pa.field("", pa.int32(), nullable=False),
@@ -1891,6 +2458,29 @@ def test_annotation_and_explicit_schema_validation_fail_closed():
return value
def test_default_function_runtime_matches_server_identity():
definition = function(python_version="3.12")(analyze_caption.__wrapped__)
runtime = definition.registration_request.runtime
assert runtime.env == {}
cases = json.loads((FIXTURES / "runtime_identity.json").read_text(encoding="utf-8"))
expected = next(
case["digest"] for case in cases if case["name"] == "empty-environment"
)
assert runtime.digest == expected
def test_environment_changes_do_not_change_source_identity():
definition = function(
pip=["openai==3.46.0"],
env={"MODE": "test"},
python_version="3.12",
)(analyze_caption.__wrapped__)
previous = analyze_caption.registration_request
changed = definition.registration_request
assert previous.artifact.digest == changed.artifact.digest
assert previous.runtime.digest != changed.runtime.digest
def test_local_function_catalog_operations_are_not_supported(tmp_path):
db = lancedb.connect(tmp_path)
message = "Function catalog operations are not supported by this database"
@@ -1936,6 +2526,205 @@ class _RawFunctionCatalog:
return None
def test_function_version_reads_requested_and_resolved_environments():
legacy = json.loads(
(FIXTURES / "remote_function_version.canonical.json").read_text()
)
legacy_version = FunctionVersion.from_json(json.dumps(legacy))
assert legacy_version.runtime is None
assert legacy_version.resolved_environment is None
assert legacy_version.environment.requested is None
assert legacy_version.environment.resolved is None
payload = _function_version_with_resolved_environment()
version = FunctionVersion.from_json(json.dumps(payload))
assert version.environment.requested is version.runtime
assert version.environment.resolved is version.resolved_environment
assert version.runtime.kind == "python"
resolved = version.resolved_environment
assert resolved.packages[0].version == "2.9.0+cu130"
assert resolved.packages[0].source == "https://packages.example/simple"
assert resolved.packages[1].source is None
assert resolved.provenance.torch_version == "torch==2.9.0+cu130"
assert resolved.warnings == tuple(payload["resolved_environment"]["warnings"])
encoded = json.loads(version.to_canonical_json())
assert encoded["runtime"]["kind"] == "python"
assert encoded["resolved_environment"]["packages"][0]["version"] == "2.9.0+cu130"
assert "source" not in encoded["resolved_environment"]["packages"][1]
assert (
encoded["resolved_environment"]["provenance"]["torch_version"]
== "torch==2.9.0+cu130"
)
assert FunctionVersion.from_json(version.to_canonical_json()) == version
invalid = json.loads(json.dumps(payload))
del invalid["resolved_environment"]["packages"]
with pytest.raises(ValueError):
FunctionVersion.from_json(json.dumps(invalid))
def test_function_version_reads_resolved_environments_by_platform():
legacy = json.loads(
(FIXTURES / "remote_function_version.canonical.json").read_text()
)
legacy_version = FunctionVersion.from_json(json.dumps(legacy))
assert legacy_version.resolved_environment is None
assert legacy_version.resolved_environments == {}
assert legacy_version.environment_report == {}
payload = _function_version_with_resolved_environments()
version = FunctionVersion.from_json(json.dumps(payload))
assert version.resolved_environment is None
assert version.resolved_environments == version.environment_report
assert set(version.environment_report) == {"linux/amd64", "linux/arm64"}
assert (
version.environment_report["linux/amd64"].packages[0].version == "2.9.0+cu130"
)
assert version.environment_report["linux/arm64"].packages == ()
assert version.environment_report["linux/arm64"].warnings == (
"arm64 environment warning",
)
encoded = json.loads(version.to_canonical_json())
assert "resolved_environment" not in encoded
assert (
encoded["resolved_environments"]["linux/amd64"]["packages"][0]["version"]
== "2.9.0+cu130"
)
assert encoded["resolved_environments"]["linux/arm64"]["packages"] == []
assert FunctionVersion.from_json(version.to_canonical_json()) == version
missing_platform = json.loads(json.dumps(payload))
del missing_platform["resolved_environments"]["linux/arm64"]
missing_version = FunctionVersion.from_json(json.dumps(missing_platform))
assert "linux/arm64" not in missing_version.environment_report
assert "linux/amd64" in missing_version.environment_report
empty_map = json.loads(json.dumps(payload))
empty_map["resolved_environments"] = {}
empty_version = FunctionVersion.from_json(json.dumps(empty_map))
assert empty_version.resolved_environments == {}
assert "resolved_environments" not in json.loads(empty_version.to_canonical_json())
invalid = json.loads(json.dumps(payload))
del invalid["resolved_environments"]["linux/amd64"]["packages"]
with pytest.raises(ValueError):
FunctionVersion.from_json(json.dumps(invalid))
@pytest.mark.asyncio
async def test_registration_job_emits_server_environment_warnings_once():
payload = _function_version_with_resolved_environment()
class InnerJob:
async def wait(self):
return json.dumps(payload)
class Inner:
async def create_function_async(
self, request_json, namespace_path=None, *, exist_ok=False
):
assert "refresh_lock" not in json.loads(request_json)
return InnerJob()
connection = object.__new__(AsyncConnection)
connection._inner = Inner()
job = await connection.create_function_async(normalize_score)
with pytest.warns(UserWarning) as recorded:
version = await job.wait()
assert [str(w.message) for w in recorded] == list(
payload["resolved_environment"]["warnings"]
)
assert version.environment.resolved.warnings == tuple(
payload["resolved_environment"]["warnings"]
)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
assert await job.wait() is not None
assert caught == []
@pytest.mark.asyncio
async def test_registration_job_emits_per_platform_environment_warnings():
payload = _function_version_with_resolved_environments()
class InnerJob:
async def wait(self):
return json.dumps(payload)
class Inner:
async def create_function_async(
self, request_json, namespace_path=None, *, exist_ok=False
):
return InnerJob()
connection = object.__new__(AsyncConnection)
connection._inner = Inner()
job = await connection.create_function_async(normalize_score)
with pytest.warns(UserWarning) as recorded:
version = await job.wait()
assert [str(w.message) for w in recorded] == [
"amd64 environment warning",
"arm64 environment warning",
]
assert version.environment_report["linux/arm64"].warnings == (
"arm64 environment warning",
)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
assert await job.wait() is not None
assert caught == []
def test_blocking_create_function_emits_server_environment_warnings():
payload = _function_version_with_resolved_environment()
class InnerJob:
async def wait(self):
return json.dumps(payload)
class Inner:
async def create_function_async(
self, request_json, namespace_path=None, *, exist_ok=False
):
return InnerJob()
connection = object.__new__(RemoteDBConnection)
connection._conn = AsyncConnection(Inner())
with pytest.warns(UserWarning) as recorded:
version = DBConnection.create_function(connection, normalize_score)
assert [str(w.message) for w in recorded] == list(
payload["resolved_environment"]["warnings"]
)
assert version.environment.resolved.packages[0].version == "2.9.0+cu130"
@pytest.mark.asyncio
async def test_catalog_readback_does_not_replay_registration_warnings():
payload = _function_version_with_resolved_environment()
connection = AsyncConnection(_RawFunctionCatalog(payload, encode=True))
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
version = await connection.get_function("embed")
listed = [item async for item in connection.list_functions()]
assert caught == []
assert version.environment.resolved.packages[0].version == "2.9.0+cu130"
assert listed[0].environment.resolved == version.resolved_environment
@pytest.mark.asyncio
async def test_catalog_readback_does_not_replay_per_platform_warnings():
payload = _function_version_with_resolved_environments()
connection = AsyncConnection(_RawFunctionCatalog(payload, encode=True))
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
version = await connection.get_function("embed")
listed = [item async for item in connection.list_functions()]
assert caught == []
assert version.environment_report == listed[0].environment_report
def _assert_execution_control_encoding(version):
encoded = json.loads(version.to_canonical_json())
assert type(encoded["batch_size"]) is int
@@ -1950,6 +2739,7 @@ async def test_async_catalog_path_preserves_execution_controls():
(FIXTURES / "remote_function_version.canonical.json").read_text()
)
definition.update(
runtime_digest=normalize_score.registration_request.runtime.digest,
batch_size=12,
row_timeout_seconds=8.0,
result_stability="input_and_context",
@@ -1977,6 +2767,7 @@ def test_sync_catalog_path_preserves_execution_controls():
(FIXTURES / "remote_function_version.canonical.json").read_text()
)
definition.update(
runtime_digest=normalize_score.registration_request.runtime.digest,
batch_size=12,
row_timeout_seconds=8.0,
result_stability="input_and_context",
@@ -2090,6 +2881,9 @@ def _mock_remote_function_catalog():
)["image"],
"signature": body["signature"],
"source_digest": body["artifact"]["digest"],
"runtime_digest": PythonRuntimeSpec.from_json(
json.dumps(body["runtime"])
).digest,
"secret_bindings": body.get("secret_bindings", []),
"created_at_millis": 1787270400000, # 2026-08-21T00:00:00Z
}
+172 -12
View File
@@ -29,6 +29,7 @@ from lancedb.query import (
CombinedFieldsQuery,
DocumentGranularity,
FullTextOperator,
FullTextSearchQuery,
MatchQuery,
MultiMatchQuery,
PhraseQuery,
@@ -530,11 +531,9 @@ async def test_fts_select_async(async_table):
def test_search_fts_phrase_query(table):
table.create_fts_index("text", with_position=False)
try:
phrase_results = table.search('"puppy runs"').limit(100).to_list()
assert False
except Exception:
pass
with pytest.raises(Exception) as error:
table.search('"puppy runs"').limit(100).to_list()
assert "FTS(with_position=True)" in exception_output(error)
table.create_fts_index("text", with_position=True, replace=True)
results = table.search("puppy").limit(100).to_list()
@@ -559,13 +558,9 @@ def test_search_fts_phrase_query(table):
@pytest.mark.asyncio
async def test_search_fts_phrase_query_async(async_table):
await async_table.create_index("text", config=FTS(with_position=False))
try:
phrase_results = (
await async_table.query().nearest_to_text("puppy runs").limit(100).to_list()
)
assert False
except Exception:
pass
with pytest.raises(Exception) as error:
await async_table.query().nearest_to_text('"puppy runs"').to_list()
assert "FTS(with_position=True)" in exception_output(error)
await async_table.create_index("text", config=FTS(with_position=True))
results = await async_table.query().nearest_to_text("puppy").limit(100).to_list()
phrase_results = (
@@ -1948,3 +1943,168 @@ async def test_async_fts_code_analyzer(mem_db_async):
rows = await table.query().nearest_to_text("http").to_list()
assert len(rows) == 1
@pytest.mark.parametrize("indexed", [False, True])
@pytest.mark.parametrize("operator,expected", [(None, 25), ("OR", 25), ("AND", 15)])
def test_simple_fts_operator_and_count(tmp_path, indexed, operator, expected):
db = ldb.connect(tmp_path)
table = db.create_table(
"matches",
pa.table(
{
"id": list(range(30)),
"text": ["gripper closed"] * 15
+ ["gripper open"] * 10
+ ["camera ready"] * 5,
}
),
)
if indexed:
table.create_index("text", config=FTS())
kwargs = {"fts_columns": "text"}
if operator is not None:
kwargs["operator"] = operator
query = table.search("gripper closed", query_type="fts", **kwargs)
assert query.count_rows() == expected
assert len(query.limit(100).to_list()) == expected
assert (
table.search("gripper closed", query_type="fts", fts_columns="text")
.operator("AND")
.count_rows()
== 15
)
if operator is not None:
assert query.to_query_object().full_text_query.operator == operator
query.where("id >= 5", prefilter=False).select(["id"]).limit(2).offset(1)
before = query.to_query_object()
assert query.count_rows() == expected - 5
assert query.to_query_object() == before
assert len(query.to_list()) <= 2
assert (
table.search("absent", query_type="fts", fts_columns="text").count_rows() == 0
)
assert (
table.search(MatchQuery("gripper closed", "text", operator="AND")).count_rows()
== 15
)
@pytest.mark.asyncio
@pytest.mark.parametrize("indexed", [False, True])
@pytest.mark.parametrize("operator,expected", [(None, 25), ("OR", 25), ("AND", 15)])
async def test_simple_fts_operator_and_count_async(
tmp_path, indexed, operator, expected
):
db = await ldb.connect_async(tmp_path)
table = await db.create_table(
"matches",
pa.table(
{
"id": list(range(30)),
"text": ["gripper closed"] * 15
+ ["gripper open"] * 10
+ ["camera ready"] * 5,
}
),
)
if indexed:
await table.create_index("text", config=FTS())
query = await table.search(
"gripper closed", query_type="fts", fts_columns="text", operator=operator
)
assert await query.count_rows() == expected
assert len(await query.limit(100).to_list()) == expected
query.where("id >= 5").postfilter().select(["id"]).limit(2).offset(1)
before = query.to_query_object()
assert await query.count_rows() == expected - 5
assert query.to_query_object() == before
direct = table.query().nearest_to_text(
"gripper closed", columns="text", operator="AND"
)
assert await direct.count_rows() == 15
assert direct.to_query_object().full_text_query.query.operator == "AND"
assert (
await table.query().nearest_to_text("absent", columns="text").count_rows() == 0
)
@pytest.mark.parametrize("with_position", [False, True])
@pytest.mark.parametrize(
"query", ['"gripper closed"', PhraseQuery("gripper closed", "text")]
)
def test_fts_phrase_count_positions(tmp_path, with_position, query):
table = ldb.connect(tmp_path).create_table(
"phrases", pa.table({"text": ["gripper closed", "gripper often closed"]})
)
table.create_index("text", config=FTS(with_position=with_position))
search = table.search(query, query_type="fts")
if with_position:
assert search.count_rows() == 1
assert len(search.to_list()) == 1
assert (
table.search("gripper closed", query_type="fts", operator="AND")
.phrase_query()
.count_rows()
== 1
)
else:
with pytest.raises(Exception) as error:
search.count_rows()
assert "FTS(with_position=True)" in exception_output(error)
@pytest.mark.asyncio
@pytest.mark.parametrize("with_position", [False, True])
@pytest.mark.parametrize(
"query", ['"gripper closed"', PhraseQuery("gripper closed", "text")]
)
async def test_fts_phrase_count_positions_async(tmp_path, with_position, query):
db = await ldb.connect_async(tmp_path)
table = await db.create_table(
"phrases", pa.table({"text": ["gripper closed", "gripper often closed"]})
)
await table.create_index("text", config=FTS(with_position=with_position))
search = table.query().nearest_to_text(query)
if with_position:
assert await search.count_rows() == 1
assert len(await search.to_list()) == 1
else:
with pytest.raises(Exception) as error:
await search.count_rows()
assert "FTS(with_position=True)" in exception_output(error)
def test_fts_operator_rejects_invalid_queries(table):
with pytest.raises(ValueError):
table.search("gripper", query_type="fts", operator="XOR")
for query in [None, [1.0, 2.0], MatchQuery("gripper", "text")]:
with pytest.raises(
ValueError, match="operator requires a string full-text query"
):
table.search(query, operator="AND")
with pytest.raises(ValueError, match="operator requires a string full-text query"):
FullTextSearchQuery(query=MatchQuery("gripper"), operator="AND")
@pytest.mark.asyncio
async def test_fts_operator_rejects_invalid_queries_async(async_table):
with pytest.raises(ValueError):
await async_table.search("gripper", query_type="fts", operator="XOR")
for query in [None, [1.0, 2.0], MatchQuery("gripper", "text")]:
with pytest.raises(
ValueError, match="operator requires a string full-text query"
):
await async_table.search(query, operator="AND")
with pytest.raises(ValueError):
async_table.query().nearest_to_text(query, operator="AND")
def test_fts_count_fast_search(tmp_path):
table = ldb.connect(tmp_path).create_table(
"matches", pa.table({"text": ["gripper closed"] * 15})
)
table.create_index("text", config=FTS())
table.add(pa.table({"text": ["gripper closed"] * 5}))
assert table.search("gripper", query_type="fts").count_rows() == 20
assert table.search("gripper", query_type="fts").fast_search().count_rows() == 15
@@ -0,0 +1,63 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import json
from pathlib import Path
import pyarrow as pa
import pytest
import lancedb
from lancedb.functions import function
@pytest.mark.asyncio
@pytest.mark.parametrize("entry", ["sync", "sync_job", "async_job"])
@pytest.mark.parametrize("exist_ok", [None, False, True])
async def test_function_exist_ok_forwards_sql_and_keeps_stored_version(entry, exist_ok):
flight = pytest.importorskip("pyarrow.flight")
fixture = (
Path(__file__).parents[3]
/ "rust/lancedb/tests/fixtures/first_class_functions/v1"
/ "remote_function_version.canonical.json"
)
stored = json.loads(fixture.read_text())
result = pa.table({"definition": [json.dumps(stored)]})
@function(name=stored["name"])
def replacement(value: float) -> float:
return value * 2
class FunctionServer(flight.FlightServerBase):
def __init__(self):
super().__init__("grpc://127.0.0.1:0")
self.requests = []
def do_get(self, context, ticket):
self.requests.append(ticket.ticket)
return flight.RecordBatchStream(result)
with FunctionServer() as server:
options = {
"api_key": "test-key",
"host_override": "http://localhost:10024",
"sql_host_override": f"grpc://127.0.0.1:{server.port}",
}
kwargs = {} if exist_ok is None else {"exist_ok": exist_ok}
kwargs["namespace_path"] = ["team"]
if entry == "async_job":
db = await lancedb.connect_async("db://analytics", **options)
job = await db.create_function_async(replacement, **kwargs)
version = await job.wait()
else:
db = lancedb.connect("db://analytics", **options)
if entry == "sync_job":
version = db.create_function_async(replacement, **kwargs).wait()
else:
version = db.create_function(replacement, **kwargs)
(request,) = server.requests
prefix = "CREATE FUNCTION IF NOT EXISTS" if exist_ok else "CREATE FUNCTION"
assert f'{prefix} "{stored["name"]}" FROM '.encode() in request
assert b'"exist_ok"' not in request
assert json.loads(version.to_canonical_json()) == stored
+330 -14
View File
@@ -7,6 +7,7 @@ from __future__ import annotations
import base64
import importlib
import hashlib
import json
import subprocess
import sys
@@ -20,7 +21,7 @@ import pyarrow as pa
import pytest
from lancedb import col
from lancedb.functions import FunctionDefinition, FunctionVersion, function
from lancedb.functions import FunctionDefinition, FunctionVersion, function, udf
FIXTURES = (
Path(__file__).parents[3]
@@ -127,6 +128,108 @@ def test_function_without_initialization_keeps_its_wire_form():
assert request["artifact"]["kind"] == "python_callable"
@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning")
@pytest.mark.parametrize("decorator", [function, udf])
@pytest.mark.parametrize("explicit_schemas", [False, True])
@pytest.mark.parametrize("class_function", [False, True])
@pytest.mark.parametrize(
("declaration", "statement"),
[
("def", "yield value"),
("def", "yield from [value]"),
("async def", "yield value"),
],
)
def test_generator_functions_are_rejected_at_decoration(
helper_package, decorator, explicit_schemas, class_function, declaration, statement
):
signature = (
"__call__(self, value: int)" if class_function else "generates(value: int)"
)
source = f"{declaration} {signature} -> int:\n {statement}\n"
if class_function:
source = "class generates:\n" + textwrap.indent(source, " ")
module = helper_package("fx_generator", {"__init__.py": source})
options = (
{
"input_schema": pa.schema([pa.field("value", pa.int64(), nullable=False)]),
"output_schema": pa.int64(),
}
if explicit_schemas
else {}
)
with pytest.raises(TypeError) as error:
decorator(**options)(module.generates)
message = str(error.value)
assert "generator Functions are not supported" in message
assert "return a value" in message
assert "return a list" in message
@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning")
@pytest.mark.parametrize("decorator", [function, udf])
@pytest.mark.parametrize("explicit_name", [False, True])
def test_lambda_functions_explain_the_named_alternative(decorator, explicit_name):
options = {"name": "double"} if explicit_name else {}
with pytest.raises(TypeError, match="lambda.*use a named def"):
decorator(**options)(lambda value: value * 2)
@pytest.mark.parametrize("class_function", [False, True])
@pytest.mark.parametrize("cache_decorator", ["lru_cache", "cache"])
def test_cached_functions_explain_where_to_keep_caches(
helper_package, class_function, cache_decorator
):
signature = "__call__(self, value: int)" if class_function else "cached(value: int)"
source = (
f"@functools.{cache_decorator}\ndef {signature} -> int:\n return value * 2\n"
)
if class_function:
source = "class cached:\n" + textwrap.indent(source, " ")
module = helper_package("fx_cached", {"__init__.py": "import functools\n" + source})
with pytest.raises(TypeError) as error:
function(module.cached)
message = str(error.value)
assert "decorated wrappers are not supported" in message
assert "inside the function body" in message
assert "class Function with a cache in __init__" in message
@pytest.mark.parametrize("class_function", [False, True])
@pytest.mark.parametrize("keyword_only", [False, True])
def test_callable_defaults_explain_class_initialization(
helper_package, class_function, keyword_only
):
parameters = "value: float, " + ("*, " if keyword_only else "")
parameters += "threshold: float = 0.5"
signature = (
f"__call__(self, {parameters})"
if class_function
else f"thresholded({parameters})"
)
source = f"def {signature} -> bool:\n return value >= threshold\n"
if class_function:
source = "class thresholded:\n" + textwrap.indent(source, " ")
module = helper_package("fx_defaults", {"__init__.py": source})
with pytest.raises(TypeError) as error:
function(module.thresholded)
message = str(error.value)
assert "defaults are not supported: 'threshold'" in message
assert "class Function's __init__" in message
assert "binding-time initialization values" in message
def test_function_can_return_a_list_from_a_generator_expression():
@function
def many(value: int) -> list[int]:
return list(item * 2 for item in range(value))
namespace = {}
exec(compile(artifact(many), "user_function.py", "exec"), namespace)
assert namespace["many"](3) == [0, 2, 4]
assert many.registration_request.signature.output.arrow_type == "list<int64>"
@pytest.mark.parametrize("kind", ["function", "class"])
@pytest.mark.parametrize(
("global_value", "value_type"),
@@ -364,6 +467,126 @@ def test_nested_class_and_closure_are_rejected_with_the_reason():
return value * factor
@pytest.mark.parametrize(
"module_name",
[
"sys",
"builtins",
"importlib",
"inspect",
"gc",
"ctypes",
"types",
"ctypes.util",
"importlib.metadata",
],
)
@pytest.mark.parametrize("import_style", ["import", "from", "global"])
@pytest.mark.parametrize("class_function", [False, True])
def test_namespace_module_errors_explain_the_rule_and_remedy(
helper_package, module_name, import_style, class_function
):
statement = f"import {module_name} as namespace_module"
body = f"{statement}\nreturn value\n"
preamble = ""
if import_style == "from":
body = f"from {module_name} import __name__\nreturn value\n"
elif import_style == "global":
preamble = statement + "\n"
body = "return str(namespace_module)\n"
if class_function:
definition = "class blocked:\n def __call__(self, value: str) -> str:\n"
source = preamble + definition + textwrap.indent(body, " ")
else:
definition = "def blocked(value: str) -> str:\n"
source = preamble + definition + textwrap.indent(body, " ")
module = helper_package("fx_namespace_import", {"__init__.py": source})
with pytest.raises(ValueError) as error:
function(module.blocked)
message = str(error.value)
assert "imports from namespace-access modules" in message
assert repr(module_name) in message
assert "builtins, ctypes, gc, importlib, inspect, sys, types" in message
assert "including submodules" in message
assert "reconstructed module namespace" in message
assert "importable helper module" in message
assert "code=, pip=, or conda=" in message
assert "dynamic namespace access" not in message
@pytest.mark.filterwarnings("ignore:lancedb.udf is deprecated:DeprecationWarning")
def test_udf_namespace_import_error_explains_the_helper_alternative():
with pytest.raises(ValueError, match="ctypes.util.*importable helper module"):
@udf
def probe(value: str) -> str:
import ctypes.util
return str(ctypes.util.find_library(value))
@pytest.mark.parametrize(
"operation", ["globals", "locals", "vars", "eval", "exec", "compile", "__import__"]
)
def test_dynamic_namespace_errors_name_the_operation_and_remedy(
helper_package, operation
):
module = helper_package(
"fx_namespace_operation",
{
"__init__.py": (
f"def blocked(value: str) -> str:\n return str({operation})\n"
)
},
)
with pytest.raises(ValueError) as error:
function(module.blocked)
message = str(error.value)
assert f"dynamic namespace access: ['{operation}']" in message
assert "Reference dependencies explicitly" in message
assert "importable helper module" in message
@pytest.mark.parametrize("ship_source", [False, True])
def test_namespace_access_in_importable_helpers_keeps_its_module_namespace(
helper_package, ship_source
):
helpers = helper_package(
"fx_namespace_helper",
{
"__init__.py": """
import ctypes.util
def module_name():
return ctypes.util.__name__
""",
},
)
entry = helper_package(
"fx_namespace_entry",
{
"__init__.py": """
from fx_namespace_helper import module_name
def probe(value: str) -> str:
return module_name() + value
""",
},
)
options = {"code": [helpers]} if ship_source else {"pip": ["fx-namespace-helper"]}
definition = function(**options)(entry.probe)
if ship_source:
files = bundle_files(definition)
assert "import ctypes.util" in files["fx_namespace_helper/__init__.py"]
source = files["user_function.py"]
else:
source = artifact(definition).decode()
namespace = {}
exec(compile(source, "user_function.py", "exec"), namespace)
assert namespace["probe"]("!") == "ctypes.util!"
def test_binding_passes_initialization_as_constants():
version = FunctionVersion.from_json(
json.dumps(
@@ -406,6 +629,102 @@ def test_binding_passes_initialization_as_constants():
version(text=col("body"), model=object())
def test_vendored_package_resources_survive_an_isolated_import(
tmp_path, helper_package
):
package = helper_package(
"fx_vendor",
{
"__init__.py": "from .vendor.model import predict",
"vendor/__init__.py": "",
"vendor/model.py": """
import hashlib
import json
from importlib.resources import files
def predict(value):
root = files("fx_vendor")
payload = root.joinpath("label-maps/payload.bin").read_bytes()
metadata = json.loads(root.joinpath("models.json").read_text())
source = root.joinpath("vendor/model.py").read_bytes()
source_digest = hashlib.sha256(source).hexdigest()
assert source_digest == metadata["source_sha256"]
assert hashlib.sha256(payload).hexdigest() == metadata["sha256"]
return value + metadata["offset"]
""",
"models.json": "{}",
},
)
payload = b"\x00\xff\r\nvendored model data"
package_root = Path(package.__file__).parent
(package_root / "label-maps").mkdir()
(package_root / "label-maps/payload.bin").write_bytes(payload)
module_path = package_root / "vendor/model.py"
module_bytes = (
module_path.read_bytes().replace(b"\r\n", b"\n").replace(b"\n", b"\r\n")
)
module_path.write_bytes(module_bytes)
(package_root / "models.json").write_bytes(
json.dumps(
{
"sha256": hashlib.sha256(payload).hexdigest(),
"source_sha256": hashlib.sha256(module_bytes).hexdigest(),
"offset": 7,
}
).encode()
+ b"\r\n"
)
entry = helper_package(
"fx_vendor_entry",
{
"__init__.py": """
import fx_vendor
from lancedb import function
@function(code=[fx_vendor])
def vendored(value: int) -> int:
return fx_vendor.predict(value)
"""
},
)
vendored = entry.vendored
first_digest = vendored.registration_request.artifact.digest
bundle = json.loads(artifact(vendored))
isolated = tmp_path / "isolated"
isolated.mkdir()
for name, content in bundle["files"].items():
target = isolated / name
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(content.encode("utf-8"))
for name, content in bundle["resources"].items():
target = isolated / name
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(base64.b64decode(content))
assert (isolated / "fx_vendor/models.json").read_bytes().endswith(b"\r\n")
result = subprocess.run(
[
sys.executable,
"-I",
"-c",
"import sys; sys.path.insert(0, sys.argv[1]); "
"from user_function import vendored; assert vendored(3) == 10",
str(isolated),
],
capture_output=True,
text=True,
)
assert result.returncode == 0, result.stderr
(package_root / "models.json").write_text('{"offset": 8}')
assert (
function(code=[package])(
vendored._function
).registration_request.artifact.digest
!= first_digest
)
def test_code_packages_ship_as_a_bundle_and_version_with_their_source(
tmp_path, helper_package
):
@@ -450,14 +769,13 @@ def test_code_packages_ship_as_a_bundle_and_version_with_their_source(
first = define()
assert len(caught) == 1
warning = str(caught[0].message)
assert "fx_helpers/fixtures/data.json" in warning
assert "fx_helpers/fixtures/data.json" not in warning
assert "fx_helpers/not-a-module.py" in warning
assert warning.index("fx_helpers/fixtures/data.json") < warning.index(
"fx_helpers/not-a-module.py"
)
assert "remove 'fx_helpers' from code=" in warning
assert "pip=" in warning
assert "conda=" in warning
assert "safe relative names" in warning
assert "importable Python module names" in warning
resources = json.loads(artifact(first))["resources"]
assert base64.b64decode(resources["fx_helpers/fixtures/data.json"]) == b"{}"
assert "__pycache__" not in warning
assert ".pyc" not in warning
shipped = bundle_files(first)
@@ -510,7 +828,7 @@ def test_code_package_cache_artifacts_do_not_warn(helper_package):
]
def test_code_package_nonidentifier_resource_dir_warns_at_boundary(helper_package):
def test_code_package_resources_keep_nonidentifier_directories(helper_package):
resources = helper_package(
"fx_resources",
{
@@ -526,11 +844,9 @@ def test_code_package_nonidentifier_resource_dir_warns_at_boundary(helper_packag
def resource_boundary(value: int) -> int:
return value
assert len(caught) == 1
warning = str(caught[0].message)
assert "fx_resources/label-maps/" in warning
assert "remove 'fx_resources' from code=" in warning
assert "labels.json" not in warning
assert not caught
resources = json.loads(artifact(resource_boundary))["resources"]
assert base64.b64decode(resources["fx_resources/label-maps/labels.json"]) == b"{}"
assert sorted(bundle_files(resource_boundary)) == [
"fx_resources/__init__.py",
"user_function.py",
@@ -0,0 +1,125 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import pytest
from lancedb import function, udf
from lancedb.functions import FunctionDefinition
def identity(value: int) -> int:
return value
@pytest.mark.parametrize(
"package",
[
"torch>=2.0,,<3",
"torch>=",
"torch=>2.0",
"torch[",
"torch; python_version >=",
"",
" torch",
"torch ",
],
)
def test_invalid_pip_requirement_fails_before_packaging(package, monkeypatch):
def unexpected_packaging(*args, **kwargs):
pytest.fail("invalid requirements must fail before packaging the function")
monkeypatch.setattr("lancedb.functions._infer_signature", unexpected_packaging)
with pytest.raises(ValueError) as error:
function(pip=["numpy", package])(identity)
assert "pip[1]" in str(error.value)
assert repr(package) in str(error.value)
@pytest.mark.parametrize(
"package",
[
"numpy>=1,,<3",
"numpy>=",
"numpy[version=]",
"numpy[unknown_field=value]",
"",
" numpy",
"numpy ",
],
)
def test_invalid_conda_requirement_names_entry(package):
with pytest.raises(ValueError) as error:
function(conda=["scipy", package])(identity)
assert "conda[1]" in str(error.value)
assert repr(package) in str(error.value)
@pytest.mark.parametrize("kind", ["pip", "conda"])
@pytest.mark.parametrize("package", [None, 42, ["numpy"]])
def test_requirement_must_be_a_string(kind, package):
with pytest.raises(TypeError, match=rf"{kind}\[1\] must be a string"):
function(**{kind: ["numpy", package]})(identity)
@pytest.mark.parametrize(
"package",
[
"numpy",
"torch>=2.0,<3",
'requests[security,socks]>=2; python_version >= "3.10"',
"numpy (>=1.26, <3)",
"six @ https://example.com/six-1.16.0.tar.gz",
"six @ git+https://github.com/benjaminp/six.git@main",
"https://example.com/six-1.16.0.tar.gz",
"git+https://github.com/benjaminp/six.git@main",
"git+ssh://git@github.com/benjaminp/six.git@main",
],
)
def test_supported_pip_requirements_are_preserved(package):
definition = function(pip=[package])(identity)
assert definition.registration_request.runtime.environment.packages == (package,)
@pytest.mark.parametrize(
"package",
[
"numpy",
"numpy=1.26",
"numpy>=1.26,<3",
"numpy=1.26=py310_0",
"numpy 1.26 py310_0",
"conda-forge::numpy>=1.26",
"conda-forge/linux-64::numpy>=1.26",
"numpy[version='>=1.26,<3',build='py310*']",
],
)
def test_supported_conda_requirements_are_preserved(package):
definition = function(conda=[package])(identity)
assert definition.registration_request.runtime.environment.packages == (package,)
def test_requirements_still_sort_and_deduplicate():
definition = function(pip=["torch>=2", "numpy", "torch>=2"])(identity)
assert definition.registration_request.runtime.environment.packages == (
"numpy",
"torch>=2",
)
def test_deprecated_udf_alias_validates_requirements():
with pytest.warns(DeprecationWarning, match="use lancedb.function"):
with pytest.raises(ValueError, match=r"pip\[0\]"):
udf(pip=["torch>=2.0,,<3"])(identity)
def test_direct_function_definition_validates_requirements():
with pytest.raises(ValueError, match=r"pip\[0\]"):
FunctionDefinition(
identity,
name=None,
input_schema=None,
output_schema=None,
pip=("torch>=2.0,,<3",),
env={},
python_version=None,
)
+42
View File
@@ -621,3 +621,45 @@ def test_index_statistics_index_type_lists_all_supported_values():
set(get_args(get_type_hints(IndexStatistics)["index_type"]))
== expected_index_types
)
@pytest.mark.asyncio
@pytest.mark.parametrize("background", [False, True])
@pytest.mark.parametrize(
"column,config", [("id", BTree()), ("vector", IvfFlat(num_partitions=1))]
)
async def test_index_exist_ok_preserves_existing_index(
some_table, background, column, config
):
await some_table.create_index(column, config=config, exist_ok=True)
version = await some_table.version()
original = await some_table.list_indices()
if background:
job = await some_table.create_index_async(
column, config=config, replace=True, exist_ok=True
)
await job.wait()
else:
await some_table.create_index(
column, config=config, replace=True, exist_ok=True
)
assert await some_table.version() == version
assert [(i.name, i.index_type) for i in await some_table.list_indices()] == [
(i.name, i.index_type) for i in original
]
@pytest.mark.asyncio
@pytest.mark.parametrize("background", [False, True])
async def test_named_index_exist_ok_checks_before_column_validation(
some_table, background
):
await some_table.create_index("id", config=BTree(), name="kept")
version = await some_table.version()
method = some_table.create_index_async if background else some_table.create_index
result = await method("missing", config=BTree(), name="kept", exist_ok=True)
if background:
assert result.id is None
await result.wait()
assert await some_table.version() == version
assert [index.name for index in await some_table.list_indices()] == ["kept"]
+279 -3
View File
@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import asyncio
import json
import time
from datetime import timedelta
from types import SimpleNamespace
@@ -10,6 +11,7 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
from lancedb.exceptions import JobCancelledError, JobFailedError
from lancedb.db import DBConnection
from lancedb.job import AsyncJob, Job, _progress_eta
from lancedb.remote.errors import HttpError, RetryError
@@ -728,15 +730,198 @@ async def test_wait_progress_bar_tracks_late_planning_without_regressing(
@pytest.mark.asyncio
async def test_wait_progress_false_keeps_legacy_inner_wait_call():
@pytest.mark.parametrize("progress", [False, None])
async def test_wait_progress_false_keeps_legacy_inner_wait_call(progress):
class NoProgressArgument:
id = "job-legacy"
job_type = None
@property
def job_type(self):
raise AssertionError("quiet waits must not inspect progress metadata")
async def wait(self):
return None
assert await AsyncJob(NoProgressArgument()).wait(progress=False) is None
assert await AsyncJob(NoProgressArgument()).wait(progress=progress) is None
class _RegistrationQuery:
id = "registration-query"
job_type = "query"
_description = None
def __init__(self, error=None):
self.ready = asyncio.Event()
self.error = error
self.state = "running"
self.wait_calls = 0
self.cancel_calls = 0
async def status(self):
return self.state
async def wait(self, progress=None):
self.wait_calls += 1
await self.ready.wait()
if self.error is not None:
self.state = (
"cancelled" if isinstance(self.error, JobCancelledError) else "failed"
)
raise self.error
self.state = "finished"
return '{"version": "1"}'
async def cancel(self):
self.cancel_calls += 1
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [False, True])
async def test_query_progress_observes_one_registration_waiter(sync, monkeypatch):
monkeypatch.setattr("lancedb.job._QUERY_PROGRESS_INTERVAL_SECONDS", 0)
inner = _RegistrationQuery()
job = AsyncJob(inner, json.loads)
updates = []
def observe(snapshot):
updates.append(snapshot)
if len(updates) == 2:
inner.ready.set()
if sync:
result = await asyncio.to_thread(Job(job).wait, progress=observe)
else:
result = await job.wait(progress=observe)
assert result == {"version": "1"}
assert inner.wait_calls == 1
assert inner.cancel_calls == 0
assert updates[0]["state"] == "running"
assert updates[-1]["state"] == "finished"
assert all(snapshot["job_id"] == inner.id for snapshot in updates)
elapsed = [snapshot["client_elapsed_time_millis"] for snapshot in updates]
assert elapsed == sorted(elapsed)
assert elapsed[0] >= 0
assert all("phase" not in snapshot for snapshot in updates)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"error",
[
JobFailedError("bake failed", job_id="registration-query"),
JobCancelledError("cancelled"),
],
)
async def test_query_progress_preserves_terminal_exceptions(error):
inner = _RegistrationQuery(error)
inner.ready.set()
updates = []
with pytest.raises(type(error)) as raised:
await AsyncJob(inner).wait(progress=updates.append)
assert raised.value is error
assert updates[-1]["state"] == inner.state
assert inner.wait_calls == 1
@pytest.mark.asyncio
async def test_query_progress_display_has_no_row_counter_and_closes_on_failure(
monkeypatch,
):
tqdm_module = pytest.importorskip("tqdm.auto")
bar = SimpleNamespace(
n=0,
total=None,
update=MagicMock(),
set_postfix_str=MagicMock(),
close=MagicMock(),
)
constructor = MagicMock(return_value=bar)
monkeypatch.setattr(tqdm_module, "tqdm", constructor)
inner = _RegistrationQuery(JobFailedError("bake failed"))
inner.ready.set()
with pytest.raises(JobFailedError, match="bake failed"):
await AsyncJob(inner).wait(progress=True)
assert "elapsed" in constructor.call_args.kwargs["bar_format"]
assert "rows" not in str(constructor.call_args)
assert bar.set_postfix_str.call_args.args == ("failed",)
bar.close.assert_called_once_with()
@pytest.mark.asyncio
@pytest.mark.parametrize("failed", [False, True])
@pytest.mark.parametrize("observer_error", ["status", "callback"])
async def test_query_progress_observer_errors_do_not_replace_result_or_server_failure(
failed, observer_error, caplog
):
error = (
JobFailedError("bake failed", job_id="registration-query") if failed else None
)
inner = _RegistrationQuery(error)
inner.ready.set()
if observer_error == "status":
inner.status = AsyncMock(side_effect=RuntimeError("observer failed"))
def observe(snapshot):
if observer_error == "callback":
raise RuntimeError("observer failed")
job = AsyncJob(inner, json.loads)
if failed:
with pytest.raises(JobFailedError) as raised:
await job.wait(progress=observe)
assert raised.value is error
else:
assert await job.wait(progress=observe) == {"version": "1"}
assert inner.wait_calls == 1
assert inner.cancel_calls == 0
assert "job progress observer failed" in caplog.text
@pytest.mark.asyncio
async def test_query_progress_timeout_keeps_registration_available_on_same_handle():
inner = _RegistrationQuery()
job = AsyncJob(inner, json.loads)
updates = []
with pytest.raises(TimeoutError, match="keep this handle"):
await job.wait(timeout=timedelta(seconds=0.01), progress=updates.append)
assert inner.state == "running"
assert inner.cancel_calls == 0
inner.ready.set()
assert await job.wait(progress=updates.append) == {"version": "1"}
assert inner.wait_calls == 2
assert updates[-1]["state"] == "finished"
@pytest.mark.parametrize("refresh_lock", [False, True])
def test_blocking_create_function_forwards_progress_to_registration_handle(
refresh_lock,
):
connection = MagicMock()
definition = object()
progress = object()
result = DBConnection.create_function(
connection, definition, refresh_lock=refresh_lock, progress=progress
)
connection.create_function_async.assert_called_once_with(
definition,
secrets=None,
exist_ok=False,
namespace_path=None,
refresh_lock=refresh_lock,
)
connection.create_function_async.return_value.wait.assert_called_once_with(
progress=progress
)
assert result is connection.create_function_async.return_value.wait.return_value
@pytest.mark.parametrize("progress", [False, None])
def test_blocking_create_function_preserves_quiet_wait_call(progress):
connection = MagicMock()
result = DBConnection.create_function(connection, object(), progress=progress)
connection.create_function_async.return_value.wait.assert_called_once_with()
assert result is connection.create_function_async.return_value.wait.return_value
@pytest.mark.asyncio
@@ -751,3 +936,94 @@ async def test_query_wait_timeout_requires_keeping_original_handle():
assert "continues on the server" in message
assert "keep this handle to continue waiting" in message
assert "db.open_job" not in message
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [False, True])
async def test_stats_returns_fresh_report_without_waiting_or_printing(sync, capsys):
reports = [
None,
"Function job: finished\nWorker utilization: unavailable\n",
"Function job: finished\nWorker utilization: 25.0%\n",
]
inner = SimpleNamespace(
stats=AsyncMock(side_effect=reports),
wait=AsyncMock(),
cancel=AsyncMock(),
)
job = AsyncJob(inner)
for expected in reports:
actual = await asyncio.to_thread(Job(job).stats) if sync else await job.stats()
assert actual == expected
inner.wait.assert_not_awaited()
inner.cancel.assert_not_awaited()
assert capsys.readouterr().out == ""
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [False, True])
async def test_stats_preserves_errors_and_rejects_untracked_jobs(sync):
error = RuntimeError("run reports are unavailable on this server")
job = AsyncJob(SimpleNamespace(stats=AsyncMock(side_effect=error)))
with pytest.raises(RuntimeError) as exc:
if sync:
await asyncio.to_thread(Job(job).stats)
else:
await job.stats()
assert exc.value is error
with pytest.raises(NotImplementedError, match="server-side Function job"):
if sync:
Job(None).stats()
else:
await AsyncJob(None).stats()
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [False, True])
async def test_export_timeline_writes_fresh_recording_without_waiting(sync, tmp_path):
trace = {
"traceEvents": [{"ph": "X", "ts": 0, "dur": 1000}],
"metadata": {"partial": True},
}
inner = SimpleNamespace(
timeline=AsyncMock(return_value=json.dumps(trace)),
wait=AsyncMock(),
cancel=AsyncMock(),
)
job = AsyncJob(inner)
path = tmp_path / "job.trace.json"
if sync:
await asyncio.to_thread(Job(job).export_timeline, str(path))
else:
await job.export_timeline(path)
assert json.loads(path.read_text()) == trace
inner.timeline.assert_awaited_once_with()
inner.wait.assert_not_awaited()
inner.cancel.assert_not_awaited()
@pytest.mark.asyncio
async def test_export_timeline_failure_preserves_existing_file(tmp_path):
path = tmp_path / "job.trace.json"
path.write_text("previous recording")
job = AsyncJob(
SimpleNamespace(
timeline=AsyncMock(side_effect=RuntimeError("unsupported server"))
)
)
with pytest.raises(RuntimeError, match="unsupported server"):
await job.export_timeline(path)
assert path.read_text() == "previous recording"
with pytest.raises(NotImplementedError, match="server-side Function job"):
await AsyncJob(None).export_timeline(path)
with pytest.raises(NotImplementedError, match="server-side Function job"):
Job(None).export_timeline(path)
@pytest.mark.asyncio
async def test_export_timeline_reports_filesystem_errors(tmp_path):
job = AsyncJob(
SimpleNamespace(timeline=AsyncMock(return_value='{"traceEvents":[]}'))
)
with pytest.raises(FileNotFoundError):
await job.export_timeline(tmp_path / "missing" / "trace.json")
+177 -1
View File
@@ -268,7 +268,7 @@ async def test_listing_lazy_pages_and_resume(listing_server, kind, asynchronous)
if kind == "jobs":
assert verb == "POST"
assert path.path == "/v1/jobs/list"
assert body == {"page_token": token, "limit": 2}
assert body == {"database": "dev", "page_token": token, "limit": 2}
else:
namespace = "team"
resource = kind.removesuffix("s")
@@ -326,3 +326,179 @@ async def test_listing_invalid_limit_does_not_fetch(listing_server, kind, page_l
with pytest.raises(ValueError, match="limit"):
await items.__anext__()
assert requests == []
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize("namespace", [[], ["team", "project"]])
@pytest.mark.parametrize("multiple_types", [False, True])
async def test_job_filters_persist_across_pages_and_resume(
listing_server, asynchronous, namespace, multiple_types
):
endpoint, requests, responses = listing_server
responses.extend(
(200, response_page("jobs", names, token))
for names, token in [(["a"], "empty"), ([], "last"), (["b"], None)]
)
db = await connection(endpoint, asynchronous)
types = ["column_refresh", "materialized_view_refresh"]
filters = dict(
table="events",
namespace_path=namespace,
state="in_progress",
created_at_gte_millis=100,
created_at_lt_millis=200,
**({"job_types": types} if multiple_types else {"job_type": types[0]}),
)
items = db.list_jobs(page_limit=1, **filters)
assert requests == []
assert (await advance(items, asynchronous)).job_id == "a"
assert len(requests) == 1
resumed = db.list_jobs(page_token=items.page_token(), page_limit=1, **filters)
assert (await advance(resumed, asynchronous)).job_id == "b"
assert resumed.page_token() is None
assert len(requests) == 3
expected = dict(
database="dev",
limit=1,
table_ref={
"db_name": "dev",
"table_id": {"namespace_path": namespace, "table_name": "events"},
},
state="in_progress",
job_types=types if multiple_types else types[:1],
created_at_gte_millis=100,
created_at_lt_millis=200,
)
for (_, path, body), token in zip(requests, [None, "empty", "last"]):
assert path == "/v1/jobs/list"
assert body == {**expected, **({"page_token": token} if token else {})}
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize(
"filters",
[
{},
{"state": "failed"},
{"job_types": ["column_refresh"]},
{"created_at_lt_millis": 200},
],
)
async def test_job_listing_without_table_stays_in_connected_database(
listing_server, asynchronous, filters
):
endpoint, requests, responses = listing_server
responses.append((200, response_page("jobs", ["a"], None)))
db = await connection(endpoint, asynchronous)
items = db.list_jobs(**filters)
assert (await advance(items, asynchronous)).job_id == "a"
assert requests[0][2] == {"database": "dev", **filters}
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize(
"filters, message",
[
({"namespace_path": ["team"]}, "requires a table"),
({"created_at_gte_millis": 200, "created_at_lt_millis": 200}, "less than"),
({"created_at_gte_millis": 201, "created_at_lt_millis": 200}, "less than"),
({"job_type": "column_refresh", "job_types": []}, "only one"),
({"state": "unknown"}, "state must be"),
],
)
async def test_invalid_job_filters_do_not_fetch(
listing_server, asynchronous, filters, message
):
endpoint, requests, _ = listing_server
db = await connection(endpoint, asynchronous)
with pytest.raises(ValueError, match=message):
items = db.list_jobs(**filters)
await advance(items, asynchronous)
assert requests == []
@pytest.mark.asyncio
async def test_listing_slice_and_index_fetch_only_needed_pages(listing_server):
endpoint, requests, responses = listing_server
responses.extend(
(200, response_page("jobs", names, token))
for names, token in [(["a", "b"], "second"), (["c", "d"], "last")]
)
db = await connection(endpoint, False)
items = db.list_jobs(table="events", page_limit=2)
assert items[:0] == []
assert items[5:2] == []
assert requests == []
assert [job.job_id for job in items[:2]] == ["a", "b"]
assert len(requests) == 1
assert items.num_page_results() == 2
assert items.page_token() == "second"
assert items[1].job_id == "b"
assert next(items).job_id == "a"
assert [job.job_id for job in items[:2]] == ["b", "c"]
assert len(requests) == 2
assert items.num_page_results() == 3
assert items.page_token() == "last"
assert [job.job_id for job in items[0:3:2][:1]] == ["b"]
assert len(requests) == 2
@pytest.mark.asyncio
async def test_listing_length_and_slices_preserve_remaining_items(listing_server):
endpoint, requests, responses = listing_server
responses.extend(
(200, response_page("jobs", names, token))
for names, token in [(["a", "b"], "empty"), ([], "last"), (["c", "d"], None)]
)
db = await connection(endpoint, False)
items = db.list_jobs(page_limit=2)
assert bool(items)
assert len(requests) == 1
assert next(items).job_id == "a"
assert len(items) == 3
assert len(requests) == 3
assert items.num_page_results() == 3
assert items.page_token() is None
assert items[-1].job_id == "d"
assert [job.job_id for job in items[::-1]] == ["d", "c", "b"]
assert [job.job_id for job in items[1:]] == ["c", "d"]
assert [job.job_id for job in items[:100:2]] == ["b", "d"]
assert [job.job_id for job in items[: 2**100 : 2**100]] == ["b"]
with pytest.raises(IndexError):
_ = items[3]
assert [job.job_id for job in items] == ["b", "c", "d"]
assert len(items) == 0
assert not items
assert len(requests) == 3
@pytest.mark.asyncio
async def test_listing_invalid_slice_does_not_fetch(listing_server):
endpoint, requests, _ = listing_server
db = await connection(endpoint, False)
items = db.list_jobs()
with pytest.raises(ValueError, match="step"):
_ = items[::0]
with pytest.raises(TypeError):
_ = items["invalid"]
with pytest.raises(TypeError):
_ = items[:1.5]
assert requests == []
@pytest.mark.asyncio
async def test_listing_slice_failure_preserves_cache_and_retry_token(listing_server):
endpoint, requests, responses = listing_server
responses.extend([(200, response_page("jobs", ["a", "b"], "retry")), (401, {})])
db = await connection(endpoint, False)
items = db.list_jobs(page_limit=2)
with pytest.raises(HttpError):
_ = items[:3]
assert items.page_token() == "retry"
assert items.num_page_results() == 2
assert [job.job_id for job in items[:2]] == ["a", "b"]
assert [job.job_id for job in items] == ["a", "b"]
assert len(requests) == 2
@@ -0,0 +1,84 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import pytest
import lancedb
@pytest.mark.experimental_functions
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize("background", [False, True])
@pytest.mark.parametrize("namespace", [False, True])
@pytest.mark.parametrize("defining_query", [False, True])
async def test_exist_ok_preserves_materialized_data(
tmp_path, asynchronous, background, namespace, defining_query
):
source_args = (
{"query": "SELECT * FROM source"} if defining_query else {"source": "source"}
)
replacement_args = {
**(
{"query": "SELECT * FROM missing"}
if defining_query
else {"source": "missing"}
),
"auto_refresh_enabled": True,
"auto_refresh_interval_seconds": 1,
}
options = {"storage_options": {"new_table_enable_stable_row_ids": "true"}}
if asynchronous:
db = (
lancedb.connect_namespace_async("dir", {"root": str(tmp_path)}, **options)
if namespace
else await lancedb.connect_async(tmp_path, **options)
)
source = await db.create_table("source", [{"id": 1}])
original = await db.create_materialized_view(
"saved", **source_args, exist_ok=True
)
definition = await original.definition()
version = await original.table.version()
await source.add([{"id": 2}])
if background:
job = await db.create_materialized_view_async(
"saved", **replacement_args, exist_ok=True
)
await job.wait()
kept = await db.open_materialized_view("saved")
else:
kept = await db.create_materialized_view(
"saved", **replacement_args, exist_ok=True
)
assert (await kept.definition()).query == definition.query
assert await kept.table.version() == version
assert (await kept.table.to_arrow()).to_pylist() == [{"id": 1}]
with pytest.raises(ValueError, match="already exists"):
await db.create_materialized_view("saved", **source_args)
else:
db = (
lancedb.connect_namespace("dir", {"root": str(tmp_path)}, **options)
if namespace
else lancedb.connect(tmp_path, **options)
)
source = db.create_table("source", [{"id": 1}])
original = db.create_materialized_view("saved", **source_args, exist_ok=True)
definition = original.definition
version = original.table.version
source.add([{"id": 2}])
if background:
job = db.create_materialized_view_async(
"saved", **replacement_args, exist_ok=True
)
job.wait()
kept = db.open_materialized_view("saved")
else:
kept = db.create_materialized_view(
"saved", **replacement_args, exist_ok=True
)
assert kept.definition.query == definition.query
assert kept.table.version == version
assert kept.table.to_arrow().to_pylist() == [{"id": 1}]
with pytest.raises(ValueError, match="already exists"):
db.create_materialized_view("saved", **source_args)
+165 -12
View File
@@ -10,6 +10,7 @@ import lancedb
import pytest
import pyarrow as pa
from lancedb.db import AsyncConnection
from lancedb.exceptions import JobFailedError
from lancedb.materialized_view import MaterializedViewDefinition
from lancedb.remote.db import RemoteDBConnection
from utils import start_server_thread
@@ -175,7 +176,8 @@ async def test_remote_refresh_reports_unknown_metrics(
assert not any("count_rows" in path for path in requests)
def test_sync_remote_create_uses_public_async_connection():
@pytest.mark.parametrize("query", [None, "SELECT name FROM people WHERE age >= 18"])
def test_sync_remote_create_uses_public_async_connection(query):
calls = []
class StubAsyncTable:
@@ -190,10 +192,12 @@ def test_sync_remote_create_uses_public_async_connection():
name,
source,
*,
query=None,
select=None,
where=None,
limit=None,
with_no_data=False,
exist_ok=False,
auto_refresh_enabled=None,
auto_refresh_interval_seconds=None,
):
@@ -201,6 +205,7 @@ def test_sync_remote_create_uses_public_async_connection():
(
name,
source,
query,
select,
where,
limit,
@@ -219,18 +224,24 @@ def test_sync_remote_create_uses_public_async_connection():
db.db_name = "example"
db.serialize = lambda: "{}"
view = db.create_materialized_view(
"adults",
"people",
select=["name"],
where="age >= 18",
limit=10,
with_no_data=True,
auto_refresh_enabled=True,
auto_refresh_interval_seconds=0.5,
)
if query is None:
view = db.create_materialized_view(
"adults",
"people",
select=["name"],
where="age >= 18",
limit=10,
with_no_data=True,
auto_refresh_enabled=True,
auto_refresh_interval_seconds=0.5,
)
assert calls == [
("adults", "people", None, ["name"], "age >= 18", 10, True, True, 0.5)
]
else:
view = db.create_materialized_view("adults", query=query)
assert calls == [("adults", None, query, None, None, None, False, None, None)]
assert view.name == "adults"
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"])
@@ -719,6 +730,7 @@ def test_remote_create_forwards_refresh_options_without_interval_default(options
"filter": None,
"limit": None,
"with_no_data": False,
"exist_ok": False,
"auto_refresh_enabled": options.get("auto_refresh_enabled"),
"auto_refresh_interval_seconds": options.get(
"auto_refresh_interval_seconds"
@@ -790,3 +802,144 @@ 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
@pytest.mark.experimental_functions
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [False, True])
@pytest.mark.parametrize("namespace", [False, True])
@pytest.mark.parametrize("background", [False, True])
@pytest.mark.parametrize(
"query, expected",
[
(
"SELECT kind, count(*) AS n FROM events GROUP BY kind",
[{"kind": "a", "n": 2}, {"kind": "b", "n": 1}],
),
(
"SELECT id, tag FROM events, UNNEST(tags) AS tag",
[{"id": 1, "tag": "x"}, {"id": 1, "tag": "y"}, {"id": 3, "tag": "z"}],
),
],
)
async def test_query_defined_materialized_view(
tmp_path, sync, namespace, background, query, expected
):
if namespace:
connect = lancedb.connect_namespace if sync else lancedb.connect_namespace_async
db = connect("dir", {"root": str(tmp_path)}, storage_options=STABLE_ROW_IDS)
elif sync:
db = lancedb.connect(tmp_path, storage_options=STABLE_ROW_IDS)
else:
db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS)
rows = [
{"id": 1, "kind": "a", "tags": ["x", "y"]},
{"id": 2, "kind": "a", "tags": []},
{"id": 3, "kind": "b", "tags": ["z"]},
]
if sync:
db.create_table("events", rows, storage_options=STABLE_ROW_IDS)
if background:
db.create_materialized_view_async("result", query=query).wait()
view = db.open_materialized_view("result")
else:
view = db.create_materialized_view("result", query=query)
actual = view.table.to_arrow().to_pylist()
assert view.definition.query == query
view.refresh()
refreshed = view.table.to_arrow().to_pylist()
else:
await db.create_table("events", rows, storage_options=STABLE_ROW_IDS)
if background:
job = await db.create_materialized_view_async("result", query=query)
await job.wait()
view = await db.open_materialized_view("result")
else:
view = await db.create_materialized_view("result", query=query)
actual = (await view.table.to_arrow()).to_pylist()
assert (await view.definition()).query == query
await view.refresh()
refreshed = (await view.table.to_arrow()).to_pylist()
assert sorted(actual, key=str) == sorted(expected, key=str)
assert sorted(refreshed, key=str) == sorted(expected, key=str)
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [False, True])
@pytest.mark.parametrize("background", [False, True])
@pytest.mark.parametrize(
"clauses",
[{"source": "people"}, {"select": []}, {"select": {}}, {"where": ""}, {"limit": 0}],
)
async def test_query_rejects_source_clauses_before_submission(
sync, background, clauses
):
connect = lancedb.connect if sync else lancedb.connect_async
db = connect("db://dev", api_key="fake", host_override="http://127.0.0.1:1")
if not sync:
db = await db
create = (
db.create_materialized_view_async if background else db.create_materialized_view
)
with pytest.raises(ValueError, match="query cannot be combined"):
if sync:
create("invalid", query="SELECT * FROM people", **clauses)
else:
await create("invalid", query="SELECT * FROM people", **clauses)
with pytest.raises(ValueError, match="either source or query"):
if sync:
create("missing")
else:
await create("missing")
@pytest.mark.asyncio
@pytest.mark.parametrize("sync", [False, True])
@pytest.mark.parametrize(
"query",
[
"SELECT kind, count(*) AS n FROM events GROUP BY kind",
"SELECT id, c.text FROM docs, chunk(body) AS c",
"SELECT id, tag FROM events, UNNEST(tags) AS tag",
"SELECT a.id FROM a JOIN b ON a.id = b.id",
],
)
async def test_remote_create_forwards_defining_query(sync, query):
native = CapturingCreateConnection()
db = AsyncConnection(native)
if sync:
remote = RemoteDBConnection.__new__(RemoteDBConnection)
remote._conn = db
job = remote.create_materialized_view_async("result", query=query)
job.wait()
else:
job = await db.create_materialized_view_async("result", query=query)
await job.wait()
assert native.calls[0][0:2] == ("result", None)
assert native.calls[0][2]["query"] == query
@pytest.mark.experimental_functions
@pytest.mark.parametrize("background", [False, True])
def test_query_with_no_data_and_invalid_query(tmp_path, background):
db = make_db(tmp_path)
query = "SELECT name FROM people WHERE age >= 18"
if background:
db.create_materialized_view_async(
"adults", query=query, with_no_data=True
).wait()
view = db.open_materialized_view("adults")
else:
view = db.create_materialized_view("adults", query=query, with_no_data=True)
assert view.table.count_rows() == 0
view.refresh()
assert view.table.count_rows() == 2
create = (
db.create_materialized_view_async if background else db.create_materialized_view
)
error = JobFailedError if background else ValueError
with pytest.raises(error, match="unsupported clause"):
result = create("invalid", query="SELECT * FROM people ORDER BY age")
if background:
result.wait()
assert "invalid" not in db.table_names()
+82 -1
View File
@@ -18,6 +18,7 @@ import lancedb
from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError
from utils import start_server_thread
from lancedb.listing import AsyncListing, Listing
from lancedb.index import FTS
from lancedb.materialized_view import DEFINITION_FORMAT, DEFINITION_META_KEY
from lancedb.namespace import (
_MAX_QUERY_K,
@@ -25,7 +26,7 @@ from lancedb.namespace import (
LanceNamespaceDBConnection,
_query_to_namespace_request,
)
from lancedb.query import Query
from lancedb.query import FullTextSearchQuery, Query
from lancedb.table import AsyncTable, LanceTable
@@ -34,6 +35,27 @@ PUSHDOWN_DATA = pa.table(
)
@pytest.mark.asyncio
@pytest.mark.parametrize("table_id", [["events"], ["analytics", "events"], ["missing"]])
async def test_custom_namespace_table_exists_uses_namespace_api(table_id):
class ExistenceNamespace(LanceNamespace):
def namespace_id(self):
return "existence-test"
def table_exists(self, request):
if request.id == ["missing"]:
raise TableNotFoundError("Table not found")
def describe_table(self, request):
raise AssertionError("Custom existence checks must not open tables")
namespace = ExistenceNamespace()
db = LanceNamespaceDBConnection(namespace)
adb = lancedb.AsyncLanceNamespaceDBConnection(namespace)
assert db.table_exists(table_id) is (table_id != ["missing"])
assert await adb.table_exists(table_id) is (table_id != ["missing"])
class TestNamespaceCreateTableOptions:
@pytest.mark.parametrize("version", ["legacy", "stable"])
@pytest.mark.parametrize("empty", [False, True])
@@ -411,8 +433,16 @@ class TestNamespaceConnection:
assert "test_ns" in db.list_namespaces().namespaces
schema = pa.schema([pa.field("id", pa.int64())])
db.create_table("root_table", schema=schema)
assert db.table_exists(["root_table"]) is True
assert "root_table" in db
assert db.table_exists(["missing"]) is False
assert "missing" not in db
table = db.create_table("test_table", schema=schema, namespace_path=["test_ns"])
assert table.namespace == ["test_ns"]
assert db.table_exists(["test_ns", "test_table"]) is True
assert db.table_exists(["test_ns", "missing"]) is False
assert "test_table" not in db
assert "test_table" in db.table_names(namespace_path=["test_ns"])
assert "test_table" in db.list_tables(namespace_path=["test_ns"]).tables
@@ -420,7 +450,10 @@ class TestNamespaceConnection:
assert opened.namespace == ["test_ns"]
db.drop_table("test_table", namespace_path=["test_ns"])
assert db.table_exists(["test_ns", "test_table"]) is False
assert db.list_tables(namespace_path=["test_ns"]).tables == []
db.drop_table("root_table")
assert "root_table" not in db
db.drop_namespace(["test_ns"])
assert "test_ns" not in db.list_namespaces().namespaces
@@ -942,12 +975,18 @@ class TestAsyncNamespaceConnection:
assert "test_ns" in (await db.list_namespaces()).namespaces
schema = pa.schema([pa.field("id", pa.int64())])
await db.create_table("root_table", schema=schema)
assert await db.table_exists(["root_table"]) is True
assert await db.table_exists(["missing"]) is False
table = await db.create_table(
"test_table", schema=schema, namespace_path=["test_ns"]
)
assert table._namespace_path == ["test_ns"]
assert table._namespace_client is None
assert table._route_pushdown_to_rust is True
assert await db.table_exists(["test_ns", "test_table"]) is True
assert await db.table_exists(["test_ns", "missing"]) is False
assert await db.table_exists(["test_table"]) is False
assert "test_table" in await db.table_names(namespace_path=["test_ns"])
assert "test_table" in (await db.list_tables(namespace_path=["test_ns"])).tables
@@ -955,7 +994,10 @@ class TestAsyncNamespaceConnection:
assert opened._namespace_path == ["test_ns"]
await db.drop_table("test_table", namespace_path=["test_ns"])
assert await db.table_exists(["test_ns", "test_table"]) is False
assert (await db.list_tables(namespace_path=["test_ns"])).tables == []
await db.drop_table("root_table")
assert await db.table_exists(["root_table"]) is False
await db.drop_namespace(["test_ns"])
assert "test_ns" not in (await db.list_namespaces()).namespaces
@@ -1483,3 +1525,42 @@ def test_python_namespace_attribute_access(tmp_path):
# Missing dunder lookups still raise, so copy/hasattr probes work.
assert not hasattr(request, "__missing_dunder__")
assert copy.deepcopy(request) == request
@pytest.mark.parametrize("columns", [None, ["text"], ["title", "body"]])
def test_namespace_fts_operator_is_preserved(columns):
request = _query_to_namespace_request(
["matches"],
Query(
full_text_query=FullTextSearchQuery(
query="gripper closed", columns=columns, operator="AND"
)
),
)
structured = request.to_dict()["full_text_query"]["structured_query"]["query"]
if columns and len(columns) > 1:
assert all(
query["operator"] == "And"
for query in structured["multi_match"]["match_queries"]
)
else:
assert structured["match"]["operator"] == "And"
assert structured["match"].get("column") == (columns[0] if columns else None)
def test_namespace_fts_count_fast_search(tmp_path):
properties = {"root": str(tmp_path)}
db = lancedb.connect_namespace("dir", properties)
table = db.create_table("matches", pa.table({"text": ["gripper"] * 15}))
table.create_index("text", config=FTS())
table.add(pa.table({"text": ["gripper"] * 5}))
assert table.search("gripper", query_type="fts").fast_search().count_rows() == 15
pushed = lancedb.connect_namespace(
"dir", properties, namespace_client_pushdown_operations=["QueryTable"]
).open_table("matches")
assert pushed.search("gripper", query_type="fts").count_rows() == 20
query = pushed.search("gripper", query_type="fts").fast_search()
assert query.use_rte(False).count_rows() == 15
query = pushed.search("gripper", query_type="fts").fast_search()
assert query.count_rows() == 15
assert len(query.limit(100).to_list()) == 15
File diff suppressed because it is too large Load Diff
+50
View File
@@ -293,6 +293,56 @@ def test_parameters_reach_the_server_as_the_values_that_were_sent():
assert echoed.column("k").to_pylist() == [10]
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize(
("exist_ok", "status"),
[
(None, "created"),
(False, "created"),
(True, "created"),
(True, "already_exists"),
],
)
async def test_create_secret_exist_ok_reaches_sql(asynchronous, exist_ok, status):
flight = pytest.importorskip("pyarrow.flight")
class SecretServer(flight.FlightServerBase):
def __init__(self):
super().__init__("grpc://127.0.0.1:0")
self.writes = []
def do_exchange(self, context, descriptor, reader, writer):
self.writes.append((descriptor.command, reader.read_all()))
result = pa.table({"status": [status]})
writer.begin(result.schema)
writer.write_table(result)
writer.close()
with SecretServer() as server:
options = {
"api_key": "test-key",
"host_override": "http://localhost:10024",
"sql_host_override": f"grpc://127.0.0.1:{server.port}",
}
kwargs = {"namespace_path": ["team", "production"]}
if exist_ok is not None:
kwargs["exist_ok"] = exist_ok
if asynchronous:
db = await lancedb.connect_async("db://analytics", **options)
await db.create_secret("api-key", "credential's value", **kwargs)
else:
db = lancedb.connect("db://analytics", **options)
db.create_secret("api-key", "credential's value", **kwargs)
((command, parameters),) = server.writes
prefix = "CREATE SECRET IF NOT EXISTS" if exist_ok else "CREATE SECRET"
sql = f'{prefix} "api-key" TYPE = GENERIC_STRING SECRET_STRING = $1'
assert sql.encode() in command
assert b"credential's value" not in command
assert parameters.column(0).to_pylist() == ["credential's value"]
@pytest.mark.parametrize("job_id", [None, "sql-job-1"])
def test_sql_input_error_metadata_crosses_native_boundary(job_id):
flight = pytest.importorskip("pyarrow.flight")
@@ -3,6 +3,7 @@
import contextlib
import json
import re
from pathlib import Path
import pytest
@@ -39,7 +40,30 @@ def remote_server(text_type=pa.string()):
command = ticket.ticket
calls.append(command)
if b"SHOW STORAGE INTEGRATIONS" in command:
result = pa.table({"name": pa.array(["zeta", NAME], type=text_type)})
match = re.search(
rb'SHOW STORAGE INTEGRATIONS IN "public" '
rb"LIMIT (\d+)(?: FROM '([^']+)')?",
command,
)
assert match is not None, command
limit = int(match.group(1))
names = [NAME, "zeta"]
if match.group(2) is not None:
assert match.group(2) == b"server-storage-page", command
names = names[1:]
page = names[:limit]
result = pa.table(
{
"namespace_path": pa.array(
["[]"] * len(page), type=pa.string()
),
"name": pa.array(page, type=text_type),
}
)
if len(names) > limit:
result = result.replace_schema_metadata(
{b"lancedb.next_page_token": b"server-storage-page"}
)
elif b"DROP STORAGE INTEGRATION" in command:
result = pa.table({"dropped": [True]})
else:
@@ -195,6 +219,10 @@ def test_sync_storage_integration_lifecycle_and_aws_information(text_type):
assert b'CREATE STORAGE INTEGRATION "raw"' in calls[0]
assert b"STORAGE_AWS_ROLE_ARN = '" + ROLE.encode() + b"'" in calls[0]
assert b'DROP STORAGE INTEGRATION "raw"' in calls[-1]
listings = [call for call in calls if b"SHOW STORAGE INTEGRATIONS" in call]
assert len(listings) == 2
assert b'SHOW STORAGE INTEGRATIONS IN "public" LIMIT 1' in listings[0]
assert b"FROM 'server-storage-page'" in listings[1]
@pytest.mark.asyncio
@@ -0,0 +1,85 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import json
from pathlib import Path
import pyarrow as pa
import pytest
import lancedb
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize(
("exist_ok", "existing"),
[(None, False), (False, False), (True, False), (True, True)],
)
async def test_storage_integration_exist_ok_preserves_server_metadata(
asynchronous, exist_ok, existing
):
flight = pytest.importorskip("pyarrow.flight")
fixture = (
Path(__file__).parents[3]
/ "rust/lancedb/tests/fixtures/storage_integration.json"
)
stored = json.loads(fixture.read_text())
stored["namespace_path"] = ["team"]
columns = {}
for key, value in stored.items():
if isinstance(value, (dict, list)):
value = json.dumps(value)
columns[key] = pa.array([None], type=pa.string()) if value is None else [value]
result = pa.table(columns)
prefix = "s3://replacement-bucket/raw/" if existing else stored["storage_prefix"]
role = (
"arn:aws:iam::999999999999:role/replacement"
if existing
else stored["aws_role_arn"]
)
class IntegrationServer(flight.FlightServerBase):
def __init__(self):
super().__init__("grpc://127.0.0.1:0")
self.requests = []
def do_get(self, context, ticket):
self.requests.append(ticket.ticket)
return flight.RecordBatchStream(result)
with IntegrationServer() as server:
connection_options = {
"api_key": "test-key",
"host_override": "http://localhost:10024",
"sql_host_override": f"grpc://127.0.0.1:{server.port}",
}
kwargs = {} if exist_ok is None else {"exist_ok": exist_ok}
kwargs.update(
storage_provider="S3",
storage_prefix=prefix,
aws_role_arn=role,
namespace_path=["team"],
)
uri = f"db://{stored['database']}"
if asynchronous:
db = await lancedb.connect_async(uri, **connection_options)
info = await db.create_storage_integration(stored["name"], **kwargs)
else:
db = lancedb.connect(uri, **connection_options)
info = db.create_storage_integration(stored["name"], **kwargs)
(request,) = server.requests
command = (
"CREATE STORAGE INTEGRATION IF NOT EXISTS"
if exist_ok
else "CREATE STORAGE INTEGRATION"
)
assert f'{command} "raw"'.encode() in request
assert prefix.encode() in request
assert role.encode() in request
assert info.storage_prefix == stored["storage_prefix"]
assert info.aws_role_arn == stored["aws_role_arn"]
assert info.aws_external_id == stored["aws_external_id"]
assert info.created_at_millis == stored["created_at_millis"]
assert info.namespace_path == ["team"]
+17 -8
View File
@@ -58,8 +58,8 @@ def test_legacy_table_replace_field_metadata(legacy_table):
]
def respond(request, body):
request.send_response(200)
def respond(request, body, status=200):
request.send_response(status)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(json.dumps(body).encode())
@@ -78,12 +78,20 @@ def test_remote_unsupported_properties(attribute):
@pytest.mark.parametrize("tables", [[], ["first", "last"]])
def test_remote_len_and_contains_follow_pages(tables):
def test_remote_len_paginates_and_contains_looks_up_table(tables):
requests = []
def handler(request):
requests.append(request.path)
query = parse_qs(urlparse(request.path).query)
url = urlparse(request.path)
if request.command == "POST":
name = url.path.split("/")[3]
assert url.path == f"/v1/table/{name}/describe/"
respond(request, {}, status=200 if name in tables else 404)
return
assert request.command == "GET"
assert url.path == "/v1/namespace/$/table/list"
query = parse_qs(url.query)
if tables and "page_token" not in query:
respond(request, {"tables": [tables[0]], "page_token": "opaque-next"})
else:
@@ -93,11 +101,12 @@ def test_remote_len_and_contains_follow_pages(tables):
with mock_lancedb_connection(handler) as db:
assert len(db) == len(tables)
assert ("last" in db) == bool(tables)
assert "missing" not in db
assert len(requests) == (2 if tables else 1)
requests.clear()
assert ("first" in db) == bool(tables)
assert len(requests) == 1
for name in ("last", "missing", "first"):
assert (name in db) is (name in tables)
assert requests == [f"/v1/table/{name}/describe/"]
requests.clear()
@pytest.mark.parametrize("namespace", [[], ["parent", "child"]])
+134 -2
View File
@@ -1837,6 +1837,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
wait_timeout=None,
name=None,
train=True,
exist_ok=False,
)
# Test with target_partition_size
@@ -1862,6 +1863,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
wait_timeout=None,
name=None,
train=True,
exist_ok=False,
)
# target_partition_size has a default value,
@@ -1886,6 +1888,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
wait_timeout=None,
name=None,
train=True,
exist_ok=False,
)
table.create_index(
@@ -1902,6 +1905,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
wait_timeout=None,
name=None,
train=True,
exist_ok=False,
)
table.create_index(
@@ -1922,6 +1926,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
wait_timeout=None,
name=None,
train=True,
exist_ok=False,
)
table.create_index(
@@ -1942,6 +1947,7 @@ def test_create_index_method(mock_create_index, mem_db: DBConnection):
wait_timeout=None,
name=None,
train=True,
exist_ok=False,
)
@@ -2073,6 +2079,7 @@ def test_create_index_name_and_train_parameters(
wait_timeout=None,
name="my_custom_index",
train=True,
exist_ok=False,
)
# Test with train=False
@@ -2084,6 +2091,7 @@ def test_create_index_name_and_train_parameters(
wait_timeout=None,
name=None,
train=False,
exist_ok=False,
)
# Test with both name and train
@@ -2095,6 +2103,7 @@ def test_create_index_name_and_train_parameters(
wait_timeout=None,
name="my_index_name",
train=True,
exist_ok=False,
)
@@ -2132,6 +2141,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection):
wait_timeout=None,
name=None,
train=True,
exist_ok=False,
)
# Scalar index via new API
@@ -2143,6 +2153,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection):
wait_timeout=None,
name=None,
train=True,
exist_ok=False,
)
# FTS index via new API
@@ -2154,6 +2165,7 @@ def test_create_index_new_api(mock_create_index, mem_db: DBConnection):
wait_timeout=None,
name=None,
train=True,
exist_ok=False,
)
@@ -3436,7 +3448,8 @@ def test_merge_insert(mem_db: DBConnection):
table.merge_insert("a")
.when_matched_update_all()
.when_not_matched_insert_all()
.execute(new_data, timeout=timedelta(seconds=10))
.use_index(False)
.execute(new_data, timeout=timedelta(seconds=10), retries=0)
)
assert merge_insert_res.version == 2
assert merge_insert_res.num_inserted_rows == 1
@@ -3515,7 +3528,7 @@ def test_merge_insert(mem_db: DBConnection):
# timeout
with pytest.raises(Exception, match="merge insert timed out"):
table.merge_insert("a").when_matched_update_all().execute(
new_data, timeout=timedelta(0)
new_data, timeout=timedelta(0), retries=255
)
@@ -6001,6 +6014,31 @@ def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size)
{"resource_budget": {"cpu_millis": 1000, "memory_bytes": 1024}},
"resource_budget",
),
(
{
"supervisor_resources": {
"cpu_millis": 1000,
"memory_bytes": 1024,
"ephemeral_storage_bytes": 2048,
}
},
"supervisor_resources",
),
(
{
"planning_workers": {
"resources": {
"cpu_millis": 1000,
"memory_bytes": 1024,
"ephemeral_storage_bytes": 2048,
},
"max_workers": 2,
"rows_per_worker": 100,
"fragments_per_worker": 1,
}
},
"planning_workers",
),
({"num_workers": 2}, "num_workers"),
({"max_executor_processes_per_worker": 2}, "max_executor_processes_per_worker"),
],
@@ -6036,6 +6074,16 @@ def test_function_errors_are_remote_only(tmp_path):
table.function_errors()
def test_function_column_status_is_remote_only(tmp_path):
db = lancedb.connect(tmp_path)
table = db.create_table("t", [{"x": 1}])
with pytest.raises(
NotImplementedError,
match="exact Function column status is supported only in LanceDB Enterprise",
):
table.wait_fresh("x")
@pytest.mark.experimental_functions
@pytest.mark.parametrize("batch_size", [None, 8])
def test_refresh_column_async_returns_job(tmp_path, batch_size):
@@ -6282,3 +6330,87 @@ async def test_async_computed_auto_refresh_uses_server_interval(tmp_path):
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
@pytest.mark.parametrize(
"method",
["create_index", "create_index_async", "create_scalar_index", "create_fts_index"],
)
@pytest.mark.parametrize("name", [None, "kept_index"])
def test_index_exist_ok_preserves_definition_and_version(mem_db, method, name):
table = mem_db.create_table(
"keep_index", [{"id": i, "text": f"document {i}"} for i in range(20)]
)
column = "text" if method == "create_fts_index" else "id"
config = FTS() if column == "text" else BTree()
table.create_index(column, config=config, name=name, exist_ok=True)
before = table.version
original = table.list_indices()
kwargs = dict(name=name, exist_ok=True)
if method in ("create_index", "create_index_async"):
kwargs["config"] = config
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
result = getattr(table, method)(column, **kwargs)
if method == "create_index_async":
result.wait()
assert table.version == before
assert [(index.name, index.index_type) for index in table.list_indices()] == [
(index.name, index.index_type) for index in original
]
with pytest.raises((ValueError, RuntimeError), match="already exists"):
table.create_index(column, config=config, name=name, replace=False)
table.create_index(column, config=config, name=name)
assert table.version > before
@pytest.mark.parametrize(
"column,name,existing",
[
("vector", "kept", "kept"),
("`docs`.`nested.dot`", None, "docs.`nested.dot`_idx"),
],
)
def test_accelerated_index_exist_ok_skips_gpu_validation(column, name, existing):
dataset = MagicMock()
dataset.list_indices.return_value = [{"name": existing}]
with patch("lancedb.table._validate_index_accelerator") as validate:
table_module._create_accelerated_index(
dataset, column=column, accelerator="cuda", name=name, exist_ok=True
)
validate.assert_not_called()
dataset.create_index.assert_not_called()
def test_accelerated_index_exist_ok_preserves_concurrent_winner():
dataset = MagicMock()
dataset.list_indices.side_effect = [[], [{"name": "vector_idx"}]]
dataset.create_index.side_effect = RuntimeError("concurrent create")
with patch("lancedb.table._validate_index_accelerator"):
table_module._create_accelerated_index(
dataset, column="vector", accelerator="cuda", replace=True, exist_ok=True
)
assert dataset.create_index.call_args.kwargs["replace"] is False
assert dataset.create_index.call_args.kwargs["name"] == "vector_idx"
@pytest.mark.parametrize("column", ["`user-id`", "`user:id`", "nested.`user-id`"])
def test_index_exist_ok_matches_lance_default_name(mem_db, column):
table = mem_db.create_table(
"quoted_index",
[{"user-id": 1, "user:id": 2, "nested": {"user-id": 4}}],
)
table.create_index(column, config=BTree())
before = table.version
table.create_index(column, config=BTree(), exist_ok=True)
assert table.version == before
assert len(table.list_indices()) == 1
def test_fts_exist_ok_matches_quoted_default_name(mem_db):
table = mem_db.create_table("quoted_fts", [{"body-text": "keep this document"}])
table.create_index("`body-text`", config=FTS())
before = table.version
table.create_index("`body-text`", config=FTS(), exist_ok=True)
assert table.version == before
assert len(table.list_indices()) == 1
+5 -1
View File
@@ -115,7 +115,11 @@ def test_vector_tuning_options(sync_table):
}.items():
assert getattr(config, name) == value
assert kwargs == dict(
wait_timeout=timeout, name="custom_idx", replace=False, train=False
wait_timeout=timeout,
name="custom_idx",
replace=False,
train=False,
exist_ok=False,
)
+71
View File
@@ -0,0 +1,71 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import json
import pyarrow as pa
import pytest
import lancedb
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
@pytest.mark.parametrize(
("exist_ok", "existing"),
[(None, False), (False, False), (True, False), (True, True)],
)
async def test_create_view_exist_ok_preserves_server_metadata(
asynchronous, exist_ok, existing
):
flight = pytest.importorskip("pyarrow.flight")
original_query = "SELECT 'original' AS original"
submitted_query = (
"SELECT 'replacement' AS replacement" if existing else original_query
)
schema = {
"fields": [{"name": "original", "nullable": True, "type": {"type": "utf8"}}],
"metadata": {
"lancedb::view::default_db": "analytics",
"lancedb::view::default_namespace": "team",
},
}
result = pa.table(
{"name": ["saved"], "query": [original_query], "schema": [json.dumps(schema)]}
)
class ViewServer(flight.FlightServerBase):
def __init__(self):
super().__init__("grpc://127.0.0.1:0")
self.requests = []
def do_get(self, context, ticket):
self.requests.append(ticket.ticket)
return flight.RecordBatchStream(result)
with ViewServer() as server:
connection_options = {
"api_key": "test-key",
"host_override": "http://localhost:10024",
"sql_host_override": f"grpc://127.0.0.1:{server.port}",
}
kwargs = {} if exist_ok is None else {"exist_ok": exist_ok}
if asynchronous:
db = await lancedb.connect_async("db://analytics", **connection_options)
view = await db.create_view(
"saved", submitted_query, namespace_path=["team"], **kwargs
)
else:
db = lancedb.connect("db://analytics", **connection_options)
view = db.create_view(
"saved", submitted_query, namespace_path=["team"], **kwargs
)
(request,) = server.requests
prefix = "CREATE VIEW IF NOT EXISTS" if exist_ok else "CREATE VIEW"
assert f'{prefix} "saved" AS {submitted_query}'.encode() in request
assert view.name == "saved"
assert view.namespace_path == ["team"]
assert view.default_namespace_path == ["team"]
assert view.query == original_query
assert view.schema.names == ["original"]
+19 -1
View File
@@ -4,12 +4,30 @@
from typing import assert_type
import lancedb
from lancedb import AsyncConnection, DBConnection
from lancedb import AsyncCatalog, AsyncConnection, Catalog, DBConnection
def check_connect_type() -> None:
assert_type(lancedb.connect("memory://"), DBConnection)
assert_type(
lancedb.connect_catalog(
uri="db://analytics",
api_key="secret",
region="us-west-2",
host_override="https://my-server.example",
),
Catalog,
)
async def check_connect_async_type() -> None:
assert_type(await lancedb.connect_async("memory://"), AsyncConnection)
assert_type(
await lancedb.connect_catalog_async(
uri="db://analytics",
api_key="secret",
region="us-west-2",
host_override="https://my-server.example",
),
AsyncCatalog,
)
+7 -1
View File
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;
@@ -127,7 +128,8 @@ impl DatabaseNames {
}
#[pyfunction]
#[pyo3(signature = (endpoint, *, api_key=None, client_config=None, sql_host_override=None, read_consistency_interval=None, oauth_config=None))]
#[allow(clippy::too_many_arguments)]
#[pyo3(signature = (endpoint, *, api_key=None, client_config=None, sql_host_override=None, read_consistency_interval=None, oauth_config=None, storage_options=None))]
pub fn connect_catalog(
py: Python<'_>,
endpoint: String,
@@ -136,6 +138,7 @@ pub fn connect_catalog(
sql_host_override: Option<String>,
read_consistency_interval: Option<f64>,
oauth_config: Option<crate::oauth::PyOAuthConfig>,
storage_options: Option<HashMap<String, String>>,
) -> PyResult<Bound<'_, PyAny>> {
let interval = read_consistency_interval
.map(Duration::try_from_secs_f64)
@@ -151,6 +154,9 @@ pub fn connect_catalog(
if let Some(config) = client_config {
builder = builder.client_config(config.into());
}
if let Some(options) = storage_options {
builder = builder.storage_options(options);
}
if let Some(endpoint) = sql_host_override {
builder = builder.sql_host_override(endpoint);
}
+112 -17
View File
@@ -23,9 +23,10 @@ use lancedb::{
connection::Connection as LanceConnection,
connection::NamespaceClientPushdownOperation,
database::namespace::LanceNamespaceDatabase,
database::{CreateTableMode, Database, ReadConsistency},
function::GpuClass as LanceGpuClass,
database::{CreateTableMode, Database, JobListFilter, JobListState, ReadConsistency},
function::{GpuClass as LanceGpuClass, RefreshColumnResult},
graph::PropertyGraphDefinition,
materialized_view::CreateMaterializedViewBuilder,
};
use pyo3::{
Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python,
@@ -34,6 +35,27 @@ use pyo3::{
types::{PyAnyMethods, PyDict, PyDictMethods, PyList},
};
fn materialized_view_builder(
connection: &LanceConnection,
name: String,
source: Option<String>,
query: Option<String>,
has_clauses: bool,
) -> PyResult<CreateMaterializedViewBuilder> {
match (source, query) {
(None, Some(query)) if !has_clauses => {
Ok(connection.create_materialized_view_from_query(name, query))
}
(Some(source), None) => Ok(connection.create_materialized_view(name, source)),
(None, None) => Err(PyValueError::new_err(
"either source or query must be provided",
)),
_ => Err(PyValueError::new_err(
"query cannot be combined with source, select, where or limit",
)),
}
}
#[pyclass]
pub struct Connection {
inner: Option<LanceConnection>,
@@ -435,7 +457,8 @@ impl Connection {
})
}
#[pyo3(signature = (target_table_name, source_uri, target_namespace_path=None, source_version=None, source_tag=None, is_shallow=true))]
#[allow(clippy::too_many_arguments)]
#[pyo3(signature = (target_table_name, source_uri, target_namespace_path=None, source_version=None, source_tag=None, is_shallow=true, *, exist_ok=false))]
pub fn clone_table(
self_: PyRef<'_, Self>,
target_table_name: String,
@@ -444,6 +467,7 @@ impl Connection {
source_version: Option<u64>,
source_tag: Option<String>,
is_shallow: bool,
exist_ok: bool,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
@@ -455,7 +479,7 @@ impl Connection {
if let Some(tag) = source_tag {
builder = builder.source_tag(tag);
}
builder = builder.is_shallow(is_shallow);
builder = builder.is_shallow(is_shallow).exist_ok(exist_ok);
future_into_py(self_.py(), async move {
let table = builder.execute().await.infer_error()?;
@@ -483,21 +507,30 @@ impl Connection {
}
#[allow(clippy::too_many_arguments)]
#[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))]
#[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None, exist_ok=false))]
pub fn create_materialized_view(
self_: PyRef<'_, Self>,
name: String,
source: String,
source: Option<String>,
projections: Option<Vec<(String, String)>>,
filter: Option<String>,
limit: Option<u64>,
with_no_data: bool,
auto_refresh_enabled: Option<bool>,
auto_refresh_interval_seconds: Option<f64>,
query: Option<String>,
exist_ok: bool,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
let builder = materialized_view_builder(
&inner,
name,
source,
query,
projections.is_some() || filter.is_some() || limit.is_some(),
)?;
future_into_py(self_.py(), async move {
let mut builder = inner.create_materialized_view(name, source);
let mut builder = builder.exist_ok(exist_ok);
if let Some(enabled) = auto_refresh_enabled {
builder = builder.auto_refresh_enabled(enabled);
}
@@ -520,21 +553,30 @@ impl Connection {
}
#[allow(clippy::too_many_arguments)]
#[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))]
#[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None, exist_ok=false))]
pub fn create_materialized_view_async(
self_: PyRef<'_, Self>,
name: String,
source: String,
source: Option<String>,
projections: Option<Vec<(String, String)>>,
filter: Option<String>,
limit: Option<u64>,
with_no_data: bool,
auto_refresh_enabled: Option<bool>,
auto_refresh_interval_seconds: Option<f64>,
query: Option<String>,
exist_ok: bool,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
let builder = materialized_view_builder(
&inner,
name,
source,
query,
projections.is_some() || filter.is_some() || limit.is_some(),
)?;
future_into_py(self_.py(), async move {
let mut builder = inner.create_materialized_view(name, source);
let mut builder = builder.exist_ok(exist_ok);
if let Some(enabled) = auto_refresh_enabled {
builder = builder.auto_refresh_enabled(enabled);
}
@@ -854,19 +896,28 @@ impl Connection {
let inner = self_.get_inner()?.clone();
future_into_py(self_.py(), async move {
let job = inner.open_job(&job_id).await.infer_error()?;
Ok(crate::job::Job::new(job))
match job.job_type().as_deref() {
Some("function_refresh" | "computed_refresh" | "refresh_column") => {
Ok(crate::job::Job::new_typed(
job.into_typed::<RefreshColumnResult>().infer_error()?,
))
}
_ => Ok(crate::job::Job::new(job)),
}
})
}
#[pyo3(signature = (request_json, namespace_path=None))]
#[pyo3(signature = (request_json, namespace_path=None, *, exist_ok=false))]
pub fn create_function_async(
self_: PyRef<'_, Self>,
request_json: String,
namespace_path: Option<Vec<String>>,
exist_ok: bool,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
let request = lancedb::function::FunctionRegistrationRequest::from_json(&request_json)
let mut request = lancedb::function::FunctionRegistrationRequest::from_json(&request_json)
.infer_error()?;
request.exist_ok = exist_ok;
let namespace_path = namespace_path.unwrap_or_default();
future_into_py(self_.py(), async move {
inner
@@ -1029,18 +1080,20 @@ impl Connection {
})
}
#[pyo3(signature = (name, value, namespace_path=None))]
#[pyo3(signature = (name, value, namespace_path=None, *, exist_ok=false))]
pub fn create_secret(
self_: PyRef<'_, Self>,
name: String,
value: String,
namespace_path: Option<Vec<String>>,
exist_ok: bool,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
let namespace_path = namespace_path.unwrap_or_default();
future_into_py(self_.py(), async move {
inner
.create_secret(name, value, &namespace_path)
.exist_ok(exist_ok)
.await
.infer_error()
})
@@ -1111,18 +1164,20 @@ impl Connection {
})
}
#[pyo3(signature = (name, query, namespace_path=None))]
#[pyo3(signature = (name, query, namespace_path=None, *, exist_ok=false))]
pub fn create_view(
self_: PyRef<'_, Self>,
name: String,
query: String,
namespace_path: Option<Vec<String>>,
exist_ok: bool,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
let namespace_path = namespace_path.unwrap_or_default();
future_into_py(self_.py(), async move {
let view = inner
.create_view(name, query, &namespace_path)
.exist_ok(exist_ok)
.await
.infer_error()?;
view_description_to_py(view)
@@ -1264,18 +1319,58 @@ impl Connection {
))
}
#[pyo3(signature = (*, page_token=None, page_limit=None))]
#[allow(clippy::too_many_arguments)]
#[pyo3(signature = (*, page_token=None, page_limit=None, table=None, namespace_path=None, state=None, job_type=None, job_types=None, created_at_gte_millis=None, created_at_lt_millis=None))]
pub fn list_jobs(
&self,
page_token: Option<String>,
page_limit: Option<u32>,
table: Option<String>,
namespace_path: Option<Vec<String>>,
state: Option<String>,
job_type: Option<String>,
job_types: Option<Vec<String>>,
created_at_gte_millis: Option<i64>,
created_at_lt_millis: Option<i64>,
) -> PyResult<crate::listing::JobListing> {
if job_type.is_some() && job_types.is_some() {
return Err(PyValueError::new_err(
"set only one of job_type and job_types",
));
}
let mut filter = JobListFilter::default();
filter.table = table;
filter.namespace_path = namespace_path.unwrap_or_default();
filter.state = state
.as_deref()
.map(|state| match state {
"in_progress" => Ok(JobListState::InProgress),
"succeeded" => Ok(JobListState::Succeeded),
"failed" => Ok(JobListState::Failed),
"canceled" => Ok(JobListState::Canceled),
"timed_out" => Ok(JobListState::TimedOut),
_ => Err(PyValueError::new_err(
"state must be one of: in_progress, succeeded, failed, canceled, timed_out",
)),
})
.transpose()?;
filter.job_types = job_types.unwrap_or_else(|| job_type.into_iter().collect());
filter.created_at_gte_millis = created_at_gte_millis;
filter.created_at_lt_millis = created_at_lt_millis;
Ok(crate::listing::JobListing::new(
self.get_inner()?
.list_jobs(crate::listing::options(page_token, page_limit)),
.list_jobs_filtered(filter, crate::listing::options(page_token, page_limit)),
))
}
pub fn server_info(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
future_into_py(self_.py(), async move {
let info = inner.server_info().await.infer_error()?;
serde_json::to_string(&info).map_err(|error| PyValueError::new_err(error.to_string()))
})
}
pub fn list_gpu_classes(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.get_inner()?.clone();
future_into_py(self_.py(), async move {
+7 -1
View File
@@ -164,9 +164,12 @@ pub fn expr_col(name: &str) -> PyExpr {
/// Create a literal value expression.
///
/// Supported Python types: `bool`, `int`, `float`, `str`, `bytes`, `date`,
/// `datetime`, `Decimal`.
/// `datetime`, `Decimal`, and `None` (SQL NULL).
#[pyfunction]
pub fn expr_lit(value: Bound<'_, PyAny>) -> PyResult<PyExpr> {
if value.is_none() {
return Ok(PyExpr(df_lit(ScalarValue::Null)));
}
// bool must be checked before int because bool is a subclass of int in Python
if let Ok(b) = value.extract::<bool>() {
return Ok(PyExpr(df_lit(b)));
@@ -174,6 +177,9 @@ pub fn expr_lit(value: Bound<'_, PyAny>) -> PyResult<PyExpr> {
if let Ok(i) = value.extract::<i64>() {
return Ok(PyExpr(df_lit(i)));
}
if let Ok(i) = value.extract::<u64>() {
return Ok(PyExpr(df_lit(i)));
}
// Decimal must be checked before f64: Python's Decimal implements __float__,
// so value.extract::<f64>() would succeed and silently truncate the value to
// f64, losing precision. Build a Decimal128 scalar to preserve it instead.
+26 -8
View File
@@ -152,6 +152,18 @@ impl Job {
self.inner.description().map(JobDescription::from)
}
pub fn timeline(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move {
Ok(inner.timeline().await.infer_error()?.to_string())
})
}
pub fn stats(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move { inner.stats().await.infer_error() })
}
#[pyo3(signature = (*, limit=None, filter=None))]
pub fn events(
self_: PyRef<'_, Self>,
@@ -228,7 +240,7 @@ impl From<lancedb::database::JobInfo> for JobInfo {
/// The server's account of why a job failed.
#[pyclass(module = "lancedb._lancedb", get_all, skip_from_py_object)]
#[derive(Clone)]
#[derive(Clone, Debug)]
pub struct JobFailureInfo {
phase: Option<String>,
message: Option<String>,
@@ -238,6 +250,18 @@ pub struct JobFailureInfo {
sql_job_id: Option<String>,
}
impl From<lancedb::error::JobFailure> for JobFailureInfo {
fn from(failure: lancedb::error::JobFailure) -> Self {
Self {
phase: failure.phase,
message: failure.message,
traceback: failure.traceback,
retryable: failure.retryable,
sql_job_id: failure.sql_job_id,
}
}
}
#[pymethods]
impl JobFailureInfo {
fn __repr__(&self) -> String {
@@ -341,13 +365,7 @@ impl From<lancedb::database::JobDescription> for JobDescription {
.filter(|result| !result.is_null())
.map(|result| result.to_string()),
_progress_json: Some(progress_json),
failure: description.failure.map(|failure| JobFailureInfo {
phase: failure.phase,
message: failure.message,
traceback: failure.traceback,
retryable: failure.retryable,
sql_job_id: failure.sql_job_id,
}),
failure: description.failure.map(Into::into),
}
}
}
+9 -3
View File
@@ -16,9 +16,10 @@ use query::{FTSQuery, HybridQuery, Query, VectorQuery};
use session::Session;
use table::{
AddColumnsResult, AddResult, AlterColumnsResult, DeleteResult, DropColumnsResult, FtsToken,
FunctionErrorFragment, FunctionErrorRecord, FunctionErrors, MergeResult, PyBlobFile,
RTEWriteSpec, RefreshColumnResult, RefreshMaterializedViewResult, Table,
UpdateFieldMetadataResult, UpdateResult,
FunctionColumnAutoRefreshStatus, FunctionColumnLastRefreshJob, FunctionColumnStatus,
FunctionColumnVersionStatus, FunctionErrorFragment, FunctionErrorRecord, FunctionErrors,
MergeResult, PyBlobFile, RTEWriteSpec, RefreshColumnResult, RefreshMaterializedViewResult,
Table, UpdateFieldMetadataResult, UpdateResult,
};
pub mod arrow;
@@ -117,6 +118,10 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<FunctionErrors>()?;
m.add_class::<FunctionErrorRecord>()?;
m.add_class::<FunctionErrorFragment>()?;
m.add_class::<FunctionColumnStatus>()?;
m.add_class::<FunctionColumnVersionStatus>()?;
m.add_class::<FunctionColumnLastRefreshJob>()?;
m.add_class::<FunctionColumnAutoRefreshStatus>()?;
m.add_class::<RefreshMaterializedViewResult>()?;
m.add_class::<AlterColumnsResult>()?;
m.add_class::<UpdateFieldMetadataResult>()?;
@@ -145,6 +150,7 @@ pub fn _lancedb(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(table::tokenize, m)?)?;
m.add_function(wrap_pyfunction!(permutation::async_permutation_builder, m)?)?;
m.add_function(wrap_pyfunction!(util::validate_table_name, m)?)?;
m.add_function(wrap_pyfunction!(util::validate_conda_requirement, m)?)?;
m.add_function(wrap_pyfunction!(util::validate_function_retry_policy, m)?)?;
m.add_function(wrap_pyfunction!(util::parse_field_path, m)?)?;
m.add_function(wrap_pyfunction!(query::fts_query_to_json, m)?)?;
+35 -2
View File
@@ -16,19 +16,20 @@ use arrow::array::make_array;
use arrow::pyarrow::FromPyArrow;
use arrow::pyarrow::IntoPyArrow;
use arrow::pyarrow::ToPyArrow;
use futures::TryStreamExt;
use lancedb::ApproxMode;
use lancedb::index::scalar::{
BooleanQuery, BoostQuery, CombinedFieldsQuery, DocumentGranularity, FtsQuery,
FullTextSearchQuery, MatchQuery, MultiMatchQuery, Occur, Operator, PhraseQuery,
};
use lancedb::query::AnalyzePlanDistributedMetrics;
use lancedb::query::QueryBase;
use lancedb::query::QueryExecutionOptions;
use lancedb::query::QueryFilter;
use lancedb::query::{
ColumnOrdering, ExecutableQuery, Query as LanceDbQuery, Select, TakeQuery as LanceDbTakeQuery,
VectorQuery as LanceDbVectorQuery,
};
use lancedb::query::{HasQuery, QueryBase};
use lancedb::table::AnyQuery;
use pyo3::Bound;
use pyo3::IntoPyObject;
@@ -616,8 +617,18 @@ impl Query {
query_text = query_text[1..query_text.len() - 1].to_string();
}
let operator = query
.get_item("operator")?
.filter(|operator| !operator.is_none())
.map(|operator| {
let operator = operator.extract::<String>()?;
Operator::try_from(operator.as_str())
.map_err(|err| PyValueError::new_err(err.to_string()))
})
.transpose()?
.unwrap_or(Operator::Or);
let query: FtsQuery = match (is_phrase, is_multi_match) {
(false, _) => MatchQuery::new(query_text).into(),
(false, _) => MatchQuery::new(query_text).with_operator(operator).into(),
(true, false) => PhraseQuery::new(query_text).into(),
(true, true) => {
return Err(PyValueError::new_err(
@@ -898,6 +909,28 @@ impl FTSQuery {
})
}
pub fn count_rows(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
let mut inner = self_
.inner
.clone()
.full_text_search(self_.fts_query.clone());
let request = inner.mut_query();
request.limit = None;
request.offset = None;
request.select = Select::columns(&["_score"]);
request.order_by = None;
request.with_row_id = false;
request.reranker = None;
future_into_py(self_.py(), async move {
let mut stream = inner.execute().await.infer_error()?;
let mut count = 0_u64;
while let Some(batch) = stream.try_next().await.infer_error()? {
count += batch.num_rows() as u64;
}
Ok(count)
})
}
pub fn nearest_to(&mut self, vector: Bound<'_, PyAny>) -> PyResult<HybridQuery> {
let vector_query = Query::new(self.inner.clone()).nearest_to(vector)?;
Ok(HybridQuery {
+352 -10
View File
@@ -15,6 +15,7 @@ use crate::{
error::PythonErrorExt,
expr::PyExpr,
index::{CodeAnalyzerOptions, IndexConfig, extract_index_params},
job::JobFailureInfo,
query::{Query, TakeQuery},
table::scannable::PyScannable,
};
@@ -29,8 +30,9 @@ use lancedb::connection::LanceFileVersion;
use lancedb::index::scalar::FtsIndexBuilder;
use lancedb::table::{
AddDataMode, ColumnAlteration, CompactionMode, CompactionOptions, Duration,
FieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionWorkerResourceBudget, IndexRemapMode,
NewColumnTransform, Ref, RefreshColumnOptions, Table as LanceDbTable,
FieldMetadataUpdate, FtsToken as LanceDbFtsToken, FunctionRefreshPlanningConfig,
FunctionRefreshPodResources, FunctionWorkerResourceBudget, IndexRemapMode, NewColumnTransform,
Ref, RefreshColumnOptions, Table as LanceDbTable,
};
use lancedb::tokenize as lancedb_tokenize;
use pyo3::{
@@ -51,6 +53,8 @@ struct RefreshColumnArgs {
max_concurrency: Option<u32>,
publication_interval_rows: Option<i64>,
resource_budget: Option<FunctionWorkerResourceBudget>,
supervisor_resources: Option<FunctionRefreshPodResources>,
planning_workers: Option<FunctionRefreshPlanningConfig>,
gpu_class: Option<String>,
gpu_count: Option<i64>,
retry_policy: Option<String>,
@@ -158,6 +162,101 @@ fn parse_resource_budget(
))
}
fn structured_integer(value: &Bound<'_, PyAny>, name: &str) -> PyResult<u64> {
if value.is_none() || value.is_instance_of::<PyBool>() {
return Err(PyValueError::new_err(format!("{name} must be an integer")));
}
let parsed = value
.extract::<u64>()
.map_err(|_| PyValueError::new_err(format!("{name} must be an integer")))?;
if parsed == 0 {
return Err(PyValueError::new_err(format!(
"{name} must be greater than zero"
)));
}
Ok(parsed)
}
fn parse_pod_resources(
resources: &Bound<'_, PyDict>,
prefix: &str,
) -> PyResult<FunctionRefreshPodResources> {
for key in resources.keys() {
let key = key
.extract::<String>()
.map_err(|_| PyValueError::new_err(format!("{prefix} keys must be strings")))?;
if !matches!(
key.as_str(),
"cpu_millis" | "memory_bytes" | "ephemeral_storage_bytes"
) {
return Err(PyValueError::new_err(format!(
"{prefix} contains unsupported key '{key}'"
)));
}
}
let get = |name: &str| -> PyResult<u64> {
let value = resources
.get_item(name)?
.ok_or_else(|| PyValueError::new_err(format!("{prefix}.{name} is required")))?;
structured_integer(&value, &format!("{prefix}.{name}"))
};
Ok(FunctionRefreshPodResources::new(
get("cpu_millis")?,
get("memory_bytes")?,
get("ephemeral_storage_bytes")?,
))
}
fn parse_supervisor_resources(
resources: Option<&Bound<'_, PyDict>>,
) -> PyResult<Option<FunctionRefreshPodResources>> {
resources
.map(|resources| parse_pod_resources(resources, "supervisor_resources"))
.transpose()
}
fn parse_planning_workers(
planning: Option<&Bound<'_, PyDict>>,
) -> PyResult<Option<FunctionRefreshPlanningConfig>> {
let Some(planning) = planning else {
return Ok(None);
};
for key in planning.keys() {
let key = key
.extract::<String>()
.map_err(|_| PyValueError::new_err("planning_workers keys must be strings"))?;
if !matches!(
key.as_str(),
"resources" | "max_workers" | "rows_per_worker" | "fragments_per_worker"
) {
return Err(PyValueError::new_err(format!(
"planning_workers contains unsupported key '{key}'"
)));
}
}
let resources = planning
.get_item("resources")?
.ok_or_else(|| PyValueError::new_err("planning_workers.resources is required"))?;
let resources = resources
.cast::<PyDict>()
.map_err(|_| PyValueError::new_err("planning_workers.resources must be a dict"))?;
let resources = parse_pod_resources(resources, "planning_workers.resources")?;
let get = |name: &str| -> PyResult<u64> {
let value = planning
.get_item(name)?
.ok_or_else(|| PyValueError::new_err(format!("planning_workers.{name} is required")))?;
structured_integer(&value, &format!("planning_workers.{name}"))
};
let max_workers = usize::try_from(get("max_workers")?)
.map_err(|_| PyValueError::new_err("planning_workers.max_workers is too large"))?;
Ok(Some(FunctionRefreshPlanningConfig::new(
resources,
max_workers,
get("rows_per_worker")?,
get("fragments_per_worker")?,
)))
}
fn refresh_column_options(args: RefreshColumnArgs) -> PyResult<RefreshColumnOptions> {
let RefreshColumnArgs {
where_clause,
@@ -165,6 +264,8 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult<RefreshColumnOpti
max_concurrency,
publication_interval_rows,
resource_budget,
supervisor_resources,
planning_workers,
gpu_class,
gpu_count,
retry_policy,
@@ -210,6 +311,8 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult<RefreshColumnOpti
options.publication_interval_rows =
positive_count(publication_interval_rows, "publication_interval_rows")?;
options.resource_budget = resource_budget;
options.supervisor_resources = supervisor_resources;
options.planning_workers = planning_workers;
options.gpu_class = gpu_class;
options.gpu_count = gpu_count
.map(|count| {
@@ -892,6 +995,140 @@ impl From<lancedb::function::FunctionErrors> for FunctionErrors {
}
}
/// Exact immutable Function revision attached to a table output.
#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)]
#[derive(Clone, Debug)]
pub struct FunctionColumnVersionStatus {
pub name: String,
pub namespace_path: Vec<String>,
pub object_id: String,
pub location: String,
pub version: String,
pub manifest_digest: String,
}
impl From<lancedb::function::FunctionVersionRef> for FunctionColumnVersionStatus {
fn from(function: lancedb::function::FunctionVersionRef) -> Self {
Self {
name: function.name,
namespace_path: function.namespace_path,
object_id: function.object_id,
location: function.location,
version: function.version,
manifest_digest: function.manifest_digest,
}
}
}
/// Latest matching refresh Job projected for a Function output.
#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)]
#[derive(Clone, Debug)]
pub struct FunctionColumnLastRefreshJob {
pub job_id: String,
pub state: String,
pub automatic: Option<bool>,
pub completed_at_millis: Option<i64>,
pub failure: Option<JobFailureInfo>,
}
impl From<lancedb::table::FunctionColumnLastRefreshJob> for FunctionColumnLastRefreshJob {
fn from(job: lancedb::table::FunctionColumnLastRefreshJob) -> Self {
Self {
job_id: job.job_id,
state: job.state,
automatic: job.automatic,
completed_at_millis: job.completed_at_millis,
failure: job.failure.map(Into::into),
}
}
}
/// Automatic-refresh projection for a Function output.
#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)]
#[derive(Clone, Debug)]
pub struct FunctionColumnAutoRefreshStatus {
pub enabled: bool,
pub interval_seconds: Option<u64>,
pub active_job_id: Option<String>,
pub state: String,
pub failure_streak: u32,
pub effective_cooldown_millis: Option<u64>,
pub blocked_reason: Option<String>,
pub next_run_at_millis: Option<i64>,
pub next_run_at_reason: Option<String>,
}
impl From<lancedb::table::FunctionColumnAutoRefreshStatus> for FunctionColumnAutoRefreshStatus {
fn from(status: lancedb::table::FunctionColumnAutoRefreshStatus) -> Self {
Self {
enabled: status.enabled,
interval_seconds: status.interval_seconds,
active_job_id: status.active_job_id,
state: status.state.as_str().to_string(),
failure_streak: status.failure_streak,
effective_cooldown_millis: status.effective_cooldown_millis,
blocked_reason: status
.blocked_reason
.map(|reason| reason.as_str().to_string()),
next_run_at_millis: status.next_run_at_millis,
next_run_at_reason: status.next_run_at_reason,
}
}
}
/// Exact four-way status of one Function output at one table version.
#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)]
#[derive(Clone, Debug)]
pub struct FunctionColumnStatus {
pub column: String,
pub binding_id: String,
pub function: FunctionColumnVersionStatus,
pub table_version: u64,
pub rows: u64,
pub fresh: u64,
pub stale: u64,
pub never_computed: u64,
pub failed: u64,
pub last_refresh_job: Option<FunctionColumnLastRefreshJob>,
pub last_failure_job: Option<FunctionColumnLastRefreshJob>,
pub auto_refresh: FunctionColumnAutoRefreshStatus,
}
#[pymethods]
impl FunctionColumnStatus {
pub fn __repr__(&self) -> String {
format!(
"FunctionColumnStatus(column={:?}, table_version={}, rows={}, fresh={}, stale={}, never_computed={}, failed={})",
self.column,
self.table_version,
self.rows,
self.fresh,
self.stale,
self.never_computed,
self.failed
)
}
}
impl From<lancedb::table::FunctionColumnStatus> for FunctionColumnStatus {
fn from(status: lancedb::table::FunctionColumnStatus) -> Self {
Self {
column: status.column,
binding_id: status.binding_id,
function: status.function.into(),
table_version: status.table_version,
rows: status.rows,
fresh: status.fresh,
stale: status.stale,
never_computed: status.never_computed,
failed: status.failed,
last_refresh_job: status.last_refresh_job.map(Into::into),
last_failure_job: status.last_failure_job.map(Into::into),
auto_refresh: status.auto_refresh.into(),
}
}
}
#[pyclass(get_all, from_py_object)]
#[derive(Clone, Debug)]
pub struct RefreshMaterializedViewResult {
@@ -1108,6 +1345,15 @@ impl PyBlobFile {
.map_err(|e| blob_file_error("tell", e))
}
fn set_buffer_size(self_: PyRef<'_, Self>, size: usize) -> PyResult<()> {
self_.ensure_open()?;
let inner = self_.inner.clone();
self_
.py()
.detach(move || block_on(async move { inner.set_buffer_size(size).await }))
.map_err(|e| blob_file_error("set_buffer_size", e))
}
fn size(self_: PyRef<'_, Self>) -> u64 {
self_.inner.size()
}
@@ -1327,7 +1573,7 @@ impl Table {
})
}
#[pyo3(signature = (data, mode, progress=None, write_parallelism=None, allow_external_blob_outside_bases=false))]
#[pyo3(signature = (data, mode, progress=None, write_parallelism=None, allow_external_blob_outside_bases=false, retries=None))]
pub fn add<'a>(
self_: PyRef<'a, Self>,
data: PyScannable,
@@ -1335,6 +1581,7 @@ impl Table {
progress: Option<Py<PyAny>>,
write_parallelism: Option<usize>,
allow_external_blob_outside_bases: bool,
retries: Option<u8>,
) -> PyResult<Bound<'a, PyAny>> {
let mut op = self_
.inner_ref()?
@@ -1347,6 +1594,9 @@ impl Table {
} else {
return Err(PyValueError::new_err(format!("Invalid mode: {}", mode)));
}
if let Some(retries) = retries {
op = op.retries(retries);
}
if let Some(write_parallelism) = write_parallelism {
op = op.write_parallelism(write_parallelism);
}
@@ -1480,7 +1730,8 @@ impl Table {
})
}
#[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None))]
#[allow(clippy::too_many_arguments)]
#[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None, exist_ok=false))]
pub fn create_index<'a>(
self_: PyRef<'a, Self>,
column: String,
@@ -1489,6 +1740,7 @@ impl Table {
wait_timeout: Option<Bound<'_, PyAny>>,
name: Option<String>,
train: Option<bool>,
exist_ok: bool,
) -> PyResult<Bound<'a, PyAny>> {
let index = extract_index_params(&index)?;
let timeout = wait_timeout
@@ -1497,6 +1749,7 @@ impl Table {
let mut op = self_
.inner_ref()?
.create_index_with_timeout(&[column], index, timeout);
op = op.exist_ok(exist_ok);
if let Some(replace) = replace {
op = op.replace(replace);
}
@@ -1513,7 +1766,8 @@ impl Table {
})
}
#[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None))]
#[allow(clippy::too_many_arguments)]
#[pyo3(signature = (column, index=None, replace=None, wait_timeout=None, *, name=None, train=None, exist_ok=false))]
pub fn create_index_async<'a>(
self_: PyRef<'a, Self>,
column: String,
@@ -1522,6 +1776,7 @@ impl Table {
wait_timeout: Option<Bound<'_, PyAny>>,
name: Option<String>,
train: Option<bool>,
exist_ok: bool,
) -> PyResult<Bound<'a, PyAny>> {
let index = extract_index_params(&index)?;
let timeout = wait_timeout
@@ -1530,6 +1785,7 @@ impl Table {
let mut op = self_
.inner_ref()?
.create_index_with_timeout(&[column], index, timeout);
op = op.exist_ok(exist_ok);
if let Some(replace) = replace {
op = op.replace(replace);
}
@@ -1830,14 +2086,28 @@ impl Table {
}
/// Read blob bytes for `row_ids` from blob v2 column `column`.
#[pyo3(signature = (column, row_ids))]
#[pyo3(signature = (column, row_ids, *, version=None, snapshot_identity=None))]
pub fn fetch_blobs(
self_: PyRef<'_, Self>,
column: String,
row_ids: Vec<u64>,
version: Option<u64>,
snapshot_identity: Option<String>,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
let inner = match (version, snapshot_identity) {
(None, None) => inner,
(Some(version), Some(identity)) => inner
.query_snapshot_with_identity(version, &identity)
.await
.infer_error()?,
_ => {
return Err(PyValueError::new_err(
"deferred blob reads require both query version and snapshot identity",
));
}
};
let blobs: LargeBinaryArray = inner
.fetch_blobs(column.as_str(), &row_ids)
.await
@@ -1884,11 +2154,12 @@ impl Table {
}
/// Open lazy blob handles for `row_ids` from blob v2 column `column`.
#[pyo3(signature = (column, row_ids))]
#[pyo3(signature = (column, row_ids, buffer_size=None))]
pub fn fetch_blob_files(
self_: PyRef<'_, Self>,
column: String,
row_ids: Vec<u64>,
buffer_size: Option<usize>,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
@@ -1896,6 +2167,13 @@ impl Table {
.fetch_blob_files(column.as_str(), &row_ids)
.await
.infer_error()?;
if let Some(size) = buffer_size {
for file in handles.iter().flatten() {
file.set_buffer_size(size)
.await
.map_err(|e| blob_file_error("set_buffer_size", e))?;
}
}
Ok(handles
.into_iter()
.map(|handle| {
@@ -1908,16 +2186,22 @@ impl Table {
})
}
#[pyo3(signature = (descriptor))]
#[pyo3(signature = (descriptor, buffer_size=None))]
pub fn open_blob_file<'py>(
self_: PyRef<'py, Self>,
descriptor: &str,
buffer_size: Option<usize>,
) -> PyResult<Bound<'py, PyAny>> {
let descriptor: BlobDescriptor = serde_json::from_str(descriptor)
.map_err(|error| PyValueError::new_err(format!("invalid blob descriptor: {error}")))?;
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
let file = inner.open_blob_file(&descriptor).await.infer_error()?;
if let Some(size) = buffer_size {
file.set_buffer_size(size)
.await
.map_err(|e| blob_file_error("set_buffer_size", e))?;
}
Ok(PyBlobFile {
inner: Arc::new(file),
closed: AtomicBool::new(false),
@@ -1985,10 +2269,12 @@ impl Table {
})
}
#[pyo3(signature = (data, parameters, retries=None))]
pub fn execute_merge_insert<'a>(
self_: PyRef<'a, Self>,
data: Bound<'a, PyAny>,
parameters: MergeInsertParams,
retries: Option<u8>,
) -> PyResult<Bound<'a, PyAny>> {
let batches: ArrowArrayStreamReader = ArrowArrayStreamReader::from_pyarrow_bound(&data)?;
let on = parameters.on.iter().map(|s| s.as_str()).collect::<Vec<_>>();
@@ -2011,6 +2297,9 @@ impl Table {
if let Some(timeout) = parameters.timeout {
builder.timeout(timeout);
}
if let Some(retries) = retries {
builder.retries(retries);
}
if let Some(use_index) = parameters.use_index {
builder.use_index(use_index);
}
@@ -2313,7 +2602,7 @@ impl Table {
})
}
#[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[allow(clippy::too_many_arguments)]
pub fn refresh_column<'py>(
self_: PyRef<'py, Self>,
@@ -2323,6 +2612,8 @@ impl Table {
max_concurrency: Option<Bound<'py, PyAny>>,
publication_interval_rows: Option<i64>,
resource_budget: Option<Bound<'py, PyDict>>,
supervisor_resources: Option<Bound<'py, PyDict>>,
planning_workers: Option<Bound<'py, PyDict>>,
gpu_class: Option<String>,
gpu_count: Option<i64>,
retry_policy: Option<String>,
@@ -2340,6 +2631,8 @@ impl Table {
max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?,
publication_interval_rows,
resource_budget: parse_resource_budget(resource_budget.as_ref())?,
supervisor_resources: parse_supervisor_resources(supervisor_resources.as_ref())?,
planning_workers: parse_planning_workers(planning_workers.as_ref())?,
gpu_class,
gpu_count,
retry_policy,
@@ -2361,7 +2654,7 @@ impl Table {
})
}
#[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[pyo3(signature = (column, *, r#where=None, batch_size=None, max_concurrency=None, publication_interval_rows=None, resource_budget=None, supervisor_resources=None, planning_workers=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[allow(clippy::too_many_arguments)]
pub fn refresh_column_async<'py>(
self_: PyRef<'py, Self>,
@@ -2371,6 +2664,8 @@ impl Table {
max_concurrency: Option<Bound<'py, PyAny>>,
publication_interval_rows: Option<i64>,
resource_budget: Option<Bound<'py, PyDict>>,
supervisor_resources: Option<Bound<'py, PyDict>>,
planning_workers: Option<Bound<'py, PyDict>>,
gpu_class: Option<String>,
gpu_count: Option<i64>,
retry_policy: Option<String>,
@@ -2388,6 +2683,8 @@ impl Table {
max_concurrency: positive_u32_integer(max_concurrency.as_ref(), "max_concurrency")?,
publication_interval_rows,
resource_budget: parse_resource_budget(resource_budget.as_ref())?,
supervisor_resources: parse_supervisor_resources(supervisor_resources.as_ref())?,
planning_workers: parse_planning_workers(planning_workers.as_ref())?,
gpu_class,
gpu_count,
retry_policy,
@@ -2428,6 +2725,51 @@ impl Table {
})
}
#[pyo3(signature = (column=None))]
pub fn column_statuses(
self_: PyRef<'_, Self>,
column: Option<String>,
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
let statuses = inner
.function_column_statuses(column.as_deref())
.await
.infer_error()?;
Ok(statuses
.into_iter()
.map(FunctionColumnStatus::from)
.collect::<Vec<_>>())
})
}
pub fn column_status(self_: PyRef<'_, Self>, column: String) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
let status = inner.function_column_status(&column).await.infer_error()?;
Ok(FunctionColumnStatus::from(status))
})
}
#[pyo3(signature = (column, timeout=None))]
pub fn wait_column_fresh<'py>(
self_: PyRef<'py, Self>,
column: String,
timeout: Option<Bound<'py, PyAny>>,
) -> PyResult<Bound<'py, PyAny>> {
let timeout = timeout
.map(|timeout| timeout.extract::<std::time::Duration>())
.transpose()?;
let inner = self_.inner_ref()?.clone();
future_into_py(self_.py(), async move {
let status = inner
.wait_for_function_column(&column, timeout)
.await
.infer_error()?;
Ok(FunctionColumnStatus::from(status))
})
}
#[pyo3(signature = (source_version=None, *, full=false, cpu_millis=None, memory_bytes=None, gpu_count=None, gpu_class=None))]
#[allow(clippy::too_many_arguments)]
pub fn refresh_materialized_view(
+8
View File
@@ -9,6 +9,7 @@ use pyo3::{
exceptions::{PyRuntimeError, PyValueError},
pyfunction,
};
use rattler_conda_types::{MatchSpec, ParseStrictness};
/// A wrapper around a rust builder
///
@@ -61,6 +62,13 @@ pub fn validate_table_name(table_name: &str) -> PyResult<()> {
.map_err(|e| PyValueError::new_err(e.to_string()))
}
#[pyfunction(name = "_validate_conda_requirement")]
pub fn validate_conda_requirement(requirement: &str) -> PyResult<()> {
MatchSpec::from_str(requirement, ParseStrictness::Lenient)
.map(|_| ())
.map_err(|error| PyValueError::new_err(error.to_string()))
}
/// Parse field references with the same identifier syntax as Lance writes.
#[pyfunction(name = "_parse_field_path")]
pub fn parse_field_path(path: &str) -> PyResult<Vec<String>> {
+9 -7
View File
@@ -2147,7 +2147,7 @@ requires-dist = [
{ name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" },
{ name = "pydantic", specifier = ">=2.7.4,<3" },
{ name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" },
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b16" },
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b22" },
{ name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" },
{ name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" },
{ name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" },
@@ -4301,7 +4301,7 @@ crypto = [
[[package]]
name = "pylance"
version = "15.0.0b16"
version = "15.0.0b22"
source = { registry = "https://pypi.fury.io/lance-format/" }
dependencies = [
{ name = "lance-namespace" },
@@ -4312,11 +4312,13 @@ dependencies = [
{ name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
]
wheels = [
{ url = "https://pypi.fury.io/lance-format/-/ver_uZ4Az/pylance-15.0.0b16-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c4ed0ab9213082d9d8cc93aa09351e84574c76ddefc422a2ad073115bd9a1b43" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1nenYa/pylance-15.0.0b16-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7f28f7b757ade1e4b556e788bc77d4ffcc351a9c8c570b35f769c457e9cc13bf" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1cb3ns/pylance-15.0.0b16-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:49f358f3ddf33d76567f56d0e4a66c218dc1a2d2f06d37d779e13c87b1c3d9a6" },
{ url = "https://pypi.fury.io/lance-format/-/ver_g7LAk/pylance-15.0.0b16-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:288c1b41f5068990672c8c182b4b79d6389c1a907c59ef6047cbee494d1e34ec" },
{ url = "https://pypi.fury.io/lance-format/-/ver_12YRtQ/pylance-15.0.0b16-cp310-abi3-win_amd64.whl", hash = "sha256:fa69acdd0960280f6fe8a83ea992fc92e2ed5a0eeb5159b90493dfc76831f752" },
{ url = "https://pypi.fury.io/lance-format/-/ver_2gkGO/pylance-15.0.0b22-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:401df8ce31ae6263656915c63d3da4411cae59bde2a6d71d12c552e3fa72b6bf" },
{ url = "https://pypi.fury.io/lance-format/-/ver_pfuJc/pylance-15.0.0b22-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f5c9ee37b23da4d6fbc341d0e18d355b1602c98fbf096e4589b08ecce57c56ea" },
{ url = "https://pypi.fury.io/lance-format/-/ver_YPb1X/pylance-15.0.0b22-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:38e6ed648816ae54ee3e76f21a30c092d47028da1f99242922ec1288d79a1722" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1a1jcd/pylance-15.0.0b22-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:1b7e9f1dfe7ff8e3cbb3b06a3ebd99667629725b6d9a119146f9e1bfac20871f" },
{ url = "https://pypi.fury.io/lance-format/-/ver_KRwHG/pylance-15.0.0b22-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:c31b41b8a8d070f969dcb9dd06aa31190f79d036b27cb5d5ae6d64d5d425502f" },
{ url = "https://pypi.fury.io/lance-format/-/ver_2cABdZ/pylance-15.0.0b22-cp310-abi3-win_amd64.whl", hash = "sha256:7b3d36ea7ab7a6a43caecc96ca7f969be11ad89d24ccc6d1788d751fb39e720d" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1j6gGW/pylance-15.0.0b22-cp310-abi3-win_arm64.whl", hash = "sha256:20c4e391b4b83008dc2b7877bdd0ad9b3b1251ea05116d79b5637807f4961cc8" },
]
[[package]]