mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
Merge main into gatekeeper/fix-4911-1
This commit is contained in:
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "lancedb-python"
|
||||
version = "0.42.0-beta.12"
|
||||
version = "0.42.0-beta.13"
|
||||
publish = false
|
||||
edition.workspace = true
|
||||
description = "Python bindings for LanceDB"
|
||||
|
||||
@@ -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()
|
||||
@@ -64,7 +64,7 @@ tests = [
|
||||
"polars>=0.19, <=1.32.3",
|
||||
"pyarrow>=16",
|
||||
"pyarrow-stubs>=16.0",
|
||||
"pylance==15.0.0b18",
|
||||
"pylance==15.0.0b21",
|
||||
"requests>=2.31.0",
|
||||
"datafusion>=54,<55",
|
||||
"opentelemetry-sdk>=1.30.0",
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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
|
||||
@@ -332,6 +347,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 +360,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 +415,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: ...
|
||||
@@ -413,6 +437,7 @@ class Job:
|
||||
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,
|
||||
*,
|
||||
@@ -538,6 +563,7 @@ 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 update(
|
||||
self, updates: Dict[str, str], where: Optional[str]
|
||||
@@ -566,6 +592,7 @@ class Table:
|
||||
*,
|
||||
name: Optional[str],
|
||||
train: Optional[bool],
|
||||
exist_ok: bool = False,
|
||||
): ...
|
||||
async def create_index_async(
|
||||
self,
|
||||
@@ -590,6 +617,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: ...
|
||||
@@ -742,7 +770,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,
|
||||
@@ -750,9 +783,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:
|
||||
@@ -1227,6 +1262,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:
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
+213
-35
@@ -58,6 +58,7 @@ from lance_namespace import (
|
||||
from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError
|
||||
|
||||
from . import __version__
|
||||
from .server_info import ServerInfo
|
||||
from ._lancedb import _append_doc_url, connect as lancedb_connect # type: ignore
|
||||
from .functions import FunctionVersion, FunctionDefinition
|
||||
from .graph import (
|
||||
@@ -67,7 +68,7 @@ from .graph import (
|
||||
PropertyGraph,
|
||||
_definition_json,
|
||||
)
|
||||
from .job import AsyncJob, Job, _typed_job
|
||||
from .job import AsyncJob, Job, _opened_job, _typed_job
|
||||
from .storage_integration import SecretReference, StorageIntegrationInfo
|
||||
from .sql import AsyncQuery as AsyncSqlQuery
|
||||
from .sql import Query as SqlQuery
|
||||
@@ -78,6 +79,7 @@ from .materialized_view import (
|
||||
MaterializedViewSource,
|
||||
SelectArg,
|
||||
normalize_select,
|
||||
_validate_create_materialized_view,
|
||||
)
|
||||
from .secrets import (
|
||||
EnvVarSecret,
|
||||
@@ -430,8 +432,12 @@ class DBConnection(EnforceOverrides):
|
||||
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:
|
||||
"""Register storage access, preserving existing configuration with
|
||||
``exist_ok=True``. Existing names are errors by default.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def describe_storage_integration(
|
||||
@@ -697,17 +703,22 @@ class DBConnection(EnforceOverrides):
|
||||
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:
|
||||
"""Define a materialized view named ``name`` over the table ``source``.
|
||||
|
||||
``exist_ok=True`` preserves an existing view's definition, data and
|
||||
refresh settings without refreshing it. Existing names error by default.
|
||||
|
||||
LanceDB Embedded creation and refresh require a source build with the
|
||||
``experimental-functions`` Cargo feature. Published packages leave it
|
||||
disabled; LanceDB Enterprise operations remain available.
|
||||
@@ -721,8 +732,12 @@ class DBConnection(EnforceOverrides):
|
||||
----------
|
||||
name: str
|
||||
The name of the view.
|
||||
source: str
|
||||
The name of the source table.
|
||||
source: str, optional
|
||||
The name of the source table. Required when ``query`` is omitted.
|
||||
query: str, optional
|
||||
The complete defining SQL query, including any GROUP BY or FROM
|
||||
Function. Mutually exclusive with ``source``, ``select``, ``where``
|
||||
and ``limit``. Supported query shapes depend on the backend.
|
||||
select: list or dict, optional
|
||||
The view's columns: column names, ``(alias, SQL expression)``
|
||||
pairs, or a dict of the same. Omitting it selects every source
|
||||
@@ -744,6 +759,13 @@ class DBConnection(EnforceOverrides):
|
||||
Returns
|
||||
-------
|
||||
MaterializedView
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> view = db.create_materialized_view( # doctest: +SKIP
|
||||
... "events_by_kind",
|
||||
... query="SELECT kind, count(*) AS n FROM events GROUP BY kind",
|
||||
... )
|
||||
"""
|
||||
raise NotImplementedError(
|
||||
_append_doc_url(
|
||||
@@ -755,17 +777,22 @@ class DBConnection(EnforceOverrides):
|
||||
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]:
|
||||
"""Submit materialized-view creation and return its job.
|
||||
|
||||
``exist_ok=True`` preserves an existing view without refreshing it.
|
||||
A skipped creation returns a completed job without a registry job ID.
|
||||
|
||||
The job may already be complete in LanceDB Embedded. In LanceDB
|
||||
Distributed, creation submits CREATE MATERIALIZED VIEW through the SQL
|
||||
server and the returned ``id`` is the registry job ID. That ID can be
|
||||
@@ -989,10 +1016,14 @@ class DBConnection(EnforceOverrides):
|
||||
definition: FunctionDefinition,
|
||||
*,
|
||||
secrets: Optional[Sequence[EnvVarSecret]] = None,
|
||||
exist_ok: bool = False,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
) -> FunctionVersion:
|
||||
"""Build and register a scalar Python function, then return its version.
|
||||
|
||||
``exist_ok=True`` returns the existing named Function version unchanged.
|
||||
By default, registration retains its existing version-creation behavior.
|
||||
|
||||
The server builds the OCI image and registers the completed artifact.
|
||||
This is the blocking counterpart of :meth:`create_function_async`.
|
||||
LanceDB Embedded connections raise ``NotImplementedError``.
|
||||
@@ -1025,7 +1056,10 @@ class DBConnection(EnforceOverrides):
|
||||
```
|
||||
"""
|
||||
return self.create_function_async(
|
||||
definition, secrets=secrets, namespace_path=namespace_path
|
||||
definition,
|
||||
secrets=secrets,
|
||||
exist_ok=exist_ok,
|
||||
namespace_path=namespace_path,
|
||||
).wait()
|
||||
|
||||
def create_function_async(
|
||||
@@ -1033,10 +1067,14 @@ class DBConnection(EnforceOverrides):
|
||||
definition: FunctionDefinition,
|
||||
*,
|
||||
secrets: Optional[Sequence[EnvVarSecret]] = None,
|
||||
exist_ok: bool = False,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
) -> Job[FunctionVersion]:
|
||||
"""Submit a scalar Python function for building and registration.
|
||||
|
||||
``exist_ok=True`` preserves an existing named version and its metadata.
|
||||
The default retains the existing version-creation behavior.
|
||||
|
||||
The server-side job builds the OCI image, then registers the completed
|
||||
artifact. The returned job has type ``query`` and the SQL query UUID as
|
||||
its ID. Waiting on it returns the immutable Function version.
|
||||
@@ -1158,14 +1196,24 @@ class DBConnection(EnforceOverrides):
|
||||
)
|
||||
|
||||
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:
|
||||
"""Create a named Secret in this database.
|
||||
|
||||
Fails if the name is taken, so a create never silently becomes a
|
||||
rotation. Nothing reads the value back: it is bound to a Function by
|
||||
Fails if the name is taken unless ``exist_ok=True``, which leaves the
|
||||
existing value unchanged. Use :meth:`alter_secret` to rotate a Secret.
|
||||
Nothing reads the value back: it is bound to a Function by
|
||||
name and resolved by the service when that Function runs. Local
|
||||
connections raise ``NotImplementedError``.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> db.create_secret("api-key", "credential", exist_ok=True) # doctest: +SKIP
|
||||
"""
|
||||
raise NotImplementedError(
|
||||
_append_doc_url(
|
||||
@@ -1248,7 +1296,12 @@ class DBConnection(EnforceOverrides):
|
||||
)
|
||||
|
||||
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:
|
||||
"""Create a view: a named query the database plans on every read.
|
||||
|
||||
@@ -1256,9 +1309,10 @@ class DBConnection(EnforceOverrides):
|
||||
is refused now rather than at the first read. A view holds no rows, and
|
||||
its readers see its sources as they are at read time.
|
||||
|
||||
There is no replace: a name already taken is an error, and changing a
|
||||
view is a drop followed by a create. LanceDB Embedded connections raise
|
||||
``NotImplementedError``.
|
||||
A name already taken is an error unless ``exist_ok=True``, which returns
|
||||
the existing view's stored query and schema without changing them.
|
||||
Changing a view is a drop followed by a create. LanceDB Embedded
|
||||
connections raise ``NotImplementedError``.
|
||||
|
||||
>>> import lancedb
|
||||
>>> db = lancedb.connect("db://my_database") # doctest: +SKIP
|
||||
@@ -1450,6 +1504,12 @@ class DBConnection(EnforceOverrides):
|
||||
specification, result, failure and event history, so there is no
|
||||
separate connection-level call for any of them.
|
||||
|
||||
For a column refresh, ``wait()`` returns a
|
||||
[RefreshColumnResult][lancedb.functions.RefreshColumnResult], including
|
||||
when the refresh was started through SQL. Other job types return
|
||||
``None`` from ``wait()``; their persisted result is available through
|
||||
``job.result`` after ``job.refresh()``.
|
||||
|
||||
Raises `JobNotFoundError` when the server has no such job, the way
|
||||
`open_table` does for a missing table.
|
||||
"""
|
||||
@@ -1460,6 +1520,22 @@ class DBConnection(EnforceOverrides):
|
||||
)
|
||||
)
|
||||
|
||||
def server_info(self) -> ServerInfo:
|
||||
"""Return the responding server's build and Function runtime information.
|
||||
|
||||
This call submits no query, Function, or job. The response is a
|
||||
JSON-compatible dictionary, convenient to include in a bug report::
|
||||
|
||||
info = db.server_info()
|
||||
print(info["query_node"]) # release, git_sha, build_date
|
||||
|
||||
Requires System Usage permission. Embedded connections and older
|
||||
servers without this endpoint raise ``NotImplementedError``.
|
||||
Different calls can reach different builds during a rolling upgrade.
|
||||
Configured images do not identify the version of a running job.
|
||||
"""
|
||||
raise NotImplementedError("Server build discovery requires a remote connection")
|
||||
|
||||
def list_gpu_classes(self) -> List[GpuClass]:
|
||||
"""List the operator-configured Function GPU classes.
|
||||
|
||||
@@ -2075,17 +2151,22 @@ class LanceDBConnection(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:
|
||||
"""Define a materialized view named ``name`` over the table ``source``.
|
||||
|
||||
``exist_ok=True`` preserves an existing view's definition, data and
|
||||
refresh settings without refreshing it. Existing names error by default.
|
||||
|
||||
LanceDB Embedded creation and refresh require a source build with the
|
||||
``experimental-functions`` Cargo feature. Published packages leave it
|
||||
disabled; LanceDB Enterprise operations remain available.
|
||||
@@ -2111,10 +2192,12 @@ class LanceDBConnection(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,
|
||||
)
|
||||
@@ -2125,12 +2208,14 @@ class LanceDBConnection(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]:
|
||||
@@ -2138,10 +2223,12 @@ class LanceDBConnection(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,
|
||||
)
|
||||
@@ -2199,6 +2286,7 @@ class LanceDBConnection(DBConnection):
|
||||
source_version: Optional[int] = None,
|
||||
source_tag: Optional[str] = None,
|
||||
is_shallow: bool = True,
|
||||
exist_ok: bool = False,
|
||||
) -> LanceTable:
|
||||
"""Clone a table from a source table.
|
||||
|
||||
@@ -2223,6 +2311,8 @@ class LanceDBConnection(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
|
||||
-------
|
||||
@@ -2238,6 +2328,7 @@ class LanceDBConnection(DBConnection):
|
||||
source_version=source_version,
|
||||
source_tag=source_tag,
|
||||
is_shallow=is_shallow,
|
||||
exist_ok=exist_ok,
|
||||
)
|
||||
)
|
||||
return LanceTable.open(
|
||||
@@ -2339,11 +2430,15 @@ class LanceDBConnection(DBConnection):
|
||||
definition: FunctionDefinition,
|
||||
*,
|
||||
secrets: Optional[Sequence[EnvVarSecret]] = None,
|
||||
exist_ok: bool = False,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
) -> 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,
|
||||
)
|
||||
)
|
||||
return Job(job)
|
||||
@@ -2431,6 +2526,7 @@ class LanceDBConnection(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(
|
||||
@@ -2448,6 +2544,7 @@ class LanceDBConnection(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,
|
||||
)
|
||||
)
|
||||
@@ -2486,9 +2583,18 @@ class LanceDBConnection(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(
|
||||
@@ -2532,10 +2638,17 @@ class LanceDBConnection(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
|
||||
@@ -3348,26 +3461,37 @@ class AsyncConnection(object):
|
||||
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,
|
||||
exist_ok: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
) -> AsyncMaterializedView:
|
||||
"""Define a materialized view named ``name`` over the table ``source``.
|
||||
|
||||
``exist_ok=True`` preserves an existing view's definition, data and
|
||||
refresh settings without refreshing it. Existing names error by default.
|
||||
|
||||
LanceDB Embedded creation and refresh require a source build with the
|
||||
``experimental-functions`` Cargo feature. Published packages leave it
|
||||
disabled; LanceDB Enterprise operations remain available.
|
||||
See
|
||||
[DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view].
|
||||
"""
|
||||
source, native_options = await self._materialized_view_source(
|
||||
source, select, where, limit
|
||||
)
|
||||
_validate_create_materialized_view(source, query, select, where, limit)
|
||||
if source is not None:
|
||||
source, native_options = await self._materialized_view_source(
|
||||
source, select, where, limit
|
||||
)
|
||||
else:
|
||||
native_options = {}
|
||||
if query is not None:
|
||||
native_options["query"] = query
|
||||
inner = await self._inner.create_materialized_view(
|
||||
name,
|
||||
source,
|
||||
@@ -3375,6 +3499,7 @@ class AsyncConnection(object):
|
||||
filter=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,
|
||||
**native_options,
|
||||
@@ -3384,24 +3509,35 @@ class AsyncConnection(object):
|
||||
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,
|
||||
exist_ok: bool = False,
|
||||
auto_refresh_enabled: Optional[bool] = None,
|
||||
auto_refresh_interval_seconds: Optional[float] = None,
|
||||
) -> AsyncJob[None]:
|
||||
"""Submit materialized-view creation and return its job.
|
||||
|
||||
``exist_ok=True`` preserves an existing view without refreshing it.
|
||||
A skipped creation returns a completed job without a registry job ID.
|
||||
|
||||
Wait for the returned job before opening or querying the view. In LanceDB
|
||||
Enterprise, creation uses SQL; ``job_type`` is ``"query"`` and ``id``
|
||||
identifies that query on this connection.
|
||||
"""
|
||||
source, native_options = await self._materialized_view_source(
|
||||
source, select, where, limit
|
||||
)
|
||||
_validate_create_materialized_view(source, query, select, where, limit)
|
||||
if source is not None:
|
||||
source, native_options = await self._materialized_view_source(
|
||||
source, select, where, limit
|
||||
)
|
||||
else:
|
||||
native_options = {}
|
||||
if query is not None:
|
||||
native_options["query"] = query
|
||||
inner = await self._inner.create_materialized_view_async(
|
||||
name,
|
||||
source,
|
||||
@@ -3409,6 +3545,7 @@ class AsyncConnection(object):
|
||||
filter=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,
|
||||
**native_options,
|
||||
@@ -3487,6 +3624,7 @@ class AsyncConnection(object):
|
||||
source_version: Optional[int] = None,
|
||||
source_tag: Optional[str] = None,
|
||||
is_shallow: bool = True,
|
||||
exist_ok: bool = False,
|
||||
) -> AsyncTable:
|
||||
"""Clone a table from a source table.
|
||||
|
||||
@@ -3511,6 +3649,8 @@ class AsyncConnection(object):
|
||||
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
|
||||
-------
|
||||
@@ -3525,6 +3665,7 @@ class AsyncConnection(object):
|
||||
source_version=source_version,
|
||||
source_tag=source_tag,
|
||||
is_shallow=is_shallow,
|
||||
exist_ok=exist_ok,
|
||||
)
|
||||
return AsyncTable(table)
|
||||
|
||||
@@ -3626,7 +3767,13 @@ class AsyncConnection(object):
|
||||
"""Open a server-side job by id. See
|
||||
[DBConnection.open_job][lancedb.db.DBConnection.open_job].
|
||||
"""
|
||||
return AsyncJob(await self._inner.open_job(job_id))
|
||||
return _opened_job(await self._inner.open_job(job_id))
|
||||
|
||||
async def server_info(self) -> ServerInfo:
|
||||
"""Read the responding server's build information. See
|
||||
[DBConnection.server_info][lancedb.db.DBConnection.server_info].
|
||||
"""
|
||||
return json.loads(await self._inner.server_info())
|
||||
|
||||
async def list_gpu_classes(self) -> List[GpuClass]:
|
||||
"""List configured Function GPU classes. See
|
||||
@@ -3639,10 +3786,14 @@ class AsyncConnection(object):
|
||||
definition: FunctionDefinition,
|
||||
*,
|
||||
secrets: Optional[Sequence[EnvVarSecret]] = None,
|
||||
exist_ok: bool = False,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
) -> AsyncJob[FunctionVersion]:
|
||||
"""Submit a scalar Python function for building and registration.
|
||||
|
||||
``exist_ok=True`` preserves an existing named version and its metadata.
|
||||
The default retains the existing version-creation behavior.
|
||||
|
||||
The server-side job builds the OCI image, then registers the completed
|
||||
artifact. The returned job has type ``query`` and the SQL query UUID as
|
||||
its ID. Waiting on it returns the immutable Function version.
|
||||
@@ -3656,7 +3807,7 @@ class AsyncConnection(object):
|
||||
raise TypeError("create_function_async requires a @function definition")
|
||||
request = definition.bind_secrets(secrets)
|
||||
inner = await self._inner.create_function_async(
|
||||
request.to_canonical_json(), namespace_path
|
||||
request.to_canonical_json(), namespace_path, exist_ok=exist_ok
|
||||
)
|
||||
return _typed_job(inner, FunctionVersion.from_json)
|
||||
|
||||
@@ -3776,6 +3927,7 @@ class AsyncConnection(object):
|
||||
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:
|
||||
"""Register cloud storage access using database-owned credential Secrets.
|
||||
@@ -3790,6 +3942,10 @@ class AsyncConnection(object):
|
||||
optionally set ``huggingface_token_secret`` to a Secret containing the
|
||||
token; omitting it selects anonymous access at the default rate limits.
|
||||
Registration returns setup instructions without verifying storage access.
|
||||
|
||||
``exist_ok=True`` returns the stored configuration unchanged when the
|
||||
integration exists, preserving its provider, prefix and credential
|
||||
bindings. Existing names are errors by default.
|
||||
"""
|
||||
azure_options = (
|
||||
azure_tenant_id_secret,
|
||||
@@ -3898,6 +4054,8 @@ class AsyncConnection(object):
|
||||
"aws_access_key_id_secret": reference(aws_access_key_id_secret),
|
||||
"aws_secret_access_key_secret": reference(aws_secret_access_key_secret),
|
||||
}
|
||||
if exist_ok:
|
||||
request["exist_ok"] = True
|
||||
info = await self._inner.create_storage_integration(
|
||||
validate_secret_name(name),
|
||||
json.dumps(request),
|
||||
@@ -3943,17 +4101,30 @@ class AsyncConnection(object):
|
||||
)
|
||||
|
||||
async 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:
|
||||
"""Create a named Secret in this database.
|
||||
|
||||
Fails if the name is taken, so a create never silently becomes a
|
||||
rotation. Nothing reads the value back.
|
||||
Fails if the name is taken unless ``exist_ok=True``, which leaves the
|
||||
existing value unchanged. Use :meth:`alter_secret` to rotate a Secret.
|
||||
Nothing reads the value back.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> await db.create_secret( # doctest: +SKIP
|
||||
... "api-key", "credential", exist_ok=True
|
||||
... )
|
||||
"""
|
||||
await self._inner.create_secret(
|
||||
validate_secret_name(name),
|
||||
value,
|
||||
list(validate_namespace_path(namespace_path)),
|
||||
exist_ok=exist_ok,
|
||||
)
|
||||
|
||||
async def alter_secret(
|
||||
@@ -4014,7 +4185,12 @@ class AsyncConnection(object):
|
||||
)
|
||||
|
||||
async 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:
|
||||
"""Create a view: a named query the database plans on every read.
|
||||
|
||||
@@ -4022,7 +4198,9 @@ class AsyncConnection(object):
|
||||
[DBConnection.create_view][lancedb.DBConnection.create_view].
|
||||
"""
|
||||
return _view_description(
|
||||
await self._inner.create_view(name, query, list(namespace_path or []))
|
||||
await self._inner.create_view(
|
||||
name, query, list(namespace_path or []), exist_ok=exist_ok
|
||||
)
|
||||
)
|
||||
|
||||
async def describe_view(
|
||||
|
||||
@@ -22,6 +22,7 @@ import symtable
|
||||
import json
|
||||
import linecache
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import textwrap
|
||||
@@ -29,6 +30,7 @@ import types
|
||||
import warnings
|
||||
from collections.abc import Mapping, Sequence
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
from typing import (
|
||||
Annotated,
|
||||
Any,
|
||||
@@ -1529,6 +1531,17 @@ def _infer_signature(
|
||||
return FunctionSignature(inputs=tuple(inputs), output=output)
|
||||
|
||||
|
||||
def _is_vectorized_callable(function: Callable[..., Any], *, method: bool) -> bool:
|
||||
parameters = _callable_parameters(function)
|
||||
if method:
|
||||
parameters = parameters[1:]
|
||||
annotations = get_type_hints(function, include_extras=True)
|
||||
annotated = tuple(annotations.get(parameter.name) for parameter in parameters)
|
||||
return (len(annotated) == 1 and annotated[0] is pa.RecordBatch) or (
|
||||
bool(annotated) and all(annotation is pa.Array for annotation in annotated)
|
||||
)
|
||||
|
||||
|
||||
# Both spellings strip from packaged source; `udf` is the deprecated alias.
|
||||
_DECORATOR_NAMES = frozenset({"function", "udf"})
|
||||
|
||||
@@ -1570,10 +1583,23 @@ _NAMESPACE_MODULES = frozenset(
|
||||
)
|
||||
|
||||
|
||||
def _namespace_acquisition(
|
||||
definition: ast.FunctionDef, references: set[str]
|
||||
) -> list[str]:
|
||||
found = set(references & _DYNAMIC_NAMESPACE_ACCESS)
|
||||
_NAMESPACE_HELPER_HINT = (
|
||||
"Move this code into an importable helper module supplied with code=, pip=, "
|
||||
"or conda=, then import and call the helper from the Function."
|
||||
)
|
||||
|
||||
|
||||
def _namespace_import_error(modules: Sequence[str]) -> ValueError:
|
||||
return ValueError(
|
||||
f"@function cannot package imports from namespace-access modules: {modules!r}. "
|
||||
f"Imports of {', '.join(sorted(_NAMESPACE_MODULES))} (including submodules) "
|
||||
"are blocked because they can access names outside the packaged "
|
||||
"Function's reconstructed module namespace. " + _NAMESPACE_HELPER_HINT
|
||||
)
|
||||
|
||||
|
||||
def _namespace_imports(definition: Union[ast.FunctionDef, ast.ClassDef]) -> list[str]:
|
||||
found: set[str] = set()
|
||||
for node in ast.walk(definition):
|
||||
if isinstance(node, ast.Import):
|
||||
found.update(
|
||||
@@ -1883,11 +1909,17 @@ class _SourcePackager:
|
||||
)
|
||||
source = ast.unparse(definition)
|
||||
references = _module_references(f"{_SOURCE_HEADER}\n\n{source}\n")
|
||||
dynamic = _namespace_acquisition(definition, references)
|
||||
dynamic = sorted(references & _DYNAMIC_NAMESPACE_ACCESS)
|
||||
if dynamic:
|
||||
raise ValueError(
|
||||
f"@function cannot package dynamic namespace access: {dynamic!r}"
|
||||
f"@function cannot package dynamic namespace access: {dynamic!r}. "
|
||||
"These operations can access names outside the packaged "
|
||||
"Function's reconstructed module namespace. Reference dependencies "
|
||||
"explicitly. " + _NAMESPACE_HELPER_HINT
|
||||
)
|
||||
namespace_imports = _namespace_imports(definition)
|
||||
if namespace_imports:
|
||||
raise _namespace_import_error(namespace_imports)
|
||||
self._warn_unshipped_direct_imports(definition)
|
||||
self._packaged.add(id(target))
|
||||
self._claim(target.__name__, ("definition", id(target)))
|
||||
@@ -1982,10 +2014,7 @@ class _SourcePackager:
|
||||
return f"from lance_blob import BlobReader as {name}"
|
||||
if isinstance(value, types.ModuleType):
|
||||
if value.__name__.split(".")[0] in _NAMESPACE_MODULES:
|
||||
raise ValueError(
|
||||
"@function cannot package dynamic namespace access: "
|
||||
f"{value.__name__!r}"
|
||||
)
|
||||
raise _namespace_import_error([value.__name__])
|
||||
try:
|
||||
imported = importlib.import_module(value.__name__)
|
||||
except ImportError:
|
||||
@@ -2077,18 +2106,12 @@ class _SourcePackager:
|
||||
self._require_importable(node.module)
|
||||
|
||||
|
||||
def _code_files(modules: Sequence[Any]) -> tuple[dict[str, str], frozenset[str]]:
|
||||
"""The Python source files of the modules and packages in ``code=``,
|
||||
keyed by their path on the Function's import path.
|
||||
|
||||
Package resources are not part of the source artifact. Warn about files
|
||||
and excluded directories that the walk leaves behind instead of silently
|
||||
producing a Function that will fail later on the worker.
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
def _code_files(
|
||||
modules: Sequence[Any],
|
||||
) -> tuple[dict[str, str], dict[str, str], frozenset[str]]:
|
||||
"""Source and byte-preserving package resources on the Function import path."""
|
||||
files: dict[str, str] = {}
|
||||
resources: dict[str, str] = {}
|
||||
names: set[str] = set()
|
||||
for module in modules:
|
||||
if not isinstance(module, types.ModuleType):
|
||||
@@ -2122,35 +2145,50 @@ def _code_files(modules: Sequence[Any]) -> tuple[dict[str, str], frozenset[str]]
|
||||
sources = []
|
||||
skipped = set()
|
||||
for directory, subdirectories, filenames in os.walk(root):
|
||||
# Only importable modules travel: data files, caches, and
|
||||
# directories that are not identifiers cannot be imported.
|
||||
kept = []
|
||||
for child in sorted(subdirectories):
|
||||
if child == "__pycache__":
|
||||
path = Path(directory) / child
|
||||
if child == "__pycache__" or child.startswith("."):
|
||||
continue
|
||||
if _SOURCE_PATH_COMPONENT.fullmatch(child):
|
||||
if not path.is_symlink() and re.fullmatch(
|
||||
r"[A-Za-z0-9_][A-Za-z0-9_.-]*", child
|
||||
):
|
||||
kept.append(child)
|
||||
else:
|
||||
relative = (Path(directory) / child).relative_to(root)
|
||||
relative = path.relative_to(root)
|
||||
skipped.add(f"{name}/{relative.as_posix()}/")
|
||||
subdirectories[:] = kept
|
||||
for filename in sorted(filenames):
|
||||
path = Path(directory) / filename
|
||||
stem, suffix = os.path.splitext(filename)
|
||||
if suffix in {".pyc", ".pyo"}:
|
||||
if suffix in {".pyc", ".pyo"} or filename.startswith("."):
|
||||
continue
|
||||
if suffix == ".py" and _SOURCE_PATH_COMPONENT.fullmatch(stem):
|
||||
sources.append(Path(directory) / filename)
|
||||
relative = path.relative_to(root)
|
||||
key = f"{name}/{relative.as_posix()}"
|
||||
if (
|
||||
path.is_symlink()
|
||||
or not path.is_file()
|
||||
or not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.-]*", filename)
|
||||
):
|
||||
skipped.add(key)
|
||||
elif suffix == ".py":
|
||||
if all(
|
||||
_SOURCE_PATH_COMPONENT.fullmatch(part)
|
||||
for part in relative.with_suffix("").parts
|
||||
):
|
||||
sources.append(path)
|
||||
else:
|
||||
skipped.add(key)
|
||||
else:
|
||||
relative = (Path(directory) / filename).relative_to(root)
|
||||
skipped.add(f"{name}/{relative.as_posix()}")
|
||||
resources[key] = base64.b64encode(path.read_bytes()).decode(
|
||||
"ascii"
|
||||
)
|
||||
if skipped:
|
||||
skipped_paths = ", ".join(sorted(skipped))
|
||||
warnings.warn(
|
||||
f"code= ships Python .py modules only; package {name!r} "
|
||||
f"will not include: {skipped_paths}. Install a package that "
|
||||
"includes the required resources with pip= or conda=, and "
|
||||
f"remove {name!r} from code= so the copied package cannot "
|
||||
"shadow the installed distribution.",
|
||||
"code= cannot ship these package paths: "
|
||||
f"{', '.join(sorted(skipped))}. "
|
||||
"Use regular files with safe relative names and importable "
|
||||
"Python module names.",
|
||||
UserWarning,
|
||||
)
|
||||
for path in sources:
|
||||
@@ -2161,12 +2199,12 @@ def _code_files(modules: Sequence[Any]) -> tuple[dict[str, str], frozenset[str]]
|
||||
if not file or not file.endswith(".py"):
|
||||
raise ValueError(f"code= ships Python source; module {name!r} has none")
|
||||
files[f"{name}.py"] = _source_text(Path(file))
|
||||
return files, frozenset(names)
|
||||
return files, resources, frozenset(names)
|
||||
|
||||
|
||||
def _source_text(path) -> str:
|
||||
try:
|
||||
return path.read_text(encoding="utf-8")
|
||||
return path.read_bytes().decode("utf-8")
|
||||
except UnicodeDecodeError as error:
|
||||
raise ValueError(f"code= ships UTF-8 source; {path} is not UTF-8") from error
|
||||
|
||||
@@ -2286,7 +2324,9 @@ class FunctionDefinition:
|
||||
once per row. A callable whose parameters are all annotated as
|
||||
``pyarrow.Array`` receives whole Arrow arrays and returns a
|
||||
``pyarrow.Array`` instead. This authoring choice is independent of the
|
||||
internal artifact adapter in the registration request.
|
||||
internal artifact adapter in the registration request. GPU Functions should
|
||||
use the Arrow form when the model supports batches: a scalar GPU callable is
|
||||
invoked once per row and leaves the model's own batching unavailable.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -2408,14 +2448,29 @@ class FunctionDefinition:
|
||||
signature = signature._copy(update={"initialization": initialization})
|
||||
else:
|
||||
signature = _infer_signature(function, input_schema, output_schema)
|
||||
code_files, code_modules = _code_files(code)
|
||||
if gpu_marker is not None:
|
||||
call = _class_call(function) if is_class else function
|
||||
if not _is_vectorized_callable(call, method=is_class):
|
||||
warnings.warn(
|
||||
f"GPU Function {function_name!r} uses a scalar callable, so each "
|
||||
"row invokes it separately and its model batch is not inferred. "
|
||||
"For GPU throughput, annotate every input as pyarrow.Array or "
|
||||
"take one pyarrow.RecordBatch, provide input_schema and "
|
||||
"output_schema, and batch inside that callable.",
|
||||
UserWarning,
|
||||
stacklevel=3,
|
||||
)
|
||||
code_files, code_resources, code_modules = _code_files(code)
|
||||
entry_source = _SourcePackager(
|
||||
code_modules, frozenset(_requirement_name(package) for package in packages)
|
||||
).package(function, signature)
|
||||
if code_files:
|
||||
kind = _PYTHON_BUNDLE_ARTIFACT
|
||||
bundle = {"files": {**code_files, _SOURCE_ENTRY_FILE: entry_source}}
|
||||
if code_resources:
|
||||
bundle["resources"] = code_resources
|
||||
source = json.dumps(
|
||||
{"files": {**code_files, _SOURCE_ENTRY_FILE: entry_source}},
|
||||
bundle,
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
@@ -2663,13 +2718,28 @@ def function(
|
||||
Other global values, including Arrow types and schemas, lists, dictionaries,
|
||||
sets, and NumPy arrays, cannot be captured as literals. Define them inside
|
||||
the function or class body instead.
|
||||
Closures, lambdas, nested definitions, mutable module-level
|
||||
objects, code that reaches the module namespace another way
|
||||
(``globals()``/``eval``, ``sys.modules``, ``builtins``), and a
|
||||
Closures, lambdas, nested definitions, mutable module-level objects, and a
|
||||
non-standard ``__builtins__`` are rejected where they can be seen and
|
||||
otherwise unsupported. Changing any packaged source, including a module in
|
||||
``code``, produces a new Function version; the environment built from
|
||||
``pip`` or ``conda`` is reused.
|
||||
otherwise unsupported.
|
||||
|
||||
**Namespace restrictions.** The packaged source cannot import ``sys``,
|
||||
``builtins``, ``importlib``, ``inspect``, ``gc``, ``ctypes``, or ``types``,
|
||||
including submodules such as ``ctypes.util`` and ``importlib.metadata``.
|
||||
Referencing a module-level alias for one of these modules is also rejected.
|
||||
References to ``globals``, ``locals``, ``vars``, ``eval``, ``exec``,
|
||||
``compile``, or ``__import__`` are rejected as dynamic namespace access.
|
||||
These restrictions are conservative: even ordinary uses such as
|
||||
``ctypes.util.find_library`` or ``sys.version`` are blocked because these
|
||||
modules can reach names outside the reconstructed Function namespace.
|
||||
Move such code into an importable helper module supplied with ``code=``,
|
||||
``pip=``, or ``conda=``, then import and call the helper from the Function.
|
||||
Helpers imported normally keep their own module namespace; these checks do
|
||||
not scan their bodies. A helper defined in ``__main__`` is packaged by source
|
||||
and is subject to the same checks.
|
||||
|
||||
Changing any packaged source, including a module in ``code``, produces a
|
||||
new Function version; the environment built from ``pip`` or ``conda`` is
|
||||
reused.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -2746,13 +2816,15 @@ def function(
|
||||
immutable Function version; per-refresh aggregate GPU budgets are
|
||||
selected through ``refresh_column`` instead of registration.
|
||||
code : sequence of module, optional
|
||||
Top-level modules or packages whose importable ``.py`` files ship
|
||||
with the Function and are importable by their own names. Package data
|
||||
files are not copied. To use a package that includes required data
|
||||
resources, install it with ``pip=`` or ``conda=`` and remove that
|
||||
package from ``code=`` so the copied Python package cannot shadow the
|
||||
installed distribution. ``@function`` warns when it skips files from a
|
||||
package in ``code=``.
|
||||
Top-level modules or packages shipped with the Function and importable
|
||||
by their own names. Package resources, including binary data and
|
||||
vendored subpackages, retain their relative paths and exact bytes.
|
||||
Source and resource changes both create a new Function version.
|
||||
Caches and hidden paths are excluded. Symlinks and unsafe paths are
|
||||
skipped with a warning. Compiled dependencies must match the remote
|
||||
runtime; use ``pip=`` or ``conda=`` for platform-specific distributions
|
||||
and ``models=`` for large model snapshots. Resource bundles require
|
||||
server support for the ``python_bundle.resources`` field.
|
||||
models : sequence of HuggingFaceModel, optional
|
||||
Immutable Hugging Face repository snapshots prepared in the worker
|
||||
node cache before user code starts. A Function may declare a
|
||||
|
||||
@@ -17,6 +17,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")
|
||||
@@ -424,6 +425,32 @@ 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.
|
||||
|
||||
@@ -648,6 +675,21 @@ 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.
|
||||
|
||||
@@ -692,3 +734,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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -696,14 +696,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
|
||||
@@ -715,12 +717,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
|
||||
)
|
||||
@@ -730,25 +734,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)
|
||||
@@ -1339,25 +1347,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.
|
||||
@@ -1366,25 +1378,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":
|
||||
|
||||
+110
-28
@@ -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
|
||||
@@ -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."
|
||||
@@ -1297,9 +1335,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 +1345,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 +1671,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 +1693,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 +1711,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 +2441,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()
|
||||
@@ -2599,8 +2655,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 +2905,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 +3618,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 +3824,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 +3844,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 +3884,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 +3967,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 +3977,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
|
||||
)
|
||||
@@ -4508,7 +4585,9 @@ class AsyncFTSQuery(AsyncStandardQuery):
|
||||
)
|
||||
results = pa.Table.from_batches(await reader.read_all(), reader.schema)
|
||||
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)
|
||||
|
||||
|
||||
@@ -4835,7 +4914,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 +5108,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):
|
||||
|
||||
@@ -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
|
||||
@@ -573,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.
|
||||
|
||||
@@ -592,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
|
||||
-------
|
||||
@@ -609,6 +615,7 @@ class RemoteDBConnection(DBConnection):
|
||||
source_version=source_version,
|
||||
source_tag=source_tag,
|
||||
is_shallow=is_shallow,
|
||||
exist_ok=exist_ok,
|
||||
)
|
||||
)
|
||||
return RemoteTable(
|
||||
@@ -789,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:
|
||||
@@ -804,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,
|
||||
)
|
||||
@@ -825,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]:
|
||||
@@ -838,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,
|
||||
)
|
||||
@@ -965,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
|
||||
@@ -978,11 +1000,15 @@ class RemoteDBConnection(DBConnection):
|
||||
definition: FunctionDefinition,
|
||||
*,
|
||||
secrets: Optional[Sequence[EnvVarSecret]] = None,
|
||||
exist_ok: bool = False,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
) -> 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,
|
||||
)
|
||||
)
|
||||
return Job(job)
|
||||
@@ -1073,6 +1099,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(
|
||||
@@ -1090,6 +1117,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,
|
||||
)
|
||||
)
|
||||
@@ -1128,9 +1156,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(
|
||||
@@ -1174,10 +1211,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
|
||||
|
||||
@@ -369,6 +369,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.
|
||||
|
||||
@@ -395,6 +396,7 @@ class RemoteTable(Table):
|
||||
self._table.create_index(
|
||||
column,
|
||||
replace=replace,
|
||||
exist_ok=exist_ok,
|
||||
config=config,
|
||||
wait_timeout=wait_timeout,
|
||||
name=name,
|
||||
@@ -433,6 +435,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.
|
||||
|
||||
@@ -492,6 +495,7 @@ class RemoteTable(Table):
|
||||
self._table.create_index(
|
||||
field_names,
|
||||
replace=replace,
|
||||
exist_ok=exist_ok,
|
||||
config=config,
|
||||
name=name,
|
||||
wait_timeout=wait_timeout,
|
||||
@@ -516,6 +520,7 @@ class RemoteTable(Table):
|
||||
replace: bool = ...,
|
||||
wait_timeout: Optional[timedelta] = ...,
|
||||
name: Optional[str] = ...,
|
||||
exist_ok: bool = ...,
|
||||
train: bool = ...,
|
||||
) -> None: ...
|
||||
|
||||
@@ -541,6 +546,7 @@ class RemoteTable(Table):
|
||||
*,
|
||||
wait_timeout: Optional[timedelta] = ...,
|
||||
name: Optional[str] = ...,
|
||||
exist_ok: bool = ...,
|
||||
train: bool = ...,
|
||||
target_partition_size: Optional[int] = ...,
|
||||
) -> None: ...
|
||||
@@ -572,6 +578,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,
|
||||
):
|
||||
@@ -675,6 +682,7 @@ class RemoteTable(Table):
|
||||
self._table.create_index(
|
||||
column,
|
||||
replace=replace,
|
||||
exist_ok=exist_ok,
|
||||
config=config,
|
||||
wait_timeout=wait_timeout,
|
||||
name=name,
|
||||
@@ -690,6 +698,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.
|
||||
@@ -702,6 +711,7 @@ class RemoteTable(Table):
|
||||
self._table.create_index_async(
|
||||
column,
|
||||
replace=replace,
|
||||
exist_ok=exist_ok,
|
||||
config=config,
|
||||
wait_timeout=wait_timeout,
|
||||
name=name,
|
||||
@@ -719,6 +729,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].
|
||||
|
||||
@@ -753,6 +764,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
|
||||
-------
|
||||
@@ -770,6 +784,7 @@ class RemoteTable(Table):
|
||||
progress=progress,
|
||||
write_parallelism=write_parallelism,
|
||||
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
|
||||
retries=retries,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
@@ -1420,13 +1435,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:
|
||||
"""
|
||||
|
||||
@@ -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]
|
||||
+139
-17
@@ -40,6 +40,7 @@ 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,
|
||||
@@ -167,6 +168,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
|
||||
@@ -1833,6 +1864,7 @@ class Table(ABC):
|
||||
replace: bool = ...,
|
||||
wait_timeout: Optional[timedelta] = ...,
|
||||
name: Optional[str] = ...,
|
||||
exist_ok: bool = ...,
|
||||
train: bool = ...,
|
||||
) -> None: ...
|
||||
|
||||
@@ -1858,6 +1890,7 @@ class Table(ABC):
|
||||
*,
|
||||
wait_timeout: Optional[timedelta] = ...,
|
||||
name: Optional[str] = ...,
|
||||
exist_ok: bool = ...,
|
||||
train: bool = ...,
|
||||
target_partition_size: Optional[int] = ...,
|
||||
) -> None: ...
|
||||
@@ -1889,6 +1922,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 +1946,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 +2004,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 +2097,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 +2182,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 +2295,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 +2356,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
|
||||
-------
|
||||
@@ -2655,8 +2700,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 +2713,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 +2724,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 +2735,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 +2747,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 +2758,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 +2775,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(
|
||||
@@ -3998,13 +4060,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:
|
||||
@@ -4288,6 +4357,7 @@ class LanceTable(Table):
|
||||
replace: bool = ...,
|
||||
wait_timeout: Optional[timedelta] = ...,
|
||||
name: Optional[str] = ...,
|
||||
exist_ok: bool = ...,
|
||||
train: bool = ...,
|
||||
) -> None: ...
|
||||
|
||||
@@ -4313,6 +4383,7 @@ class LanceTable(Table):
|
||||
*,
|
||||
wait_timeout: Optional[timedelta] = ...,
|
||||
name: Optional[str] = ...,
|
||||
exist_ok: bool = ...,
|
||||
train: bool = ...,
|
||||
target_partition_size: Optional[int] = ...,
|
||||
) -> None: ...
|
||||
@@ -4344,6 +4415,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,
|
||||
):
|
||||
@@ -4367,6 +4439,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
|
||||
@@ -4435,8 +4510,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,
|
||||
@@ -4462,7 +4539,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",
|
||||
@@ -4479,7 +4555,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"),
|
||||
@@ -4501,6 +4580,7 @@ class LanceTable(Table):
|
||||
self._table.create_index(
|
||||
column,
|
||||
replace=replace,
|
||||
exist_ok=exist_ok,
|
||||
config=config,
|
||||
wait_timeout=wait_timeout,
|
||||
name=name,
|
||||
@@ -4516,6 +4596,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.
|
||||
@@ -4534,6 +4615,7 @@ class LanceTable(Table):
|
||||
self._table.create_index_async(
|
||||
column,
|
||||
replace=replace,
|
||||
exist_ok=exist_ok,
|
||||
config=config,
|
||||
wait_timeout=wait_timeout,
|
||||
name=name,
|
||||
@@ -4654,6 +4736,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.
|
||||
|
||||
@@ -4680,6 +4763,7 @@ class LanceTable(Table):
|
||||
self._table.create_index(
|
||||
column,
|
||||
replace=replace,
|
||||
exist_ok=exist_ok,
|
||||
config=config,
|
||||
wait_timeout=wait_timeout,
|
||||
name=name,
|
||||
@@ -4717,6 +4801,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.
|
||||
|
||||
@@ -4778,6 +4863,7 @@ class LanceTable(Table):
|
||||
self._table.create_index(
|
||||
field_names,
|
||||
replace=replace,
|
||||
exist_ok=exist_ok,
|
||||
config=config,
|
||||
name=name,
|
||||
wait_timeout=wait_timeout,
|
||||
@@ -4800,6 +4886,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
|
||||
@@ -4831,6 +4918,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
|
||||
-------
|
||||
@@ -4848,6 +4939,7 @@ class LanceTable(Table):
|
||||
progress=progress,
|
||||
write_parallelism=write_parallelism,
|
||||
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
|
||||
retries=retries,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
@@ -6770,6 +6862,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
|
||||
@@ -6800,6 +6893,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.
|
||||
@@ -6855,6 +6951,7 @@ class AsyncTable:
|
||||
column,
|
||||
index=config,
|
||||
replace=replace,
|
||||
exist_ok=exist_ok,
|
||||
wait_timeout=wait_timeout,
|
||||
name=name,
|
||||
train=train,
|
||||
@@ -6892,6 +6989,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.
|
||||
@@ -6910,6 +7008,7 @@ class AsyncTable:
|
||||
column,
|
||||
index=config,
|
||||
replace=replace,
|
||||
exist_ok=exist_ok,
|
||||
wait_timeout=wait_timeout,
|
||||
name=name,
|
||||
train=train,
|
||||
@@ -7059,6 +7158,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].
|
||||
|
||||
@@ -7097,6 +7197,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()
|
||||
@@ -7151,6 +7255,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):
|
||||
@@ -8614,32 +8719,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.
|
||||
|
||||
@@ -8654,7 +8776,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:
|
||||
|
||||
@@ -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 == []
|
||||
@@ -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
|
||||
@@ -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}]
|
||||
@@ -18,6 +18,7 @@ import subprocess
|
||||
import sys
|
||||
import typing
|
||||
import urllib.parse
|
||||
import warnings
|
||||
from typing import Optional
|
||||
|
||||
import pyarrow as pa
|
||||
@@ -658,9 +659,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 +713,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 [
|
||||
{
|
||||
@@ -888,7 +945,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 +956,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 +967,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"
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -7,6 +7,7 @@ from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import importlib
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -466,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(
|
||||
@@ -508,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
|
||||
):
|
||||
@@ -552,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)
|
||||
@@ -612,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",
|
||||
{
|
||||
@@ -628,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",
|
||||
|
||||
@@ -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"]
|
||||
|
||||
@@ -754,6 +754,46 @@ async def test_query_wait_timeout_requires_keeping_original_handle():
|
||||
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):
|
||||
|
||||
@@ -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)
|
||||
@@ -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()
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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")
|
||||
|
||||
@@ -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"]
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
|
||||
@@ -6292,3 +6304,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
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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"]
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
+77
-14
@@ -24,8 +24,9 @@ use lancedb::{
|
||||
connection::NamespaceClientPushdownOperation,
|
||||
database::namespace::LanceNamespaceDatabase,
|
||||
database::{CreateTableMode, Database, ReadConsistency},
|
||||
function::GpuClass as LanceGpuClass,
|
||||
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)
|
||||
@@ -1276,6 +1331,14 @@ impl Connection {
|
||||
))
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
@@ -159,6 +159,11 @@ impl Job {
|
||||
})
|
||||
}
|
||||
|
||||
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>,
|
||||
|
||||
+53
-6
@@ -1243,6 +1243,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()
|
||||
}
|
||||
@@ -1462,7 +1471,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,
|
||||
@@ -1470,6 +1479,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()?
|
||||
@@ -1482,6 +1492,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);
|
||||
}
|
||||
@@ -1615,7 +1628,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,
|
||||
@@ -1624,6 +1638,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
|
||||
@@ -1632,6 +1647,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);
|
||||
}
|
||||
@@ -1648,7 +1664,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,
|
||||
@@ -1657,6 +1674,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
|
||||
@@ -1665,6 +1683,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);
|
||||
}
|
||||
@@ -1965,14 +1984,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
|
||||
@@ -2019,11 +2052,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 {
|
||||
@@ -2031,6 +2065,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| {
|
||||
@@ -2043,16 +2084,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),
|
||||
|
||||
Generated
+9
-8
@@ -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.0b18" },
|
||||
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b21" },
|
||||
{ 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.0b18"
|
||||
version = "15.0.0b21"
|
||||
source = { registry = "https://pypi.fury.io/lance-format/" }
|
||||
dependencies = [
|
||||
{ name = "lance-namespace" },
|
||||
@@ -4312,12 +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_Rs8tZ/pylance-15.0.0b18-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:255e782b016555c3f8072bb3d2a33dfdb3cb67b5ccf10a6a999fd007c58b16ab" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1D7wV0/pylance-15.0.0b18-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:11adaf98d8e2960bb25d30315720cb93a2ac291d3fec29cd9726e1085cd9e40f" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_pK9DO/pylance-15.0.0b18-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aea39d714821d561b655f2d046129700a5ff95c3352813edd6af15ec6d9d29e2" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_28PrEd/pylance-15.0.0b18-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:c19b3293be41ae4a87a67123e8d7233b0c5508aa39012c26525ab9d19884386d" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_kV8Di/pylance-15.0.0b18-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:7a48686ab4777b58fe9f0e17a68048b779c071879d48035afb3e79b81b9d47a1" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1pAhhP/pylance-15.0.0b18-cp310-abi3-win_amd64.whl", hash = "sha256:dc32e4731b78c8325d1bd0f0e23f13f7dab7ed1f0fcda47d52661d44c8bfc83a" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_mzSgZ/pylance-15.0.0b21-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:251682fe543131c371a6af45d8c672ea53b6ee83b5f777885f15ce383144d820" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1UfHMZ/pylance-15.0.0b21-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9cbc92a2bac73f179a382e1bdb495fa3631a17e35687c2f00721af073eeb445a" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_Ugv8b/pylance-15.0.0b21-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:59bd56971aa41a21783e938e18a752fdaa97a37cfdd8940ed2f37d0c665d0fdd" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1mO0GG/pylance-15.0.0b21-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a0da124e95240e448daa981664a5e64e87bc99411eb4c408cbd50147096654f4" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1n5aaN/pylance-15.0.0b21-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:341a1abcd62e6134982968a5236f8128d88211ab288d329924a812d87e555555" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_RVDDc/pylance-15.0.0b21-cp310-abi3-win_amd64.whl", hash = "sha256:f5dbd51b2553d70b927c537672bad41075cd8615f5e951008d7cd59c7365e587" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_GJeqW/pylance-15.0.0b21-cp310-abi3-win_arm64.whl", hash = "sha256:ddd517d555c6674c94b0eeee78ed6c3c3ac7b32319e27c47dd6f78a2639d6837" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
Reference in New Issue
Block a user