Merge remote-tracking branch 'origin/main' into xuanwo/blob-beta19-current-consumers-20261112

This commit is contained in:
Xuanwo
2026-11-13 06:37:08 +00:00
48 changed files with 5102 additions and 242 deletions
+7 -2
View File
@@ -185,6 +185,7 @@ 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
@@ -348,24 +349,28 @@ 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,
) -> 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,
) -> Job: ...
def list_materialized_views(
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
+69 -14
View File
@@ -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 (
@@ -78,6 +79,7 @@ from .materialized_view import (
MaterializedViewSource,
SelectArg,
normalize_select,
_validate_create_materialized_view,
)
from .secrets import (
EnvVarSecret,
@@ -697,8 +699,9 @@ 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,
@@ -721,8 +724,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 +751,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,8 +769,9 @@ 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,
@@ -1476,6 +1491,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.
@@ -2091,8 +2122,9 @@ 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,
@@ -2127,6 +2159,7 @@ class LanceDBConnection(DBConnection):
self._conn.create_materialized_view(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
@@ -2141,8 +2174,9 @@ 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,
@@ -2154,6 +2188,7 @@ class LanceDBConnection(DBConnection):
self._conn.create_materialized_view_async(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
@@ -3373,8 +3408,9 @@ 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,
@@ -3390,9 +3426,15 @@ class AsyncConnection(object):
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,
@@ -3409,8 +3451,9 @@ 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,
@@ -3424,9 +3467,15 @@ class AsyncConnection(object):
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,
@@ -3653,6 +3702,12 @@ class AsyncConnection(object):
"""
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
[DBConnection.list_gpu_classes][lancedb.db.DBConnection.list_gpu_classes].
@@ -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
+12 -4
View File
@@ -696,8 +696,9 @@ 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,
@@ -715,6 +716,7 @@ class LanceNamespaceDBConnection(DBConnection):
self._inner.create_materialized_view(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
@@ -730,8 +732,9 @@ 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,
@@ -743,6 +746,7 @@ class LanceNamespaceDBConnection(DBConnection):
self._inner.create_materialized_view_async(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
@@ -1339,8 +1343,9 @@ 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,
@@ -1352,6 +1357,7 @@ class AsyncLanceNamespaceDBConnection:
view = await self._inner.create_materialized_view(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
@@ -1366,8 +1372,9 @@ 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,
@@ -1379,6 +1386,7 @@ class AsyncLanceNamespaceDBConnection:
return await self._inner.create_materialized_view_async(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
+15 -2
View File
@@ -4,6 +4,8 @@
from __future__ import annotations
from lancedb.server_info import ServerInfo
from dataclasses import replace
from datetime import timedelta
import json
@@ -790,8 +792,9 @@ 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,
@@ -805,6 +808,7 @@ class RemoteDBConnection(DBConnection):
self._conn.create_materialized_view(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
@@ -826,8 +830,9 @@ 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,
@@ -839,6 +844,7 @@ class RemoteDBConnection(DBConnection):
self._conn.create_materialized_view_async(
name,
source,
query=query,
select=select,
where=where,
limit=limit,
@@ -966,6 +972,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
+33
View File
@@ -0,0 +1,33 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Remote server build information returned as JSON-compatible dictionaries."""
from typing import Optional, TypedDict
class ServerBuildInfo(TypedDict):
"""Immutable identity compiled into a server executable."""
release: str
git_sha: str
build_date: Optional[str]
class ServerInfo(TypedDict):
"""The responding query node and its configured Function runtime.
``query_node`` can be ``None`` when the executable has no build metadata.
``build_date`` is a UTC RFC 3339 timestamp when known. During a rolling
upgrade, separate requests can reach different query-node builds.
Configured images do not establish the version of a running job.
"""
query_node: Optional[ServerBuildInfo]
lance_version: str
lancedb_version: str
function_worker_protocol_version: int
configured_query_node_image: Optional[str]
configured_job_worker_image: Optional[str]
configured_sql_job_image: Optional[str]
configured_gpu_worker_image: Optional[str]
+10 -2
View File
@@ -2661,8 +2661,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
@@ -8652,6 +8656,10 @@ 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(
+380
View File
@@ -0,0 +1,380 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
"""Exercise the public sync/async range APIs over bounded loopback HTTP."""
import asyncio
import hashlib
import json
from pathlib import Path
import socket
import threading
import lancedb._lancedb as native
import pyarrow as pa
import pytest
from lancedb.remote.errors import HttpError, TableNotFoundError
from test_remote_db import mock_lancedb_connection
MIB = 1024 * 1024
IDENTITY = "v1:" + "a" * 64
ROUTE = "/v1/table/test/fetch_blob_ranges/"
def payload(row, offset, length, version):
pattern = bytes((row * 17 + i + version) % 251 for i in range(251))
start = offset % 251
return (pattern * ((start + length + 250) // 251))[start : start + length]
class RangeServer:
def __init__(self, fault=None):
self.fault = fault
self.calls = []
self.fetches = []
self.identities = []
self.stalled = threading.Event()
self.release = threading.Event()
def __call__(self, request):
request.connection.settimeout(15)
size = int(request.headers.get("Content-Length", 0))
assert size <= 256 * 1024
body = json.loads(request.rfile.read(size) or b"{}")
self.calls.append((request.command, request.path, body))
if request.path in (
"/v1/table/test/describe/",
"/v1/table/test/branches/list/",
):
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.send_header("phalanx-version", "1.13.0-beta.0")
if request.path.endswith("/describe/"):
request.send_header("x-lancedb-blob-ranges", "1")
request.end_headers()
response = (
{
"branches": {
"experiment": {
"parentBranch": None,
"parentVersion": 1,
"createAt": 1,
"manifestSize": 1,
}
}
}
if request.path.endswith("branches/list/")
else {"version": 8, "schema": {"fields": []}}
)
request.wfile.write(json.dumps(response).encode())
return
assert (request.command, request.path) == ("POST", ROUTE)
self.fetches.append(body)
self.identities.append(request.headers.get("x-lancedb-query-snapshot"))
assert body["column"] == "image"
assert body["branch"] == "experiment"
ranges = body["ranges"]
assert len(ranges) <= 1024
assert sum(r["length"] for r in ranges) <= 64 * MIB
version = body["version"] or (7 if len(self.fetches) == 1 else 8)
values = [
None
if r["row_id"] == 20
else payload(r["row_id"], r["offset"], r["length"], version)
for r in ranges
]
fault = (
self.fault
if len(self.fetches) > 1 or str(self.fault).startswith("first-")
else None
)
if fault in ("recreated", "gone"):
request.send_response(400 if fault == "recreated" else 404)
request.end_headers()
request.wfile.write(
b"query snapshot identity mismatch: source gone or replaced"
)
return
if fault == "stall" and len(self.fetches) == 2:
request.send_response(200)
request.send_header("Content-Type", "application/vnd.apache.arrow.stream")
request.send_header("x-lancedb-version", str(version))
request.send_header("x-lancedb-query-snapshot", IDENTITY)
request.end_headers()
request.wfile.flush()
self.stalled.set()
assert self.release.wait(15), "test did not release stalled response"
return
if fault == "structured400":
request.send_response(400)
request.send_header("x-lancedb-error-code", "invalid_input")
request.end_headers()
request.wfile.write(b'{"error":"range exceeds blob size"}')
return
if isinstance(fault, int):
request.send_response(fault)
request.end_headers()
request.wfile.write(b"ordinary server failure")
return
if fault == "disconnect":
request.connection.shutdown(socket.SHUT_RDWR)
return
column = "wrong" if fault == "column" else "value"
data_type = pa.binary() if fault == "type" else pa.large_binary()
if fault == "count":
values = []
elif fault == "length":
values = [b""]
batch = pa.table({column: pa.array(values, type=data_type)})
sink = pa.BufferOutputStream()
with pa.ipc.new_stream(sink, batch.schema) as writer:
writer.write_table(batch, max_chunksize=257)
ipc = sink.getvalue().to_pybytes()
if fault == "eos":
ipc = ipc[:-8]
elif fault == "body":
ipc = ipc[: len(ipc) // 2]
request.send_response(200)
request.send_header("Content-Type", "application/vnd.apache.arrow.stream")
if fault != "version":
request.send_header("x-lancedb-version", str(version))
if fault not in ("missing-identity", "first-missing-identity"):
identity = (
"broken"
if fault == "first-invalid-identity"
else "v1:" + "b" * 64
if fault == "wrong-identity"
else IDENTITY
)
request.send_header("x-lancedb-query-snapshot", identity)
request.send_header(
"Content-Length", str(len(ipc) + (10 if fault == "transport" else 0))
)
request.end_headers()
for i in range(0, len(ipc), 8192):
request.wfile.write(ipc[i : i + 8192])
async def fetch(table, requests, use_async):
result = table.fetch_blob_ranges("image", requests)
return await result if use_async else result
def api(db, use_async, version=None):
table = db.open_table("test", branch="experiment", version=version)
return table._table if use_async else table
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
@pytest.mark.parametrize("version", [None, 3])
async def test_range_sdk_order_snapshot_and_overwrite(use_async, version):
handler = RangeServer()
with mock_lancedb_connection(handler) as db:
table = api(db, use_async, version)
requests = [(20 if i % 9 == 0 else 10 + i % 7, i, i % 4) for i in range(1025)]
requests += [(10, 0, 0), (10, 2, 3), (10, 2, 3)]
result = await fetch(table, requests, use_async)
assert isinstance(result, pa.LargeBinaryArray)
assert result.to_pylist() == [
None if row == 20 else payload(row, offset, length, version or 7)
for row, offset, length in requests
]
assert [b["version"] for b in handler.fetches] == [version, version or 7]
result = await fetch(table, [(10, 0, 1)], use_async)
assert result.to_pylist() == [payload(10, 0, 1, version or 8)]
assert handler.fetches[-1]["version"] == version
assert len(handler.fetches) == 3
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_range_sdk_cached_reopen_negotiates_capability(use_async):
handler = RangeServer()
with mock_lancedb_connection(handler) as db:
for version in (7, 8):
table = api(db, use_async)
result = await fetch(table, [(10, 0, 1)], use_async)
assert result.to_pylist() == [payload(10, 0, 1, version)]
assert len(handler.fetches) == 2
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_range_sdk_large_single_and_aggregate_budget(use_async):
handler = RangeServer()
with mock_lancedb_connection(handler) as db:
table = api(db, use_async)
requests = [
(10, 3, 33 * MIB),
(30, 7, 33 * MIB),
(40, 11, 70 * MIB),
(20, 0, 2**64 - 1),
]
# The loopback server advances latest after the first partition.
result = await fetch(table, requests, use_async)
assert len(result) == 4
for i, (row, offset, length) in enumerate(requests[:3]):
expected = payload(row, offset, length, 7)
assert (
hashlib.sha256(result[i].as_buffer()).digest()
== hashlib.sha256(expected).digest()
)
assert len(result[i].as_buffer()) == length
assert result[3].as_py() is None
assert len(handler.fetches) == 3
assert [b["version"] for b in handler.fetches] == [None, 7, 7]
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
@pytest.mark.parametrize(
"fault",
[
"type",
"column",
"count",
"length",
"eos",
"body",
"transport",
"version",
"disconnect",
401,
403,
404,
429,
500,
],
)
async def test_range_sdk_later_failure_rejects_entire_call(use_async, fault):
handler = RangeServer(fault=fault)
with mock_lancedb_connection(
handler, retry_config={"retries": 2, "connect_retries": 2, "read_retries": 2}
) as db:
table = api(db, use_async)
with pytest.raises(Exception) as exc:
await fetch(table, [(10, 0, 1)] * 1025, use_async)
if fault == 404:
assert isinstance(exc.value, TableNotFoundError)
assert isinstance(exc.value.__cause__, HttpError)
assert exc.value.__cause__.status_code == 404
else:
assert not isinstance(exc.value, ValueError)
if isinstance(fault, int):
assert exc.value.status_code == fault
assert len(handler.fetches) == 2
assert all(
path in ("/v1/table/test/describe/", "/v1/table/test/branches/list/", ROUTE)
for _, path, _ in handler.calls
)
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_range_sdk_structured_400_preserves_value_error(use_async):
handler = RangeServer(fault="structured400")
with mock_lancedb_connection(handler) as db:
table = api(db, use_async)
with pytest.raises(ValueError, match="range exceeds blob size"):
await fetch(table, [(10, 0, 1)] * 1025, use_async)
assert len(handler.fetches) == 2
@pytest.mark.asyncio
async def test_range_sdk_async_cancel_releases_only_request_permit():
handler = RangeServer(fault="stall")
with mock_lancedb_connection(handler, blob_request_concurrency=1) as db:
table = api(db, True)
pending = asyncio.create_task(fetch(table, [(10, 0, 1)] * 2049, True))
try:
assert await asyncio.to_thread(handler.stalled.wait, 10)
pending.cancel()
with pytest.raises(asyncio.CancelledError):
await pending
assert len(handler.fetches) == 2
result = await asyncio.wait_for(fetch(table, [(10, 0, 1)], True), 5)
assert result.to_pylist() == [payload(10, 0, 1, 8)]
assert len(handler.fetches) == 3
finally:
pending.cancel()
handler.release.set()
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_range_sdk_integer_validation_and_empty_zero_io(use_async):
handler = RangeServer()
with mock_lancedb_connection(handler) as db:
table = api(db, use_async)
before = len(handler.calls)
assert (await fetch(table, [], use_async)).to_pylist() == []
for request in [
(-1, 0, 1),
(2**64, 0, 1),
(10, -1, 1),
(10, 0, -1),
(10, 0, 2**64),
(10, 0.5, 1),
(20, 2**64 - 1, 1),
(10, 0),
]:
with pytest.raises((ValueError, OverflowError, TypeError)):
await fetch(table, [request], use_async)
assert len(handler.calls) == before
def test_range_sdk_loaded_artifact_identity():
artifact = Path(native.__file__).resolve()
digest = hashlib.sha256()
with artifact.open("rb") as source:
for chunk in iter(lambda: source.read(1024 * 1024), b""):
digest.update(chunk)
print(f"loaded native artifact={artifact} sha256={digest.hexdigest()}")
assert artifact.is_file()
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
@pytest.mark.parametrize(
"fault", ["missing-identity", "wrong-identity", "recreated", "gone"]
)
@pytest.mark.parametrize("huge", [False, True])
async def test_range_sdk_original_identity_survives_every_partition(
use_async, fault, huge
):
handler = RangeServer(fault=fault)
with mock_lancedb_connection(handler) as db:
table = api(db, use_async)
requests = [(10, 0, 64 * MIB + 1)] if huge else [(10, 0, 1)] * 1025
error = (
ValueError
if fault == "recreated"
else TableNotFoundError
if fault == "gone"
else NotImplementedError
)
with pytest.raises(
error, match="snapshot identity" if fault != "gone" else None
):
await fetch(table, requests, use_async)
assert handler.identities == [None, IDENTITY]
assert len(handler.fetches) == 2
assert [body["version"] for body in handler.fetches] == [None, 7]
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
@pytest.mark.parametrize("fault", ["first-missing-identity", "first-invalid-identity"])
async def test_range_sdk_bulk_requires_identity_before_payload_acceptance(
use_async, fault
):
handler = RangeServer(fault=fault)
with mock_lancedb_connection(handler) as db:
table = api(db, use_async)
before = len(handler.calls)
with pytest.raises(NotImplementedError, match="snapshot identity"):
await fetch(table, [(10, 0, 1)] * 1025, use_async)
assert len(handler.fetches) == 1
assert len(handler.calls) == before + 1
+163 -12
View File
@@ -10,6 +10,7 @@ import lancedb
import pytest
import pyarrow as pa
from lancedb.db import AsyncConnection
from lancedb.exceptions import JobFailedError
from lancedb.materialized_view import MaterializedViewDefinition
from lancedb.remote.db import RemoteDBConnection
from utils import start_server_thread
@@ -175,7 +176,8 @@ async def test_remote_refresh_reports_unknown_metrics(
assert not any("count_rows" in path for path in requests)
def test_sync_remote_create_uses_public_async_connection():
@pytest.mark.parametrize("query", [None, "SELECT name FROM people WHERE age >= 18"])
def test_sync_remote_create_uses_public_async_connection(query):
calls = []
class StubAsyncTable:
@@ -190,6 +192,7 @@ def test_sync_remote_create_uses_public_async_connection():
name,
source,
*,
query=None,
select=None,
where=None,
limit=None,
@@ -201,6 +204,7 @@ def test_sync_remote_create_uses_public_async_connection():
(
name,
source,
query,
select,
where,
limit,
@@ -219,18 +223,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"])
@@ -790,3 +800,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()
+131 -2
View File
@@ -5466,6 +5466,7 @@ def blob_remote_table(
*,
server_version=Version("0.5.0"),
location=None,
range_capability=None,
version_header="1",
framing="file",
requests=None,
@@ -5487,6 +5488,8 @@ def blob_remote_table(
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.send_header("phalanx-version", str(server_version))
if range_capability is not None:
request.send_header("x-lancedb-blob-ranges", range_capability)
request.end_headers()
response = dict(BLOB_DESCRIBE_RESPONSE)
response["version"] = body.get("version") or state["version"]
@@ -5594,6 +5597,42 @@ def blob_remote_table(
writer_factory = pa.ipc.new_file if framing == "file" else pa.ipc.new_stream
with writer_factory(request.wfile, response_table.schema) as writer:
writer.write_table(response_table, max_chunksize=1)
elif (
range_capability == "1"
and request.path == "/v1/table/test/fetch_blob_ranges/"
):
size = int(request.headers["Content-Length"])
body = json.loads(request.rfile.read(size))
payloads = {10: b"alpha", 20: None, 30: b"gamma", 40: b""}
values = []
for item in body["ranges"]:
row, offset, length = (
item[key] for key in ("row_id", "offset", "length")
)
error = None
if row not in payloads:
error = "only 1 exist"
elif payloads[row] is not None and offset + length > len(payloads[row]):
error = "range exceeds blob size"
if error:
request.send_response(400)
request.end_headers()
request.wfile.write(error.encode())
return
payload = payloads[row]
values.append(
None if payload is None else payload[offset : offset + length]
)
response_table = pa.table(
{"value": pa.array(values, type=pa.large_binary())}
)
request.send_response(200)
request.send_header("Content-Type", "application/vnd.apache.arrow.stream")
request.send_header("x-lancedb-version", "1")
request.send_header("x-lancedb-query-snapshot", "v1:" + "a" * 64)
request.end_headers()
with pa.ipc.new_stream(request.wfile, response_table.schema) as writer:
writer.write_table(response_table)
elif request.path == "/v1/table/test/fetch_blobs/":
content_len = int(request.headers.get("Content-Length", 0))
body = json.loads(request.rfile.read(content_len))
@@ -5901,8 +5940,11 @@ def test_sync_remote_blob_pandas_avoids_storage_access(
@pytest.mark.asyncio
@pytest.mark.parametrize("use_async", [False, True])
async def test_remote_fetch_blob_ranges(use_async):
with blob_remote_table() as remote_table:
@pytest.mark.parametrize("range_capability", [None, "0", "2", "1"])
async def test_remote_fetch_blob_ranges(use_async, range_capability):
with blob_remote_table(
server_version="1.13.0-beta.0", range_capability=range_capability
) as remote_table:
table = remote_table._table if use_async else remote_table
requests = [
(30, 2, 3),
@@ -6497,6 +6539,93 @@ def test_remote_job_handle_reports_its_own_detail():
}
@pytest.mark.parametrize("is_async", [False, True])
@pytest.mark.parametrize("known_build", [False, True])
@pytest.mark.asyncio
async def test_remote_server_info(is_async, known_build):
requests = []
expected = {
"query_node": {
"release": "1.2.3",
"git_sha": "0123456789ab",
"build_date": "2024-01-01T00:00:00Z",
}
if known_build
else None,
"lance_version": "5.0.0",
"lancedb_version": "0.42.0",
"function_worker_protocol_version": 25,
"configured_query_node_image": "example.invalid/query:configured",
"configured_job_worker_image": "example.invalid/cpu:configured",
"configured_sql_job_image": "example.invalid/cli:configured",
"configured_gpu_worker_image": "example.invalid/worker:configured",
}
def handler(request):
requests.append((request.command, request.path))
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(json.dumps(expected).encode())
if is_async:
async with mock_lancedb_connection_async(handler) as db:
actual = await db.server_info()
else:
with mock_lancedb_connection(handler) as db:
actual = db.server_info()
assert actual == expected
assert json.loads(json.dumps(actual)) == expected
assert requests == [("GET", "/v1/server/info")]
@pytest.mark.parametrize("is_async", [False, True])
@pytest.mark.parametrize("status", [404, 403])
@pytest.mark.asyncio
async def test_remote_server_info_errors(is_async, status):
requests = []
def handler(request):
requests.append((request.command, request.path))
request.send_response(status)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(
json.dumps(
{
"error": "discovery unavailable",
"server": {
"release": "1.2.3",
"git_sha": "0123456789ab",
"build_date": "2024-01-01T00:00:00Z",
},
}
).encode()
)
expected_error = NotImplementedError if status == 404 else HttpError
with pytest.raises(expected_error) as caught:
if is_async:
async with mock_lancedb_connection_async(handler) as db:
await db.server_info()
else:
with mock_lancedb_connection(handler) as db:
db.server_info()
if status == 404:
assert "/v1/server/info" in str(caught.value)
else:
# Permission responses do not carry the input-error classifier header.
# The native HTTP error and Python conversion must retain provenance.
assert "discovery unavailable" in str(caught.value)
assert "1.2.3" in str(caught.value)
assert "0123456789ab" in str(caught.value)
assert "2024-01-01T00:00:00Z" in str(caught.value)
assert caught.value.status_code == 403
assert requests == [("GET", "/v1/server/info")]
@pytest.mark.parametrize("is_async", [False, True])
@pytest.mark.asyncio
async def test_remote_list_gpu_classes(is_async):
+52 -6
View File
@@ -26,6 +26,7 @@ use lancedb::{
database::{CreateTableMode, Database, ReadConsistency},
function::{GpuClass as LanceGpuClass, RefreshColumnResult},
graph::PropertyGraphDefinition,
materialized_view::CreateMaterializedViewBuilder,
};
use pyo3::{
Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python,
@@ -34,6 +35,27 @@ use pyo3::{
types::{PyAnyMethods, PyDict, PyDictMethods, PyList},
};
fn materialized_view_builder(
connection: &LanceConnection,
name: String,
source: Option<String>,
query: Option<String>,
has_clauses: bool,
) -> PyResult<CreateMaterializedViewBuilder> {
match (source, query) {
(None, Some(query)) if !has_clauses => {
Ok(connection.create_materialized_view_from_query(name, query))
}
(Some(source), None) => Ok(connection.create_materialized_view(name, source)),
(None, None) => Err(PyValueError::new_err(
"either source or query must be provided",
)),
_ => Err(PyValueError::new_err(
"query cannot be combined with source, select, where or limit",
)),
}
}
#[pyclass]
pub struct Connection {
inner: Option<LanceConnection>,
@@ -483,21 +505,29 @@ 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))]
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>,
) -> 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;
if let Some(enabled) = auto_refresh_enabled {
builder = builder.auto_refresh_enabled(enabled);
}
@@ -520,21 +550,29 @@ 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))]
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>,
) -> 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;
if let Some(enabled) = auto_refresh_enabled {
builder = builder.auto_refresh_enabled(enabled);
}
@@ -1285,6 +1323,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 {