mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
Merge current Blob consumers into Lance beta19 update
This commit is contained in:
@@ -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()
|
||||
@@ -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")
|
||||
|
||||
@@ -397,6 +397,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: ...
|
||||
@@ -543,6 +544,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]
|
||||
@@ -747,7 +749,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,
|
||||
@@ -755,9 +762,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:
|
||||
|
||||
@@ -1529,6 +1529,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 +1581,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 +1907,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 +2012,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:
|
||||
@@ -2286,7 +2313,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,6 +2437,18 @@ class FunctionDefinition:
|
||||
signature = signature._copy(update={"initialization": initialization})
|
||||
else:
|
||||
signature = _infer_signature(function, input_schema, output_schema)
|
||||
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_modules = _code_files(code)
|
||||
entry_source = _SourcePackager(
|
||||
code_modules, frozenset(_requirement_name(package) for package in packages)
|
||||
@@ -2663,13 +2704,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
|
||||
----------
|
||||
|
||||
+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):
|
||||
|
||||
@@ -719,6 +719,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 +754,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 +774,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 +1425,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:
|
||||
"""
|
||||
|
||||
@@ -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,
|
||||
@@ -2255,6 +2256,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 +2317,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
|
||||
-------
|
||||
@@ -2664,6 +2670,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 +2681,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 +2692,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 +2704,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 +2715,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 +2732,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 +4017,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:
|
||||
@@ -4800,6 +4826,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 +4858,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 +4879,7 @@ class LanceTable(Table):
|
||||
progress=progress,
|
||||
write_parallelism=write_parallelism,
|
||||
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
|
||||
retries=retries,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
@@ -7059,6 +7091,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 +7130,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 +7188,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):
|
||||
@@ -8620,26 +8658,39 @@ class AsyncTable:
|
||||
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 +8705,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 == []
|
||||
@@ -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"
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -466,6 +466,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(
|
||||
|
||||
@@ -59,20 +59,124 @@ import pyarrow as pa
|
||||
from utils import start_server_thread
|
||||
|
||||
|
||||
def make_mock_http_handler(handler):
|
||||
def make_mock_http_handler(handler, *, buffer_body=True):
|
||||
class MockLanceDBHandler(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
handler(self)
|
||||
|
||||
def do_POST(self):
|
||||
handler(self)
|
||||
if not buffer_body:
|
||||
handler(self)
|
||||
return
|
||||
|
||||
def do_PUT(self):
|
||||
handler(self)
|
||||
# HTTP/1.0 closes after the response. Leaving a streamed upload unread
|
||||
# can reset the connection while the client is still writing its body.
|
||||
# Keep the original framing so handlers can inspect the actual request.
|
||||
source = self.rfile
|
||||
body = bytearray()
|
||||
if self.headers.get("Transfer-Encoding") == "chunked":
|
||||
while True:
|
||||
line = source.readline()
|
||||
assert line.endswith(b"\r\n")
|
||||
body.extend(line)
|
||||
size = int(line.split(b";")[0], 16)
|
||||
if size == 0:
|
||||
while True:
|
||||
line = source.readline()
|
||||
assert line.endswith(b"\r\n")
|
||||
body.extend(line)
|
||||
if line == b"\r\n":
|
||||
break
|
||||
break
|
||||
chunk = source.read(size + 2)
|
||||
assert len(chunk) == size + 2 and chunk[-2:] == b"\r\n"
|
||||
body.extend(chunk)
|
||||
else:
|
||||
size = int(self.headers.get("Content-Length", 0))
|
||||
body.extend(source.read(size))
|
||||
assert len(body) == size
|
||||
self.rfile = io.BytesIO(body)
|
||||
try:
|
||||
handler(self)
|
||||
finally:
|
||||
self.rfile.close()
|
||||
self.rfile = source
|
||||
|
||||
do_PUT = do_POST
|
||||
|
||||
return MockLanceDBHandler
|
||||
|
||||
|
||||
@pytest.mark.parametrize("chunked", [False, True])
|
||||
@pytest.mark.parametrize("read_body", [False, True])
|
||||
def test_mock_http_handler_waits_for_body(chunked, read_body):
|
||||
body = (
|
||||
b"7;ext=value\r\npayload\r\n0\r\nX-Trailer: value\r\n\r\n"
|
||||
if chunked
|
||||
else b"payload"
|
||||
)
|
||||
received = []
|
||||
|
||||
def handler(request):
|
||||
if read_body:
|
||||
assert (request.headers.get("Transfer-Encoding") == "chunked") == chunked
|
||||
received.append(request.rfile.read(len(body)))
|
||||
request.send_response(200)
|
||||
request.end_headers()
|
||||
|
||||
with http.server.HTTPServer(
|
||||
("127.0.0.1", 0), make_mock_http_handler(handler)
|
||||
) as server:
|
||||
thread = start_server_thread(server)
|
||||
try:
|
||||
with socket.create_connection(server.server_address, timeout=2) as client:
|
||||
framing = (
|
||||
"Transfer-Encoding: chunked" if chunked else "Content-Length: 7"
|
||||
)
|
||||
client.sendall(
|
||||
f"POST / HTTP/1.0\r\nHost: localhost\r\n{framing}\r\n\r\n".encode()
|
||||
)
|
||||
client.settimeout(0.1)
|
||||
with pytest.raises(TimeoutError):
|
||||
client.recv(1024)
|
||||
client.settimeout(2)
|
||||
client.sendall(body)
|
||||
assert client.recv(1024).startswith(b"HTTP/1.0 200")
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
assert received == ([body] if read_body else [])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("disconnect", [False, True])
|
||||
def test_mock_http_handler_allows_early_failure(disconnect):
|
||||
def handler(request):
|
||||
if disconnect:
|
||||
request.connection.shutdown(socket.SHUT_RDWR)
|
||||
request.close_connection = True
|
||||
else:
|
||||
request.send_response(413)
|
||||
request.end_headers()
|
||||
|
||||
with http.server.HTTPServer(
|
||||
("127.0.0.1", 0), make_mock_http_handler(handler, buffer_body=False)
|
||||
) as server:
|
||||
thread = start_server_thread(server)
|
||||
try:
|
||||
with socket.create_connection(server.server_address, timeout=2) as client:
|
||||
client.sendall(
|
||||
b"POST / HTTP/1.0\r\nHost: localhost\r\nContent-Length: 7\r\n\r\n"
|
||||
)
|
||||
response = client.recv(1024)
|
||||
if disconnect:
|
||||
assert response == b""
|
||||
else:
|
||||
assert response.startswith(b"HTTP/1.0 413")
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("db_name", ["a" * 64, "invalid..database"])
|
||||
def test_connect_rejects_invalid_cloud_dns_hostname(db_name):
|
||||
with pytest.raises(ValueError, match="DNS labels must contain 1 to 63 bytes"):
|
||||
@@ -80,9 +184,9 @@ def test_connect_rejects_invalid_cloud_dns_hostname(db_name):
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def mock_lancedb_connection(handler, **client_config):
|
||||
def mock_lancedb_connection(handler, *, buffer_body=True, **client_config):
|
||||
with http.server.ThreadingHTTPServer(
|
||||
("127.0.0.1", 0), make_mock_http_handler(handler)
|
||||
("127.0.0.1", 0), make_mock_http_handler(handler, buffer_body=buffer_body)
|
||||
) as server:
|
||||
port = server.server_address[1]
|
||||
handle = start_server_thread(server)
|
||||
@@ -108,9 +212,9 @@ def mock_lancedb_connection(handler, **client_config):
|
||||
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def mock_lancedb_connection_async(handler, **client_config):
|
||||
async def mock_lancedb_connection_async(handler, *, buffer_body=True, **client_config):
|
||||
with http.server.HTTPServer(
|
||||
("127.0.0.1", 0), make_mock_http_handler(handler)
|
||||
("127.0.0.1", 0), make_mock_http_handler(handler, buffer_body=buffer_body)
|
||||
) as server:
|
||||
port = server.server_address[1]
|
||||
handle = start_server_thread(server)
|
||||
@@ -135,6 +239,76 @@ async def mock_lancedb_connection_async(handler, **client_config):
|
||||
handle.join()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sync_api", [False, True])
|
||||
@pytest.mark.parametrize("retries", [None, 0])
|
||||
@pytest.mark.parametrize("status", [429, 504])
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_retry_override(sync_api, retries, status):
|
||||
attempts = 0
|
||||
|
||||
def handler(request):
|
||||
nonlocal attempts
|
||||
if request.path.endswith("/describe/"):
|
||||
payload = {
|
||||
"version": 1,
|
||||
"schema": {
|
||||
"fields": [
|
||||
{"name": "id", "type": {"type": "int64"}, "nullable": True}
|
||||
]
|
||||
},
|
||||
}
|
||||
request.send_response(200)
|
||||
request.end_headers()
|
||||
request.wfile.write(json.dumps(payload).encode())
|
||||
return
|
||||
assert request.path.endswith("/insert/")
|
||||
body = bytearray()
|
||||
if request.headers.get("Transfer-Encoding") == "chunked":
|
||||
while True:
|
||||
size = int(request.rfile.readline().strip(), 16)
|
||||
if size == 0:
|
||||
request.rfile.readline()
|
||||
break
|
||||
body.extend(request.rfile.read(size))
|
||||
request.rfile.read(2)
|
||||
else:
|
||||
body.extend(
|
||||
request.rfile.read(int(request.headers.get("Content-Length", 0)))
|
||||
)
|
||||
assert pa.ipc.open_stream(body).read_all().to_pylist() == [{"id": 1}]
|
||||
attempts += 1
|
||||
request.send_response(status if attempts == 1 else 200)
|
||||
request.end_headers()
|
||||
request.wfile.write(b'{"version": 2}')
|
||||
|
||||
config = {
|
||||
"retry_config": {
|
||||
"retries": 3,
|
||||
"statuses": [429, 504],
|
||||
"backoff_factor": 0,
|
||||
"backoff_jitter": 0,
|
||||
}
|
||||
}
|
||||
expected_success = status == 429 and retries is None
|
||||
if sync_api:
|
||||
with mock_lancedb_connection(handler, **config) as db:
|
||||
table = db.open_table("test")
|
||||
if expected_success:
|
||||
assert table.add([{"id": 1}], retries=retries).version == 2
|
||||
else:
|
||||
with pytest.raises((HttpError, RetryError)):
|
||||
table.add([{"id": 1}], retries=retries)
|
||||
else:
|
||||
async with mock_lancedb_connection_async(handler, **config) as db:
|
||||
table = await db.open_table("test")
|
||||
if expected_success:
|
||||
assert (await table.add([{"id": 1}], retries=retries)).version == 2
|
||||
else:
|
||||
with pytest.raises((HttpError, RetryError)):
|
||||
await table.add([{"id": 1}], retries=retries)
|
||||
assert attempts == (2 if expected_success else 1)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def missing_table_handler(cached, namespace_path):
|
||||
request_ids = []
|
||||
@@ -1248,7 +1422,7 @@ async def test_create_table_timeout_is_actionable(timeout_config):
|
||||
request.close_connection = True
|
||||
|
||||
async with mock_lancedb_connection_async(
|
||||
handler, timeout_config=timeout_config
|
||||
handler, buffer_body=False, timeout_config=timeout_config
|
||||
) as db:
|
||||
batch = pa.record_batch({"id": [1, 2]})
|
||||
reader = pa.RecordBatchReader.from_batches(batch.schema, [batch])
|
||||
@@ -5076,10 +5250,14 @@ def test_remote_schema_restores_blob_extensions(use_async, with_pylance, nested)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.parametrize("mode", ["merge", "overwrite"])
|
||||
@pytest.mark.parametrize(
|
||||
"mode,part_status",
|
||||
[("merge", 200), ("overwrite", 200), ("overwrite", 503)],
|
||||
ids=["merge", "overwrite", "overwrite-retry"],
|
||||
)
|
||||
@pytest.mark.parametrize("target_with_ranges", [False, True])
|
||||
async def test_remote_writes_normalize_blob_layouts(
|
||||
use_async, mode, target_with_ranges
|
||||
use_async, mode, part_status, target_with_ranges, mem_db
|
||||
):
|
||||
description = json.loads(json.dumps(BLOB_DESCRIBE_RESPONSE))
|
||||
if target_with_ranges:
|
||||
@@ -5088,29 +5266,77 @@ async def test_remote_writes_normalize_blob_layouts(
|
||||
for name in ("position", "size")
|
||||
)
|
||||
received = []
|
||||
paths = []
|
||||
staged = {}
|
||||
part_attempts = []
|
||||
published = mem_db.create_table(
|
||||
"published",
|
||||
[{"id": 0, "image": b"before"}],
|
||||
schema=pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]),
|
||||
)
|
||||
|
||||
def handler(request):
|
||||
if request.path == "/v1/table/test/describe/":
|
||||
path = urlparse(request.path).path
|
||||
query = parse_qs(urlparse(request.path).query)
|
||||
status = 200
|
||||
if path == "/v1/table/test/describe/":
|
||||
response = description
|
||||
else:
|
||||
expected = "merge_insert" if mode == "merge" else "insert"
|
||||
assert urlparse(request.path).path == f"/v1/table/test/{expected}/"
|
||||
if request.headers.get("Transfer-Encoding") == "chunked":
|
||||
body = bytearray()
|
||||
while size := int(request.rfile.readline().split(b";")[0], 16):
|
||||
body.extend(request.rfile.read(size))
|
||||
assert request.rfile.read(2) == b"\r\n"
|
||||
assert request.rfile.read(2) == b"\r\n"
|
||||
paths.append(path.removeprefix("/v1/table/test/"))
|
||||
body = request.rfile.read()
|
||||
if path == "/v1/table/test/multipart_write/create":
|
||||
assert mode == "overwrite"
|
||||
assert paths == ["multipart_write/create"]
|
||||
assert not query and not body
|
||||
response = {"upload_id": "blob-overwrite"}
|
||||
elif path == "/v1/table/test/insert/":
|
||||
assert mode == "overwrite"
|
||||
assert query["mode"] == ["overwrite"]
|
||||
assert query["upload_id"] == ["blob-overwrite"]
|
||||
part_id = query["upload_part_id"][0]
|
||||
assert str(uuid.UUID(part_id)) == part_id
|
||||
part_attempts.append((part_id, body))
|
||||
assert published.version == 1
|
||||
assert published.search().select(["id"]).to_list() == [{"id": 0}]
|
||||
if staged:
|
||||
assert staged == {part_id: body}
|
||||
else:
|
||||
staged[part_id] = body
|
||||
assert body[-8:] == b"\xff\xff\xff\xff\x00\x00\x00\x00"
|
||||
received.append(pa.ipc.open_stream(body).read_all())
|
||||
status = part_status if len(part_attempts) == 1 else 200
|
||||
response = {}
|
||||
elif path == "/v1/table/test/multipart_write/complete":
|
||||
assert mode == "overwrite"
|
||||
assert query == {"upload_id": ["blob-overwrite"]} and not body
|
||||
expected_attempts = 2 if part_status == 503 else 1
|
||||
assert paths == ["multipart_write/create"] + [
|
||||
"insert/"
|
||||
] * expected_attempts + ["multipart_write/complete"]
|
||||
assert len(staged) == len(received) == 1
|
||||
assert part_attempts == [part_attempts[0]] * expected_attempts
|
||||
assert published.version == 1
|
||||
published.add(received[0], mode="overwrite")
|
||||
response = {"version": published.version}
|
||||
else:
|
||||
body = request.rfile.read(int(request.headers["Content-Length"]))
|
||||
received.append(pa.ipc.open_stream(body).read_all())
|
||||
response = {
|
||||
"version": 2,
|
||||
"num_updated_rows": 0,
|
||||
"num_inserted_rows": 2,
|
||||
"num_deleted_rows": 0,
|
||||
}
|
||||
request.send_response(200)
|
||||
assert mode == "merge"
|
||||
assert path == "/v1/table/test/merge_insert/"
|
||||
# merge_insert still streams a chunked body; preserve its framing.
|
||||
if request.headers.get("Transfer-Encoding") == "chunked":
|
||||
stream = io.BytesIO(body)
|
||||
body = bytearray()
|
||||
while size := int(stream.readline().split(b";")[0], 16):
|
||||
body.extend(stream.read(size))
|
||||
assert stream.read(2) == b"\r\n"
|
||||
assert stream.read(2) == b"\r\n"
|
||||
received.append(pa.ipc.open_stream(body).read_all())
|
||||
response = {
|
||||
"version": 2,
|
||||
"num_updated_rows": 0,
|
||||
"num_inserted_rows": 2,
|
||||
"num_deleted_rows": 0,
|
||||
}
|
||||
request.send_response(status)
|
||||
request.send_header("Content-Type", "application/json")
|
||||
request.send_header("phalanx-version", "0.5.0")
|
||||
request.end_headers()
|
||||
@@ -5143,7 +5369,23 @@ async def test_remote_writes_normalize_blob_layouts(
|
||||
else:
|
||||
result = table.add(data, mode="overwrite")
|
||||
if use_async:
|
||||
await result
|
||||
result = await result
|
||||
assert result.version == 2
|
||||
|
||||
if mode == "overwrite":
|
||||
assert published.version == 2
|
||||
hits = published.search().select(["id"]).with_row_id(True).to_arrow()
|
||||
by_id = dict(zip(hits["id"].to_pylist(), hits["_rowid"].to_pylist()))
|
||||
assert set(by_id) == {1, 2}
|
||||
row_ids = [by_id[1], by_id[2]]
|
||||
assert published.fetch_blobs("image", row_ids).to_pylist() == [b"payload", None]
|
||||
payload, null = published.fetch_blob_files("image", row_ids)
|
||||
assert null is None
|
||||
with payload:
|
||||
assert payload.read_range(1, 3) == b"ayl"
|
||||
assert payload.read() == b"payload"
|
||||
else:
|
||||
assert paths == ["merge_insert/"]
|
||||
|
||||
assert len(received) == 1
|
||||
images = received[0]["image"].combine_chunks()
|
||||
@@ -5220,14 +5462,34 @@ def blob_descriptor_take_table():
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def blob_remote_table(*, server_version=Version("0.5.0"), location=None):
|
||||
def blob_remote_table(
|
||||
*,
|
||||
server_version=Version("0.5.0"),
|
||||
location=None,
|
||||
version_header="1",
|
||||
framing="file",
|
||||
requests=None,
|
||||
state=None,
|
||||
empty=False,
|
||||
schema_version=None,
|
||||
search_scores=False,
|
||||
snapshot_supported=True,
|
||||
identity_header="v1:" + "a" * 64,
|
||||
verify_identity=True,
|
||||
):
|
||||
if state is None:
|
||||
state = {"version": 1}
|
||||
|
||||
def handler(request):
|
||||
if request.path == "/v1/table/test/describe/":
|
||||
content_len = int(request.headers.get("Content-Length", 0))
|
||||
body = json.loads(request.rfile.read(content_len)) if content_len else {}
|
||||
request.send_response(200)
|
||||
request.send_header("Content-Type", "application/json")
|
||||
request.send_header("phalanx-version", str(server_version))
|
||||
request.end_headers()
|
||||
response = dict(BLOB_DESCRIBE_RESPONSE)
|
||||
response["version"] = body.get("version") or state["version"]
|
||||
if location is not None:
|
||||
response["location"] = str(location)
|
||||
request.wfile.write(json.dumps(response).encode())
|
||||
@@ -5260,9 +5522,22 @@ def blob_remote_table(*, server_version=Version("0.5.0"), location=None):
|
||||
elif request.path == "/v1/table/test/query/":
|
||||
content_len = int(request.headers.get("Content-Length", 0))
|
||||
body = json.loads(request.rfile.read(content_len))
|
||||
if requests is not None:
|
||||
requests.append(("query", body))
|
||||
columns = body.get("columns")
|
||||
assert columns in (None, ["id", "image"], ["id"], ["image"])
|
||||
if columns == ["id"]:
|
||||
assert columns in (
|
||||
None,
|
||||
["id", "image"],
|
||||
["id"],
|
||||
["image"],
|
||||
{"payload": "image"},
|
||||
)
|
||||
if isinstance(columns, dict):
|
||||
response_table = blob_query_response_table().select(["image", "_rowid"])
|
||||
response_table = response_table.rename_columns(["payload", "_rowid"])
|
||||
if not body.get("with_row_id", False):
|
||||
response_table = response_table.drop(["_rowid"])
|
||||
elif columns == ["id"]:
|
||||
response_table = blob_query_response_table().select(["id"])
|
||||
else:
|
||||
if columns == ["image"]:
|
||||
@@ -5279,25 +5554,86 @@ def blob_remote_table(*, server_version=Version("0.5.0"), location=None):
|
||||
response_table = blob_query_response_table()
|
||||
if not body.get("with_row_id", False):
|
||||
response_table = response_table.drop(["_rowid"])
|
||||
if search_scores and not body.get("filter", "").startswith("_rowid IN"):
|
||||
if body.get("vector"):
|
||||
response_table = response_table.append_column(
|
||||
"_distance", pa.array([0.1, 0.2, 0.3], type=pa.float32())
|
||||
)
|
||||
elif body.get("full_text_query"):
|
||||
response_table = response_table.append_column(
|
||||
"_score", pa.array([3.0, 2.0, 1.0], type=pa.float32())
|
||||
)
|
||||
if empty:
|
||||
response_table = response_table.slice(0, 0)
|
||||
if schema_version is not None:
|
||||
response_table = response_table.replace_schema_metadata(
|
||||
{
|
||||
b"lancedb:query_version": schema_version.encode(),
|
||||
b"lancedb:query_snapshot": ("v1:" + "f" * 64).encode(),
|
||||
}
|
||||
)
|
||||
request.send_response(200)
|
||||
request.send_header("Content-Type", "application/vnd.apache.arrow.file")
|
||||
request.send_header("x-lancedb-version", "1")
|
||||
request.send_header(
|
||||
"Content-Type", f"application/vnd.apache.arrow.{framing}"
|
||||
)
|
||||
header = (
|
||||
version_header(body) if callable(version_header) else version_header
|
||||
)
|
||||
if header is not None:
|
||||
request.send_header("x-lancedb-version", header)
|
||||
if snapshot_supported:
|
||||
request.send_header("x-lancedb-query-version", header)
|
||||
identity = (
|
||||
identity_header(body)
|
||||
if callable(identity_header)
|
||||
else identity_header
|
||||
)
|
||||
if identity is not None:
|
||||
request.send_header("x-lancedb-query-snapshot", identity)
|
||||
request.end_headers()
|
||||
with pa.ipc.new_file(request.wfile, response_table.schema) as writer:
|
||||
writer.write_table(response_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 request.path == "/v1/table/test/fetch_blobs/":
|
||||
content_len = int(request.headers.get("Content-Length", 0))
|
||||
body = json.loads(request.rfile.read(content_len))
|
||||
assert body["column"] == "image"
|
||||
assert body["row_ids"] == [10, 20, 30]
|
||||
if requests is not None:
|
||||
requests.append(("fetch_blobs", body))
|
||||
payloads = {10: b"alpha", 20: None, 30: b"gamma", 40: b""}
|
||||
if state["version"] > 1 and body.get("version") != 1:
|
||||
payloads = {row: b"new-version" for row in payloads}
|
||||
response_table = pa.table(
|
||||
{"image": pa.array([b"alpha", None, b"gamma"], type=pa.large_binary())}
|
||||
{
|
||||
"image": pa.array(
|
||||
[payloads[row] for row in body["row_ids"]],
|
||||
type=pa.large_binary(),
|
||||
)
|
||||
}
|
||||
)
|
||||
request.send_response(200)
|
||||
request.send_header("Content-Type", "application/vnd.apache.arrow.stream")
|
||||
if verify_identity and request.headers.get("x-lancedb-query-snapshot"):
|
||||
request.send_header(
|
||||
"x-lancedb-query-snapshot",
|
||||
request.headers["x-lancedb-query-snapshot"],
|
||||
)
|
||||
request.end_headers()
|
||||
with pa.ipc.new_stream(request.wfile, response_table.schema) as writer:
|
||||
writer.write_table(response_table)
|
||||
elif request.path == "/v1/table/test/insert/":
|
||||
if request.headers.get("Transfer-Encoding") == "chunked":
|
||||
while size := int(request.rfile.readline().split(b";")[0], 16):
|
||||
request.rfile.read(size)
|
||||
assert request.rfile.read(2) == b"\r\n"
|
||||
assert request.rfile.read(2) == b"\r\n"
|
||||
else:
|
||||
request.rfile.read(int(request.headers.get("Content-Length", 0)))
|
||||
state["version"] += 1
|
||||
request.send_response(200)
|
||||
request.send_header("Content-Type", "application/json")
|
||||
request.end_headers()
|
||||
request.wfile.write(json.dumps({"version": state["version"]}).encode())
|
||||
else:
|
||||
request.send_response(404)
|
||||
request.end_headers()
|
||||
@@ -5306,6 +5642,222 @@ def blob_remote_table(*, server_version=Version("0.5.0"), location=None):
|
||||
yield db.open_table("test")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.parametrize("framing", ["file", "stream"])
|
||||
@pytest.mark.parametrize("method", ["to_arrow", "to_list", "to_pandas", "to_batches"])
|
||||
async def test_remote_blob_bytes_conversion(use_async, framing, method):
|
||||
if method == "to_pandas":
|
||||
pytest.importorskip("pandas")
|
||||
requests = []
|
||||
with blob_remote_table(framing=framing, requests=requests) as remote_table:
|
||||
table = remote_table._table if use_async else remote_table
|
||||
query = table.query() if use_async else table.search()
|
||||
query = query.select(["id", "image"])
|
||||
if method == "to_batches":
|
||||
kwargs = {"max_batch_length" if use_async else "batch_size": 1}
|
||||
reader = query.to_batches(blob_mode="bytes", **kwargs)
|
||||
if use_async:
|
||||
reader = await reader
|
||||
batches = [batch async for batch in reader]
|
||||
else:
|
||||
batches = list(reader)
|
||||
assert all(batch.num_rows == 1 for batch in batches)
|
||||
result = pa.Table.from_batches(batches, schema=reader.schema).to_pylist()
|
||||
else:
|
||||
result = getattr(query, method)(blob_mode="bytes")
|
||||
if use_async:
|
||||
result = await result
|
||||
if method == "to_arrow":
|
||||
assert result.schema.field("image").type == pa.large_binary()
|
||||
result = result.to_pylist()
|
||||
elif method == "to_pandas":
|
||||
result = result.to_dict("records")
|
||||
assert result == [
|
||||
{"id": 1, "image": b"alpha"},
|
||||
{"id": 2, "image": None},
|
||||
{"id": 3, "image": b"gamma"},
|
||||
]
|
||||
fetches = [body for path, body in requests if path == "fetch_blobs"]
|
||||
assert fetches
|
||||
assert all(body["version"] == 1 for body in fetches)
|
||||
assert [row for body in fetches for row in body["row_ids"]] == [10, 20, 30]
|
||||
descriptor_queries = [
|
||||
body
|
||||
for path, body in requests
|
||||
if path == "query" and body.get("filter", "").startswith("_rowid IN")
|
||||
]
|
||||
assert all(body["version"] == 1 for body in descriptor_queries)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.parametrize("framing", ["file", "stream"])
|
||||
async def test_remote_blob_bytes_keeps_query_snapshot_during_writes(use_async, framing):
|
||||
requests = []
|
||||
state = {"version": 1}
|
||||
with blob_remote_table(
|
||||
framing=framing, requests=requests, state=state
|
||||
) as remote_table:
|
||||
table = remote_table._table if use_async else remote_table
|
||||
query = table.query() if use_async else table.search()
|
||||
kwargs = {"max_batch_length" if use_async else "batch_size": 1}
|
||||
reader = query.select(["id", "image"]).to_batches(blob_mode="bytes", **kwargs)
|
||||
if use_async:
|
||||
reader = await reader
|
||||
# The query has selected v1; commit v2 before consuming any payloads.
|
||||
write = table.add([{"id": 4, "image": b"new-version"}])
|
||||
if use_async:
|
||||
await write
|
||||
version = await table.version() if use_async else table.version
|
||||
assert version == 2
|
||||
if use_async:
|
||||
rows = [row async for batch in reader for row in batch.to_pylist()]
|
||||
else:
|
||||
rows = [row for batch in reader for row in batch.to_pylist()]
|
||||
assert [row["image"] for row in rows] == [b"alpha", None, b"gamma"]
|
||||
fetches = [body for path, body in requests if path == "fetch_blobs"]
|
||||
assert all(body["version"] == 1 for body in fetches)
|
||||
# Snapshot fetches must not check out the caller's live handle.
|
||||
version = await table.version() if use_async else table.version
|
||||
assert version == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.parametrize("version_header", [None, "invalid", "0", "-1", str(2**64)])
|
||||
async def test_remote_blob_bytes_invalid_snapshot(use_async, version_header):
|
||||
requests = []
|
||||
with blob_remote_table(
|
||||
version_header=version_header, requests=requests, schema_version="1"
|
||||
) as remote_table:
|
||||
table = remote_table._table if use_async else remote_table
|
||||
query = table.query() if use_async else table.search()
|
||||
with pytest.raises(NotImplementedError, match="x-lancedb-query-version"):
|
||||
result = query.to_arrow(blob_mode="bytes")
|
||||
if use_async:
|
||||
await result
|
||||
assert not any(path == "fetch_blobs" for path, _ in requests)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.parametrize("framing", ["file", "stream"])
|
||||
async def test_remote_blob_bytes_empty_results(use_async, framing):
|
||||
requests = []
|
||||
with blob_remote_table(
|
||||
empty=True, framing=framing, requests=requests
|
||||
) as remote_table:
|
||||
table = remote_table._table if use_async else remote_table
|
||||
query = table.query() if use_async else table.search()
|
||||
result = query.to_arrow(blob_mode="bytes")
|
||||
if use_async:
|
||||
result = await result
|
||||
assert result.num_rows == 0
|
||||
assert result.schema.field("image").type == pa.large_binary()
|
||||
assert result.column_names == ["id", "image"]
|
||||
assert not any(path == "fetch_blobs" for path, _ in requests)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.parametrize("kind", ["vector", "fts", "hybrid"])
|
||||
@pytest.mark.parametrize("rerank", [False, True])
|
||||
async def test_remote_blob_bytes_search_queries(use_async, kind, rerank):
|
||||
with blob_remote_table(search_scores=True) as remote_table:
|
||||
if use_async:
|
||||
query = remote_table._table.query()
|
||||
if kind in ("vector", "hybrid"):
|
||||
query = query.nearest_to([1.0, 2.0])
|
||||
if kind in ("fts", "hybrid"):
|
||||
query = query.nearest_to_text("hello")
|
||||
elif kind == "vector":
|
||||
query = remote_table.search([1.0, 2.0], vector_column_name="vector")
|
||||
elif kind == "fts":
|
||||
query = remote_table.search("hello", query_type="fts")
|
||||
else:
|
||||
query = (
|
||||
remote_table.search(query_type="hybrid", vector_column_name="vector")
|
||||
.vector([1.0, 2.0])
|
||||
.text("hello")
|
||||
)
|
||||
if rerank:
|
||||
from lancedb.rerankers import RRFReranker
|
||||
|
||||
class StripMetadataReranker(RRFReranker):
|
||||
def rerank_vector(self, query, vector_results):
|
||||
return vector_results.append_column(
|
||||
"_relevance_score", pa.array([3.0, 2.0, 1.0])
|
||||
).replace_schema_metadata(None)
|
||||
|
||||
def rerank_fts(self, query, fts_results):
|
||||
return self.rerank_vector(query, fts_results)
|
||||
|
||||
def rerank_hybrid(self, query, vector_results, fts_results):
|
||||
return (
|
||||
super()
|
||||
.rerank_hybrid(query, vector_results, fts_results)
|
||||
.replace_schema_metadata(None)
|
||||
)
|
||||
|
||||
kwargs = {"query_string": "hello"} if kind == "vector" else {}
|
||||
query = query.rerank(StripMetadataReranker(), **kwargs)
|
||||
result = query.select(["id", "image"]).to_arrow(blob_mode="bytes")
|
||||
if use_async:
|
||||
result = await result
|
||||
assert result["image"].to_pylist() == [b"alpha", None, b"gamma"]
|
||||
assert "_rowid" not in result.column_names
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
async def test_remote_blob_bytes_hybrid_rejects_different_snapshots(use_async):
|
||||
def header(body):
|
||||
return "2" if body.get("full_text_query") else "1"
|
||||
|
||||
requests = []
|
||||
with blob_remote_table(
|
||||
search_scores=True, version_header=header, requests=requests
|
||||
) as remote_table:
|
||||
if use_async:
|
||||
query = (
|
||||
remote_table._table.query()
|
||||
.nearest_to([1.0, 2.0])
|
||||
.nearest_to_text("hello")
|
||||
)
|
||||
else:
|
||||
query = (
|
||||
remote_table.search(query_type="hybrid", vector_column_name="vector")
|
||||
.vector([1.0, 2.0])
|
||||
.text("hello")
|
||||
)
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="inconsistent x-lancedb-query-version"
|
||||
):
|
||||
result = query.select(["id", "image"]).to_arrow(blob_mode="bytes")
|
||||
if use_async:
|
||||
await result
|
||||
assert not any(path == "fetch_blobs" for path, _ in requests)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.parametrize("with_row_id", [False, True])
|
||||
async def test_remote_blob_bytes_alias_and_explicit_row_ids(use_async, with_row_id):
|
||||
with blob_remote_table() as remote_table:
|
||||
query = remote_table._table.query() if use_async else remote_table.search()
|
||||
query = query.select({"payload": "image"})
|
||||
if with_row_id:
|
||||
query = query.with_row_id() if use_async else query.with_row_id(True)
|
||||
result = query.to_arrow(blob_mode="bytes")
|
||||
if use_async:
|
||||
result = await result
|
||||
assert result["payload"].to_pylist() == [b"alpha", None, b"gamma"]
|
||||
assert ("_rowid" in result.column_names) == with_row_id
|
||||
if with_row_id:
|
||||
assert result["_rowid"].to_pylist() == [10, 20, 30]
|
||||
|
||||
|
||||
def test_remote_blob_columns_and_fetch():
|
||||
with blob_remote_table() as table:
|
||||
assert table.blob_columns() == ["image"]
|
||||
@@ -5327,7 +5879,7 @@ def test_sync_remote_blob_pandas_avoids_storage_access(
|
||||
raise AssertionError("remote storage must not be opened")
|
||||
|
||||
monkeypatch.setattr(lance, "dataset", fail_dataset)
|
||||
with blob_remote_table(location=location) as table:
|
||||
with blob_remote_table(location=location, version_header=None) as table:
|
||||
monkeypatch.setattr(table, "to_lance", fail_dataset)
|
||||
query = table.search().select(["id", "image"])
|
||||
if blob_mode == "descriptions":
|
||||
@@ -5340,8 +5892,11 @@ def test_sync_remote_blob_pandas_avoids_storage_access(
|
||||
NotImplementedError, match="stable table snapshot"
|
||||
) as exc:
|
||||
query.to_pandas(blob_mode=blob_mode)
|
||||
assert "fetch_blobs(column, row_ids)" in str(exc.value)
|
||||
assert "with_row_id(True)" in str(exc.value)
|
||||
if blob_mode == "bytes":
|
||||
assert "x-lancedb-query-version" in str(exc.value)
|
||||
else:
|
||||
assert "fetch_blobs(column, row_ids)" in str(exc.value)
|
||||
assert "with_row_id(True)" in str(exc.value)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -5425,7 +5980,7 @@ async def test_async_remote_blob_descriptions_to_pandas_uses_server(monkeypatch)
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("blob_mode", ["bytes", "lazy"])
|
||||
async def test_async_remote_blob_pandas_rejects_unpinned_fetch(monkeypatch, blob_mode):
|
||||
with blob_remote_table() as remote_table:
|
||||
with blob_remote_table(version_header=None) as remote_table:
|
||||
table = remote_table._table
|
||||
|
||||
async def fail_uri():
|
||||
@@ -5450,8 +6005,8 @@ async def test_async_remote_blob_pandas_rejects_unpinned_fetch(monkeypatch, blob
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["to_arrow", "to_list"])
|
||||
def test_remote_search_bytes_refused_before_query(monkeypatch, method):
|
||||
with blob_remote_table() as table:
|
||||
def test_remote_search_bytes_requires_response_version(method):
|
||||
with blob_remote_table(version_header=None) as table:
|
||||
query = table.search().select(["id", "image"])
|
||||
descriptions = getattr(query, method)(blob_mode="descriptions")
|
||||
images = (
|
||||
@@ -5461,19 +6016,15 @@ def test_remote_search_bytes_refused_before_query(monkeypatch, method):
|
||||
)
|
||||
assert "_lance_row_id" not in images[0]
|
||||
|
||||
def fail_query(*args, **kwargs):
|
||||
raise AssertionError("bytes must be refused before the query runs")
|
||||
|
||||
monkeypatch.setattr(table, "_execute_query", fail_query)
|
||||
with pytest.raises(NotImplementedError, match="stable table snapshot"):
|
||||
with pytest.raises(NotImplementedError, match="x-lancedb-query-version"):
|
||||
getattr(query, method)(blob_mode="bytes")
|
||||
with pytest.raises(ValueError, match="blob_mode must be one of"):
|
||||
table.to_pandas(blob_mode="handles")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_remote_to_arrow_bytes_refused_before_query(monkeypatch):
|
||||
with blob_remote_table() as remote_table:
|
||||
async def test_async_remote_to_arrow_bytes_requires_response_version(monkeypatch):
|
||||
with blob_remote_table(version_header=None) as remote_table:
|
||||
table = remote_table._table
|
||||
|
||||
async def fail_fetch(*args, **kwargs):
|
||||
@@ -5481,8 +6032,7 @@ async def test_async_remote_to_arrow_bytes_refused_before_query(monkeypatch):
|
||||
|
||||
monkeypatch.setattr(table, "fetch_blobs", fail_fetch)
|
||||
query = table.query().select(["id", "image"])
|
||||
monkeypatch.setattr(query, "to_batches", fail_fetch)
|
||||
with pytest.raises(NotImplementedError, match="stable table snapshot"):
|
||||
with pytest.raises(NotImplementedError, match="x-lancedb-query-version"):
|
||||
await query.to_arrow(blob_mode="bytes")
|
||||
with pytest.raises(NotImplementedError, match="stable table snapshot"):
|
||||
await table.to_arrow(blob_mode="bytes")
|
||||
@@ -5579,7 +6129,7 @@ def test_remote_blob_query_to_pandas():
|
||||
|
||||
@pytest.mark.parametrize("blob_mode", ["default", "lazy", "bytes"])
|
||||
def test_remote_blob_query_to_pandas_rejects_unpinned_fetch(monkeypatch, blob_mode):
|
||||
with blob_remote_table() as table:
|
||||
with blob_remote_table(version_header=None) as table:
|
||||
|
||||
def fail_fetch(*args, **kwargs):
|
||||
raise AssertionError("blob fetch must not use an unpinned remote table")
|
||||
@@ -6642,3 +7192,102 @@ def test_remote_optimize_rejects_explicit_pruning_before_submitting():
|
||||
table.optimize(delete_unverified=True)
|
||||
|
||||
assert server.tickets == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.parametrize("framing", ["file", "stream"])
|
||||
async def test_remote_blob_bytes_rejects_legacy_watermark(use_async, framing):
|
||||
requests = []
|
||||
with blob_remote_table(
|
||||
framing=framing,
|
||||
snapshot_supported=False,
|
||||
version_header="1",
|
||||
schema_version="1",
|
||||
requests=requests,
|
||||
) as remote_table:
|
||||
table = remote_table._table if use_async else remote_table
|
||||
query = table.query() if use_async else table.search()
|
||||
descriptors = query.to_arrow(blob_mode="descriptions")
|
||||
if use_async:
|
||||
descriptors = await descriptors
|
||||
assert descriptors.num_rows == 3
|
||||
assert pa.types.is_struct(descriptors.schema.field("image").type)
|
||||
query = table.query() if use_async else table.search()
|
||||
with pytest.raises(NotImplementedError, match="x-lancedb-query-version"):
|
||||
result = query.to_arrow(blob_mode="bytes")
|
||||
if use_async:
|
||||
await result
|
||||
assert not any(path == "fetch_blobs" for path, _ in requests)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.parametrize("identity_header", [None, "", "v2:" + "a" * 64, "v1:broken"])
|
||||
async def test_remote_blob_bytes_requires_trustworthy_identity(
|
||||
use_async, identity_header
|
||||
):
|
||||
requests = []
|
||||
with blob_remote_table(
|
||||
identity_header=identity_header, schema_version="1", requests=requests
|
||||
) as remote_table:
|
||||
table = remote_table._table if use_async else remote_table
|
||||
query = table.query() if use_async else table.search()
|
||||
# Ordinary descriptors still work, even with forged Arrow schema metadata.
|
||||
result = query.to_arrow(blob_mode="descriptions")
|
||||
if use_async:
|
||||
result = await result
|
||||
assert result.num_rows == 3
|
||||
with pytest.raises(NotImplementedError, match="x-lancedb-query-snapshot"):
|
||||
result = query.to_arrow(blob_mode="bytes")
|
||||
if use_async:
|
||||
await result
|
||||
assert not any(path == "fetch_blobs" for path, _ in requests)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
async def test_remote_blob_bytes_rejects_unverified_serving_node(use_async):
|
||||
with blob_remote_table(verify_identity=False) as remote_table:
|
||||
table = remote_table._table if use_async else remote_table
|
||||
query = table.query() if use_async else table.search()
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="did not verify the query snapshot identity"
|
||||
):
|
||||
result = query.to_arrow(blob_mode="bytes")
|
||||
if use_async:
|
||||
await result
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
async def test_remote_blob_bytes_hybrid_rejects_same_version_different_incarnations(
|
||||
use_async,
|
||||
):
|
||||
requests = []
|
||||
|
||||
def identity(body):
|
||||
return "v1:" + ("b" if body.get("full_text_query") else "a") * 64
|
||||
|
||||
with blob_remote_table(
|
||||
search_scores=True, identity_header=identity, requests=requests
|
||||
) as remote_table:
|
||||
if use_async:
|
||||
query = (
|
||||
remote_table._table.query()
|
||||
.nearest_to([1.0, 2.0])
|
||||
.nearest_to_text("hello")
|
||||
)
|
||||
else:
|
||||
query = (
|
||||
remote_table.search(query_type="hybrid", vector_column_name="vector")
|
||||
.vector([1.0, 2.0])
|
||||
.text("hello")
|
||||
)
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="inconsistent x-lancedb-query-version"
|
||||
):
|
||||
result = query.select(["id", "image"]).to_arrow(blob_mode="bytes")
|
||||
if use_async:
|
||||
await result
|
||||
assert not any(path == "fetch_blobs" for path, _ in requests)
|
||||
|
||||
+45
-4
@@ -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);
|
||||
}
|
||||
@@ -1965,14 +1978,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 +2046,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 +2059,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 +2078,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),
|
||||
|
||||
Reference in New Issue
Block a user